qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
56,472 | <p>I'm trying to send messages to Objective-C objects in gdb.</p>
<pre><code>(gdb) p $esi
$2 = (void *) 0x1268160
(gdb) po $esi
<NSArray: 0x1359c0>
(gdb) po [$esi count]
Target does not respond to this message selector.
</code></pre>
<p>I can't send any message to it. Am I missing something? Do I really need the symbols, or something else?</p>
| [
{
"answer_id": 57279,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 1,
"selected": false,
"text": "<p>Is it possible that you need to cast <code>$esi</code>?</p>\n\n<pre><code>p (NSUInteger)[(NSArray *)$esi count]\n</c... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5577/"
] | I'm trying to send messages to Objective-C objects in gdb.
```
(gdb) p $esi
$2 = (void *) 0x1268160
(gdb) po $esi
<NSArray: 0x1359c0>
(gdb) po [$esi count]
Target does not respond to this message selector.
```
I can't send any message to it. Am I missing something? Do I really need the symbols, or something else? | If you must override gdb and send a message to an object when it will not let you, you can use performSelector:
```
(gdb) print (int)[receivedData count]
Target does not respond to this message selector.
(gdb) print (int)[receivedData performSelector:@selector(count) ]
2008-09-15 00:46:35.854 Executable[1008:20b] *** -[NSConcreteMutableData count]:
unrecognized selector sent to instance 0x105f2e0
```
If you need to pass an argument use withObject:
```
(gdb) print (int)[receivedData performSelector:@selector(count) withObject:myObject ]
``` |
56,500 | <p>I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put</p>
<pre><code>extern "C" _declspec(dllexport) char* MyNewVariable = 0;
</code></pre>
<p>which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including</p>
<pre><code>_declspec(dllimport) char* MyNewVariable;
</code></pre>
<p>but that just gives me a linker error:</p>
<p>unresolved external symbol "__declspec(dllimport) char * MyNewVariable" (__imp_?MyNewVariable@@3PADA)</p>
<pre><code>extern "C" _declspec(dllimport) char* MyNewVariable;
</code></pre>
<p>as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it:</p>
<p>unresolved external symbol __imp__MyNewVariable</p>
<p>How do I write the declaration so that the C++ DLL variable is accessible from the C app?</p>
<hr>
<h2>The Answer</h2>
<p>As identified by botismarius and others (many thanks to all), I needed to link with the DLL's .lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the .lib file.</p>
| [
{
"answer_id": 56513,
"author": "Tony Lee",
"author_id": 5819,
"author_profile": "https://Stackoverflow.com/users/5819",
"pm_score": 2,
"selected": false,
"text": "<p>extern \"C\" is how you remove decoration - it should work to use:</p>\n\n<p>extern \"C\" declspec(dllimport) char MyNewV... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5816/"
] | I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put
```
extern "C" _declspec(dllexport) char* MyNewVariable = 0;
```
which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including
```
_declspec(dllimport) char* MyNewVariable;
```
but that just gives me a linker error:
unresolved external symbol "\_\_declspec(dllimport) char \* MyNewVariable" (\_\_imp\_?MyNewVariable@@3PADA)
```
extern "C" _declspec(dllimport) char* MyNewVariable;
```
as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it:
unresolved external symbol \_\_imp\_\_MyNewVariable
How do I write the declaration so that the C++ DLL variable is accessible from the C app?
---
The Answer
----------
As identified by botismarius and others (many thanks to all), I needed to link with the DLL's .lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the .lib file. | you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the `.lib` file. And yes, you should also declare the variable as:
```
extern "C" { declspec(dllimport) char MyNewVariable; }
``` |
56,521 | <p>I have a "numeric textbox" in C# .NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type <code>double?</code> (or <code>Nullable<double></code>). It's nullable to support the case where the user doesn't enter anything.</p>
<p>The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent():</p>
<pre><code>this.numericTextBox1.Value = 1;
</code></pre>
<p>Remember 'Value' is of type <code>Nullable<double></code>. This generates the following warning whenever I try to reopen the form in the Designer:</p>
<pre><code>Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'.
</code></pre>
<p>As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 56528,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": -1,
"selected": false,
"text": "<p>Could it help to setting the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueat... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a "numeric textbox" in C# .NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type `double?` (or `Nullable<double>`). It's nullable to support the case where the user doesn't enter anything.
The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent():
```
this.numericTextBox1.Value = 1;
```
Remember 'Value' is of type `Nullable<double>`. This generates the following warning whenever I try to reopen the form in the Designer:
```
Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'.
```
As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying.
Any suggestions? | Or, if you don't want the designer adding any code at all... add this to the Property.
```
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
``` |
56,547 | <p>How do you perform a CROSS JOIN with LINQ to SQL?</p>
| [
{
"answer_id": 56612,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 8,
"selected": true,
"text": "<p>A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.</p>\n\n<pre>\nvar ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5556/"
] | How do you perform a CROSS JOIN with LINQ to SQL? | A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.
```
var combo = from p in people
from c in cars
select new
{
p.Name,
c.Make,
c.Model,
c.Colour
};
``` |
56,554 | <p>Let's say I want to represent <code>\q</code> (or any other particular "backslash-escaped character"). That is, I want to match <code>\q</code> but not <code>\\q</code>, since the latter is a backslash-escaped backslash followed by a <code>q</code>. Yet <code>\\\q</code> would match, since it's a backslash-escaped backslash followed by a backslash-escaped <code>q</code>. (Well, it would match the <code>\q</code> at the end, not the <code>\\</code> at the beginning.)</p>
<p>I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp.</p>
| [
{
"answer_id": 56583,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.codinghorror.com/blog/archives/001016.html\" rel=\"nofollow noreferrer\">Now You Have Two Problem... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | Let's say I want to represent `\q` (or any other particular "backslash-escaped character"). That is, I want to match `\q` but not `\\q`, since the latter is a backslash-escaped backslash followed by a `q`. Yet `\\\q` would match, since it's a backslash-escaped backslash followed by a backslash-escaped `q`. (Well, it would match the `\q` at the end, not the `\\` at the beginning.)
I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp. | Updated:
My new and improved Perl regex, supporting more than 3 backslashes:
```
/(?<!\\) # Not preceded by a single backslash
(?>\\\\)* # an even number of backslashes
\\q # Followed by a \q
/x;
```
or if your regex library doesn't support extended syntax.
```
/(?<!\\)(?>\\\\)*\\q/
```
Output of my test program:
```
q does not match
\q does match
\\q does not match
\\\q does match
\\\\q does not match
\\\\\q does match
```
Older version
```
/(?:(?<!\\)|(?<=\\\\))\\q/
``` |
56,568 | <p>How do you actually perform datetime operations such as adding date, finding difference, find out how many days excluding weekends in an interval? I personally started to pass some of these operations to my postgresql dbms as typically I would only need to issue one sql statement to obtain an answer, however, to do it in PHP way I would have to write a lot more code that means more chances for errors to occur...</p>
<p>Are there any libraries in PHP that does datetime operation in a way that don't require a lot of code? that beats sql in a situation where 'Given two dates, how many workdays are there between the two dates? Implement in either SQL, or $pet_lang' that is solved by making this query?</p>
<pre class="lang-sql prettyprint-override"><code>SELECT COUNT(*) AS total_days
FROM (SELECT date '2008-8-26' + generate_series(0,
(date '2008-9-1' - date '2008-8-26')) AS all_days) AS calendar
WHERE EXTRACT(isodow FROM all_days) < 6;
</code></pre>
| [
{
"answer_id": 56595,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 3,
"selected": false,
"text": "<p>While for most datetime operations I would normally convert to Unixtime and perform addition subtraction etc. on the ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742/"
] | How do you actually perform datetime operations such as adding date, finding difference, find out how many days excluding weekends in an interval? I personally started to pass some of these operations to my postgresql dbms as typically I would only need to issue one sql statement to obtain an answer, however, to do it in PHP way I would have to write a lot more code that means more chances for errors to occur...
Are there any libraries in PHP that does datetime operation in a way that don't require a lot of code? that beats sql in a situation where 'Given two dates, how many workdays are there between the two dates? Implement in either SQL, or $pet\_lang' that is solved by making this query?
```sql
SELECT COUNT(*) AS total_days
FROM (SELECT date '2008-8-26' + generate_series(0,
(date '2008-9-1' - date '2008-8-26')) AS all_days) AS calendar
WHERE EXTRACT(isodow FROM all_days) < 6;
``` | PHP5+'s DateTime object is useful because it is leap time and
daylight savings aware, but it needs some extension to really
solve the problem. I wrote the following to solve a similar problem.
The find\_WeekdaysFromThisTo() method is brute-force, but it works reasonably quickly if your time span is less than 2 years.
```
$tryme = new Extended_DateTime('2007-8-26');
$newer = new Extended_DateTime('2008-9-1');
print 'Weekdays From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_WeekdaysFromThisTo($newer) ."\n";
/* Output: Weekdays From 2007-08-26 To 2008-09-01: 265 */
print 'All Days From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_AllDaysFromThisTo($newer) ."\n";
/* Output: All Days From 2007-08-26 To 2008-09-01: 371 */
$timefrom = $tryme->find_TimeFromThisTo($newer);
print 'Between '.$tryme->format('Y-m-d').' and '.$newer->format('Y-m-d').' there are '.
$timefrom['years'].' years, '.$timefrom['months'].' months, and '.$timefrom['days'].
' days.'."\n";
/* Output: Between 2007-08-26 and 2008-09-01 there are 1 years, 0 months, and 5 days. */
class Extended_DateTime extends DateTime {
public function find_TimeFromThisTo($newer) {
$timefrom = array('years'=>0,'months'=>0,'days'=>0);
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$timefrom['years'] = $this->find_YearsFromThisTo($testnewer);
$mod = '-'.$timefrom['years'].' years';
$testnewer -> modify($mod);
$timefrom['months'] = $this->find_MonthsFromThisTo($testnewer);
$mod = '-'.$timefrom['months'].' months';
$testnewer -> modify($mod);
$timefrom['days'] = $this->find_AllDaysFromThisTo($testnewer);
return $timefrom;
} // end function find_TimeFromThisTo
public function find_YearsFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 year');
while ( $this->format('U') < $testnewer->format('U')) {
$count ++;
$testnewer -> modify ('-1 year');
}
return $count;
} // end function find_YearsFromThisTo
public function find_MonthsFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 month');
while ( $this->format('U') < $testnewer->format('U')) {
$count ++;
$testnewer -> modify ('-1 month');
}
return $count;
} // end function find_MonthsFromThisTo
public function find_AllDaysFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 day');
while ( $this->format('U') < $testnewer->format('U')) {
$count ++;
$testnewer -> modify ('-1 day');
}
return $count;
} // end function find_AllDaysFromThisTo
public function find_WeekdaysFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 day');
while ( $this->format('U') < $testnewer->format('U')) {
// If the calculated day is not Sunday or Saturday, count this day
if ($testnewer->format('w') != '0' && $testnewer->format('w') != '6')
$count ++;
$testnewer -> modify ('-1 day');
}
return $count;
} // end function find_WeekdaysFromThisTo
public function set_Day($newday) {
if (is_int($newday) && $newday > 0 && $newday < 32 && checkdate($this->format('m'),$newday,$this->format('Y')))
$this->setDate($this->format('Y'),$this->format('m'),$newday);
} // end function set_Day
public function set_Month($newmonth) {
if (is_int($newmonth) && $newmonth > 0 && $newmonth < 13)
$this->setDate($this->format('Y'),$newmonth,$this->format('d'));
} // end function set_Month
public function set_Year($newyear) {
if (is_int($newyear) && $newyear > 0)
$this->setDate($newyear,$this->format('m'),$this->format('d'));
} // end function set_Year
} // end class Extended_DateTime
``` |
56,574 | <p>A while back I was reading the W3C article on '<a href="http://www.w3.org/International/articles/text-reuse/" rel="noreferrer">Re-using Strings in Scripted Content</a>', which contains some useful advice on internationalisation, but which strikes me as at odds iwth the DRY (Don't Repeat Yourself) principle of eliminating repetitive code.</p>
<p>To take their example, we might have some code like this...</p>
<pre><code>print "The printer is ";
if (printer.working) {
print "on.\n";
} else {
print "off.\n";
}
print "The stapler is ";
if (stapler.working) {
print "on.\n";
} else {
print "off.\n";
}
</code></pre>
<p>My instinct would be to eliminate the repetition roughly as follows...</p>
<pre><code>report-state(printer, "printer");
report-state(stapler, "stapler");
function report-state(name, object) {
print "The "+name+" is ";
if (object.working) {
print "on\n";
} else {
print "off\n";
}
}
</code></pre>
<p>...but doing so would cause a difficulty in the code if we needed to localise it to Spanish because the word for 'on' is apparently different in those two cases.</p>
<p>So, I guess my question is, how have other developers approached balancing the DRY principle with internationalisation of their code?</p>
<p>Part of me wants to argue that internationalisation is one of those extreme programming “<a href="http://www.extremeprogramming.org/rules/early.html" rel="noreferrer">you arent gonna need it</a>” situations. On the flip side however, refactoring with the DRY principle in mind is supposed to balance this by making it easy to implement functionality as it’s required, not harder as it does here.</p>
| [
{
"answer_id": 56609,
"author": "badbod99",
"author_id": 3614,
"author_profile": "https://Stackoverflow.com/users/3614",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest using a CMS rather than hardcoding in your textual values to cover localisation.</p>\n"
},
{
"ans... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | A while back I was reading the W3C article on '[Re-using Strings in Scripted Content](http://www.w3.org/International/articles/text-reuse/)', which contains some useful advice on internationalisation, but which strikes me as at odds iwth the DRY (Don't Repeat Yourself) principle of eliminating repetitive code.
To take their example, we might have some code like this...
```
print "The printer is ";
if (printer.working) {
print "on.\n";
} else {
print "off.\n";
}
print "The stapler is ";
if (stapler.working) {
print "on.\n";
} else {
print "off.\n";
}
```
My instinct would be to eliminate the repetition roughly as follows...
```
report-state(printer, "printer");
report-state(stapler, "stapler");
function report-state(name, object) {
print "The "+name+" is ";
if (object.working) {
print "on\n";
} else {
print "off\n";
}
}
```
...but doing so would cause a difficulty in the code if we needed to localise it to Spanish because the word for 'on' is apparently different in those two cases.
So, I guess my question is, how have other developers approached balancing the DRY principle with internationalisation of their code?
Part of me wants to argue that internationalisation is one of those extreme programming “[you arent gonna need it](http://www.extremeprogramming.org/rules/early.html)” situations. On the flip side however, refactoring with the DRY principle in mind is supposed to balance this by making it easy to implement functionality as it’s required, not harder as it does here. | I'd try to keep complete sentences in the language resource. As you said you might need different words in different contexts. But a bigger problem is that the order of sentences might be different in different languages. So building up strings from words can cause problems.
Just store
```
The printer is on
The printer is off
The stapler is on
The stapler is off
```
in the language resource for every language. The repetition here is less of a maintenance headache than trying to figure out where all the single words are going to pop up in your application. |
56,591 | <p>Ok, this is bit of an obscure question, but hopefully someone can help me out with it.</p>
<p>The system I'm working on builds a dynamic SQL string for execution inside a stored procedure, and part of that dynamic SQL defining column aliases, which themselves are actually values retrieved from another table of user generated data.</p>
<p>So, for example, the string might look something like;</p>
<pre><code>SELECT table1.Col1 AS "This is an alias" FROM table1
</code></pre>
<p>This works fine. However, the value that is used for the alias can potentially contain a double quote character, which breaks the outer quotes. I thought that I could maybe escape double quotes inside the alias somehow, but I've had no luck figuring out how to do so. Backslash doesn't work, and using two double quotes in a row results in this error;</p>
<pre><code>SQL Error: ORA-03001: unimplemented feature
03001. 00000 - "unimplemented feature"
*Cause: This feature is not implemented.
</code></pre>
<p>Has anyone had any experience with this issue before?
Cheers for any insight anyone has.</p>
<p>p.s. the quotes are needed around the aliases because they can contain spaces.</p>
| [
{
"answer_id": 56636,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 1,
"selected": false,
"text": "<p>When I run this:</p>\n\n<pre><code>select 'test\"columnname\"' from dual\n</code></pre>\n\n<p>Oracle returns this (noti... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5827/"
] | Ok, this is bit of an obscure question, but hopefully someone can help me out with it.
The system I'm working on builds a dynamic SQL string for execution inside a stored procedure, and part of that dynamic SQL defining column aliases, which themselves are actually values retrieved from another table of user generated data.
So, for example, the string might look something like;
```
SELECT table1.Col1 AS "This is an alias" FROM table1
```
This works fine. However, the value that is used for the alias can potentially contain a double quote character, which breaks the outer quotes. I thought that I could maybe escape double quotes inside the alias somehow, but I've had no luck figuring out how to do so. Backslash doesn't work, and using two double quotes in a row results in this error;
```
SQL Error: ORA-03001: unimplemented feature
03001. 00000 - "unimplemented feature"
*Cause: This feature is not implemented.
```
Has anyone had any experience with this issue before?
Cheers for any insight anyone has.
p.s. the quotes are needed around the aliases because they can contain spaces. | Can you just put another character instead of double quotes and replace that with double quotes in the code?
Something like this:
```
SELECT table1.Col1 AS "This is |not| an alias" FROM table1
```
Then just replace | with ".
I know it's a hack, but I can't think of any better solution... And what you are doing there is a hack anyway. The "nice" way would be to select the values and the column names separately and associate them in your code. That would make things much cleaner. |
56,628 | <p>I'm not a SQL expert, and I'm reminded of the fact every time I need to do something beyond the basics. I have a test database that is not large in size, but the transaction log definitely is. How do I clear out the transaction log?</p>
| [
{
"answer_id": 56647,
"author": "Johnno Nolan",
"author_id": 1116,
"author_profile": "https://Stackoverflow.com/users/1116",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a simple and <strong>very inelegant</strong> & <strong>potentially dangerous</strong> way. </p>\n\n<ol>\... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] | I'm not a SQL expert, and I'm reminded of the fact every time I need to do something beyond the basics. I have a test database that is not large in size, but the transaction log definitely is. How do I clear out the transaction log? | Making a log file smaller should really be reserved for scenarios where it encountered unexpected growth which you do not expect to happen again. If the log file will grow to the same size again, not very much is accomplished by shrinking it temporarily. Now, depending on the recovery goals of your database, these are the actions you should take.
First, take a full backup
=========================
Never make any changes to your database without ensuring you can restore it should something go wrong.
If you care about point-in-time recovery
========================================
(And by point-in-time recovery, I mean you care about being able to restore to anything other than a full or differential backup.)
Presumably your database is in `FULL` recovery mode. If not, then make sure it is:
```
ALTER DATABASE testdb SET RECOVERY FULL;
```
Even if you are taking regular full backups, the log file will grow and grow until you perform a *log* backup - this is for your protection, not to needlessly eat away at your disk space. You should be performing these log backups quite frequently, according to your recovery objectives. For example, if you have a business rule that states you can afford to lose no more than 15 minutes of data in the event of a disaster, you should have a job that backs up the log every 15 minutes. Here is a script that will generate timestamped file names based on the current time (but you can also do this with maintenance plans etc., just don't choose any of the shrink options in maintenance plans, they're awful).
```
DECLARE @path NVARCHAR(255) = N'\\backup_share\log\testdb_'
+ CONVERT(CHAR(8), GETDATE(), 112) + '_'
+ REPLACE(CONVERT(CHAR(8), GETDATE(), 108),':','')
+ '.trn';
BACKUP LOG foo TO DISK = @path WITH INIT, COMPRESSION;
```
Note that `\\backup_share\` should be on a different machine that represents a different underlying storage device. Backing these up to the same machine (or to a different machine that uses the same underlying disks, or a different VM that's on the same physical host) does not really help you, since if the machine blows up, you've lost your database *and* its backups. Depending on your network infrastructure it may make more sense to backup locally and then transfer them to a different location behind the scenes; in either case, you want to get them off the primary database machine as quickly as possible.
Now, once you have regular log backups running, it should be reasonable to shrink the log file to something more reasonable than whatever it's blown up to now. This does *not* mean running `SHRINKFILE` over and over again until the log file is 1 MB - even if you are backing up the log frequently, it still needs to accommodate the sum of any concurrent transactions that can occur. Log file autogrow events are expensive, since SQL Server has to zero out the files (unlike data files when instant file initialization is enabled), and user transactions have to wait while this happens. You want to do this grow-shrink-grow-shrink routine as little as possible, and you certainly don't want to make your users pay for it.
Note that you may need to back up the log twice before a shrink is possible (thanks Robert).
So, you need to come up with a practical size for your log file. Nobody here can tell you what that is without knowing a lot more about your system, but if you've been frequently shrinking the log file and it has been growing again, a good watermark is probably 10-50% higher than the largest it's been. Let's say that comes to 200 MB, and you want any subsequent autogrowth events to be 50 MB, then you can adjust the log file size this way:
```
USE [master];
GO
ALTER DATABASE Test1
MODIFY FILE
(NAME = yourdb_log, SIZE = 200MB, FILEGROWTH = 50MB);
GO
```
Note that if the log file is currently > 200 MB, you may need to run this first:
```
USE yourdb;
GO
DBCC SHRINKFILE(yourdb_log, 200);
GO
```
If you don't care about point-in-time recovery
==============================================
If this is a test database, and you don't care about point-in-time recovery, then you should make sure that your database is in `SIMPLE` recovery mode.
```
ALTER DATABASE testdb SET RECOVERY SIMPLE;
```
Putting the database in `SIMPLE` recovery mode will make sure that SQL Server re-uses portions of the log file (essentially phasing out inactive transactions) instead of growing to keep a record of *all* transactions (like `FULL` recovery does until you back up the log). `CHECKPOINT` events will help control the log and make sure that it doesn't need to grow unless you generate a lot of t-log activity between `CHECKPOINT`s.
Next, you should make absolute sure that this log growth was truly due to an abnormal event (say, an annual spring cleaning or rebuilding your biggest indexes), and not due to normal, everyday usage. If you shrink the log file to a ridiculously small size, and SQL Server just has to grow it again to accommodate your normal activity, what did you gain? Were you able to make use of that disk space you freed up only temporarily? If you need an immediate fix, then you can run the following:
```
USE yourdb;
GO
CHECKPOINT;
GO
CHECKPOINT; -- run twice to ensure file wrap-around
GO
DBCC SHRINKFILE(yourdb_log, 200); -- unit is set in MBs
GO
```
Otherwise, set an appropriate size and growth rate. As per the example in the point-in-time recovery case, you can use the same code and logic to determine what file size is appropriate and set reasonable autogrowth parameters.
Some things you don't want to do
================================
* **Back up the log with `TRUNCATE_ONLY` option and then `SHRINKFILE`**. For one, this `TRUNCATE_ONLY` option has been deprecated and is no longer available in current versions of SQL Server. Second, if you are in `FULL` recovery model, this will destroy your log chain and require a new, full backup.
* **Detach the database, delete the log file, and re-attach**. I can't emphasize how dangerous this can be. Your database may not come back up, it may come up as suspect, you may have to revert to a backup (if you have one), etc. etc.
* **Use the "shrink database" option**. `DBCC SHRINKDATABASE` and the maintenance plan option to do the same are bad ideas, especially if you really only need to resolve a log problem issue. Target the file you want to adjust and adjust it independently, using `DBCC SHRINKFILE` or `ALTER DATABASE ... MODIFY FILE` (examples above).
* **Shrink the log file to 1 MB**. This looks tempting because, hey, SQL Server will let me do it in certain scenarios, and look at all the space it frees! Unless your database is read only (and it is, you should mark it as such using `ALTER DATABASE`), this will absolutely just lead to many unnecessary growth events, as the log has to accommodate current transactions regardless of the recovery model. What is the point of freeing up that space temporarily, just so SQL Server can take it back slowly and painfully?
* **Create a second log file**. This will provide temporarily relief for the drive that has filled your disk, but this is like trying to fix a punctured lung with a band-aid. You should deal with the problematic log file directly instead of just adding another potential problem. Other than redirecting some transaction log activity to a different drive, a second log file really does nothing for you (unlike a second data file), since only one of the files can ever be used at a time. [Paul Randal also explains why multiple log files can bite you later](http://www.sqlskills.com/blogs/paul/multiple-log-files-and-why-theyre-bad/).
Be proactive
============
Instead of shrinking your log file to some small amount and letting it constantly autogrow at a small rate on its own, set it to some reasonably large size (one that will accommodate the sum of your largest set of concurrent transactions) and set a reasonable autogrow setting as a fallback, so that it doesn't have to grow multiple times to satisfy single transactions and so that it will be relatively rare for it to ever have to grow during normal business operations.
The worst possible settings here are 1 MB growth or 10% growth. Funny enough, these are the defaults for SQL Server (which I've complained about and [asked for changes to no avail](https://web.archive.org/web/20140108204835/http://connect.microsoft.com:80/SQLServer/feedback/details/415343)) - 1 MB for data files, and 10% for log files. The former is much too small in this day and age, and the latter leads to longer and longer events every time (say, your log file is 500 MB, first growth is 50 MB, next growth is 55 MB, next growth is 60.5 MB, etc. etc. - and on slow I/O, believe me, you will really notice this curve).
Further reading
===============
Please don't stop here; while much of the advice you see out there about shrinking log files is inherently bad and even potentially disastrous, there are some people who care more about data integrity than freeing up disk space.
[A blog post I wrote in 2009, when I saw a few "here's how to shrink the log file" posts spring up](https://sqlblog.org/2009/07/27/oh-the-horror-please-stop-telling-people-they-should-shrink-their-log-files).
[A blog post Brent Ozar wrote four years ago, pointing to multiple resources, in response to a SQL Server Magazine article that should *not* have been published](http://www.brentozar.com/archive/2009/08/stop-shrinking-your-database-files-seriously-now/).
[A blog post by Paul Randal explaining why t-log maintenance is important](http://www.sqlskills.com/blogs/paul/importance-of-proper-transaction-log-size-management/) and [why you shouldn't shrink your data files, either](http://www.sqlskills.com/blogs/paul/why-you-should-not-shrink-your-data-files/).
[Mike Walsh has a great answer covering some of these aspects too, including reasons why you might not be able to shrink your log file immediately](https://dba.stackexchange.com/questions/29829/why-does-the-transaction-log-keep-growing-or-run-out-of-space). |
56,630 | <p>Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments. It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen. (To see an example, click <a href="http://news.slashdot.org/news/08/09/10/2257242.shtml" rel="nofollow noreferrer">here</a>.)</p>
<p>My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down? I know this will involve a combination of CSS and javascript. I'm not necessarily looking for a full example of working code, but what steps will my code need to go through?</p>
| [
{
"answer_id": 56759,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 3,
"selected": true,
"text": "<p>Okay, I figured it out. I will post it here in case it help anyone else. This solution uses prototype, and an internal l... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4257/"
] | Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments. It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen. (To see an example, click [here](http://news.slashdot.org/news/08/09/10/2257242.shtml).)
My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down? I know this will involve a combination of CSS and javascript. I'm not necessarily looking for a full example of working code, but what steps will my code need to go through? | Okay, I figured it out. I will post it here in case it help anyone else. This solution uses prototype, and an internal library that gives me the registerEvent, getElementX and getElementY functions, which do what you would think.
```
var MenuManager = Class.create({
initialize: function initialize(menuElt) {
this.menu = $(menuElt);
this.homePosn = { x: getElementX(this.menu), y: getElementY(this.menu) };
registerEvent(document, 'scroll', this.handleScroll.bind(this));
this.handleScroll();
},
handleScroll: function handleScroll() {
this.scrollOffset = document.viewport.getScrollOffsets().top;
if (this.scrollOffset > this.homePosn.y) {
this.menu.style.position = 'fixed';
this.menu.style.top = 0;
this.menu.style.left = this.homePosn.x;
} else {
this.menu.style.position = 'absolute';
this.menu.style.top = null;
this.menu.style.left = null;
}
}
});
```
Just call the constructor with the id of your menu, and the class will take it from there. |
56,638 | <p>I want to convert a number that is in <a href="https://en.wikipedia.org/wiki/Netscape_Portable_Runtime#Time" rel="nofollow noreferrer">PRTime</a> format (a 64-bit integer representing the number of microseconds since midnight (00:00:00) 1 January 1970 Coordinated Universal Time (UTC)) to a <code>DateTime</code>.</p>
<p>Note that this is slightly different than the usual "number of milliseconds since 1/1/1970".</p>
| [
{
"answer_id": 56674,
"author": "Barry",
"author_id": 845,
"author_profile": "https://Stackoverflow.com/users/845",
"pm_score": 3,
"selected": true,
"text": "<pre><code>Dim prTimeInMillis As UInt64\nprTimeInMillis = prTime/1000\n\nDim prDateTime As New DateTime(1970, 1, 1)\nprDateTime = ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842864/"
] | I want to convert a number that is in [PRTime](https://en.wikipedia.org/wiki/Netscape_Portable_Runtime#Time) format (a 64-bit integer representing the number of microseconds since midnight (00:00:00) 1 January 1970 Coordinated Universal Time (UTC)) to a `DateTime`.
Note that this is slightly different than the usual "number of milliseconds since 1/1/1970". | ```
Dim prTimeInMillis As UInt64
prTimeInMillis = prTime/1000
Dim prDateTime As New DateTime(1970, 1, 1)
prDateTime = prDateTime.AddMilliseconds(prTimeInMillis)
``` |
56,655 | <p>This is the day of weird behavior.</p>
<p>We have a Win32 project made with Delphi 2007, which hosts the .NET runtime and calls into .NET to show new forms, as part of a transition period.</p>
<p>Recently we've begun experiencing exceptions at seemingly random locations and points of our code: Arithmetic overflow or underflow.</p>
<p>The stack trace of one of these looks like this:</p>
<pre><code>at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.RunDialog(Form form)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
at Gatsoft.Gat.UI.Windows.Forms.Remanaging.RemanageForm.DelphiOpenInNewMode(String employeeCode, String departmentCode, DateTime date) in C:\Dev\VS.NET\Gatsoft\Gatsoft.Gat.UI.Windows\Forms\Remanaging\RemanageForm.Delphi.cs:line 67
</code></pre>
<p>In the Visual Studio solution, one of the outmost class libraries (ie. pulls in all the references it can), has set a specific debug program, targetted for the Delphi project output. This allows us to debug .NET code from Visual Studio, even though the main bulk of the program is written in Delphi.</p>
<p>The problem only occurs when run from the debugger, not if we just run the exe file directly (either through explorer, shortcuts, or even <kbd>Ctrl</kbd>+<kbd>F5</kbd> inside Visual Studio).</p>
<p>There's apparently no spyware on the machine (as hinted by <a href="http://bytes.com/forum/thread106203.html" rel="nofollow noreferrer">this</a>).</p>
<p>Any other things we can check?</p>
<hr />
<p><strong>Edit:</strong> It looks like the .NET debugger is enabling this SNaN flags, and the Delphi debugger does not. We'll have to investigate this further, but for now I'll accept <a href="https://stackoverflow.com/users/6550/lorenzo-boccaccia">@Lorenzo Boccaccia</a>'s answer.</p>
<h2>Apparently Solved</h2>
<p>Ok, it looks like we've finally nailed this problem. The problem started occuring without having the debugger attached as well, for our testers, so we had to prioritize the problem way up.</p>
<p>Finally we found one common issue with the machines that had the problem, they are Dell Lattitude D620 laptops with an NVIDIA Quadro NVS 110M, with an old driver from a system image used to provision the laptops, from back in 2006.</p>
<p>I found one post on the web, though I lost the url when I rebooted to update the display driver, that had a .NET service crashing, mostly when the machine was busy doing something on the screen. One way to reproduce his problem was to open a command prompt to C:\ and doing a <code>DIR /S</code> to just force a massive amount of screen updates, which would trigger the crash.</p>
<p>He too had a NVIDIA video card.</p>
<p>The problem on my machine occured roughly every 2-4 startups of our program, but after updating the video driver I've had 123 successfull startups without any problems. (BTW I can recommend <a href="http://www.autohotkey.com/" rel="nofollow noreferrer">AutoHotKey</a> for such things).</p>
<p>So it looks like we've found the culprit, an old/buggy NVIDIA driver.</p>
<p>Updated this question so that perhaps someone in the future can save some time.</p>
<p>Now, if you'll excuse me, I'm going to go cry in a corner.</p>
<h2>Jinxed!</h2>
<p>I must've jinxed it. No sooner had I posted the above update than a colleague laptop failed, after updating the video driver.</p>
<p>Still, I'm positive it's a problem outside of our application now, so it just remains to figure out which specific things to update.</p>
<hr />
<p><strong>Further updates</strong>: Ok, my machine is now apparently fixed, not so with my colleagues machine. So far we've updated the BIOS, Chipset drivers, and currently SP3 for XP is on its way in.</p>
<p>A burn-in test will be done tonight, where the app will be left overnight starting up, as the problem cropped up either during startup, or at the first time some WinForms .NET code was executed. This app is mainly a Delphi Win32 app, but it hosts the .NET runtime, and the problem seems to be related to .NET code. When we "boot" the .NET runtime, the problem can appear, or when we fire the first .NET window from Win32 then it can also appear.</p>
<hr />
<p>Statistically I'm ready to release this code now. Over the night the application has been started 3051 times without errors, whereas before I updated the video driver it crashed every 2-4 times.</p>
<h2>Prodded and found(!/?)</h2>
<p>This bug-fixing ordeal feels like going to the doctor, where the following conversation ensues:</p>
<pre><code>Doc: Does this hurt?
Me: No...
Doc: What about now?
</code></pre>
<p>I've prodded and poked the application and finally I think I've found something we did that introduced this problem.</p>
<p>In our app we host the .NET runtime, from a Delphi 2007 Win32 application, and in our glue-code we have the following line (now):</p>
<pre><code> rc := CorBindToRuntimeEx('v2.0.50727', 'wks',
STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN or STARTUP_CONCURRENT_GC,
@clsid, @iid, UnkRuntimeEngine);
</code></pre>
<p>The two constants in the middle there was originally just a 0, meaning <em>pick the defaults</em>. This change was introduced a few months ago and the problem has been slowly creeping in on us after this. The change was introduced in order to encourage ANTS profiler to load our Win32 application + hosted .NET runtime in order to do performance profiling and the changes we introduced back then made that work. Additionally, the problem with arithmetic overflow/underflow has slowly been getting worse so I bet the problem didn't appear for a while after the change so it wasn't attributed to any of the changes we did.</p>
<p>Also, since we only (originally) saw the problem when running through the debugger, we thought something was wrong with Visual Studio and/or Delphi.</p>
<p>Anyway, statistically now, with a browser on one screen doing repeated scrolling up and down triggered by a javascript (apparently needed in order to trigger the bug), then I have been able to successfully start the application 726 times with a 0 in the call, and it crashes 5 out of 17 times with the two constants there.</p>
<pre><code>Doc: Does this hurt?
</code></pre>
<p>And let's not get into who made that change in the first place. I'm sure the culprit wants to be left anonymous... <em>cough</em></p>
| [
{
"answer_id": 56696,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 1,
"selected": false,
"text": "<p>Have you added all the WMI components? As far as I know, you need all the WMI components to access the counters!</p>\n... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] | This is the day of weird behavior.
We have a Win32 project made with Delphi 2007, which hosts the .NET runtime and calls into .NET to show new forms, as part of a transition period.
Recently we've begun experiencing exceptions at seemingly random locations and points of our code: Arithmetic overflow or underflow.
The stack trace of one of these looks like this:
```
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.RunDialog(Form form)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
at Gatsoft.Gat.UI.Windows.Forms.Remanaging.RemanageForm.DelphiOpenInNewMode(String employeeCode, String departmentCode, DateTime date) in C:\Dev\VS.NET\Gatsoft\Gatsoft.Gat.UI.Windows\Forms\Remanaging\RemanageForm.Delphi.cs:line 67
```
In the Visual Studio solution, one of the outmost class libraries (ie. pulls in all the references it can), has set a specific debug program, targetted for the Delphi project output. This allows us to debug .NET code from Visual Studio, even though the main bulk of the program is written in Delphi.
The problem only occurs when run from the debugger, not if we just run the exe file directly (either through explorer, shortcuts, or even `Ctrl`+`F5` inside Visual Studio).
There's apparently no spyware on the machine (as hinted by [this](http://bytes.com/forum/thread106203.html)).
Any other things we can check?
---
**Edit:** It looks like the .NET debugger is enabling this SNaN flags, and the Delphi debugger does not. We'll have to investigate this further, but for now I'll accept [@Lorenzo Boccaccia](https://stackoverflow.com/users/6550/lorenzo-boccaccia)'s answer.
Apparently Solved
-----------------
Ok, it looks like we've finally nailed this problem. The problem started occuring without having the debugger attached as well, for our testers, so we had to prioritize the problem way up.
Finally we found one common issue with the machines that had the problem, they are Dell Lattitude D620 laptops with an NVIDIA Quadro NVS 110M, with an old driver from a system image used to provision the laptops, from back in 2006.
I found one post on the web, though I lost the url when I rebooted to update the display driver, that had a .NET service crashing, mostly when the machine was busy doing something on the screen. One way to reproduce his problem was to open a command prompt to C:\ and doing a `DIR /S` to just force a massive amount of screen updates, which would trigger the crash.
He too had a NVIDIA video card.
The problem on my machine occured roughly every 2-4 startups of our program, but after updating the video driver I've had 123 successfull startups without any problems. (BTW I can recommend [AutoHotKey](http://www.autohotkey.com/) for such things).
So it looks like we've found the culprit, an old/buggy NVIDIA driver.
Updated this question so that perhaps someone in the future can save some time.
Now, if you'll excuse me, I'm going to go cry in a corner.
Jinxed!
-------
I must've jinxed it. No sooner had I posted the above update than a colleague laptop failed, after updating the video driver.
Still, I'm positive it's a problem outside of our application now, so it just remains to figure out which specific things to update.
---
**Further updates**: Ok, my machine is now apparently fixed, not so with my colleagues machine. So far we've updated the BIOS, Chipset drivers, and currently SP3 for XP is on its way in.
A burn-in test will be done tonight, where the app will be left overnight starting up, as the problem cropped up either during startup, or at the first time some WinForms .NET code was executed. This app is mainly a Delphi Win32 app, but it hosts the .NET runtime, and the problem seems to be related to .NET code. When we "boot" the .NET runtime, the problem can appear, or when we fire the first .NET window from Win32 then it can also appear.
---
Statistically I'm ready to release this code now. Over the night the application has been started 3051 times without errors, whereas before I updated the video driver it crashed every 2-4 times.
Prodded and found(!/?)
----------------------
This bug-fixing ordeal feels like going to the doctor, where the following conversation ensues:
```
Doc: Does this hurt?
Me: No...
Doc: What about now?
```
I've prodded and poked the application and finally I think I've found something we did that introduced this problem.
In our app we host the .NET runtime, from a Delphi 2007 Win32 application, and in our glue-code we have the following line (now):
```
rc := CorBindToRuntimeEx('v2.0.50727', 'wks',
STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN or STARTUP_CONCURRENT_GC,
@clsid, @iid, UnkRuntimeEngine);
```
The two constants in the middle there was originally just a 0, meaning *pick the defaults*. This change was introduced a few months ago and the problem has been slowly creeping in on us after this. The change was introduced in order to encourage ANTS profiler to load our Win32 application + hosted .NET runtime in order to do performance profiling and the changes we introduced back then made that work. Additionally, the problem with arithmetic overflow/underflow has slowly been getting worse so I bet the problem didn't appear for a while after the change so it wasn't attributed to any of the changes we did.
Also, since we only (originally) saw the problem when running through the debugger, we thought something was wrong with Visual Studio and/or Delphi.
Anyway, statistically now, with a browser on one screen doing repeated scrolling up and down triggered by a javascript (apparently needed in order to trigger the bug), then I have been able to successfully start the application 726 times with a 0 in the call, and it crashes 5 out of 17 times with the two constants there.
```
Doc: Does this hurt?
```
And let's not get into who made that change in the first place. I'm sure the culprit wants to be left anonymous... *cough* | It looks like this is what I was missing: <http://msdn.microsoft.com/en-us/library/aa939695.aspx> |
56,658 | <h3>Summary</h3>
<p>What's the best way to ensure a table cell cannot be less than a certain minimum width. </p>
<h3>Example</h3>
<p>I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space.</p>
<h3>Browser compatibility</h3>
<p>I possible I would like to find a solution that works in</p>
<ul>
<li>IE 6-8</li>
<li>FF 2-3</li>
<li>Safari</li>
</ul>
<p>In order of preference.</p>
| [
{
"answer_id": 56663,
"author": "James B",
"author_id": 2951,
"author_profile": "https://Stackoverflow.com/users/2951",
"pm_score": 7,
"selected": true,
"text": "<p>This CSS should suffice:</p>\n\n<pre><code>td { min-width: 100px; }\n</code></pre>\n\n<p>However, it's not always obeyed co... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182/"
] | ### Summary
What's the best way to ensure a table cell cannot be less than a certain minimum width.
### Example
I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space.
### Browser compatibility
I possible I would like to find a solution that works in
* IE 6-8
* FF 2-3
* Safari
In order of preference. | This CSS should suffice:
```
td { min-width: 100px; }
```
However, it's not always obeyed correctly (the min-width attribute) by all browsers (for example, IE6 dislikes it a great deal).
**Edit:** As for an IE6 (and before) solution, there isn't one that works reliably under all circumstances, as far as I know. Using the nowrap HTML attribute doesn't really achieve the desired result, as that just prevents line-breaks in the cell, rather than specifying a minimum width.
However, if nowrap is used in conjunction with a regular cell width property (such as using width: 100px), the 100px will act *like* a minimum width and the cell will still expand with the text (due to the nowrap). This is a less-than-ideal solution, which cannot be fully applied using CSS and, as such, would be tedious to implement if you have many tables you wish to apply this to. (Of course, this entire alternative solution falls down if you want to have dynamic line-breaks in your cells, anyway). |
56,682 | <p>In Windows, is there an easy way to tell if a folder has a subfile that has changed?</p>
<p>I verified, and the last modified date on the folder does not get updated when a subfile changes.</p>
<p>Is there a registry entry I can set that will modify this behavior?</p>
<p>If it matters, I am using an NTFS volume. </p>
<p>I would ultimately like to have this ability from a C++ program. </p>
<p><strong>Scanning an entire directory recursively will not work for me because the folder is much too large.</strong></p>
<p><strong>Update: I really need a way to do this without a process running while the change occurs. So installing a file system watcher is not optimal for me.</strong> </p>
<p><strong>Update2: The archive bit will also not work because it has the same problem as the last modification date. The file's archive bit will be set, but the folders will not.</strong></p>
| [
{
"answer_id": 56695,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 1,
"selected": false,
"text": "<p>If you can't run a process when the change occurs, then there's not much you can do except scan the filesystem, and che... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] | In Windows, is there an easy way to tell if a folder has a subfile that has changed?
I verified, and the last modified date on the folder does not get updated when a subfile changes.
Is there a registry entry I can set that will modify this behavior?
If it matters, I am using an NTFS volume.
I would ultimately like to have this ability from a C++ program.
**Scanning an entire directory recursively will not work for me because the folder is much too large.**
**Update: I really need a way to do this without a process running while the change occurs. So installing a file system watcher is not optimal for me.**
**Update2: The archive bit will also not work because it has the same problem as the last modification date. The file's archive bit will be set, but the folders will not.** | This [article](http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx) should help. Basically, you create one or more notification object such as:
```
HANDLE dwChangeHandles[2];
dwChangeHandles[0] = FindFirstChangeNotification(
lpDir, // directory to watch
FALSE, // do not watch subtree
FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes
if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)
{
printf("\n ERROR: FindFirstChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
// Watch the subtree for directory creation and deletion.
dwChangeHandles[1] = FindFirstChangeNotification(
lpDrive, // directory to watch
TRUE, // watch the subtree
FILE_NOTIFY_CHANGE_DIR_NAME); // watch dir name changes
if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)
{
printf("\n ERROR: FindFirstChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
```
and then you wait for a notification:
```
while (TRUE)
{
// Wait for notification.
printf("\nWaiting for notification...\n");
DWORD dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles,
FALSE, INFINITE);
switch (dwWaitStatus)
{
case WAIT_OBJECT_0:
// A file was created, renamed, or deleted in the directory.
// Restart the notification.
if ( FindNextChangeNotification(dwChangeHandles[0]) == FALSE )
{
printf("\n ERROR: FindNextChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
break;
case WAIT_OBJECT_0 + 1:
// Restart the notification.
if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE )
{
printf("\n ERROR: FindNextChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
break;
case WAIT_TIMEOUT:
// A time-out occurred. This would happen if some value other
// than INFINITE is used in the Wait call and no changes occur.
// In a single-threaded environment, you might not want an
// INFINITE wait.
printf("\nNo changes in the time-out period.\n");
break;
default:
printf("\n ERROR: Unhandled dwWaitStatus.\n");
ExitProcess(GetLastError());
break;
}
}
}
``` |
56,692 | <p>Consider the class below that represents a Broker:</p>
<pre><code>public class Broker
{
public string Name = string.Empty;
public int Weight = 0;
public Broker(string n, int w)
{
this.Name = n;
this.Weight = w;
}
}
</code></pre>
<p>I'd like to randomly select a Broker from an array, taking into account their weights.</p>
<p>What do you think of the code below?</p>
<pre><code>class Program
{
private static Random _rnd = new Random();
public static Broker GetBroker(List<Broker> brokers, int totalWeight)
{
// totalWeight is the sum of all brokers' weight
int randomNumber = _rnd.Next(0, totalWeight);
Broker selectedBroker = null;
foreach (Broker broker in brokers)
{
if (randomNumber <= broker.Weight)
{
selectedBroker = broker;
break;
}
randomNumber = randomNumber - broker.Weight;
}
return selectedBroker;
}
static void Main(string[] args)
{
List<Broker> brokers = new List<Broker>();
brokers.Add(new Broker("A", 10));
brokers.Add(new Broker("B", 20));
brokers.Add(new Broker("C", 20));
brokers.Add(new Broker("D", 10));
// total the weigth
int totalWeight = 0;
foreach (Broker broker in brokers)
{
totalWeight += broker.Weight;
}
while (true)
{
Dictionary<string, int> result = new Dictionary<string, int>();
Broker selectedBroker = null;
for (int i = 0; i < 1000; i++)
{
selectedBroker = GetBroker(brokers, totalWeight);
if (selectedBroker != null)
{
if (result.ContainsKey(selectedBroker.Name))
{
result[selectedBroker.Name] = result[selectedBroker.Name] + 1;
}
else
{
result.Add(selectedBroker.Name, 1);
}
}
}
Console.WriteLine("A\t\t" + result["A"]);
Console.WriteLine("B\t\t" + result["B"]);
Console.WriteLine("C\t\t" + result["C"]);
Console.WriteLine("D\t\t" + result["D"]);
result.Clear();
Console.WriteLine();
Console.ReadLine();
}
}
}
</code></pre>
<p>I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.</p>
<p>Is there a more accurate algorithm?</p>
<p>Thanks!</p>
| [
{
"answer_id": 56735,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "<p>Your algorithm is nearly correct. However, the test should be <code><</code> instead of <code><=</code>:</p>\n... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868/"
] | Consider the class below that represents a Broker:
```
public class Broker
{
public string Name = string.Empty;
public int Weight = 0;
public Broker(string n, int w)
{
this.Name = n;
this.Weight = w;
}
}
```
I'd like to randomly select a Broker from an array, taking into account their weights.
What do you think of the code below?
```
class Program
{
private static Random _rnd = new Random();
public static Broker GetBroker(List<Broker> brokers, int totalWeight)
{
// totalWeight is the sum of all brokers' weight
int randomNumber = _rnd.Next(0, totalWeight);
Broker selectedBroker = null;
foreach (Broker broker in brokers)
{
if (randomNumber <= broker.Weight)
{
selectedBroker = broker;
break;
}
randomNumber = randomNumber - broker.Weight;
}
return selectedBroker;
}
static void Main(string[] args)
{
List<Broker> brokers = new List<Broker>();
brokers.Add(new Broker("A", 10));
brokers.Add(new Broker("B", 20));
brokers.Add(new Broker("C", 20));
brokers.Add(new Broker("D", 10));
// total the weigth
int totalWeight = 0;
foreach (Broker broker in brokers)
{
totalWeight += broker.Weight;
}
while (true)
{
Dictionary<string, int> result = new Dictionary<string, int>();
Broker selectedBroker = null;
for (int i = 0; i < 1000; i++)
{
selectedBroker = GetBroker(brokers, totalWeight);
if (selectedBroker != null)
{
if (result.ContainsKey(selectedBroker.Name))
{
result[selectedBroker.Name] = result[selectedBroker.Name] + 1;
}
else
{
result.Add(selectedBroker.Name, 1);
}
}
}
Console.WriteLine("A\t\t" + result["A"]);
Console.WriteLine("B\t\t" + result["B"]);
Console.WriteLine("C\t\t" + result["C"]);
Console.WriteLine("D\t\t" + result["D"]);
result.Clear();
Console.WriteLine();
Console.ReadLine();
}
}
}
```
I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.
Is there a more accurate algorithm?
Thanks! | Your algorithm is nearly correct. However, the test should be `<` instead of `<=`:
```
if (randomNumber < broker.Weight)
```
This is because 0 is inclusive in the random number while `totalWeight` is exclusive. In other words, a broker with weight 0 would still have a small chance of being selected – not at all what you want. This accounts for broker A having more hits than broker D.
Other than that, your algorithm is fine and in fact the canonical way of solving this problem. |
56,698 | <p>I would like to generate a list of differences between 2 instances of the the same object. Object in question:</p>
<pre><code>public class Step
{
[DataMember]
public StepInstanceInfo InstanceInfo { get; set; }
[DataMember]
public Collection<string> AdHocRules { get; set; }
[DataMember]
public Collection<StepDoc> StepDocs
{...}
[DataMember]
public Collection<StepUsers> StepUsers
{...}
}
</code></pre>
<p>What I would like to do is <strong>find an intelligent way to return an object that lists the differences between the two instances</strong> (for example, let me know that 2 specific StepDocs were added, 1 specific StepUser was removed, and one rule was changed from "Go" to "Stop"). I have been looking into using a MD5 hash, but I can't find any good examples of traversing an object like this and returning a <strong>manifest of the specific differences</strong> (not just indicating that they are different).</p>
<p><em>Additional Background:</em> the reason that I need to do this is the API that I am supporting allows clients to SaveStep(Step step)...this works great for persisting the Step object to the db using entities and repositories. I need to raise specific events (like this user was added, etc) from this SaveStep method, though, in order to alert another system (workflow engine) that a specific element in the step has changed.
Thank you.</p>
| [
{
"answer_id": 56774,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Implementing the IComparable interface in your object may provide you with the functionality you need. This will provide yo... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I would like to generate a list of differences between 2 instances of the the same object. Object in question:
```
public class Step
{
[DataMember]
public StepInstanceInfo InstanceInfo { get; set; }
[DataMember]
public Collection<string> AdHocRules { get; set; }
[DataMember]
public Collection<StepDoc> StepDocs
{...}
[DataMember]
public Collection<StepUsers> StepUsers
{...}
}
```
What I would like to do is **find an intelligent way to return an object that lists the differences between the two instances** (for example, let me know that 2 specific StepDocs were added, 1 specific StepUser was removed, and one rule was changed from "Go" to "Stop"). I have been looking into using a MD5 hash, but I can't find any good examples of traversing an object like this and returning a **manifest of the specific differences** (not just indicating that they are different).
*Additional Background:* the reason that I need to do this is the API that I am supporting allows clients to SaveStep(Step step)...this works great for persisting the Step object to the db using entities and repositories. I need to raise specific events (like this user was added, etc) from this SaveStep method, though, in order to alert another system (workflow engine) that a specific element in the step has changed.
Thank you. | You'll need a separate object, like StepDiff with collections for removed and added items. The easiest way to do something like this is to copy the collections from each of the old and new objects, so that StepDiff has collectionOldStepDocs and collectionNewStepDocs.
Grab the shorter collection and iterate through it and see if each StepDoc exists in the other collection. If so, delete the StepDoc reference from both collections. Then when you're finished iterating, collectionOldStepDocs contains stepDocs that were deleted and collectionNewStepDocs contains the stepDocs that were added.
From there you should be able to build your manifest in whatever way necessary. |
56,709 | <p>I get the following error message in SQL Server 2005:</p>
<pre><code>User '<username>' does not have permission to run DBCC DBREINDEX for object '<table>'.
</code></pre>
<p>Which minimum role do I have to give to user in order to run the command?</p>
| [
{
"answer_id": 56720,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 4,
"selected": true,
"text": "<p>You will need to be a member of the <strong>db_ddladmin</strong> or the <strong>db_owner</strong> role AFAIK</p>\n"
},
... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | I get the following error message in SQL Server 2005:
```
User '<username>' does not have permission to run DBCC DBREINDEX for object '<table>'.
```
Which minimum role do I have to give to user in order to run the command? | You will need to be a member of the **db\_ddladmin** or the **db\_owner** role AFAIK |
56,729 | <p>Can somebody give me a complete and working example of calling the <code>AllocateAndInitializeSid</code> function from C# code?</p>
<p>I found <a href="http://msdn.microsoft.com/en-us/library/aa375213(VS.85).aspx" rel="nofollow noreferrer">this</a>: </p>
<pre><code>BOOL WINAPI AllocateAndInitializeSid(
__in PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority,
__in BYTE nSubAuthorityCount,
__in DWORD dwSubAuthority0,
__in DWORD dwSubAuthority1,
__in DWORD dwSubAuthority2,
__in DWORD dwSubAuthority3,
__in DWORD dwSubAuthority4,
__in DWORD dwSubAuthority5,
__in DWORD dwSubAuthority6,
__in DWORD dwSubAuthority7,
__out PSID *pSid
);
</code></pre>
<p>and I don't know how to construct the signature of this method - what should I do with <code>PSID_IDENTIFIER_AUTHORITY</code> and <code>PSID</code> types? How should I pass them - using <code>ref</code> or <code>out</code>?</p>
| [
{
"answer_id": 56745,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "<p>For Platform Invoke www.pinvoke.net is your new best friend!</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/advap... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95/"
] | Can somebody give me a complete and working example of calling the `AllocateAndInitializeSid` function from C# code?
I found [this](http://msdn.microsoft.com/en-us/library/aa375213(VS.85).aspx):
```
BOOL WINAPI AllocateAndInitializeSid(
__in PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority,
__in BYTE nSubAuthorityCount,
__in DWORD dwSubAuthority0,
__in DWORD dwSubAuthority1,
__in DWORD dwSubAuthority2,
__in DWORD dwSubAuthority3,
__in DWORD dwSubAuthority4,
__in DWORD dwSubAuthority5,
__in DWORD dwSubAuthority6,
__in DWORD dwSubAuthority7,
__out PSID *pSid
);
```
and I don't know how to construct the signature of this method - what should I do with `PSID_IDENTIFIER_AUTHORITY` and `PSID` types? How should I pass them - using `ref` or `out`? | Using [P/Invoke Interop Assistant](http://www.codeplex.com/clrinterop):
```
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct SidIdentifierAuthority {
/// BYTE[6]
[System.Runtime.InteropServices.MarshalAsAttribute(
System.Runtime.InteropServices.UnmanagedType.ByValArray,
SizeConst = 6,
ArraySubType =
System.Runtime.InteropServices.UnmanagedType.I1)]
public byte[] Value;
}
public partial class NativeMethods {
/// Return Type: BOOL->int
///pIdentifierAuthority: PSID_IDENTIFIER_AUTHORITY->_SID_IDENTIFIER_AUTHORITY*
///nSubAuthorityCount: BYTE->unsigned char
///nSubAuthority0: DWORD->unsigned int
///nSubAuthority1: DWORD->unsigned int
///nSubAuthority2: DWORD->unsigned int
///nSubAuthority3: DWORD->unsigned int
///nSubAuthority4: DWORD->unsigned int
///nSubAuthority5: DWORD->unsigned int
///nSubAuthority6: DWORD->unsigned int
///nSubAuthority7: DWORD->unsigned int
///pSid: PSID*
[System.Runtime.InteropServices.DllImportAttribute("advapi32.dll", EntryPoint = "AllocateAndInitializeSid")]
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool AllocateAndInitializeSid(
[System.Runtime.InteropServices.InAttribute()]
ref SidIdentifierAuthority pIdentifierAuthority,
byte nSubAuthorityCount,
uint nSubAuthority0,
uint nSubAuthority1,
uint nSubAuthority2,
uint nSubAuthority3,
uint nSubAuthority4,
uint nSubAuthority5,
uint nSubAuthority6,
uint nSubAuthority7,
out System.IntPtr pSid);
}
``` |
56,737 | <p>Is the standard Java 1.6 <a href="http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilder.html" rel="noreferrer">javax.xml.parsers.DocumentBuilder</a> class thread safe? Is it safe to call the parse() method from several threads in parallel?</p>
<p>The JavaDoc doesn't mention the issue, but the <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html" rel="noreferrer">JavaDoc for the same class</a> in Java 1.4 specifically says that it <em>isn't</em> meant to be concurrent; so can I assume that in 1.6 it is?</p>
<p>The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.</p>
| [
{
"answer_id": 56815,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": true,
"text": "<p>Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementa... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1605/"
] | Is the standard Java 1.6 [javax.xml.parsers.DocumentBuilder](http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilder.html) class thread safe? Is it safe to call the parse() method from several threads in parallel?
The JavaDoc doesn't mention the issue, but the [JavaDoc for the same class](http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html) in Java 1.4 specifically says that it *isn't* meant to be concurrent; so can I assume that in 1.6 it is?
The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time. | Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal:
```
private static final ThreadLocal<DocumentBuilder> builderLocal =
new ThreadLocal<DocumentBuilder>() {
@Override protected DocumentBuilder initialValue() {
try {
return
DocumentBuilderFactory
.newInstance(
"xx.MyDocumentBuilderFactory",
getClass().getClassLoader()
).newDocumentBuilder();
} catch (ParserConfigurationException exc) {
throw new IllegalArgumentException(exc);
}
}
};
```
(Disclaimer: Not so much as attempted to compile the code.) |
56,767 | <p>Is there a difference (performance, overhead) between these two ways of merging data sets?</p>
<pre><code>MyTypedDataSet aDataSet = new MyTypedDataSet();
aDataSet .Merge(anotherDataSet);
aDataSet .Merge(yetAnotherDataSet);
</code></pre>
<p>and</p>
<pre><code>MyTypedDataSet aDataSet = anotherDataSet;
aDataSet .Merge(yetAnotherDataSet);
</code></pre>
<p>Which do you recommend?</p>
| [
{
"answer_id": 56772,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>Those two lines do different things.</p>\n\n<p>The first one creates a new set, and then merges a second set into it.</p>\n\n<... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
] | Is there a difference (performance, overhead) between these two ways of merging data sets?
```
MyTypedDataSet aDataSet = new MyTypedDataSet();
aDataSet .Merge(anotherDataSet);
aDataSet .Merge(yetAnotherDataSet);
```
and
```
MyTypedDataSet aDataSet = anotherDataSet;
aDataSet .Merge(yetAnotherDataSet);
```
Which do you recommend? | While Keith is right, I suppose the example was simply badly chosen. Generally, it is better to initialize to the “right” object from the beginning and *not* construct an intermediate, empty object as in your case. Two reasons:
1. Performance. This should be obvious: Object creation costs time so creating less objects is better.
2. *Much* more important however, it better states your **intent**. You do generally *not* intend to create stateless/empty objects. Rather, you intend to create objects with some state or content. Do it. No need to create a useless (because empty) temporary. |
56,801 | <p>I was reviewing some code that a consultant checked in and notice they were using SQLCLR. I don't have any experience with it so thought I would research what it was about. I noticed that they used</p>
<pre><code>Dim cn As New SqlConnection("server=LOCALHOST;integrated security=yes;database=" & sDb)
</code></pre>
<p>instead of</p>
<pre><code>DIM conn As New SqlConnection("context connection=true")
</code></pre>
<p>I'm wondering what the difference since it's localhost on the first?</p>
| [
{
"answer_id": 56864,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 4,
"selected": true,
"text": "<p>The context connection uses the user's already established connection to the server. So you inherit things like their data... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2357/"
] | I was reviewing some code that a consultant checked in and notice they were using SQLCLR. I don't have any experience with it so thought I would research what it was about. I noticed that they used
```
Dim cn As New SqlConnection("server=LOCALHOST;integrated security=yes;database=" & sDb)
```
instead of
```
DIM conn As New SqlConnection("context connection=true")
```
I'm wondering what the difference since it's localhost on the first? | The context connection uses the user's already established connection to the server. So you inherit things like their database context, connection options, etc.
Using localhost will connect to the server using a normal shared memory connection. This can be useful if you don't want to use the user's connection (i.e. if you want to connect to a different database, or with different options, etc).
In most cases you should use the context connection, since it doesn't create a separate connection to the server.
Also, be warned that using a separate connection means you are not part of the user's transaction and are subject to normal locking semantics. |
56,810 | <p>I have used fork() in C to start another process. How do I start a new thread?</p>
| [
{
"answer_id": 56818,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 3,
"selected": false,
"text": "<p>pthreads is a good start, look <a href=\"https://computing.llnl.gov/tutorials/pthreads/\" rel=\"noreferrer\">here</a></p>\n"
... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] | I have used fork() in C to start another process. How do I start a new thread? | Since you mentioned fork() I assume you're on a Unix-like system, in which case [POSIX threads](http://en.wikipedia.org/wiki/POSIX_Threads) (usually referred to as pthreads) are what you want to use.
Specifically, pthread\_create() is the function you need to create a new thread. Its arguments are:
```
int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *
(*start_routine)(void *), void * arg);
```
The first argument is the returned pointer to the thread id. The second argument is the thread arguments, which can be NULL unless you want to start the thread with a specific priority. The third argument is the function executed by the thread. The fourth argument is the single argument passed to the thread function when it is executed. |
56,812 | <p>I'm trying to consume a SharePoint webservice from ColdFusion via cfinvoke ('cause I don't want to deal with (read: parse) the SOAP response itself).</p>
<p>The SOAP response includes a byte-order-mark character (BOM), which produces the following exception in CF:</p>
<pre><code>"Cannot perform web service invocation GetList.
The fault returned when invoking the web service operation is:
'AxisFault
faultCode: {http://www.w3.org/2003/05/soap-envelope}Server.userException
faultSubcode:
faultString: org.xml.sax.SAXParseException: Content is not allowed in prolog."
</code></pre>
<p>The standard for UTF-8 encoding optionally includes the BOM character (<a href="http://unicode.org/faq/utf_bom.html#29" rel="nofollow noreferrer">http://unicode.org/faq/utf_bom.html#29</a>). Microsoft almost universally includes the BOM character with UTF-8 encoded streams . From what I can tell there’s no way to change that in IIS. The XML parser that JRun (ColdFusion) uses by default doesn’t handle the BOM character for UTF-8 encoded XML streams. So, it appears that the way to fix this is to change the XML parser used by JRun (<a href="http://www.bpurcell.org/blog/index.cfm?mode=entry&entry=942" rel="nofollow noreferrer">http://www.bpurcell.org/blog/index.cfm?mode=entry&entry=942</a>).</p>
<p>Adobe says that it doesn't handle the BOM character (see comments from anoynomous and halL on May 2nd and 5th).<br />
<a href="http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments" rel="nofollow noreferrer">http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments</a></p>
| [
{
"answer_id": 56896,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like ColdFusion is using Apache Axis under the covers.</p>\n\n<p>This doesn't apply exactly to your solution, but... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5849/"
] | I'm trying to consume a SharePoint webservice from ColdFusion via cfinvoke ('cause I don't want to deal with (read: parse) the SOAP response itself).
The SOAP response includes a byte-order-mark character (BOM), which produces the following exception in CF:
```
"Cannot perform web service invocation GetList.
The fault returned when invoking the web service operation is:
'AxisFault
faultCode: {http://www.w3.org/2003/05/soap-envelope}Server.userException
faultSubcode:
faultString: org.xml.sax.SAXParseException: Content is not allowed in prolog."
```
The standard for UTF-8 encoding optionally includes the BOM character (<http://unicode.org/faq/utf_bom.html#29>). Microsoft almost universally includes the BOM character with UTF-8 encoded streams . From what I can tell there’s no way to change that in IIS. The XML parser that JRun (ColdFusion) uses by default doesn’t handle the BOM character for UTF-8 encoded XML streams. So, it appears that the way to fix this is to change the XML parser used by JRun (<http://www.bpurcell.org/blog/index.cfm?mode=entry&entry=942>).
Adobe says that it doesn't handle the BOM character (see comments from anoynomous and halL on May 2nd and 5th).
<http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments> | I'm going to say that the answer to your question (is it possible?) is no. I don't know that definitively, but the poster who commented just above halL ([in the comments on this page](http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_g-h_09.html#comments)) gave a work-around for the problem -- so I assume it is possible to deal with when parsing manually.
You say that you're using CFInvoke because you don't want to deal with the soap response yourself. It looks like you don't have any choice. |
56,820 | <p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html" rel="noreferrer">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p>
<pre><code>n = 5.59
round(n, 1) # 5.6
</code></pre>
<p>But, in actuality, good old floating point weirdness creeps in and you get:</p>
<pre><code>5.5999999999999996
</code></pre>
<p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html" rel="noreferrer">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html" rel="noreferrer">See here also</a>.</p>
<p>Short of creating my own round library, is there any way around this?</p>
| [
{
"answer_id": 56832,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": -1,
"selected": false,
"text": "<p>What about:</p>\n\n<pre><code>round(n,1)+epsilon\n</code></pre>\n"
},
{
"answer_id": 56833,
"author": "Jimmy",
... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] | The documentation for the [round()](http://docs.python.org/lib/built-in-funcs.html) function states that you pass it a number, and the positions past the decimal to round. Thus it *should* do this:
```
n = 5.59
round(n, 1) # 5.6
```
But, in actuality, good old floating point weirdness creeps in and you get:
```
5.5999999999999996
```
For the purposes of UI, I need to display `5.6`. I poked around the Internet and found some [documentation](http://mail.python.org/pipermail/python-list/2005-September/340383.html) that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. [See here also](http://www.python.org/doc/2.5.1/tut/node16.html).
Short of creating my own round library, is there any way around this? | I can't help the way it's stored, but at least formatting works correctly:
```
'%.1f' % round(n, 1) # Gives you '5.6'
``` |
56,837 | <p>My problem is that my XML document contains snippets of XHTML within it and while passing it through an XSLT I would like it to render those snippets without mangling them.</p>
<p>I've tried wrapping the snippet in a CDATA but it doesn't work since less than and greater than are translated to < and > as opposed to being echoed directly.</p>
<p>What's the XSL required for doing this?</p>
| [
{
"answer_id": 56858,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 0,
"selected": false,
"text": "<p>xsl:copy-of</p>\n"
},
{
"answer_id": 58466,
"author": "DaveP",
"author_id": 3577,
"author_profile": ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] | My problem is that my XML document contains snippets of XHTML within it and while passing it through an XSLT I would like it to render those snippets without mangling them.
I've tried wrapping the snippet in a CDATA but it doesn't work since less than and greater than are translated to < and > as opposed to being echoed directly.
What's the XSL required for doing this? | ```
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
```
This is referred to as the "identity transformation" in the [XSLT specification](http://www.w3.org/TR/xslt#copying). |
56,843 | <p>I'm looking for a builder for <a href="http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html" rel="noreferrer">HQL</a> in Java. I want to get rid of things like:</p>
<pre><code>StringBuilder builder = new StringBuilder()
.append("select stock from ")
.append( Stock.class.getName() )
.append( " as stock where stock.id = ")
.append( id );
</code></pre>
<p>I'd rather have something like:</p>
<pre><code>HqlBuilder builder = new HqlBuilder()
.select( "stock" )
.from( Stock.class.getName() ).as( "stock" )
.where( "stock.id" ).equals( id );
</code></pre>
<p>I googled a bit, and I couldn't find one.</p>
<p>I wrote a quick & dumb <code>HqlBuilder</code> that suits my needs for now, but I'd love to find one that has more users and tests than me alone.</p>
<p>Note: I'd like to be able to do things like this and more, which I failed to do with the Criteria API:</p>
<pre><code>select stock
from com.something.Stock as stock, com.something.Bonus as bonus
where stock.someValue = bonus.id
</code></pre>
<p>ie. select all stocks whose property <code>someValue</code> points to <em>any</em> bonus from the Bonus table.</p>
<p>Thanks!</p>
| [
{
"answer_id": 56866,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": false,
"text": "<p>Doesn't the <a href=\"http://www.hibernate.org/hib_docs/v3/reference/en/html/querycriteria.html\" rel=\"noreferrer\">Crite... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
] | I'm looking for a builder for [HQL](http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html) in Java. I want to get rid of things like:
```
StringBuilder builder = new StringBuilder()
.append("select stock from ")
.append( Stock.class.getName() )
.append( " as stock where stock.id = ")
.append( id );
```
I'd rather have something like:
```
HqlBuilder builder = new HqlBuilder()
.select( "stock" )
.from( Stock.class.getName() ).as( "stock" )
.where( "stock.id" ).equals( id );
```
I googled a bit, and I couldn't find one.
I wrote a quick & dumb `HqlBuilder` that suits my needs for now, but I'd love to find one that has more users and tests than me alone.
Note: I'd like to be able to do things like this and more, which I failed to do with the Criteria API:
```
select stock
from com.something.Stock as stock, com.something.Bonus as bonus
where stock.someValue = bonus.id
```
ie. select all stocks whose property `someValue` points to *any* bonus from the Bonus table.
Thanks! | @[Sébastien Rocca-Serra](https://stackoverflow.com/questions/56843/looking-for-an-hql-builder-hibernate-query-language#57001)
Now we're getting somewhere concrete. The sort of join you're trying to do isn't really possible through the Criteria API, but a sub-query should accomplish the same thing. First you create a `DetachedCriteria` for the bonus table, then use the `IN` operator for `someValue`.
```
DetachedCriteria bonuses = DetachedCriteria.forClass(Bonus.class);
List stocks = session.createCriteria(Stock.class)
.add(Property.forName("someValue").in(bonuses)).list();
```
This is equivalent to
```
select stock
from com.something.Stock as stock
where stock.someValue in (select bonus.id from com.something.Bonus as bonus)
```
The only downside would be if you have references to different tables in `someValue` and your ID's are not unique across all tables. But your query would suffer from the same flaw. |
56,865 | <p>A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results?</p>
<p>I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just looking for some guidance as to what the code for calling a given web service would look like. </p>
<p>(Any sample web service can be chosen as an example.)</p>
| [
{
"answer_id": 57090,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import org.restlet.Client;\nimport org.restlet.data.Protocol;\nimport org.restlet.data.Reference;\nimport org.res... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results?
I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just looking for some guidance as to what the code for calling a given web service would look like.
(Any sample web service can be chosen as an example.) | There's roughly a gajillion HTTP client libraries (Restlet is quite a bit more than that, but I already had that code snippet for something else), but they should all provide support for sending GET requests. Here's a rather less featureful snippet that uses [HttpClient](http://hc.apache.org/httpclient-3.x/tutorial.html) from Apache Commons:
```
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=restbook&query=HttpClient");
client.executeMethod(method);
``` |
56,867 | <p>When should I use an interface and when should I use a base class? </p>
<p>Should it always be an interface if I don't want to actually define a base implementation of the methods?</p>
<p>If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.</p>
| [
{
"answer_id": 56871,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 7,
"selected": false,
"text": "<p>Modern style is to define IPet <em>and</em> PetBase.</p>\n\n<p>The advantage of the interface is that other code can u... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2871/"
] | When should I use an interface and when should I use a base class?
Should it always be an interface if I don't want to actually define a base implementation of the methods?
If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet. | Let's take your example of a Dog and a Cat class, and let's illustrate using C#:
Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:
```cs
public abstract class Mammal
```
This base class will probably have default methods such as:
* Feed
* Mate
All of which are behavior that have more or less the same implementation between either species. To define this you will have:
```cs
public class Dog : Mammal
public class Cat : Mammal
```
Now let's suppose there are other mammals, which we will usually see in a zoo:
```cs
public class Giraffe : Mammal
public class Rhinoceros : Mammal
public class Hippopotamus : Mammal
```
This will still be valid because at the core of the functionality `Feed()` and `Mate()` will still be the same.
However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:
```cs
public interface IPettable
{
IList<Trick> Tricks{get; set;}
void Bathe();
void Train(Trick t);
}
```
The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea.
Your Dog and Cat definitions should now look like:
```cs
public class Dog : Mammal, IPettable
public class Cat : Mammal, IPettable
```
Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.
Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly *as required* basis. |
56,895 | <p>How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set.</p>
<hr>
<p>As I had a specific query in mind when I was doing this, I ended up doing as @dougman suggested, over about 10% of rows the tables concerned and comparing the results, ensuring there was no out of place results.</p>
| [
{
"answer_id": 56931,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 3,
"selected": false,
"text": "<p>This sounds to me like a an NP complete problem. I'm not sure there is a sure fire way to prove this kind of thing</p>\n"
},... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
] | How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set.
---
As I had a specific query in mind when I was doing this, I ended up doing as @dougman suggested, over about 10% of rows the tables concerned and comparing the results, ensuring there was no out of place results. | The best you can do is compare the 2 query outputs based on a given set of inputs looking for any differences. To say that they will always return the same results for all inputs really depends on the data.
For Oracle one of the better if not best approaches (very efficient) is here (`Ctrl`+`F` Comparing the Contents of Two Tables):
[<http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html>](http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html)
Which boils down to:
```
select c1,c2,c3,
count(src1) CNT1,
count(src2) CNT2
from (select a.*,
1 src1,
to_number(null) src2
from a
union all
select b.*,
to_number(null) src1,
2 src2
from b
)
group by c1,c2,c3
having count(src1) <> count(src2);
``` |
56,905 | <p>Ran into an “Out of Stack Space” error trying to serialize an ASP.Net AJAX Array object. </p>
<p>Here is the scenario with simplified code:</p>
<ol>
<li><p><code>Default.aspx</code></p></li>
<li><p><code>MainScript.js</code></p>
<pre><code>function getObject(){
return new Array();
}
function function1(obj){
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
function function2(){
var obj=getObject();
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
</code></pre></li>
<li><p><code>Content.aspx</code></p></li>
<li><p><code>ContentScript.js</code></p>
<pre><code>function serializeObject(){
var obj=window.top.getObject();
window.top.function1(obj); // <– This works fine
obj=new Array();
window.top.function1(obj); // <– this causes an Out of Stack Space error
}
</code></pre></li>
</ol>
<p>The code for the sample pages and JavaScript is <a href="http://braincells2pixels.wordpress.com/2008/02/14/aspnet-ajax-javascript-serialization-error/" rel="nofollow noreferrer">here</a>.</p>
<p>Posting the code for the aspx pages here posed a problem. So please check the above link to see the code for the aspx pages.</p>
<p>A web page (default.aspx) with an IFrame on that hosts a content page (content.aspx). </p>
<p>Clicking the “Serialize Object” button calls the JavaScript function serializeObject(). The serialization works fine for Array objects created in the top window (outside the frame). However if the array object is created in the IFrame, serialization bombs with an out of stack space error. I stepped through ASP.Net AJAX JS files and what I discovered is, the process goes into an endless loop trying to figure out the type of the array object. Endless call to Number.IsInstanceOf and pretty soon you get an out of stack error.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 57433,
"author": "d91-jal",
"author_id": 5085,
"author_profile": "https://Stackoverflow.com/users/5085",
"pm_score": 0,
"selected": false,
"text": "<p>I have no way of testing your code right now, but it looks like a bug in JavaScriptSerializer.serialize to me. My guess is... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3635/"
] | Ran into an “Out of Stack Space” error trying to serialize an ASP.Net AJAX Array object.
Here is the scenario with simplified code:
1. `Default.aspx`
2. `MainScript.js`
```
function getObject(){
return new Array();
}
function function1(obj){
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
function function2(){
var obj=getObject();
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
```
3. `Content.aspx`
4. `ContentScript.js`
```
function serializeObject(){
var obj=window.top.getObject();
window.top.function1(obj); // <– This works fine
obj=new Array();
window.top.function1(obj); // <– this causes an Out of Stack Space error
}
```
The code for the sample pages and JavaScript is [here](http://braincells2pixels.wordpress.com/2008/02/14/aspnet-ajax-javascript-serialization-error/).
Posting the code for the aspx pages here posed a problem. So please check the above link to see the code for the aspx pages.
A web page (default.aspx) with an IFrame on that hosts a content page (content.aspx).
Clicking the “Serialize Object” button calls the JavaScript function serializeObject(). The serialization works fine for Array objects created in the top window (outside the frame). However if the array object is created in the IFrame, serialization bombs with an out of stack space error. I stepped through ASP.Net AJAX JS files and what I discovered is, the process goes into an endless loop trying to figure out the type of the array object. Endless call to Number.IsInstanceOf and pretty soon you get an out of stack error.
Any ideas? | This problem happens because Sys.Serialization.JavaScriptSerializer can't serialize objects from others frames, but only those objects which where instantiated in the current window (which calls serialize() method). The only workaround which is known for me it's making clone of the object from other frame before calling serialize() method.
Example of the clone() methode you can find here (comments in Russian):
[link text](http://snowcore.net/clone-javascript-object) |
56,908 | <p>Is there any way to create a virtual drive in "(My) Computer" and manipulate it, somewhat like JungleDisk does it?</p>
<p>It probably does something like:</p>
<pre><code>override OnRead(object sender, Event e) {
ShowFilesFromAmazon();
}
</code></pre>
<p>Are there any API:s for this? Maybe to write to an XML-file or a database, instead of a real drive.</p>
<hr>
<p>The <a href="http://dokan-dev.net/en/" rel="noreferrer">Dokan Library</a> seems to be the answer that mostly corresponds with my question, even though <a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx" rel="noreferrer">System.IO.IsolatedStorage</a> seems to be the most standardized and most Microsoft-environment adapted.</p>
| [
{
"answer_id": 56919,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, use the classes in <a href=\"http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx\" rel=\"nofo... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] | Is there any way to create a virtual drive in "(My) Computer" and manipulate it, somewhat like JungleDisk does it?
It probably does something like:
```
override OnRead(object sender, Event e) {
ShowFilesFromAmazon();
}
```
Are there any API:s for this? Maybe to write to an XML-file or a database, instead of a real drive.
---
The [Dokan Library](http://dokan-dev.net/en/) seems to be the answer that mostly corresponds with my question, even though [System.IO.IsolatedStorage](http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx) seems to be the most standardized and most Microsoft-environment adapted. | You can use the [Dokan library](https://dokan-dev.github.io/) to create a virtual drive. There is a .Net wrapper for interfacing with C#. |
56,913 | <p>I have a whole bunch of files with filenames using our lovely Swedish letters <strong>å å</strong> and <strong>ö</strong>.
For various reasons I now need to convert these to an [a-zA-Z] range. Just removing anything outside this range is fairly easy. The thing that's causing me trouble is that I'd like to replace <strong>å</strong> with <strong>a</strong>, <strong>ö</strong> with <strong>o</strong> and so on. </p>
<p>This is charset troubles at their worst.</p>
<p>I have a set of test files:</p>
<pre><code>files\Copy of New Text Documen åäö t.txt
files\fofo.txt
files\New Text Document.txt
files\worstcase åäöÅÄÖéÉ.txt
</code></pre>
<p>I'm basing my script on this line, piping it's results into various commands</p>
<pre><code>for %%X in (files\*.txt) do (echo %%X)
</code></pre>
<p>The wierd thing is that if I print the results of this (the plain for-loop that is) into a file I get this output:</p>
<pre><code>files\Copy of New Text Documen †„” t.txt
files\fofo.txt
files\New Text Document.txt
files\worstcase †„”Ž™‚.txt
</code></pre>
<p>So something wierd is happening to my filenames before they even reach the other tools (I've been trying to do this using a sed port for Windows from something called GnuWin32 but no luck so far) and doing the replace on these characters doesn't help either.</p>
<p>How would you solve this problem? I'm open to any type of tools, commandline or otherwise…</p>
<p><strong>EDIT:</strong> This is a one time problem, so I'm looking for a quick 'n ugly fix</p>
| [
{
"answer_id": 56924,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 0,
"selected": false,
"text": "<p>I would write this in C++, C#, or Java -- environments where I know for certain that you can get the Unicode character... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/914/"
] | I have a whole bunch of files with filenames using our lovely Swedish letters **å å** and **ö**.
For various reasons I now need to convert these to an [a-zA-Z] range. Just removing anything outside this range is fairly easy. The thing that's causing me trouble is that I'd like to replace **å** with **a**, **ö** with **o** and so on.
This is charset troubles at their worst.
I have a set of test files:
```
files\Copy of New Text Documen åäö t.txt
files\fofo.txt
files\New Text Document.txt
files\worstcase åäöÅÄÖéÉ.txt
```
I'm basing my script on this line, piping it's results into various commands
```
for %%X in (files\*.txt) do (echo %%X)
```
The wierd thing is that if I print the results of this (the plain for-loop that is) into a file I get this output:
```
files\Copy of New Text Documen †„” t.txt
files\fofo.txt
files\New Text Document.txt
files\worstcase †„”Ž™‚.txt
```
So something wierd is happening to my filenames before they even reach the other tools (I've been trying to do this using a sed port for Windows from something called GnuWin32 but no luck so far) and doing the replace on these characters doesn't help either.
How would you solve this problem? I'm open to any type of tools, commandline or otherwise…
**EDIT:** This is a one time problem, so I'm looking for a quick 'n ugly fix | You can use this code (Python)
Rename international files
==========================
```
# -*- coding: cp1252 -*-
import os, shutil
base_dir = "g:\\awk\\" # Base Directory (includes subdirectories)
char_table_1 = "áéíóúñ"
char_table_2 = "aeioun"
adirs = os.walk (base_dir)
for adir in adirs:
dir = adir[0] + "\\" # Directory
# print "\nDir : " + dir
for file in adir[2]: # List of files
if os.access(dir + file, os.R_OK):
file2 = file
for i in range (0, len(char_table_1)):
file2 = file2.replace (char_table_1[i], char_table_2[i])
if file2 <> file:
# Different, rename
print dir + file, " => ", file2
shutil.move (dir + file, dir + file2)
###
```
You have to change your encoding and your char tables (I tested this script with Spanish files and works fine). You can comment the "move" line to check if it's working ok, and remove the comment later to do the renaming. |
56,943 | <p>I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.</p>
<pre><code>if (YesNoDialog.ask("Are you sure?") == true) {
// yes was chosen
} else {
// no was chosen
}
</code></pre>
| [
{
"answer_id": 56970,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": -1,
"selected": false,
"text": "<p>I dont have programed in Java ME, but i found in it's reference for optional packages the\n<a href=\"http://java.sun.com/... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5896/"
] | I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.
```
if (YesNoDialog.ask("Are you sure?") == true) {
// yes was chosen
} else {
// no was chosen
}
``` | You need an [Alert](http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Alert.html):
>
> An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next Displayable. An alert can contain a text string and an image. The intended use of Alert is to inform the user about errors and other exceptional conditions.
>
>
>
With 2 [commands](http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Command.html) ("Yes"/"No" in your case):
>
> If there are two or more Commands present on the Alert, it is automatically turned into a modal Alert, and the timeout value is always FOREVER. The Alert remains on the display until a Command is invoked.
>
>
>
These are built-in classes supported in MIDP 1.0 and higher. Also your code snippet will never work. Such an API would need to block the calling thread awaiting for the user to select and answer. This goes exactly in the opposite direction of the UI interaction model of MIDP, which is based in callbacks and delegation. You need to provide your own class, implementing [CommandListener](http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/CommandListener.html), and prepare your code for asynchronous execution.
Here is an (untested!) example class based on Alert:
```
public class MyPrompter implements CommandListener {
private Alert yesNoAlert;
private Command softKey1;
private Command softKey2;
private boolean status;
public MyPrompter() {
yesNoAlert = new Alert("Attention");
yesNoAlert.setString("Are you sure?");
softKey1 = new Command("No", Command.BACK, 1);
softKey2 = new Command("Yes", Command.OK, 1);
yesNoAlert.addCommand(softKey1);
yesNoAlert.addCommand(softKey2);
yesNoAlert.setCommandListener(this);
status = false;
}
public Displayable getDisplayable() {
return yesNoAlert;
}
public boolean getStatus() {
return status;
}
public void commandAction(Command c, Displayable d) {
status = c.getCommandType() == Command.OK;
// maybe do other stuff here. remember this is asynchronous
}
};
```
To use it (again, untested and on top of my head):
```
MyPrompter prompt = new MyPrompter();
Display.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable());
```
This code will make the prompt the current displayed form in your app, but it *won't block your thread* like in the example you posted. You need to continue running and wait for a commandAction invocation. |
56,946 | <p>Say I have:</p>
<pre><code><ul>
<li id="x">
<a href="x">x</a>
</li>
<li id="y">
<a href="y">y</a>
<ul>
<li id="z">
<a href="z">z</a>
</li>
</ul>
</li>
</ul>
</code></pre>
<p>I want to add a class value to all the list items that are the parents of z. So, I want to modify y but not x.</p>
<p>Obviously, I can parse this into some kind of associative array and then recurse backwards. Any ideas how I can do it with just text processing (string replacing, regular expression, etc)?</p>
<p>Thanks!</p>
| [
{
"answer_id": 56958,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest you parse it into a DOM and recurse backwards like you were thinking. Regular expressions don't work very well fo... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Say I have:
```
<ul>
<li id="x">
<a href="x">x</a>
</li>
<li id="y">
<a href="y">y</a>
<ul>
<li id="z">
<a href="z">z</a>
</li>
</ul>
</li>
</ul>
```
I want to add a class value to all the list items that are the parents of z. So, I want to modify y but not x.
Obviously, I can parse this into some kind of associative array and then recurse backwards. Any ideas how I can do it with just text processing (string replacing, regular expression, etc)?
Thanks! | I would use XSLT. You can specify to search for nodes that are ancestors of z . |
56,950 | <p>We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired...</p>
<p>I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example:</p>
<pre><code>Value
----------
143.55
3532.13
1.75
</code></pre>
<p>How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever".</p>
<p>I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control.</p>
<p>Thank you.</p>
| [
{
"answer_id": 56972,
"author": "d91-jal",
"author_id": 5085,
"author_profile": "https://Stackoverflow.com/users/5085",
"pm_score": 5,
"selected": true,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms189527.aspx\" rel=\"noreferrer\">STR function</a> has an optional l... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2230/"
] | We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired...
I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example:
```
Value
----------
143.55
3532.13
1.75
```
How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever".
I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control.
Thank you. | The [STR function](http://msdn.microsoft.com/en-us/library/ms189527.aspx) has an optional length argument as well as a number-of-decimals one.
```
SELECT STR(123.45, 6, 1)
------
123.5
(1 row(s) affected)
``` |
56,954 | <p>The code</p>
<pre><code>private SomeClass<Integer> someClass;
someClass = EasyMock.createMock(SomeClass.class);
</code></pre>
<p>gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass<Integer>".</p>
| [
{
"answer_id": 56996,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>The two obvious routes are to suppress the warning or mock a subclass.</p>\n\n<pre><code>private static clas... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792/"
] | The code
```
private SomeClass<Integer> someClass;
someClass = EasyMock.createMock(SomeClass.class);
```
gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass<Integer>". | AFAIK, you can't avoid the unchecked warning when a class name literal is involved, and the `SuppressWarnings` annotation is the only way to handle this.
Note that it is good form to narrow the scope of the `SuppressWarnings` annotation as much as possible. You can apply this annotation to a single local variable assignment:
```
public void testSomething() {
@SuppressWarnings("unchecked")
Foo<Integer> foo = EasyMock.createMock(Foo.class);
// Rest of test method may still expose other warnings
}
```
or use a helper method:
```
@SuppressWarnings("unchecked")
private static <T> Foo<T> createFooMock() {
return (Foo<T>)EasyMock.createMock(Foo.class);
}
public void testSomething() {
Foo<String> foo = createFooMock();
// Rest of test method may still expose other warnings
}
``` |
56,968 | <p>I'm trying to attach an instance of UIScrollbar component to a dynamic text field inside of an instance of a class that is being made after some XML is loaded. The scroll bar component is getting properly attached, as the size of the slider varies depending on the amount of content in the text field, however, it won't scroll.</p>
<p>Here's the code:</p>
<pre><code>function xmlLoaded(evt:Event):void
{
//do some stuff
for(var i:int = 0; i < numProfiles; i++)
{
var thisProfile:profile = new profile();
thisProfile.alpha = 0;
thisProfile.x = 0;
thisProfile.y = 0;
thisProfile.name = "profile" + i;
profilecontainer.addChild(thisProfile);
thisProfile.profiletextholder.profilename.htmlText = profiles[i].attribute("name");
thisProfile.profiletextholder.profiletext.htmlText = profiles[i].profiletext;
//add scroll bar
var vScrollBar:UIScrollBar = new UIScrollBar();
vScrollBar.direction = ScrollBarDirection.VERTICAL;
vScrollBar.move(thisProfile.profiletextholder.profiletext.x + thisProfile.profiletextholder.profiletext.width, thisProfile.profiletextholder.profiletext.y);
vScrollBar.height = thisProfile.profiletextholder.profiletext.height;
vScrollBar.scrollTarget = thisProfile.profiletextholder.profiletext;
vScrollBar.name = "scrollbar";
vScrollBar.update();
vScrollBar.visible = (thisProfile.profiletextholder.profiletext.maxScrollV > 1);
thisProfile.profiletextholder.addChild(vScrollBar);
//do some more stuff
}
}
</code></pre>
<p>I've also tried it with a UIScrollBar component within the movieclip/class itself, and it still doesn't work. Any ideas?</p>
| [
{
"answer_id": 57197,
"author": "Jeff Winkworth",
"author_id": 1306,
"author_profile": "https://Stackoverflow.com/users/1306",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried putting the UI scrollbar onto the stage, binding it to the textfield at design time, and then callin... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm trying to attach an instance of UIScrollbar component to a dynamic text field inside of an instance of a class that is being made after some XML is loaded. The scroll bar component is getting properly attached, as the size of the slider varies depending on the amount of content in the text field, however, it won't scroll.
Here's the code:
```
function xmlLoaded(evt:Event):void
{
//do some stuff
for(var i:int = 0; i < numProfiles; i++)
{
var thisProfile:profile = new profile();
thisProfile.alpha = 0;
thisProfile.x = 0;
thisProfile.y = 0;
thisProfile.name = "profile" + i;
profilecontainer.addChild(thisProfile);
thisProfile.profiletextholder.profilename.htmlText = profiles[i].attribute("name");
thisProfile.profiletextholder.profiletext.htmlText = profiles[i].profiletext;
//add scroll bar
var vScrollBar:UIScrollBar = new UIScrollBar();
vScrollBar.direction = ScrollBarDirection.VERTICAL;
vScrollBar.move(thisProfile.profiletextholder.profiletext.x + thisProfile.profiletextholder.profiletext.width, thisProfile.profiletextholder.profiletext.y);
vScrollBar.height = thisProfile.profiletextholder.profiletext.height;
vScrollBar.scrollTarget = thisProfile.profiletextholder.profiletext;
vScrollBar.name = "scrollbar";
vScrollBar.update();
vScrollBar.visible = (thisProfile.profiletextholder.profiletext.maxScrollV > 1);
thisProfile.profiletextholder.addChild(vScrollBar);
//do some more stuff
}
}
```
I've also tried it with a UIScrollBar component within the movieclip/class itself, and it still doesn't work. Any ideas? | You might try adding the scrollbar once your textfield is initialized from a separate function similar to this:
```
private function assignScrollBar(tf:TextField, sb:UIScrollBar):void {
trace("assigning scrollbar");
sb.move(tf.x + tf.width, tf.y);
sb.setSize(15, tf.height);
sb.direction = ScrollBarDirection.VERTICAL;
sb.scrollTarget = tf;
addChild(sb);
sb.update();
}
```
That is how I currently doing it. |
56,974 | <p>In the following snippet:</p>
<pre><code>public class a {
public void otherMethod(){}
public void doStuff(String str, InnerClass b){}
public void method(a){
doStuff("asd",
new InnerClass(){
public void innerMethod(){
otherMethod();
}
}
);
}
}
</code></pre>
<p>Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is <code>outer.otherMethod()</code>, or something of the like, but can't seem to find anything.</p>
| [
{
"answer_id": 56987,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 9,
"selected": true,
"text": "<p>In general you use <code>OuterClassName.this</code> to refer to the enclosing instance of the outer class.</p>\n\n<... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] | In the following snippet:
```
public class a {
public void otherMethod(){}
public void doStuff(String str, InnerClass b){}
public void method(a){
doStuff("asd",
new InnerClass(){
public void innerMethod(){
otherMethod();
}
}
);
}
}
```
Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is `outer.otherMethod()`, or something of the like, but can't seem to find anything. | In general you use `OuterClassName.this` to refer to the enclosing instance of the outer class.
In your example that would be `a.this.otherMethod()` |
56,975 | <p>I'm currently looping through a datareader and calling the System.Net.Mail.SmtpClient's Send() method. The problem with this is that it's slow. Each email takes about 5-10 seconds to send (it's possible this is just an issue with my host). I had to override the executionTimeout default in my web.config file (it defaults to 90 seconds) like this:</p>
<pre><code> <httpRuntime executionTimeout="3000" />
</code></pre>
<p>One caveat: I'm on a shared host, so I don't think it is possible for me to send using the PickupDirectoryFromIis option (at least, it gave me errors when I turned it on).</p>
| [
{
"answer_id": 56988,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "<p>You could send the mail asynchronous. That way the timeout should not interrupt your sending.</p>\n\n<p>This article should he... | 2008/09/11 | [
"https://Stackoverflow.com/questions/56975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4965/"
] | I'm currently looping through a datareader and calling the System.Net.Mail.SmtpClient's Send() method. The problem with this is that it's slow. Each email takes about 5-10 seconds to send (it's possible this is just an issue with my host). I had to override the executionTimeout default in my web.config file (it defaults to 90 seconds) like this:
```
<httpRuntime executionTimeout="3000" />
```
One caveat: I'm on a shared host, so I don't think it is possible for me to send using the PickupDirectoryFromIis option (at least, it gave me errors when I turned it on). | You could send the mail asynchronous. That way the timeout should not interrupt your sending.
This article should help you get started with that: [Sending Emails Asynchronously in C#](http://www.eggheadcafe.com/articles/20030720.asp).
There is another approach here: <http://www.vikramlakhotia.com/Sending_Email_asynchronously_in_AspNet_20.aspx>
And off course there are several commercial clients available, but the only one that i have tried and can recommend is <http://www.aspnetemail.com/> |
57,010 | <p>Please, now that I've re-written the question, and before it suffers from further <a href="https://stackoverflow.com/questions/56103/fastest-gun-in-the-west-problem">fast-gun answers</a> or premature closure by <a href="https://stackoverflow.com/users/905/keith">eager editors</a> let me point out that this is not a duplicate of <a href="https://stackoverflow.com/questions/9673/remove-duplicates-from-array">this question</a>. I know how to remove duplicates from an array.</p>
<p>This question is about removing <strong>sequences</strong> from an array, not duplicates in the strict sense.</p>
<p>Consider this sequence of elements in an array;</p>
<pre><code>[0] a
[1] a
[2] b
[3] c
[4] c
[5] a
[6] c
[7] d
[8] c
[9] d
</code></pre>
<p>In this example I want to obtain the following...</p>
<pre><code>[0] a
[1] b
[2] c
[3] a
[4] c
[5] d
</code></pre>
<p>Notice that duplicate elements are retained but that sequences of the same element have been reduced to a single instance of that element.</p>
<p>Further, notice that when two lines repeat they should be reduced to one set (of two lines).</p>
<pre><code>[0] c
[1] d
[2] c
[3] d
</code></pre>
<p>...reduces to...</p>
<pre><code>[0] c
[1] d
</code></pre>
<p>I'm coding in C# but algorithms in any language appreciated.</p>
| [
{
"answer_id": 57013,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "<p>I would dump them all into your favorite Set implementation.</p>\n\n<p>EDIT: Now that I understand the question, ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4200/"
] | Please, now that I've re-written the question, and before it suffers from further [fast-gun answers](https://stackoverflow.com/questions/56103/fastest-gun-in-the-west-problem) or premature closure by [eager editors](https://stackoverflow.com/users/905/keith) let me point out that this is not a duplicate of [this question](https://stackoverflow.com/questions/9673/remove-duplicates-from-array). I know how to remove duplicates from an array.
This question is about removing **sequences** from an array, not duplicates in the strict sense.
Consider this sequence of elements in an array;
```
[0] a
[1] a
[2] b
[3] c
[4] c
[5] a
[6] c
[7] d
[8] c
[9] d
```
In this example I want to obtain the following...
```
[0] a
[1] b
[2] c
[3] a
[4] c
[5] d
```
Notice that duplicate elements are retained but that sequences of the same element have been reduced to a single instance of that element.
Further, notice that when two lines repeat they should be reduced to one set (of two lines).
```
[0] c
[1] d
[2] c
[3] d
```
...reduces to...
```
[0] c
[1] d
```
I'm coding in C# but algorithms in any language appreciated. | Here's C# app i wrote that solves this problem.
**takes**
aabccacdcd
**outputs**
abcacd
Probably looks pretty messy, took me a bit to get my head around the dynamic pattern length bit.
```
class Program
{
private static List<string> values;
private const int MAX_PATTERN_LENGTH = 4;
static void Main(string[] args)
{
values = new List<string>();
values.AddRange(new string[] { "a", "b", "c", "c", "a", "c", "d", "c", "d" });
for (int i = MAX_PATTERN_LENGTH; i > 0; i--)
{
RemoveDuplicatesOfLength(i);
}
foreach (string s in values)
{
Console.WriteLine(s);
}
}
private static void RemoveDuplicatesOfLength(int dupeLength)
{
for (int i = 0; i < values.Count; i++)
{
if (i + dupeLength > values.Count)
break;
if (i + dupeLength + dupeLength > values.Count)
break;
var patternA = values.GetRange(i, dupeLength);
var patternB = values.GetRange(i + dupeLength, dupeLength);
bool isPattern = ComparePatterns(patternA, patternB);
if (isPattern)
{
values.RemoveRange(i, dupeLength);
}
}
}
private static bool ComparePatterns(List<string> pattern, List<string> candidate)
{
for (int i = 0; i < pattern.Count; i++)
{
if (pattern[i] != candidate[i])
return false;
}
return true;
}
}
```
*fixed the initial values to match the questions values* |
57,020 | <p>Was considering the <code>System.Collections.ObjectModel ObservableCollection<T></code> class. This one is strange because </p>
<ul>
<li>it has an Add Method which takes <strong>one</strong> item only. No AddRange or equivalent. </li>
<li>the Notification event arguments has a NewItems property, which is a <strong>IList</strong> (of objects.. not T)</li>
</ul>
<p>My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec?</p>
<p><em>Update: Don't want to roll my own as far as feasible. I'd have to build in add/remove/change etc.. a whole lot of stuff.</em></p>
<hr>
<p>Related Q:<br>
<a href="https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579">https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each</a></p>
| [
{
"answer_id": 57029,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>Inherit from List<T> and override the Add() and AddRange() methods to raise an event?</p>\n"
},
{
"answer... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
] | Was considering the `System.Collections.ObjectModel ObservableCollection<T>` class. This one is strange because
* it has an Add Method which takes **one** item only. No AddRange or equivalent.
* the Notification event arguments has a NewItems property, which is a **IList** (of objects.. not T)
My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec?
*Update: Don't want to roll my own as far as feasible. I'd have to build in add/remove/change etc.. a whole lot of stuff.*
---
Related Q:
[https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each](https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579) | It seems that the `INotifyCollectionChanged` interface allows for updating when multiple items were added, so I'm not sure why `ObservableCollection<T>` doesn't have an `AddRange`. You could make an extension method for `AddRange`, but that would cause an event for every item that is added. If that isn't acceptable you should be able to inherit from `ObservableCollection<T>` as follows:
```
public class MyObservableCollection<T> : ObservableCollection<T>
{
// matching constructors ...
bool isInAddRange = false;
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
// intercept this when it gets called inside the AddRange method.
if (!isInAddRange)
base.OnCollectionChanged(e);
}
public void AddRange(IEnumerable<T> items)
{
isInAddRange = true;
foreach (T item in items)
Add(item);
isInAddRange = false;
var e = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Add,
items.ToList());
base.OnCollectionChanged(e);
}
}
``` |
57,054 | <p>I've got a collection that implements an interface that extends both IList<T> and List. </p>
<pre><code>public Interface IMySpecialCollection : IList<MyObject>, IList { ... }
</code></pre>
<p>That means I have two versions of the indexer. </p>
<p>I wish the generic implementation to be used, so I implement that one normally:</p>
<pre><code>public MyObject this[int index] { .... }
</code></pre>
<p>I only need the IList version for serialization, so I implement it explicitly, to keep it hidden:</p>
<pre><code>object IList.this[int index] { ... }
</code></pre>
<p>However, in my unit tests, the following</p>
<pre><code>MyObject foo = target[0];
</code></pre>
<p>results in a compiler error</p>
<blockquote>
<p>The call is ambiguous between the
following methods or properties</p>
</blockquote>
<p>I'm a bit surprised at this; I believe I've done it before and it works fine. What am I missing here? How can I get IList<T> and IList to coexist within the same interface?</p>
<p><strong>Edit</strong> IList<T> does <em>not</em> implement IList, and I <strong>must</strong> implement IList for serialization. I'm not interested in workarounds, I want to know what I'm missing.</p>
<p><strong>Edit again</strong>: I've had to drop IList from the interface and move it on my class. I don't want to do this, as classes that implement the interface are eventually going to be serialized to Xaml, which requires collections to implement IDictionary or IList...</p>
| [
{
"answer_id": 57072,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>List<T> implies IList, so it's a bad idea to use both in the same class.</p>\n"
},
{
"answer_id": 57084,... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've got a collection that implements an interface that extends both IList<T> and List.
```
public Interface IMySpecialCollection : IList<MyObject>, IList { ... }
```
That means I have two versions of the indexer.
I wish the generic implementation to be used, so I implement that one normally:
```
public MyObject this[int index] { .... }
```
I only need the IList version for serialization, so I implement it explicitly, to keep it hidden:
```
object IList.this[int index] { ... }
```
However, in my unit tests, the following
```
MyObject foo = target[0];
```
results in a compiler error
>
> The call is ambiguous between the
> following methods or properties
>
>
>
I'm a bit surprised at this; I believe I've done it before and it works fine. What am I missing here? How can I get IList<T> and IList to coexist within the same interface?
**Edit** IList<T> does *not* implement IList, and I **must** implement IList for serialization. I'm not interested in workarounds, I want to know what I'm missing.
**Edit again**: I've had to drop IList from the interface and move it on my class. I don't want to do this, as classes that implement the interface are eventually going to be serialized to Xaml, which requires collections to implement IDictionary or IList... | You can't do this with
`public interface IMySpecialCollection : IList<MyObject>, IList { ... }`
But you can do what you want with a class, you will need to make the implementations for one of the interfaces explicit. In my example I made IList explicit.
`public class MySpecialCollection : IList<MyObject>, IList { ... }`
`IList<object> myspecialcollection = new MySpecialCollection();
IList list = (IList)myspecialcollection;`
Have you considered having IMySpecialCollection implement ISerializable for serialization?
Supporting multiple collection types seems a bit wrong to me. You may also want to look at casting yout IList to IEnumerable for serialization since IList just wraps IEnumerable and ICollection. |
57,091 | <p>Let's say I have a parent DIV. Inside, there are three child DIVs: header, content and footer. Header is attached to the top of the parent and fills it horizontally. Footer is attached to the bottom of the parent and fills it horizontally too. Content is supposed to fill all the space between header and footer.</p>
<p>The parent has to have a fixed width and height. The content DIV has to fill all available space between header and footer. When the content size of the content DIV exceeds the space between header and footer, <strong><em>the content DIV should display scrollbars and allow appropriate scrolling</em></strong> so that the footer contents should never be obscured nor the footer obscure content.</p>
<p>Now comes the hard part: <strong><em>you don't know the height of the header nor footer beforehand</em></strong> (eg. header and footer are filled dynamically). How can content be positioned <strong><em>without using JavaScript</em></strong>?</p>
<p>Example:</p>
<pre><code><div style="position : relative; width : 200px; height : 200px; background-color : #e0e0ff; overflow : hidden;">
<div style="background-color: #80ff80; position : absolute; left : 0; right : 0; top : 0;">
header
</div>
<div style="background-color: #8080ff; overflow : auto; position : absolute;">
content (how to position it?)
</div>
<div style="background-color: #ff8080; position : absolute; bottom : 0px; left :0; right : 0;">
footer
</div>
</div>
</code></pre>
<hr>
<p><strong>To clarify this event further</strong> - the target layout that I'm trying to achieve will be used in a business web application. <strong><em>The parent DIV will have a fixed, but unknown size</em></strong> (for instance, it will be exactly the size of the browser viewport, sizing itself along with sizing the browser window by the user). Let's call the parent DIV a "screen".</p>
<p>The header will contain a set of filtering controls (like textboxes, drop down lists and a "filter" button) that should wrap to the next line if there is insufficient horizontal space (so its height can change any time to accomodate line breaking). <strong><em>The header should always be visible and attached to the top</em></strong> of the "screen".</p>
<p>The footer will contain a set of buttons, like on a dialog window. These too can wrap to next line if there is not enough space horizontally. <strong><em>The footer must be attached to the bottom</em></strong> of the "screen" to be accessible and visible at all times.</p>
<p>The content will contain "screen" contents, like dialog fields etc. If there are too few fields, the rest of the content will be "blank" (in this case the footer should not begin right after the content, but still be attached to the bottom of the "screen" which is fixed size). If there are too many fields, <strong><em>the content DIV will provide scrollbar(s)</em></strong> to access the hidden controls (in this case the content DIV must not extend itself below the footer, as the scrollbar would be partially hidden). </p>
<p>I hope this clarifies the question a little bit further, as I have too low rep to enter comments to your repsonses.</p>
| [
{
"answer_id": 57119,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 0,
"selected": false,
"text": "<p>Absolute positioning is messing you up. Try something like this:</p>\n\n<p>HTML:</p>\n\n<pre><code><div id=\"wrapper\"... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5348/"
] | Let's say I have a parent DIV. Inside, there are three child DIVs: header, content and footer. Header is attached to the top of the parent and fills it horizontally. Footer is attached to the bottom of the parent and fills it horizontally too. Content is supposed to fill all the space between header and footer.
The parent has to have a fixed width and height. The content DIV has to fill all available space between header and footer. When the content size of the content DIV exceeds the space between header and footer, ***the content DIV should display scrollbars and allow appropriate scrolling*** so that the footer contents should never be obscured nor the footer obscure content.
Now comes the hard part: ***you don't know the height of the header nor footer beforehand*** (eg. header and footer are filled dynamically). How can content be positioned ***without using JavaScript***?
Example:
```
<div style="position : relative; width : 200px; height : 200px; background-color : #e0e0ff; overflow : hidden;">
<div style="background-color: #80ff80; position : absolute; left : 0; right : 0; top : 0;">
header
</div>
<div style="background-color: #8080ff; overflow : auto; position : absolute;">
content (how to position it?)
</div>
<div style="background-color: #ff8080; position : absolute; bottom : 0px; left :0; right : 0;">
footer
</div>
</div>
```
---
**To clarify this event further** - the target layout that I'm trying to achieve will be used in a business web application. ***The parent DIV will have a fixed, but unknown size*** (for instance, it will be exactly the size of the browser viewport, sizing itself along with sizing the browser window by the user). Let's call the parent DIV a "screen".
The header will contain a set of filtering controls (like textboxes, drop down lists and a "filter" button) that should wrap to the next line if there is insufficient horizontal space (so its height can change any time to accomodate line breaking). ***The header should always be visible and attached to the top*** of the "screen".
The footer will contain a set of buttons, like on a dialog window. These too can wrap to next line if there is not enough space horizontally. ***The footer must be attached to the bottom*** of the "screen" to be accessible and visible at all times.
The content will contain "screen" contents, like dialog fields etc. If there are too few fields, the rest of the content will be "blank" (in this case the footer should not begin right after the content, but still be attached to the bottom of the "screen" which is fixed size). If there are too many fields, ***the content DIV will provide scrollbar(s)*** to access the hidden controls (in this case the content DIV must not extend itself below the footer, as the scrollbar would be partially hidden).
I hope this clarifies the question a little bit further, as I have too low rep to enter comments to your repsonses. | I'm going to get downmodded for this, but this sounds like a job for a table.
What you're trying to do is to set the total height of three contiguous divs as a unit, and a 1x3 table with height 100% is actually a cleaner solution. |
57,094 | <p>I have ASP.NET web pages for which I want to build automated tests (using WatiN & MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use IIS.</p>
| [
{
"answer_id": 57105,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 4,
"selected": true,
"text": "<p>From what I know, you can fire up the dev server from the command prompt with the following path/syntax:</p>\n\n<pre><code>C:\... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | I have ASP.NET web pages for which I want to build automated tests (using WatiN & MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use IIS. | From what I know, you can fire up the dev server from the command prompt with the following path/syntax:
```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT]
```
...so I could imagine you could easily use Process.Start() to launch the particulars you need through some code.
Naturally you'll want to adjust that version number to whatever is most recent/desired for you. |
57,104 | <p>I'm going to be starting a project soon that requires support for large-ish binary files. I'd like to use Ruby on Rails for the webapp, but I'm concerned with the BLOB support. In my experience with other languages, frameworks, and databases, BLOBs are often overlooked and thus have poor, difficult, and/or buggy functionality.</p>
<p>Does RoR spport BLOBs adequately? Are there any gotchas that creep up once you're already committed to Rails?</p>
<p>BTW: I want to be using PostgreSQL and/or MySQL as the backend database. Obviously, BLOB support in the underlying database is important. For the moment, I want to avoid focusing on the DB's BLOB capabilities; I'm more interested in how Rails itself reacts. Ideally, Rails should be hiding the details of the database from me, and so I should be able to switch from one to the other. If this is <em>not</em> the case (ie: there's some problem with using Rails with a particular DB) then please do mention it. </p>
<p>UPDATE: Also, I'm not just talking about ActiveRecord here. I'll need to handle binary files on the HTTP side (file upload effectively). That means getting access to the appropriate HTTP headers and streams via Rails. I've updated the question title and description to reflect this.</p>
| [
{
"answer_id": 57112,
"author": "Teflon Ted",
"author_id": 4061,
"author_profile": "https://Stackoverflow.com/users/4061",
"pm_score": 2,
"selected": false,
"text": "<p>I think your best bet is the attachment_fu plug-in:\n<a href=\"http://github.com/technoweenie/attachment_fu/tree/master... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
] | I'm going to be starting a project soon that requires support for large-ish binary files. I'd like to use Ruby on Rails for the webapp, but I'm concerned with the BLOB support. In my experience with other languages, frameworks, and databases, BLOBs are often overlooked and thus have poor, difficult, and/or buggy functionality.
Does RoR spport BLOBs adequately? Are there any gotchas that creep up once you're already committed to Rails?
BTW: I want to be using PostgreSQL and/or MySQL as the backend database. Obviously, BLOB support in the underlying database is important. For the moment, I want to avoid focusing on the DB's BLOB capabilities; I'm more interested in how Rails itself reacts. Ideally, Rails should be hiding the details of the database from me, and so I should be able to switch from one to the other. If this is *not* the case (ie: there's some problem with using Rails with a particular DB) then please do mention it.
UPDATE: Also, I'm not just talking about ActiveRecord here. I'll need to handle binary files on the HTTP side (file upload effectively). That means getting access to the appropriate HTTP headers and streams via Rails. I've updated the question title and description to reflect this. | +1 for attachment\_fu
I use attachment\_fu in one of my apps and MUST store files in the DB (for annoying reasons which are outside the scope of this convo).
The (one?) tricky thing dealing w/BLOB's I've found is that you need a separate code path to send the data to the user -- you can't simply in-line a path on the filesystem like you would if it was a plain-Jane file.
e.g. if you're storing avatar information, you can't simply do:
```
<%= image_tag @youruser.avatar.path %>
```
you have to write some wrapper logic and use send\_data, e.g. (below is JUST an example w/attachment\_fu, in practice you'd need to DRY this up)
```
send_data(@youruser.avatar.current_data, :type => @youruser.avatar.content_type, :filename => @youruser.avatar.filename, :disposition => 'inline' )
```
Unfortunately, as far as I know attachment\_fu (I don't have the latest version) does not do clever wrapping for you -- you've gotta write it yourself.
P.S.
Seeing your question edit - Attachment\_fu handles all that annoying stuff that you mention -- about needing to know file paths and all that crap -- EXCEPT the one little issue when storing in the DB. Give it a try; it's the standard for rails apps. IF you insist on re-inventing the wheel, the source code for attachment\_fu should document most of the gotchas, too! |
57,124 | <p>I know I can call the GetVersionEx Win32 API function to retrieve Windows version. In most cases returned value reflects the version of my Windows, but sometimes that is not so.</p>
<p>If a user runs my application under the compatibility layer, then GetVersionEx won't be reporting the real version but the version enforced by the compatibility layer. For example, if I'm running Vista and execute my program in "Windows NT 4" compatibility mode, GetVersionEx won't return version 6.0 but 4.0.</p>
<p>Is there a way to bypass this behaviour and get true Windows version?</p>
| [
{
"answer_id": 57128,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 5,
"selected": false,
"text": "<p>WMI QUery:</p>\n\n<pre><code>\"Select * from Win32_OperatingSystem\"\n</code></pre>\n\n<p>EDIT: Actually better would be:<... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4997/"
] | I know I can call the GetVersionEx Win32 API function to retrieve Windows version. In most cases returned value reflects the version of my Windows, but sometimes that is not so.
If a user runs my application under the compatibility layer, then GetVersionEx won't be reporting the real version but the version enforced by the compatibility layer. For example, if I'm running Vista and execute my program in "Windows NT 4" compatibility mode, GetVersionEx won't return version 6.0 but 4.0.
Is there a way to bypass this behaviour and get true Windows version? | The best approach I know is to check if specific API is exported from some DLL. Each new Windows version adds new functions and by checking the existance of those functions one can tell which OS the application is running on. For example, Vista exports [GetLocaleInfoEx](http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx) from kernel32.dll while previous Windowses didn't.
To cut the long story short, here is one such list containing only exports from kernel32.dll.
```
> *function: implemented in*
> GetLocaleInfoEx: Vista
> GetLargePageMinimum: Vista, Server 2003
GetDLLDirectory: Vista, Server 2003, XP SP1
GetNativeSystemInfo: Vista, Server 2003, XP SP1, XP
ReplaceFile: Vista, Server 2003, XP SP1, XP, 2000
OpenThread: Vista, Server 2003, XP SP1, XP, 2000, ME
GetThreadPriorityBoost: Vista, Server 2003, XP SP1, XP, 2000, NT 4
IsDebuggerPresent: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98
GetDiskFreeSpaceEx: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98, 95 OSR2
ConnectNamedPipe: Vista, Server 2003, XP SP1, XP, 2000, NT 4, NT 3
Beep: Vista, Server 2003, XP SP1, XP, 2000, ME, 98, 95 OSR2, 95
```
Writing the function to determine the real OS version is simple; just proceed from newest OS to oldest and use [GetProcAddress](http://msdn.microsoft.com/en-us/library/ms683212.aspx) to check exported APIs. Implementing this in any language should be trivial.
The following code in Delphi was extracted from the free [DSiWin32](http://gp.17slon.com/gp/dsiwin32.htm) library):
```
TDSiWindowsVersion = (wvUnknown, wvWin31, wvWin95, wvWin95OSR2, wvWin98,
wvWin98SE, wvWinME, wvWin9x, wvWinNT3, wvWinNT4, wvWin2000, wvWinXP,
wvWinNT, wvWinServer2003, wvWinVista);
function DSiGetWindowsVersion: TDSiWindowsVersion;
var
versionInfo: TOSVersionInfo;
begin
versionInfo.dwOSVersionInfoSize := SizeOf(versionInfo);
GetVersionEx(versionInfo);
Result := wvUnknown;
case versionInfo.dwPlatformID of
VER_PLATFORM_WIN32s: Result := wvWin31;
VER_PLATFORM_WIN32_WINDOWS:
case versionInfo.dwMinorVersion of
0:
if Trim(versionInfo.szCSDVersion[1]) = 'B' then
Result := wvWin95OSR2
else
Result := wvWin95;
10:
if Trim(versionInfo.szCSDVersion[1]) = 'A' then
Result := wvWin98SE
else
Result := wvWin98;
90:
if (versionInfo.dwBuildNumber = 73010104) then
Result := wvWinME;
else
Result := wvWin9x;
end; //case versionInfo.dwMinorVersion
VER_PLATFORM_WIN32_NT:
case versionInfo.dwMajorVersion of
3: Result := wvWinNT3;
4: Result := wvWinNT4;
5:
case versionInfo.dwMinorVersion of
0: Result := wvWin2000;
1: Result := wvWinXP;
2: Result := wvWinServer2003;
else Result := wvWinNT
end; //case versionInfo.dwMinorVersion
6: Result := wvWinVista;
end; //case versionInfo.dwMajorVersion
end; //versionInfo.dwPlatformID
end; { DSiGetWindowsVersion }
function DSiGetTrueWindowsVersion: TDSiWindowsVersion;
function ExportsAPI(module: HMODULE; const apiName: string): boolean;
begin
Result := GetProcAddress(module, PChar(apiName)) <> nil;
end; { ExportsAPI }
var
hKernel32: HMODULE;
begin { DSiGetTrueWindowsVersion }
hKernel32 := GetModuleHandle('kernel32');
Win32Check(hKernel32 <> 0);
if ExportsAPI(hKernel32, 'GetLocaleInfoEx') then
Result := wvWinVista
else if ExportsAPI(hKernel32, 'GetLargePageMinimum') then
Result := wvWinServer2003
else if ExportsAPI(hKernel32, 'GetNativeSystemInfo') then
Result := wvWinXP
else if ExportsAPI(hKernel32, 'ReplaceFile') then
Result := wvWin2000
else if ExportsAPI(hKernel32, 'OpenThread') then
Result := wvWinME
else if ExportsAPI(hKernel32, 'GetThreadPriorityBoost') then
Result := wvWinNT4
else if ExportsAPI(hKernel32, 'IsDebuggerPresent') then //is also in NT4!
Result := wvWin98
else if ExportsAPI(hKernel32, 'GetDiskFreeSpaceEx') then //is also in NT4!
Result := wvWin95OSR2
else if ExportsAPI(hKernel32, 'ConnectNamedPipe') then
Result := wvWinNT3
else if ExportsAPI(hKernel32, 'Beep') then
Result := wvWin95
else // we have no idea
Result := DSiGetWindowsVersion;
end; { DSiGetTrueWindowsVersion }
```
--- updated 2009-10-09
It turns out that it gets very hard to do an "undocumented" OS detection on Vista SP1 and higher. A look at the [API changes](http://msdn.microsoft.com/en-us/library/aa383687(VS.85).aspx) shows that all Windows 2008 functions are also implemented in Vista SP1 and that all Windows 7 functions are also implemented in Windows 2008 R2. Too bad :(
--- end of update
FWIW, this is a problem I encountered in practice. We (the company I work for) have a program that was not really Vista-ready when Vista was released (and some weeks after that ...). It was not working under the compatibility layer either. (Some DirectX problems. Don't ask.)
We didn't want too-smart-for-their-own-good users to run this app on Vista at all - compatibility mode or not - so I had to find a solution (a guy smarter than me pointed me into right direction; the stuff above is not my brainchild). Now I'm posting it for your pleasure and to help all poor souls that will have to solve this problem in the future. Google, please index this article!
If you have a better solution (or an upgrade and/or fix for mine), please post an answer here ... |
57,140 | <p>Say instead of returning void a method you returned a reference to the class even if it didn't make any particular semantic sense. It seems to me like it would give you more options on how the methods are called, allowing you to use it in a fluent-interface-like style and I can't really think of any disadvantages since you don't have to do anything with the return value (even store it).</p>
<p>So suppose you're in a situation where you want to update an object and then return its current value.
instead of saying </p>
<pre><code>myObj.Update();
var val = myObj.GetCurrentValue();
</code></pre>
<p>you will be able to combine the two lines to say</p>
<pre><code>var val = myObj.Update().GetCurrentValue();
</code></pre>
<hr>
<p><strong>EDIT:</strong> I asked the below on a whim, in retrospect, I agree that its likely to be unnecessary and complicating, however my question regarding returning this rather than void stands.</p>
<p>On a related note, what do you guys think of having the language include a new bit of syntactic sugar:</p>
<pre><code>var val = myObj.Update()<.GetCurrentValue();
</code></pre>
<p>This operator would have a low order of precedence so myObj.Update() would execute first and then call GetCurrentValue() on myObj instead of the void return of Update.</p>
<p>Essentially I'm imagining an operator that will say "call the method on the right-hand side of the operator on the first valid object on the left". Any thoughts?</p>
| [
{
"answer_id": 57165,
"author": "argv0",
"author_id": 5595,
"author_profile": "https://Stackoverflow.com/users/5595",
"pm_score": 2,
"selected": false,
"text": "<p>Returning \"self\" or \"this\" is a common pattern, sometimes referred to as <a href=\"http://www.martinfowler.com/dslwip/Me... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | Say instead of returning void a method you returned a reference to the class even if it didn't make any particular semantic sense. It seems to me like it would give you more options on how the methods are called, allowing you to use it in a fluent-interface-like style and I can't really think of any disadvantages since you don't have to do anything with the return value (even store it).
So suppose you're in a situation where you want to update an object and then return its current value.
instead of saying
```
myObj.Update();
var val = myObj.GetCurrentValue();
```
you will be able to combine the two lines to say
```
var val = myObj.Update().GetCurrentValue();
```
---
**EDIT:** I asked the below on a whim, in retrospect, I agree that its likely to be unnecessary and complicating, however my question regarding returning this rather than void stands.
On a related note, what do you guys think of having the language include a new bit of syntactic sugar:
```
var val = myObj.Update()<.GetCurrentValue();
```
This operator would have a low order of precedence so myObj.Update() would execute first and then call GetCurrentValue() on myObj instead of the void return of Update.
Essentially I'm imagining an operator that will say "call the method on the right-hand side of the operator on the first valid object on the left". Any thoughts? | I know in Java they're actually thinking about making this standard behaviour for void methods. If you do that you don't need the extra syntactic sugar.
The only downside I can think of is performance. But that's easilly measured. I'll get back to you with the results in a few minutes :-)
Edit:
Returning a reference is a bit slower than returning void .. what a surprise. So that's the only downside. A few more ticks when calling your function. |
57,145 | <p>While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc).</p>
<pre><code>class Foo
{
ArrayList<Bar> bars = new ArrayList<Bar>(10);
}
</code></pre>
<p>A part of me keeps nagging at me that it's wasteful to use complex dynamic collections for something this small in size. Is there a better way of implementing something like this? Or is this the norm?</p>
<p>Note, I'm not hit with any (noticeable) performance penalties or anything like that. This is just me wondering if there isn't a better way to do things.</p>
| [
{
"answer_id": 57177,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "<p>The overhead is very small. It is possible to write a hybrid array list that has fields for the first few it... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2881/"
] | While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc).
```
class Foo
{
ArrayList<Bar> bars = new ArrayList<Bar>(10);
}
```
A part of me keeps nagging at me that it's wasteful to use complex dynamic collections for something this small in size. Is there a better way of implementing something like this? Or is this the norm?
Note, I'm not hit with any (noticeable) performance penalties or anything like that. This is just me wondering if there isn't a better way to do things. | The `ArrayList` class in Java has only two data members, a reference to an `Object[]` array and a size—which you need anyway if you don't use an `ArrayList`. So the only advantage to not using an `ArrayList` is saving one object allocation, which is unlikely ever to be a big deal.
If you're creating and disposing of many, many instances of your container class (and by extension your `ArrayList` instance) every second, you *might* have a slight problem with garbage collection churn—but that's something to worry about if it ever occurs. Garbage collection is typically the least of your worries. |
57,152 | <p>Let's say I've got Alpha things that may or may not <em>be</em> or be <em>related to</em> Bravo or Charlie things.</p>
<p>These are one-to-one relationships: No Alpha will relate to more than one Bravo. And no Bravo will relate to more than one Alpha.</p>
<p>I've got a few goals:</p>
<ul>
<li>a system that's easy to learn and
maintain.</li>
<li>data integrity enforced within my
database.</li>
<li>a schema that matches the
real-world, logical organization of
my data.</li>
<li>classes/objects within my
programming that map well to
database tables (à la Linq to SQL)</li>
<li>speedy read and write operations</li>
<li>effective use of space (few null fields)</li>
</ul>
<p>I've got three ideas…</p>
<pre><code>PK = primary key
FK = foreign key
NU = nullable
</code></pre>
<p>One table with many nullalbe fields (flat file)…</p>
<pre><code> Alphas
--------
PK AlphaId
AlphaOne
AlphaTwo
AlphaThree
NU BravoOne
NU BravoTwo
NU BravoThree
NU CharlieOne
NU CharlieTwo
NU CharlieThree
</code></pre>
<p>Many tables with zero nullalbe fields…</p>
<pre><code> Alphas
--------
PK AlphaId
AlphaOne
AlphaTwo
AlphaThree
Bravos
--------
FK PK AlphaId
BravoOne
BravoTwo
BravoThree
Charlies
--------
FK PK AlphaId
CharlieOne
CharlieTwo
CharlieThree
</code></pre>
<p>Best (or worst) of both: Lots of nullalbe foreign keys to many tables…</p>
<pre><code> Alphas
--------
PK AlphaId
AlphaOne
AlphaTwo
AlphaThree
NU FK BravoId
NU FK CharlieId
Bravos
--------
PK BravoId
BravoOne
BravoTwo
BravoThree
Charlies
--------
PK CharlieId
CharlieOne
CharlieTwo
CharlieThree
</code></pre>
<p>What if an Alpha must be either Bravo or Charlie, but not both?</p>
<p>What if instead of just Bravos and Charlies, Alphas could also be any of Deltas, Echos, Foxtrots, or Golfs, etc…?</p>
<hr>
<p><strong>EDIT:</strong> This is a portion of the question: <a href="https://stackoverflow.com/questions/56981/which-is-the-best-database-schema-for-my-navigation#57056">Which is the best database schema for my navigation?</a></p>
| [
{
"answer_id": 57164,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 1,
"selected": false,
"text": "<p>One more approach is having 3 tables for storing the 3 entities and having a separate table for storing the relations... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | Let's say I've got Alpha things that may or may not *be* or be *related to* Bravo or Charlie things.
These are one-to-one relationships: No Alpha will relate to more than one Bravo. And no Bravo will relate to more than one Alpha.
I've got a few goals:
* a system that's easy to learn and
maintain.
* data integrity enforced within my
database.
* a schema that matches the
real-world, logical organization of
my data.
* classes/objects within my
programming that map well to
database tables (à la Linq to SQL)
* speedy read and write operations
* effective use of space (few null fields)
I've got three ideas…
```
PK = primary key
FK = foreign key
NU = nullable
```
One table with many nullalbe fields (flat file)…
```
Alphas
--------
PK AlphaId
AlphaOne
AlphaTwo
AlphaThree
NU BravoOne
NU BravoTwo
NU BravoThree
NU CharlieOne
NU CharlieTwo
NU CharlieThree
```
Many tables with zero nullalbe fields…
```
Alphas
--------
PK AlphaId
AlphaOne
AlphaTwo
AlphaThree
Bravos
--------
FK PK AlphaId
BravoOne
BravoTwo
BravoThree
Charlies
--------
FK PK AlphaId
CharlieOne
CharlieTwo
CharlieThree
```
Best (or worst) of both: Lots of nullalbe foreign keys to many tables…
```
Alphas
--------
PK AlphaId
AlphaOne
AlphaTwo
AlphaThree
NU FK BravoId
NU FK CharlieId
Bravos
--------
PK BravoId
BravoOne
BravoTwo
BravoThree
Charlies
--------
PK CharlieId
CharlieOne
CharlieTwo
CharlieThree
```
What if an Alpha must be either Bravo or Charlie, but not both?
What if instead of just Bravos and Charlies, Alphas could also be any of Deltas, Echos, Foxtrots, or Golfs, etc…?
---
**EDIT:** This is a portion of the question: [Which is the best database schema for my navigation?](https://stackoverflow.com/questions/56981/which-is-the-best-database-schema-for-my-navigation#57056) | If you want each Alpha to be related to by only one Bravo I would vote for the possibility with using a combined FK/PK:
```
Bravos
--------
FK PK AlphaId
BravoOne
BravoTwo
BravoThree
```
This way one and only one Bravo may refer to your Alphas.
If the Bravos and Charlies have to be mutually exclusive, the simplest method would probably to create a discriminator field:
```
Alpha
--------
PK AlphaId
PK AlphaType NOT NULL IN ("Bravo", "Charlie")
AlphaOne
AlphaTwo
AlphaThree
Bravos
--------
FK PK AlphaId
FK PK AlphaType == "Bravo"
BravoOne
BravoTwo
BravoThree
Charlies
--------
FK PK AlphaId
FK PK AlphaType == "Charlie"
CharlieOne
CharlieTwo
CharlieThree
```
This way the AlphaType field forces the records to always belong to exactly one subtype. |
57,168 | <p>I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility).</p>
| [
{
"answer_id": 57172,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >\n</code></pre>\n"
}... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
] | I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility). | As long as there are no identity columns you can just
```
INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]
``` |
57,183 | <p>How do I get the history of commits that have been made to the repository for a particular user? </p>
<p>I am able to access CVS either through the command line or TortioseCVS, so a solution using either method is sufficient.</p>
| [
{
"answer_id": 57218,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": true,
"text": "<pre><code>cvs history -u username\n</code></pre>\n\n<p>gives a history of changes the user has made</p>\n"
},
{
... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498/"
] | How do I get the history of commits that have been made to the repository for a particular user?
I am able to access CVS either through the command line or TortioseCVS, so a solution using either method is sufficient. | ```
cvs history -u username
```
gives a history of changes the user has made |
57,202 | <p>I would like to put a link to a webpage in an alert dialog box so that I can give a more detailed description of how to fix the error that makes the dialog box get created. </p>
<p>How can I make the dialog box show something like this:</p>
<pre><code>There was an error. Go to this page to fix it.
wwww.TheWebPageToFix.com
</code></pre>
<p>Thanks.</p>
| [
{
"answer_id": 57204,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 3,
"selected": false,
"text": "<p>You can't. Alert boxes don't support html. You should display the error as part of the page, it's nicer than J... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | I would like to put a link to a webpage in an alert dialog box so that I can give a more detailed description of how to fix the error that makes the dialog box get created.
How can I make the dialog box show something like this:
```
There was an error. Go to this page to fix it.
wwww.TheWebPageToFix.com
```
Thanks. | You could try asking them if they wish to visit via window.prompt:
```
if(window.prompt('Do you wish to visit the following website?','http://www.google.ca'))
location.href='http://www.google.ca/';
```
Also, Internet Explorer supports modal dialogs so you could try showing one of those:
```
if (window.showModalDialog)
window.showModalDialog("mypage.html","popup","dialogWidth:255px;dialogHeight:250px");
else
window.open("mypage.html","name","height=255,width=250,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes");
``` |
57,238 | <p>Say I have several JavaScript includes in a page:</p>
<pre><code><script type="text/javascript" src="/js/script0.js"></script>
<script type="text/javascript" src="/js/script1.js"></script>
<script type="text/javascript" src="/js/script2.js"></script>
<script type="text/javascript" src="/js/script3.js"></script>
<script type="text/javascript" src="/js/script4.js"></script>
</code></pre>
<p>Is there a way i can tell if any of those weren't found (404) without having to manually check each one? I guess i'm looking for an online tool or something similar. Any ideas?</p>
| [
{
"answer_id": 57246,
"author": "Alex Argo",
"author_id": 5885,
"author_profile": "https://Stackoverflow.com/users/5885",
"pm_score": 4,
"selected": true,
"text": "<p>If you get the <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"noreferrer\" title=\"Firebug\">Fireb... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
] | Say I have several JavaScript includes in a page:
```
<script type="text/javascript" src="/js/script0.js"></script>
<script type="text/javascript" src="/js/script1.js"></script>
<script type="text/javascript" src="/js/script2.js"></script>
<script type="text/javascript" src="/js/script3.js"></script>
<script type="text/javascript" src="/js/script4.js"></script>
```
Is there a way i can tell if any of those weren't found (404) without having to manually check each one? I guess i'm looking for an online tool or something similar. Any ideas? | If you get the [Firebug](https://addons.mozilla.org/en-US/firefox/addon/1843 "Firebug") firefox plugin and enable the consoles it should tell you when there are errors retrieving resources in the console. |
57,243 | <p>I am trying to do something I've done a million times and it's not working, can anyone tell me why?</p>
<p>I have a table for people who sent in resumes, and it has their email address in it...</p>
<p>I want to find out if any of these people have NOT signed up on the web site. The aspnet_Membership table has all the people who ARE signed up on the web site.</p>
<p>There are 9472 job seekers, with unique email addresses.</p>
<p>This query produces 1793 results:</p>
<pre><code>select j.email from jobseeker j
join aspnet_Membership m on j.email = m.email
</code></pre>
<p>This suggests that there should be 7679 (9472-1793) emails of people who are not signed up on the web site. Since 1793 of them DID match, I would expect the rest of them DON'T match... but when I do the query for that, I get nothing!</p>
<p>Why is this query giving me nothing???</p>
<pre><code>select j.email
from jobseeker j
where j.email not in (select email from aspnet_Membership)
</code></pre>
<p>I don't know how that could be not working - it basically says "show me all the emails which are IN the jobseeker table, but NOT IN the aspnet_Membership table... </p>
| [
{
"answer_id": 57251,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>You could have a lot of duplicates out there. I'm not seeing the query error off the top of my head, but you might ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5255/"
] | I am trying to do something I've done a million times and it's not working, can anyone tell me why?
I have a table for people who sent in resumes, and it has their email address in it...
I want to find out if any of these people have NOT signed up on the web site. The aspnet\_Membership table has all the people who ARE signed up on the web site.
There are 9472 job seekers, with unique email addresses.
This query produces 1793 results:
```
select j.email from jobseeker j
join aspnet_Membership m on j.email = m.email
```
This suggests that there should be 7679 (9472-1793) emails of people who are not signed up on the web site. Since 1793 of them DID match, I would expect the rest of them DON'T match... but when I do the query for that, I get nothing!
Why is this query giving me nothing???
```
select j.email
from jobseeker j
where j.email not in (select email from aspnet_Membership)
```
I don't know how that could be not working - it basically says "show me all the emails which are IN the jobseeker table, but NOT IN the aspnet\_Membership table... | We had a very similar problem recently where the subquery was returning null values sometimes. Then, the in statement treats null in a weird way, I think always matching the value, so if you change your query to:
```
select j.email
from jobseeker j
where j.email not in (select email from aspnet_Membership
where email is not null)
```
it may work.... |
57,350 | <p>I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path?</p>
| [
{
"answer_id": 57361,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Environment.GetFolderPath( Environment.SpecialFolders.LocalApplicationData);?</p>\n\n<p>I can't remember if there is a \"L... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path? | How about this, for example:
```
String appData =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
```
I don't see an enum for just the Local Settings folder.
<http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx> has a list with examples. |
57,355 | <p>I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have:</p>
<pre><code>struct Widget
{
Widget():x(0), y(0), z(0){}
int x, y, z;
};
struct WidgetHolder //Just a simple struct to hold four Widgets.
{
WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){}
Widget& A;
Widget& B;
Widget& C;
Widget& D;
};
class Test //This class uses four widgets internally, and must provide access to them externally.
{
public:
const WidgetHolder AccessWidgets() const
{
//This should return our four widgets, but I don't want anyone messing with them.
return WidgetHolder(A, B, C, D);
}
WidgetHolder AccessWidgets()
{
//This should return our four widgets, I don't care if they get changed.
return WidgetHolder(A, B, C, D);
}
private:
Widget A, B, C, D;
};
int main()
{
const Test unchangeable;
unchangeable.AccessWidgets().A.x = 1; //Why does this compile, shouldn't the Widget& be const?
}
</code></pre>
<p>Basically, I have a class called test. It uses four widgets internally, and I need it to return these, but if test was declared const, I want the widgets returned const also.</p>
<p>Can someone explain to me why the code in main() compiles?</p>
<p>Thank you very much.</p>
| [
{
"answer_id": 57364,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 2,
"selected": false,
"text": "<p>unchangeable.AccessWidgets():</p>\n\n<p>At this point, you are creating a new object of type WidgetHolder. \nThis o... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3175/"
] | I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have:
```
struct Widget
{
Widget():x(0), y(0), z(0){}
int x, y, z;
};
struct WidgetHolder //Just a simple struct to hold four Widgets.
{
WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){}
Widget& A;
Widget& B;
Widget& C;
Widget& D;
};
class Test //This class uses four widgets internally, and must provide access to them externally.
{
public:
const WidgetHolder AccessWidgets() const
{
//This should return our four widgets, but I don't want anyone messing with them.
return WidgetHolder(A, B, C, D);
}
WidgetHolder AccessWidgets()
{
//This should return our four widgets, I don't care if they get changed.
return WidgetHolder(A, B, C, D);
}
private:
Widget A, B, C, D;
};
int main()
{
const Test unchangeable;
unchangeable.AccessWidgets().A.x = 1; //Why does this compile, shouldn't the Widget& be const?
}
```
Basically, I have a class called test. It uses four widgets internally, and I need it to return these, but if test was declared const, I want the widgets returned const also.
Can someone explain to me why the code in main() compiles?
Thank you very much. | This compiles because although the WidgetHolder is a const object, this const-ness does not automatically apply to objects pointed to (referenced by) the WidgetHolder. Think of it at a machine level - if the WidgetHolder object itself were held in read-only memory, you could still write to things that were pointed to by the WidgetHolder.
The problem appears to lie in this line:
```
WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){}
```
As Frank mentioned, your references inside the WidgetHolder class are going to hold invalid references after the constructor returns. Therefore, you should change this to:
```
WidgetHolder(Widget &a, Widget &b, Widget &c, Widget &d): A(a), B(b), C(c), D(d){}
```
After you do that, it won't compile, and I leave it as an exercise for the reader to work out the rest of the solution. |
57,380 | <p>Will the code below work if the clock on the server is ahead of the clock on the client?</p>
<pre><code>Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1))
</code></pre>
<p>EDIT: the reason I ask is on one of our web apps some users are claiming they are seeing the pages ( account numbers, etc ) from a user that previously used that machine. Yet we use the line above and others to 'prevent' this from happening.</p>
| [
{
"answer_id": 57407,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/49547/making-sure-a-webpage-is-not-cached-across-all-browsers\">This quest... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2357/"
] | Will the code below work if the clock on the server is ahead of the clock on the client?
```
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1))
```
EDIT: the reason I ask is on one of our web apps some users are claiming they are seeing the pages ( account numbers, etc ) from a user that previously used that machine. Yet we use the line above and others to 'prevent' this from happening. | [This question](https://stackoverflow.com/questions/49547/making-sure-a-webpage-is-not-cached-across-all-browsers) covers making sure a webpage is not cached. It seems you have to set several properties to ensure a web page is not cached across all browsers. |
57,383 | <p>I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it?<br>
I am rethrowing the InnerException, but this destroys the stack trace.<br>
Example code:</p>
<pre><code>public void test1()
{
// Throw an exception for testing purposes
throw new ArgumentException("test1");
}
void test2()
{
try
{
MethodInfo mi = typeof(Program).GetMethod("test1");
mi.Invoke(this, null);
}
catch (TargetInvocationException tiex)
{
// Throw the new exception
throw tiex.InnerException;
}
}
</code></pre>
| [
{
"answer_id": 57387,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 5,
"selected": false,
"text": "<p>I think your best bet would be to just put this in your catch block:</p>\n\n<pre><code>throw;\n</code></pre>\n\n<p>And the... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] | I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it?
I am rethrowing the InnerException, but this destroys the stack trace.
Example code:
```
public void test1()
{
// Throw an exception for testing purposes
throw new ArgumentException("test1");
}
void test2()
{
try
{
MethodInfo mi = typeof(Program).GetMethod("test1");
mi.Invoke(this, null);
}
catch (TargetInvocationException tiex)
{
// Throw the new exception
throw tiex.InnerException;
}
}
``` | In **.NET 4.5** there is now the [`ExceptionDispatchInfo`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo) class.
This lets you capture an exception and re-throw it without changing the stack-trace:
```
using ExceptionDispatchInfo =
System.Runtime.ExceptionServices.ExceptionDispatchInfo;
try
{
task.Wait();
}
catch(AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
```
This works on any exception, not just `AggregateException`.
It was introduced due to the `await` C# language feature, which unwraps the inner exceptions from `AggregateException` instances in order to make the asynchronous language features more like the synchronous language features. |
57,421 | <p>I would like to make an ajax call to a different server (same domain and box, just a different port.)
e.g.</p>
<p>My page is</p>
<pre>
http://localhost/index.html
</pre>
<p>I would like to make a ajax get request to:</p>
<pre>
http://localhost:7076/?word=foo
</pre>
<p>I am getting this error:</p>
<pre>
Access to restricted URI denied (NS_ERROR_DOM_BAD_URI)
</pre>
<p>I know that you can not make an ajax request to a different domain, but it seem this also included different ports? are there any workarounds?</p>
| [
{
"answer_id": 57435,
"author": "Joseph Bui",
"author_id": 3275,
"author_profile": "https://Stackoverflow.com/users/3275",
"pm_score": 3,
"selected": true,
"text": "<p>Have a certain page on your port 80 server proxy requests to the other port. For example:</p>\n\n<pre><code>http://local... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I would like to make an ajax call to a different server (same domain and box, just a different port.)
e.g.
My page is
```
http://localhost/index.html
```
I would like to make a ajax get request to:
```
http://localhost:7076/?word=foo
```
I am getting this error:
```
Access to restricted URI denied (NS_ERROR_DOM_BAD_URI)
```
I know that you can not make an ajax request to a different domain, but it seem this also included different ports? are there any workarounds? | Have a certain page on your port 80 server proxy requests to the other port. For example:
```
http://localhost/proxy?port=7076&url=%2f%3fword%3dfoo
```
Note the url encoding on the last query string argument value. |
57,439 | <p>No, this is not a question about generics.</p>
<p>I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory).</p>
<p>My problem is that <code>CreateInstance</code> fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter.</p>
<p>Example</p>
<pre><code>// Fails
Activator.CreateInstance(type);
// Works
Activator.CreateInstance(type, true);
</code></pre>
<p>I wanted to make the factory generic to make it a little simpler, like this:</p>
<pre><code>public class GenericFactory<T> where T : MyAbstractType
{
public static T GetInstance()
{
return Activator.CreateInstance<T>();
}
}
</code></pre>
<p>However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal).</p>
<p>Did I miss something or it isn't possible?</p>
| [
{
"answer_id": 57450,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 5,
"selected": true,
"text": "<p>To get around this, couldnt you just alter your usage as such:</p>\n\n<pre><code>public class GenericFactory<T> whe... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | No, this is not a question about generics.
I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory).
My problem is that `CreateInstance` fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter.
Example
```
// Fails
Activator.CreateInstance(type);
// Works
Activator.CreateInstance(type, true);
```
I wanted to make the factory generic to make it a little simpler, like this:
```
public class GenericFactory<T> where T : MyAbstractType
{
public static T GetInstance()
{
return Activator.CreateInstance<T>();
}
}
```
However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal).
Did I miss something or it isn't possible? | To get around this, couldnt you just alter your usage as such:
```
public class GenericFactory<T> where T : MyAbstractType
{
public static T GetInstance()
{
return Activator.CreateInstance(typeof(T), true);
}
}
```
Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results. |
57,479 | <p>Help! I am using jQuery to make an AJAX call to fill in a drop-down dynamically given the user's previous input (from another drop-down, that is filled server-side). In all other browsers aside from Firefox (IE6/7, Opera, Safari), my append call actually appends the information below my existing option - "Select An ". But in Firefox, it automatically selects the last item given to the select control, regardless of whether I specify the JQuery action to .append or to replace (.html()). </p>
<pre><code><select name="Products" id="Products" onchange="getHeadings(this.value);">
<option value="">Select Product</option>
</select>
function getProducts(Category) {
$.ajax({
type: "GET",
url: "getInfo.cfm",
data: "Action=getProducts&Category=" + Category,
success: function(result){
$("#Products").html(result);
}
});
};
</code></pre>
<p>Any thoughts? I have tried in the past to also transmit another blank first option, and then trigger a JavaScript option to re-select the first index, but this triggers the onChange event in my code, rather annoying for the user.</p>
<hr>
<p>Update:</p>
<p>Here's an example of what the script would return</p>
<pre><code><option value="3">Option 1</option>
<option value="4">Option 2</option>
<option value="6">Option 3</option>
</code></pre>
<p>Optionally, if using the .html() method instead of the .append(), I would put another</p>
<pre><code><option value="">Select a Product</option>
</code></pre>
<p>at the top of the result.</p>
<hr>
<p>@Darryl Hein</p>
<p>Here's an example of what the script would return</p>
<pre><code><option value="3">Option 1</option>
<option value="4">Option 2</option>
<option value="6">Option 3</option>
</code></pre>
<p>Optionally, if using the .html() method instead of the .append(), I would put another</p>
<pre><code><option value="">Select a Product</option>
</code></pre>
<p>at the top of the result.</p>
| [
{
"answer_id": 57514,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 0,
"selected": false,
"text": "<p>I just did the following and it worked fine:</p>\n\n<pre><code><select name=\"Products\" id=\"Products\">\n<o... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5405/"
] | Help! I am using jQuery to make an AJAX call to fill in a drop-down dynamically given the user's previous input (from another drop-down, that is filled server-side). In all other browsers aside from Firefox (IE6/7, Opera, Safari), my append call actually appends the information below my existing option - "Select An ". But in Firefox, it automatically selects the last item given to the select control, regardless of whether I specify the JQuery action to .append or to replace (.html()).
```
<select name="Products" id="Products" onchange="getHeadings(this.value);">
<option value="">Select Product</option>
</select>
function getProducts(Category) {
$.ajax({
type: "GET",
url: "getInfo.cfm",
data: "Action=getProducts&Category=" + Category,
success: function(result){
$("#Products").html(result);
}
});
};
```
Any thoughts? I have tried in the past to also transmit another blank first option, and then trigger a JavaScript option to re-select the first index, but this triggers the onChange event in my code, rather annoying for the user.
---
Update:
Here's an example of what the script would return
```
<option value="3">Option 1</option>
<option value="4">Option 2</option>
<option value="6">Option 3</option>
```
Optionally, if using the .html() method instead of the .append(), I would put another
```
<option value="">Select a Product</option>
```
at the top of the result.
---
@Darryl Hein
Here's an example of what the script would return
```
<option value="3">Option 1</option>
<option value="4">Option 2</option>
<option value="6">Option 3</option>
```
Optionally, if using the .html() method instead of the .append(), I would put another
```
<option value="">Select a Product</option>
```
at the top of the result. | Can you just change your success function to reset the selected item to the first option?
```
$("#Products").append(result).selectedIndex = 0;
```
or to set it to the previous selection?
```
var tmpIdx = $("#Products").selectedIndex;
$("#Products").append(result).selectedIndex = tmpIdx;
```
If the onChange event should not fire then you can always set a flag to indicate that the form is updating and change events can check for that flag and exit if it is set. |
57,483 | <p>What is the difference between a pointer variable and a reference variable?</p>
| [
{
"answer_id": 57490,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>Apart from syntactic sugar, a reference is a <code>const</code> pointer (<em>not</em> pointer to a <code>const</code>). You ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] | What is the difference between a pointer variable and a reference variable? | 1. A pointer can be re-assigned:
```
int x = 5;
int y = 6;
int *p;
p = &x;
p = &y;
*p = 10;
assert(x == 5);
assert(y == 10);
```
A reference cannot be re-bound, and must be bound at initialization:
```
int x = 5;
int y = 6;
int &q; // error
int &r = x;
```
2. A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary `&` operator and a certain amount of space that can be measured with the `sizeof` operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable.
```
int x = 0;
int &r = x;
int *p = &x;
int *p2 = &r;
assert(p == p2); // &x == &r
assert(&p != &p2);
```
3. You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection.
```
int x = 0;
int y = 0;
int *p = &x;
int *q = &y;
int **pp = &p;
**pp = 2;
pp = &q; // *pp is now q
**pp = 4;
assert(y == 4);
assert(x == 2);
```
4. A pointer can be assigned `nullptr`, whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference to `nullptr`, but this is [undefined](https://stackoverflow.com/questions/2397984/) and will not behave consistently.
```
/* the code below is undefined; your compiler may optimise it
* differently, emit warnings, or outright refuse to compile it */
int &r = *static_cast<int *>(nullptr);
// prints "null" under GCC 10
std::cout
<< (&r != nullptr
? "not null" : "null")
<< std::endl;
bool f(int &r) { return &r != nullptr; }
// prints "not null" under GCC 10
std::cout
<< (f(*static_cast<int *>(nullptr))
? "not null" : "null")
<< std::endl;
```
You can, however, have a reference to a pointer whose value is `nullptr`.
5. Pointers can iterate over an array; you can use `++` to go to the next item that a pointer is pointing to, and `+ 4` to go to the 5th element. This is no matter what size the object is that the pointer points to.
6. A pointer needs to be dereferenced with `*` to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses `->` to access its members whereas a reference uses a `.`.
7. References cannot be put into an array, whereas pointers can be (Mentioned by user @litb)
8. Const references can be bound to temporaries. Pointers cannot (not without some indirection):
```
const int &x = int(12); // legal C++
int *y = &int(12); // illegal to take the address of a temporary.
```
This makes `const &` more convenient to use in argument lists and so forth. |
57,484 | <p>I'm trying to do a basic "OR" on three fields using a hibernate criteria query.</p>
<p>Example</p>
<pre><code>class Whatever{
string name;
string address;
string phoneNumber;
}
</code></pre>
<p>I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber".</p>
| [
{
"answer_id": 57526,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 8,
"selected": true,
"text": "<p>You want to use <code>Restrictions.disjuntion()</code>. Like so</p>\n\n<pre><code>session.createCriteria(Whatever.class)\n ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | I'm trying to do a basic "OR" on three fields using a hibernate criteria query.
Example
```
class Whatever{
string name;
string address;
string phoneNumber;
}
```
I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber". | You want to use `Restrictions.disjuntion()`. Like so
```
session.createCriteria(Whatever.class)
.add(Restrictions.disjunction()
.add(Restrictions.eq("name", queryString))
.add(Restrictions.eq("address", queryString))
.add(Restrictions.eq("phoneNumber", queryString))
);
```
See the Hibernate doc [here](http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-narrowing). |
57,488 | <p>Does anyone know of a way to declare a date constant that is compatible with international dates?</p>
<p>I've tried:</p>
<pre><code>' not international compatible
public const ADate as Date = #12/31/04#
' breaking change if you have an optional parameter that defaults to this value
' because it isnt constant.
public shared readonly ADate As New Date(12, 31, 04)
</code></pre>
| [
{
"answer_id": 57511,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p>OK, I am unsure what you are trying to do here:</p>\n\n<ul>\n<li>The code you are posting is <strong>NOT</strong> .NET, a... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5966/"
] | Does anyone know of a way to declare a date constant that is compatible with international dates?
I've tried:
```
' not international compatible
public const ADate as Date = #12/31/04#
' breaking change if you have an optional parameter that defaults to this value
' because it isnt constant.
public shared readonly ADate As New Date(12, 31, 04)
``` | If you look at the IL generated by the statement
```
public const ADate as Date = #12/31/04#
```
You'll see this:
```
.field public static initonly valuetype [mscorlib]System.DateTime ADate
.custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 00 C0 2F CE E2 BC C6 08 00 00 )
```
Notice that the [DateTimeConstantAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.datetimeconstantattribute.aspx) is being initialized with a constructor that takes an int64 tick count. Since this tick count is being determined at complile time, it seems unlikely that any localization is coming into play when this value is initialized at runtime. My guess is that the error is with some other date handling in your code, not the const initialization. |
57,493 | <p>In my WPF application, I have a number of databound TextBoxes. The <code>UpdateSourceTrigger</code> for these bindings is <code>LostFocus</code>. The object is saved using the File menu. The problem I have is that it is possible to enter a new value into a TextBox, select Save from the File menu, and never persist the new value (the one visible in the TextBox) because accessing the menu does not remove focus from the TextBox. How can I fix this? Is there some way to force all the controls in a page to databind?</p>
<p><em>@palehorse: Good point. Unfortunately, I need to use LostFocus as my UpdateSourceTrigger in order to support the type of validation I want.</em></p>
<p><em>@dmo: I had thought of that. It seems, however, like a really inelegant solution for a relatively simple problem. Also, it requires that there be some control on the page which is is always visible to receive the focus. My application is tabbed, however, so no such control readily presents itself.</em></p>
<p><em>@Nidonocu: The fact that using the menu did not move focus from the TextBox confused me as well. That is, however, the behavior I am seeing. The following simple example demonstrates my problem:</em></p>
<pre class="lang-xml prettyprint-override"><code><Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ObjectDataProvider x:Key="MyItemProvider" />
</Window.Resources>
<DockPanel LastChildFill="True">
<Menu DockPanel.Dock="Top">
<MenuItem Header="File">
<MenuItem Header="Save" Click="MenuItem_Click" />
</MenuItem>
</Menu>
<StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}">
<Label Content="Enter some text and then File > Save:" />
<TextBox Text="{Binding ValueA}" />
<TextBox Text="{Binding ValueB}" />
</StackPanel>
</DockPanel>
</Window>
</code></pre>
<pre><code>using System;
using System.Text;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication2
{
public partial class Window1 : Window
{
public MyItem Item
{
get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; }
set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; }
}
public Window1()
{
InitializeComponent();
Item = new MyItem();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB));
}
}
public class MyItem
{
public string ValueA { get; set; }
public string ValueB { get; set; }
}
}
</code></pre>
| [
{
"answer_id": 57506,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried setting the UpdateSourceTrigger to PropertyChanged? Alternatively, you could call the UpdateSOurce() metho... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] | In my WPF application, I have a number of databound TextBoxes. The `UpdateSourceTrigger` for these bindings is `LostFocus`. The object is saved using the File menu. The problem I have is that it is possible to enter a new value into a TextBox, select Save from the File menu, and never persist the new value (the one visible in the TextBox) because accessing the menu does not remove focus from the TextBox. How can I fix this? Is there some way to force all the controls in a page to databind?
*@palehorse: Good point. Unfortunately, I need to use LostFocus as my UpdateSourceTrigger in order to support the type of validation I want.*
*@dmo: I had thought of that. It seems, however, like a really inelegant solution for a relatively simple problem. Also, it requires that there be some control on the page which is is always visible to receive the focus. My application is tabbed, however, so no such control readily presents itself.*
*@Nidonocu: The fact that using the menu did not move focus from the TextBox confused me as well. That is, however, the behavior I am seeing. The following simple example demonstrates my problem:*
```xml
<Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ObjectDataProvider x:Key="MyItemProvider" />
</Window.Resources>
<DockPanel LastChildFill="True">
<Menu DockPanel.Dock="Top">
<MenuItem Header="File">
<MenuItem Header="Save" Click="MenuItem_Click" />
</MenuItem>
</Menu>
<StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}">
<Label Content="Enter some text and then File > Save:" />
<TextBox Text="{Binding ValueA}" />
<TextBox Text="{Binding ValueB}" />
</StackPanel>
</DockPanel>
</Window>
```
```
using System;
using System.Text;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication2
{
public partial class Window1 : Window
{
public MyItem Item
{
get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; }
set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; }
}
public Window1()
{
InitializeComponent();
Item = new MyItem();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB));
}
}
public class MyItem
{
public string ValueA { get; set; }
public string ValueB { get; set; }
}
}
``` | >
> Suppose you have a TextBox in a window, and a ToolBar with a Save button in it. Assume the TextBox’s Text property is bound to a property on a business object, and the binding’s UpdateSourceTrigger property is set to the default value of LostFocus, meaning that the bound value is pushed back to the business object property when the TextBox loses input focus. Also, assume that the ToolBar’s Save button has its Command property set to ApplicationCommands.Save command.
>
>
> In that situation, if you edit the TextBox and click the Save button with the mouse, there is a problem. When clicking on a Button in a ToolBar, the TextBox does not lose focus. Since the TextBox’s LostFocus event does not fire, the Text property binding does not update the source property of the business object.
>
>
> Obviously you should not validate and save an object if the most recently edited value in the UI has not yet been pushed into the object. This is the exact problem Karl had worked around, by writing code in his window that manually looked for a TextBox with focus and updated the source of the data binding. His solution worked fine, but it got me thinking about a generic solution that would also be useful outside of this particular scenario. Enter CommandGroup…
>
>
>
Taken from Josh Smith’s CodeProject article about [CommandGroup](http://www.codeproject.com/KB/WPF/commandgroup.aspx) |
57,522 | <p>I can create the following and reference it using</p>
<pre><code>area[0].states[0]
area[0].cities[0]
var area = [
{
"State" : "Texas",
"Cities" : ['Austin','Dallas','San Antonio']
},
{
"State" :"Arkansas",
"Cities" : ['Little Rock','Texarkana','Hot Springs']
}
] ;
</code></pre>
<p>How could I restructure "area" so that if I know the name of the state, I can use it in a reference to get the array of cities?</p>
<p>Thanks</p>
<p><strong>EDIT</strong> Attempting to implement with the answers I received (thanks @Eli Courtwright, @17 of 26, and @JasonBunting) I realize my question was incomplete. I need to loop through "area" the first time referencing "state" by index, then when I have the selection of the "state", I need to loop back through a structure using the value of "state" to get the associated "cities". I do want to start with the above structure (although I am free to build it how I want) and I don't mind a conversion similar to @eli's answer (although I was not able to get that conversion to work). Should have been more complete in first question. Trying to implement 2 select boxes where the selection from the first populates the second...I will load this array structure in a js file when the page loads.</p>
| [
{
"answer_id": 57531,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 2,
"selected": true,
"text": "<p>If you want to just create it that way to begin with, just say</p>\n\n<pre><code>area = {\n \"Texas\": ['Austin'... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] | I can create the following and reference it using
```
area[0].states[0]
area[0].cities[0]
var area = [
{
"State" : "Texas",
"Cities" : ['Austin','Dallas','San Antonio']
},
{
"State" :"Arkansas",
"Cities" : ['Little Rock','Texarkana','Hot Springs']
}
] ;
```
How could I restructure "area" so that if I know the name of the state, I can use it in a reference to get the array of cities?
Thanks
**EDIT** Attempting to implement with the answers I received (thanks @Eli Courtwright, @17 of 26, and @JasonBunting) I realize my question was incomplete. I need to loop through "area" the first time referencing "state" by index, then when I have the selection of the "state", I need to loop back through a structure using the value of "state" to get the associated "cities". I do want to start with the above structure (although I am free to build it how I want) and I don't mind a conversion similar to @eli's answer (although I was not able to get that conversion to work). Should have been more complete in first question. Trying to implement 2 select boxes where the selection from the first populates the second...I will load this array structure in a js file when the page loads. | If you want to just create it that way to begin with, just say
```
area = {
"Texas": ['Austin','Dallas','San Antonio']
}
```
and so on. If you're asking how to take an existing object and convert it into this, just say
```
states = {}
for(var j=0; j<area.length; j++)
states[ area[0].State ] = area[0].Cities
```
After running the above code, you could say
```
states["Texas"]
```
which would return
```
['Austin','Dallas','San Antonio']
``` |
57,537 | <p>In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying.</p>
<p>It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost.</p>
<p>Does anyone know of a method for getting the context directory so that I can load and write files to disk?</p>
| [
{
"answer_id": 57563,
"author": "Walter Rumsby",
"author_id": 1654,
"author_profile": "https://Stackoverflow.com/users/1654",
"pm_score": -1,
"selected": false,
"text": "<p>Do you mean:</p>\n\n<pre><code>public class MyServlet extends HttpServlet {\n\n public void init(final ServletCo... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4682/"
] | In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying.
It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost.
Does anyone know of a method for getting the context directory so that I can load and write files to disk? | This should give you the real path that you can use to extract / edit files.
[Javadoc Link](http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String))
We're doing something similar in a context listener.
```
public class MyServlet extends HttpServlet {
public void init(final ServletConfig config) {
final String context = config.getServletContext().getRealPath("/");
...
}
...
}
``` |
57,560 | <p>What's the best way in c# to determine is a given QFE/patch has been installed?</p>
| [
{
"answer_id": 57626,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 1,
"selected": false,
"text": "<p>The most reliable way is to determine which files are impacted by the QFE and use <code>System.Diagnostics.FileVersionInf... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2564/"
] | What's the best way in c# to determine is a given QFE/patch has been installed? | Use WMI and inspect the [Win32\_QuickFixEngineering](http://msdn.microsoft.com/en-us/library/aa394391.aspx) enumeration.
From TechNet:
```
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colQuickFixes = objWMIService.ExecQuery _
("Select * from Win32_QuickFixEngineering")
For Each objQuickFix in colQuickFixes
Wscript.Echo "Computer: " & objQuickFix.CSName
Wscript.Echo "Description: " & objQuickFix.Description
Wscript.Echo "Hot Fix ID: " & objQuickFix.HotFixID
Wscript.Echo "Installation Date: " & objQuickFix.InstallDate
Wscript.Echo "Installed By: " & objQuickFix.InstalledBy
Next
```
**The HotFixID is what you want to examine.**
Here's the output on my system:
```
Hot Fix ID: KB941569
Description: Security Update for Windows XP (KB941569)
Hot Fix ID: KB937143-IE7
Description: Security Update for Windows Internet Explorer 7 (KB937143)
Hot Fix ID: KB938127-IE7
Description: Security Update for Windows Internet Explorer 7 (KB938127)
Hot Fix ID: KB939653-IE7
Description: Security Update for Windows Internet Explorer 7 (KB939653)
Hot Fix ID: KB942615-IE7
Description: Security Update for Windows Internet Explorer 7 (KB942615)
Hot Fix ID: KB944533-IE7
Description: Security Update for Windows Internet Explorer 7 (KB944533)
Hot Fix ID: KB947864-IE7
Description: Hotfix for Windows Internet Explorer 7 (KB947864)
Hot Fix ID: KB950759-IE7
Description: Security Update for Windows Internet Explorer 7 (KB950759)
Hot Fix ID: KB953838-IE7
Description: Security Update for Windows Internet Explorer 7 (KB953838)
Hot Fix ID: MSCompPackV1
Description: Microsoft Compression Client Pack 1.0 for Windows XP
Hot Fix ID: KB873339
Description: Windows XP Hotfix - KB873339
Hot Fix ID: KB885835
Description: Windows XP Hotfix - KB885835
Hot Fix ID: KB885836
Description: Windows XP Hotfix - KB885836
Hot Fix ID: KB886185
Description: Windows XP Hotfix - KB886185
Hot Fix ID: KB887472
Description: Windows XP Hotfix - KB887472
Hot Fix ID: KB888302
Description: Windows XP Hotfix - KB888302
Hot Fix ID: KB890046
Description: Security Update for Windows XP (KB890046)
``` |
57,577 | <p>What is the easiest way to merge XML from two distinct DOM Documents? Is there a way other than using the Canonical <a href="http://support.microsoft.com/kb/311530" rel="nofollow noreferrer">DataReader</a> approach and then messing with the outputted DOM. What I basically want is to AppendChild to XmlElements without getting: <code>The node to be inserted is from a different document context.</code> Here is C# code that I want to work, that obviously won't (what I am doing is merging two documents which have bunch of nodes that I am interested in parts of):</p>
<pre><code>XmlDocument doc1 = new XmlDocument();
doc1.LoadXml("<a><items><item1/><item2/><item3/></items></a>");
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml("<b><items><item4/><item5/><item6/></items></b>");
XmlNode doc2Node = doc2.SelectSingleNode("/b/items");
XmlNodeList doc1Nodes = doc1.SelectNodes("/a/items/*");
foreach (XmlNode doc1Node in doc1Nodes)
{
doc2Node.AppendChild(doc1Node);
}
</code></pre>
| [
{
"answer_id": 57593,
"author": "ckarras",
"author_id": 5688,
"author_profile": "https://Stackoverflow.com/users/5688",
"pm_score": 4,
"selected": true,
"text": "<p>You can use the XmlDocument.ImportNode method to copy a node from a XmlDocument to another.</p>\n"
},
{
"answer_id"... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] | What is the easiest way to merge XML from two distinct DOM Documents? Is there a way other than using the Canonical [DataReader](http://support.microsoft.com/kb/311530) approach and then messing with the outputted DOM. What I basically want is to AppendChild to XmlElements without getting: `The node to be inserted is from a different document context.` Here is C# code that I want to work, that obviously won't (what I am doing is merging two documents which have bunch of nodes that I am interested in parts of):
```
XmlDocument doc1 = new XmlDocument();
doc1.LoadXml("<a><items><item1/><item2/><item3/></items></a>");
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml("<b><items><item4/><item5/><item6/></items></b>");
XmlNode doc2Node = doc2.SelectSingleNode("/b/items");
XmlNodeList doc1Nodes = doc1.SelectNodes("/a/items/*");
foreach (XmlNode doc1Node in doc1Nodes)
{
doc2Node.AppendChild(doc1Node);
}
``` | You can use the XmlDocument.ImportNode method to copy a node from a XmlDocument to another. |
57,599 | <p>What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)?</p>
<p>The <code>datediff</code> function doesn't handle year boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">stored procedure</a>.</p>
| [
{
"answer_id": 57642,
"author": "Michael Runyon",
"author_id": 5405,
"author_profile": "https://Stackoverflow.com/users/5405",
"pm_score": 0,
"selected": false,
"text": "<p>Are you trying to calculate the total days/months/years of an age? do you have a starting date? Or are you trying t... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845/"
] | What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)?
The `datediff` function doesn't handle year boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my [stored procedure](http://en.wikipedia.org/wiki/Stored_procedure). | Here is some T-SQL that gives you the number of years, months, and days since the day specified in @date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate.
```
DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int
SELECT @date = '2/29/04'
SELECT @tmpdate = @date
SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(m, @months, @tmpdate)
SELECT @days = DATEDIFF(d, @tmpdate, GETDATE())
SELECT @years, @months, @days
``` |
57,600 | <p>Should developers avoid using <a href="http://msdn.microsoft.com/en-us/library/923ahwt1.aspx" rel="nofollow noreferrer">continue</a> in C# or its equivalent in other languages to force the next iteration of a loop? Would arguments for or against overlap with arguments about <a href="https://stackoverflow.com/questions/46586/goto-still-considered-harmful">Goto</a>? </p>
| [
{
"answer_id": 57606,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think continue could ever be as difficult as goto since continue never moves execution out of the code block that ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2831/"
] | Should developers avoid using [continue](http://msdn.microsoft.com/en-us/library/923ahwt1.aspx) in C# or its equivalent in other languages to force the next iteration of a loop? Would arguments for or against overlap with arguments about [Goto](https://stackoverflow.com/questions/46586/goto-still-considered-harmful)? | I think there should be more use of continue!
Too often I come across code like:
```
for (...)
{
if (!cond1)
{
if (!cond2)
{
... highly indented lines ...
}
}
}
```
instead of
```
for (...)
{
if (cond1 || cond2)
{
continue;
}
...
}
```
Use it to make the code more readable! |
57,615 | <p>I have a console app in which I want to give the user <em>x</em> seconds to respond to the prompt. If no input is made after a certain period of time, program logic should continue. We assume a timeout means empty response.</p>
<p>What is the most straightforward way of approaching this?</p>
| [
{
"answer_id": 57639,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 3,
"selected": false,
"text": "<p>I think you will need to make a secondary thread and poll for a key on the console. I know of no built in way to accomplis... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] | I have a console app in which I want to give the user *x* seconds to respond to the prompt. If no input is made after a certain period of time, program logic should continue. We assume a timeout means empty response.
What is the most straightforward way of approaching this? | I'm surprised to learn that after 5 years, all of the answers still suffer from one or more of the following problems:
* A function other than ReadLine is used, causing loss of functionality. (Delete/backspace/up-key for previous input).
* Function behaves badly when invoked multiple times (spawning multiple threads, many hanging ReadLine's, or otherwise unexpected behavior).
* Function relies on a busy-wait. Which is a horrible waste since the wait is expected to run anywhere from a number of seconds up to the timeout, which might be multiple minutes. A busy-wait which runs for such an ammount of time is a horrible suck of resources, which is especially bad in a multithreading scenario. If the busy-wait is modified with a sleep this has a negative effect on responsiveness, although I admit that this is probably not a huge problem.
I believe my solution will solve the original problem without suffering from any of the above problems:
```
class Reader {
private static Thread inputThread;
private static AutoResetEvent getInput, gotInput;
private static string input;
static Reader() {
getInput = new AutoResetEvent(false);
gotInput = new AutoResetEvent(false);
inputThread = new Thread(reader);
inputThread.IsBackground = true;
inputThread.Start();
}
private static void reader() {
while (true) {
getInput.WaitOne();
input = Console.ReadLine();
gotInput.Set();
}
}
// omit the parameter to read a line without a timeout
public static string ReadLine(int timeOutMillisecs = Timeout.Infinite) {
getInput.Set();
bool success = gotInput.WaitOne(timeOutMillisecs);
if (success)
return input;
else
throw new TimeoutException("User did not provide input within the timelimit.");
}
}
```
Calling is, of course, very easy:
```
try {
Console.WriteLine("Please enter your name within the next 5 seconds.");
string name = Reader.ReadLine(5000);
Console.WriteLine("Hello, {0}!", name);
} catch (TimeoutException) {
Console.WriteLine("Sorry, you waited too long.");
}
```
Alternatively, you can use the `TryXX(out)` convention, as shmueli suggested:
```
public static bool TryReadLine(out string line, int timeOutMillisecs = Timeout.Infinite) {
getInput.Set();
bool success = gotInput.WaitOne(timeOutMillisecs);
if (success)
line = input;
else
line = null;
return success;
}
```
Which is called as follows:
```
Console.WriteLine("Please enter your name within the next 5 seconds.");
string name;
bool success = Reader.TryReadLine(out name, 5000);
if (!success)
Console.WriteLine("Sorry, you waited too long.");
else
Console.WriteLine("Hello, {0}!", name);
```
In both cases, you cannot mix calls to `Reader` with normal `Console.ReadLine` calls: if the `Reader` times out, there will be a hanging `ReadLine` call. Instead, if you want to have a normal (non-timed) `ReadLine` call, just use the `Reader` and omit the timeout, so that it defaults to an infinite timeout.
So how about those problems of the other solutions I mentioned?
* As you can see, ReadLine is used, avoiding the first problem.
* The function behaves properly when invoked multiple times. Regardless of whether a timeout occurs or not, only one background thread will ever be running and only at most one call to ReadLine will ever be active. Calling the function will always result in the latest input, or in a timeout, and the user won't have to hit enter more than once to submit his input.
* And, obviously, the function does not rely on a busy-wait. Instead it uses proper multithreading techniques to prevent wasting resources.
The only problem that I foresee with this solution is that it is not thread-safe. However, multiple threads can't really ask the user for input at the same time, so synchronization should be happening before making a call to `Reader.ReadLine` anyway. |
57,625 | <p>This one will take some explaining. What I've done is create a specific custom message queue in SQL Server 2005. I have a table with messages that contain timestamps for both acknowledgment and completion. The stored procedure that callers execute to obtain the next message in their queue also acknowledges the message. So far so good. Well, if the system is experiencing a massive amount of transactions (thousands per minute), isn't it possible for a message to be acknowledged by another execution of the stored procedure while another is prepared to so itself? Let me help by showing my SQL code in the stored proc:</p>
<pre><code>--Grab the next message id
declare @MessageId uniqueidentifier
set @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands);
--Acknowledge the message
update ActionMessages
set AcknowledgedTime = getdate()
where ActionMessageId = @MessageId
--Select the entire message
...
...
</code></pre>
<p>In the above code, couldn't another stored procedure running at the same time obtain the same id and attempt to acknowledge it at the same time? Could I (or should I) implement some sort of locking to prevent another stored proc from acknowledging messages that another stored proc is querying? </p>
<p>Wow, did any of this even make sense? It's a bit difficult to put to words...</p>
| [
{
"answer_id": 57637,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": -1,
"selected": false,
"text": "<p>You want to wrap your code in a transaction, then SQL server will handle locking the appropriate rows or tables.</p>\n\n... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] | This one will take some explaining. What I've done is create a specific custom message queue in SQL Server 2005. I have a table with messages that contain timestamps for both acknowledgment and completion. The stored procedure that callers execute to obtain the next message in their queue also acknowledges the message. So far so good. Well, if the system is experiencing a massive amount of transactions (thousands per minute), isn't it possible for a message to be acknowledged by another execution of the stored procedure while another is prepared to so itself? Let me help by showing my SQL code in the stored proc:
```
--Grab the next message id
declare @MessageId uniqueidentifier
set @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands);
--Acknowledge the message
update ActionMessages
set AcknowledgedTime = getdate()
where ActionMessageId = @MessageId
--Select the entire message
...
...
```
In the above code, couldn't another stored procedure running at the same time obtain the same id and attempt to acknowledge it at the same time? Could I (or should I) implement some sort of locking to prevent another stored proc from acknowledging messages that another stored proc is querying?
Wow, did any of this even make sense? It's a bit difficult to put to words... | Something like this
```
--Grab the next message id
begin tran
declare @MessageId uniqueidentifier
select top 1 @MessageId = ActionMessageId from UnacknowledgedDemands with(holdlock, updlock);
--Acknowledge the message
update ActionMessages
set AcknowledgedTime = getdate()
where ActionMessageId = @MessageId
-- some error checking
commit tran
--Select the entire message
...
...
``` |
57,652 | <p>Scenario:</p>
<ol>
<li>The user has two monitors.</li>
<li>Their browser is open on the secondary monitor.</li>
<li>They click a link in the browser which calls window.open() with a specific top and left window offset.</li>
<li>The popup window always opens on their primary monitor.</li>
</ol>
<p>Is there any way in JavaScript to get the popup window to open on the same monitor as the initial browser window (the opener)?</p>
| [
{
"answer_id": 57680,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": -1,
"selected": false,
"text": "<p>as long as you know the x and y position that falls on the particular monitor you can do:</p>\n\n<pre><code>var x = 0;\nvar... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1436/"
] | Scenario:
1. The user has two monitors.
2. Their browser is open on the secondary monitor.
3. They click a link in the browser which calls window.open() with a specific top and left window offset.
4. The popup window always opens on their primary monitor.
Is there any way in JavaScript to get the popup window to open on the same monitor as the initial browser window (the opener)? | You can't specify the monitor, but you can specify the position of the popup window as being relative to the where the click caused the window to popup.
Use the getMouseXY() function to get values to pass as the left and top args to the window.open() method. (the left and top args only work with V3 and up browsers).
window.open docs:
<http://www.javascripter.net/faq/openinga.htm>
```
function getMouseXY( e ) {
if ( event.clientX ) { // Grab the x-y pos.s if browser is IE.
CurrentLeft = event.clientX + document.body.scrollLeft;
CurrentTop = event.clientY + document.body.scrollTop;
}
else { // Grab the x-y pos.s if browser isn't IE.
CurrentLeft = e.pageX;
CurrentTop = e.pageY;
}
if ( CurrentLeft < 0 ) { CurrentLeft = 0; };
if ( CurrentTop < 0 ) { CurrentTop = 0; };
return true;
}
``` |
57,665 | <p>Is there an easy way to return data to web service clients in JSON using Rails?</p>
| [
{
"answer_id": 57706,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://wiki.rubyonrails.org/rails/pages/HowtoGenerateJSON\" rel=\"nofollow noreferrer\">http://wiki.rubyo... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5988/"
] | Is there an easy way to return data to web service clients in JSON using Rails? | Rails resource gives a RESTful interface for your model. Let's see.
Model
=====
```
class Contact < ActiveRecord::Base
...
end
```
Routes
======
```
map.resources :contacts
```
Controller
==========
```
class ContactsController < ApplicationController
...
def show
@contact = Contact.find(params[:id]
respond_to do |format|
format.html
format.xml {render :xml => @contact}
format.js {render :json => @contact.json}
end
end
...
end
```
So this gives you an API interfaces without the need to define special methods to get the type of respond required
Eg.
```
/contacts/1 # Responds with regular html page
/contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes
/contacts/1.js # Responds with json output of Contact.find(1) and its attributes
``` |
57,679 | <p>I'm trying to determine, based on the result of this call, if it was successful. The <code>successFunction</code> doesn't get called, so I'm assuming it was not. How do I know what went wrong?</p>
<pre><code>xmlRequest = $.post("/url/file/", { 'id' : object.id }, successFunction, 'json');
</code></pre>
<p>Do I use the xmlRequest object?</p>
| [
{
"answer_id": 57688,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 3,
"selected": false,
"text": "<p>You could use the $.ajaxComplete() and/or $.ajaxError() methods to attach function to those events. I would also recommen... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
] | I'm trying to determine, based on the result of this call, if it was successful. The `successFunction` doesn't get called, so I'm assuming it was not. How do I know what went wrong?
```
xmlRequest = $.post("/url/file/", { 'id' : object.id }, successFunction, 'json');
```
Do I use the xmlRequest object? | You can use:
```
$.ajax({
url:"/url/file/",
dataType:"json"
data:{ 'id' : object.id }
error:function(request){alert(request.statusText)}
success:successFunction
})
``` |
57,708 | <p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p>
<p>For example:</p>
<p>I get back:</p>
<pre><code>&#x01ce;
</code></pre>
<p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
| [
{
"answer_id": 57745,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "<p>You could find an answer here -- <a href=\"https://stackoverflow.com/questions/53224/getting-international-characters-from-a-w... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] | I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?
For example:
I get back:
```
ǎ
```
which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value `u'\u01ce'` | The standard lib’s very own HTMLParser has an undocumented function unescape() which does exactly what you think it does:
up to Python 3.4:
```
import HTMLParser
h = HTMLParser.HTMLParser()
h.unescape('© 2010') # u'\xa9 2010'
h.unescape('© 2010') # u'\xa9 2010'
```
Python 3.4+:
```
import html
html.unescape('© 2010') # u'\xa9 2010'
html.unescape('© 2010') # u'\xa9 2010'
``` |
57,731 | <p>I have a table in SQL Server that I inherited from a legacy system thats still in production that is structured according to the code below. I created a SP to query the table as described in the code below the table create statement. My issue is that, sporadically, calls from .NET to this SP both through the Enterprise Library 4 and through a DataReader object are slow. The SP is called through a loop structure in the Data Layer that specifies the params that go into the SP for the purpose of populating user objects. It's also important to mention that a slow call will not take place on every pass the loop structure. It will generally be fine for most of a day or more, and then start presenting which makes it extremely hard to debug.</p>
<p>The table in question contains about 5 million rows. The calls that are slow, for instance, will take as long as 10 seconds, while the calls that are fast will take 0 to 10 milliseconds on average. I checked for locking/blocking transactions during the slow calls, none were found. I created some custom performance counters in the data layer to monitor call times. Essentially, when performance is bad, it's really bad for that one call. But when it's good, it's really good. I've been able to recreate the issue on a few different developer machines, but not on our development and staging database servers, which of course have beefier hardware. Generally, the problem is resolved through restarting the SQL server services, but not always. There are indexes on the table for the fields I'm querying, but there are more indexes than I would like. However, I'm hesitant to remove any or toy with the indexes due to the impact it may have on the legacy system. Has anyone experienced a problem like this before, or do you have a recommendation to remedy it? </p>
<pre><code>CREATE TABLE [dbo].[product_performance_quarterly](
[performance_id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[product_id] [int] NULL,
[month] [int] NULL,
[year] [int] NULL,
[performance] [decimal](18, 6) NULL,
[gross_or_net] [char](15) NULL,
[vehicle_type] [char](30) NULL,
[quarterly_or_monthly] [char](1) NULL,
[stamp] [datetime] NULL CONSTRAINT [DF_product_performance_quarterly_stamp] DEFAULT (getdate()),
[eA_loaded] [nchar](10) NULL,
[vehicle_type_id] [int] NULL,
[yearmonth] [char](6) NULL,
[gross_or_net_id] [tinyint] NULL,
CONSTRAINT [PK_product_performance_quarterly_4_19_04] PRIMARY KEY CLUSTERED
(
[performance_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[product_performance_quarterly] WITH NOCHECK ADD CONSTRAINT [FK_product_performance_quarterlyProduct_id] FOREIGN KEY([product_id])
REFERENCES [dbo].[products] ([product_id])
GO
ALTER TABLE [dbo].[product_performance_quarterly] CHECK CONSTRAINT [FK_product_performance_quarterlyProduct_id]
CREATE PROCEDURE [eA.Analytics.Calculations].[USP.GetCalculationData]
(
@PRODUCTID INT, --products.product_id
@BEGINYEAR INT, --year to begin retrieving performance data
@BEGINMONTH INT, --month to begin retrieving performance data
@ENDYEAR INT, --year to end retrieving performance data
@ENDMONTH INT, --month to end retrieving performance data
@QUARTERLYORMONTHLY VARCHAR(1), --do you want quarterly or monthly data?
@VEHICLETYPEID INT, --what product vehicle type are you looking for?
@GROSSORNETID INT --are your looking gross of fees data or net of fees data?
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @STARTDATE VARCHAR(6),
@ENDDATE VARCHAR(6),
@vBEGINMONTH VARCHAR(2),
@vENDMONTH VARCHAR(2)
IF LEN(@BEGINMONTH) = 1
SET @vBEGINMONTH = '0' + CAST(@BEGINMONTH AS VARCHAR(1))
ELSE
SET @vBEGINMONTH = @BEGINMONTH
IF LEN(@ENDMONTH) = 1
SET @vENDMONTH = '0' + CAST(@ENDMONTH AS VARCHAR(1))
ELSE
SET @vENDMONTH = @ENDMONTH
SET @STARTDATE = CAST(@BEGINYEAR AS VARCHAR(4)) + @vBEGINMONTH
SET @ENDDATE = CAST(@ENDYEAR AS VARCHAR(4)) + @vENDMONTH
--because null values for gross_or_net_id and vehicle_type_id are represented in
--multiple ways (true null, empty string, or 0) in the PPQ table, need to account for all possible variations if
--a -1 is passed in from the .NET code, which represents an enumerated value that
--indicates that the value(s) should be true null.
IF @VEHICLETYPEID = '-1' AND @GROSSORNETID = '-1'
SELECT
PPQ.YEARMONTH, PPQ.PERFORMANCE
FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ
WITH (NOLOCK)
WHERE
(PPQ.PRODUCT_ID = @PRODUCTID)
AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE)
AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY)
AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '')
AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '')
ORDER BY PPQ.YEARMONTH ASC
IF @VEHICLETYPEID <> '-1' AND @GROSSORNETID <> '-1'
SELECT
PPQ.YEARMONTH, PPQ.PERFORMANCE
FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ
WITH (NOLOCK)
WHERE
(PPQ.PRODUCT_ID = @PRODUCTID)
AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE)
AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY)
AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID )
AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID)
ORDER BY PPQ.YEARMONTH ASC
IF @VEHICLETYPEID = '-1' AND @GROSSORNETID <> '-1'
SELECT
PPQ.YEARMONTH, PPQ.PERFORMANCE
FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ
WITH (NOLOCK)
WHERE
(PPQ.PRODUCT_ID = @PRODUCTID)
AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE)
AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY)
AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '')
AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID)
ORDER BY PPQ.YEARMONTH ASC
IF @VEHICLETYPEID <> '-1' AND @GROSSORNETID = '-1'
SELECT
PPQ.YEARMONTH, PPQ.PERFORMANCE
FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ
WITH (NOLOCK)
WHERE
(PPQ.PRODUCT_ID = @PRODUCTID)
AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE)
AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY)
AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID)
AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '')
ORDER BY PPQ.YEARMONTH ASC
END
</code></pre>
| [
{
"answer_id": 57741,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like another query is running in the background that has locked the table and your innocent query is simply waitin... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a table in SQL Server that I inherited from a legacy system thats still in production that is structured according to the code below. I created a SP to query the table as described in the code below the table create statement. My issue is that, sporadically, calls from .NET to this SP both through the Enterprise Library 4 and through a DataReader object are slow. The SP is called through a loop structure in the Data Layer that specifies the params that go into the SP for the purpose of populating user objects. It's also important to mention that a slow call will not take place on every pass the loop structure. It will generally be fine for most of a day or more, and then start presenting which makes it extremely hard to debug.
The table in question contains about 5 million rows. The calls that are slow, for instance, will take as long as 10 seconds, while the calls that are fast will take 0 to 10 milliseconds on average. I checked for locking/blocking transactions during the slow calls, none were found. I created some custom performance counters in the data layer to monitor call times. Essentially, when performance is bad, it's really bad for that one call. But when it's good, it's really good. I've been able to recreate the issue on a few different developer machines, but not on our development and staging database servers, which of course have beefier hardware. Generally, the problem is resolved through restarting the SQL server services, but not always. There are indexes on the table for the fields I'm querying, but there are more indexes than I would like. However, I'm hesitant to remove any or toy with the indexes due to the impact it may have on the legacy system. Has anyone experienced a problem like this before, or do you have a recommendation to remedy it?
```
CREATE TABLE [dbo].[product_performance_quarterly](
[performance_id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[product_id] [int] NULL,
[month] [int] NULL,
[year] [int] NULL,
[performance] [decimal](18, 6) NULL,
[gross_or_net] [char](15) NULL,
[vehicle_type] [char](30) NULL,
[quarterly_or_monthly] [char](1) NULL,
[stamp] [datetime] NULL CONSTRAINT [DF_product_performance_quarterly_stamp] DEFAULT (getdate()),
[eA_loaded] [nchar](10) NULL,
[vehicle_type_id] [int] NULL,
[yearmonth] [char](6) NULL,
[gross_or_net_id] [tinyint] NULL,
CONSTRAINT [PK_product_performance_quarterly_4_19_04] PRIMARY KEY CLUSTERED
(
[performance_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[product_performance_quarterly] WITH NOCHECK ADD CONSTRAINT [FK_product_performance_quarterlyProduct_id] FOREIGN KEY([product_id])
REFERENCES [dbo].[products] ([product_id])
GO
ALTER TABLE [dbo].[product_performance_quarterly] CHECK CONSTRAINT [FK_product_performance_quarterlyProduct_id]
CREATE PROCEDURE [eA.Analytics.Calculations].[USP.GetCalculationData]
(
@PRODUCTID INT, --products.product_id
@BEGINYEAR INT, --year to begin retrieving performance data
@BEGINMONTH INT, --month to begin retrieving performance data
@ENDYEAR INT, --year to end retrieving performance data
@ENDMONTH INT, --month to end retrieving performance data
@QUARTERLYORMONTHLY VARCHAR(1), --do you want quarterly or monthly data?
@VEHICLETYPEID INT, --what product vehicle type are you looking for?
@GROSSORNETID INT --are your looking gross of fees data or net of fees data?
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @STARTDATE VARCHAR(6),
@ENDDATE VARCHAR(6),
@vBEGINMONTH VARCHAR(2),
@vENDMONTH VARCHAR(2)
IF LEN(@BEGINMONTH) = 1
SET @vBEGINMONTH = '0' + CAST(@BEGINMONTH AS VARCHAR(1))
ELSE
SET @vBEGINMONTH = @BEGINMONTH
IF LEN(@ENDMONTH) = 1
SET @vENDMONTH = '0' + CAST(@ENDMONTH AS VARCHAR(1))
ELSE
SET @vENDMONTH = @ENDMONTH
SET @STARTDATE = CAST(@BEGINYEAR AS VARCHAR(4)) + @vBEGINMONTH
SET @ENDDATE = CAST(@ENDYEAR AS VARCHAR(4)) + @vENDMONTH
--because null values for gross_or_net_id and vehicle_type_id are represented in
--multiple ways (true null, empty string, or 0) in the PPQ table, need to account for all possible variations if
--a -1 is passed in from the .NET code, which represents an enumerated value that
--indicates that the value(s) should be true null.
IF @VEHICLETYPEID = '-1' AND @GROSSORNETID = '-1'
SELECT
PPQ.YEARMONTH, PPQ.PERFORMANCE
FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ
WITH (NOLOCK)
WHERE
(PPQ.PRODUCT_ID = @PRODUCTID)
AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE)
AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY)
AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '')
AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '')
ORDER BY PPQ.YEARMONTH ASC
IF @VEHICLETYPEID <> '-1' AND @GROSSORNETID <> '-1'
SELECT
PPQ.YEARMONTH, PPQ.PERFORMANCE
FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ
WITH (NOLOCK)
WHERE
(PPQ.PRODUCT_ID = @PRODUCTID)
AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE)
AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY)
AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID )
AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID)
ORDER BY PPQ.YEARMONTH ASC
IF @VEHICLETYPEID = '-1' AND @GROSSORNETID <> '-1'
SELECT
PPQ.YEARMONTH, PPQ.PERFORMANCE
FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ
WITH (NOLOCK)
WHERE
(PPQ.PRODUCT_ID = @PRODUCTID)
AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE)
AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY)
AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '')
AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID)
ORDER BY PPQ.YEARMONTH ASC
IF @VEHICLETYPEID <> '-1' AND @GROSSORNETID = '-1'
SELECT
PPQ.YEARMONTH, PPQ.PERFORMANCE
FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ
WITH (NOLOCK)
WHERE
(PPQ.PRODUCT_ID = @PRODUCTID)
AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE)
AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY)
AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID)
AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '')
ORDER BY PPQ.YEARMONTH ASC
END
``` | I have seen this happen with indexes that were out of date. It could also be a parameter sniffing problem, where a different query plan is being used for different parameters that come in to the stored procedure.
You should capture the parameters of the slow calls and see if they are the same ones each time it runs slow.
You might also try running the tuning wizard and see if it recommends any indexes.
You don't want to worry about having too many indexes until you can prove that updates and inserts are happening too slow (time needed to modify the index plus locking/contention), or you are running out of disk space for them. |
57,751 | <p>I want to find any text in a file that matches a regexp of the form <em>t</em><code>[A-Z]</code><em>u</em> (i.e., a match <em>t</em> followed by a capital letter and another match <em>u</em>, and transform the matched text so that the capital letter is lowercase. For example, for the regexp <code>x[A-Z]y</code></p>
<pre><code>xAy
</code></pre>
<p>becomes</p>
<pre><code>xay
</code></pre>
<p>and</p>
<pre><code>xZy
</code></pre>
<p>becomes</p>
<pre><code>xzy
</code></pre>
<p>Emacs' <code>query-replace</code> function allows back-references, but AFAIK not the transformation of the matched text. Is there a built-in function that does this? Does anybody have a short Elisp function I could use?</p>
<p><strong>UPDATE</strong></p>
<p>@Marcel Levy has it: <code>\,</code> in a replacement expression introduces an (arbitrary?) Elisp expression. E.g., the solution to the above is</p>
<pre><code>M-x replace-regexp <RET> x\([A-Z]\)z <RET> x\,(downcase \1)z
</code></pre>
| [
{
"answer_id": 57794,
"author": "Marcel Levy",
"author_id": 676,
"author_profile": "https://Stackoverflow.com/users/676",
"pm_score": 5,
"selected": true,
"text": "<p>It looks like <a href=\"http://steve-yegge.blogspot.com/\" rel=\"noreferrer\">Steve Yegge</a> actually already posted the... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | I want to find any text in a file that matches a regexp of the form *t*`[A-Z]`*u* (i.e., a match *t* followed by a capital letter and another match *u*, and transform the matched text so that the capital letter is lowercase. For example, for the regexp `x[A-Z]y`
```
xAy
```
becomes
```
xay
```
and
```
xZy
```
becomes
```
xzy
```
Emacs' `query-replace` function allows back-references, but AFAIK not the transformation of the matched text. Is there a built-in function that does this? Does anybody have a short Elisp function I could use?
**UPDATE**
@Marcel Levy has it: `\,` in a replacement expression introduces an (arbitrary?) Elisp expression. E.g., the solution to the above is
```
M-x replace-regexp <RET> x\([A-Z]\)z <RET> x\,(downcase \1)z
``` | It looks like [Steve Yegge](http://steve-yegge.blogspot.com/) actually already posted the answer to this a few years back: ["Shiny and New: Emacs 22."](http://steve-yegge.blogspot.com/2006/06/shiny-and-new-emacs-22.html) Scroll down to "Changing Case in Replacement Strings" and you'll see his example code using the `replace-regexp` function.
The general answer is that you use "\," to call any lisp expression as part of the replacement string, as in `\,(capitalize \1)`. Reading the help text, it looks like it's only in interactive mode, but that seems like the one place where this would be most necessary. |
57,766 | <p>I am getting the below error and call stack at the same time everyday after several hours of application use. Can anyone shed some light on what is happening?</p>
<pre><code>System.InvalidOperationException: BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress.
at System.Drawing.BufferedGraphicsContext.Dispose(Boolean disposing)
at System.Drawing.BufferedGraphicsContext.Dispose()
at System.Drawing.BufferedGraphicsContext.AllocBufferInTempManager(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle)
at System.Drawing.BufferedGraphicsContext.Allocate(IntPtr targetDC, Rectangle targetRectangle)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.MenuStrip.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code></pre>
| [
{
"answer_id": 57820,
"author": "qbeuek",
"author_id": 5348,
"author_profile": "https://Stackoverflow.com/users/5348",
"pm_score": 0,
"selected": false,
"text": "<p>a shot in the dark - are you painting from multiple threads? If you are doing painting related work, do it on the GUI threa... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4770/"
] | I am getting the below error and call stack at the same time everyday after several hours of application use. Can anyone shed some light on what is happening?
```
System.InvalidOperationException: BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress.
at System.Drawing.BufferedGraphicsContext.Dispose(Boolean disposing)
at System.Drawing.BufferedGraphicsContext.Dispose()
at System.Drawing.BufferedGraphicsContext.AllocBufferInTempManager(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle)
at System.Drawing.BufferedGraphicsContext.Allocate(IntPtr targetDC, Rectangle targetRectangle)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.MenuStrip.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
``` | There is a very long MSDN forums discussion of this error [here](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=200483&SiteID=1). In most cases the error is apparently associated with either:
1. An underlying OutOfMemory problem, which manifests as the BufferedGraphicsContext exception, possibly due to a framework bug.
2. A GDI object leak (creating GDI objects and not disposing them).
I recall seeing this error myself a year or so ago, and it was definitely associated with a memory problem that made our app fill up all available VM after a long run, so #1 agrees with what I have observed. |
57,791 | <p>I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.</p>
<p>Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads. </p>
<p>The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?</p>
| [
{
"answer_id": 57798,
"author": "Tom Kidd",
"author_id": 2577,
"author_profile": "https://Stackoverflow.com/users/2577",
"pm_score": 2,
"selected": false,
"text": "<p><strong>EDIT:</strong> My \"workaround\" below is complete overkill, based on my lack of understanding. Go with Shog9's a... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577/"
] | I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.
Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads.
The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out? | Let me guess: the help "icon" is actually a link with a `javascript:` url? Change it to a real button, a real link, or at least put the functionality in an onclick event handler (that prevents the default behavior). Problem solved.
```
<!-- clicking this link will do nothing. No onbeforeunload handler triggered.
Nothing.
And you could put something in before the return false bit...
...and the onunload handler would still not get called... -->
<a href="http://www.google.com/" onclick="return false;">blah1</a>
<!-- this should also do nothing, but IE will trigger the onbeforeunload
handler -->
<a href="javascript:void(0)">blah2</a>
``` |
57,803 | <p>How do you convert decimal values to their hexadecimal equivalent in JavaScript?</p>
| [
{
"answer_id": 57805,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 13,
"selected": true,
"text": "<p>Convert a number to a hexadecimal string with:</p>\n<pre><code>hexString = yourNumber.toString(16);\n</code></pre>\n<p>An... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5556/"
] | How do you convert decimal values to their hexadecimal equivalent in JavaScript? | Convert a number to a hexadecimal string with:
```
hexString = yourNumber.toString(16);
```
And reverse the process with:
```
yourNumber = parseInt(hexString, 16);
``` |
57,804 | <p>Now, before you say it: I <strong>did</strong> Google and my <code>hbm.xml</code> file <strong>is</strong> an Embedded Resource. </p>
<p>Here is the code I am calling:</p>
<pre><code>ISession session = GetCurrentSession();
var returnObject = session.Get<T>(Id);
</code></pre>
<p>Here is my mapping file for the class:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true">
<id name="ID" column="ID" unsaved-value="0">
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<property name="NumberOfBuckets" column="NumberOfBuckets" />
<property name="SearchCriteriaOne" column="SearchCriteriaOne" />
<bag name="_Businesses" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Business, HQData"/>
</bag>
<bag name="_Buckets" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Bucket, HQData"/>
</bag>
</class>
</hibernate-mapping>
</code></pre>
<p>Has anyone run to this issue before?</p>
<p>Here is the full error message:</p>
<blockquote>
<pre>MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id)
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory()
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e)
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436</pre>
</blockquote>
<p><strong>Update</strong>, here's what the solution for <em>my</em> scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime. </p>
| [
{
"answer_id": 57860,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 2,
"selected": false,
"text": "<p>Should it be <code>name=\"Id\"</code>? Typos are a likely cause.</p>\n\n<p>Next would be to try it out with a non-gene... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] | Now, before you say it: I **did** Google and my `hbm.xml` file **is** an Embedded Resource.
Here is the code I am calling:
```
ISession session = GetCurrentSession();
var returnObject = session.Get<T>(Id);
```
Here is my mapping file for the class:
```xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true">
<id name="ID" column="ID" unsaved-value="0">
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<property name="NumberOfBuckets" column="NumberOfBuckets" />
<property name="SearchCriteriaOne" column="SearchCriteriaOne" />
<bag name="_Businesses" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Business, HQData"/>
</bag>
<bag name="_Buckets" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Bucket, HQData"/>
</bag>
</class>
</hibernate-mapping>
```
Has anyone run to this issue before?
Here is the full error message:
>
>
> ```
> MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id)
> in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id)
> in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory()
> in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e)
> in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
> ```
>
>
**Update**, here's what the solution for *my* scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime. | Sounds like you forgot to add a mapping assembly to the session factory configuration..
If you're using app.config...
```
.
.
<property name="show_sql">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="Project.DomainModel"/> <!-- Here -->
</session-factory>
.
.
``` |
57,812 | <p>I have a div with <code>id="a"</code> that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works:</p>
<pre><code>$("#a").removeClass("bg*");
</code></pre>
| [
{
"answer_id": 57819,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 4,
"selected": false,
"text": "<p>You don't need any jQuery specific code to handle this. Just use a RegExp to replace them:</p>\n\n<pre><code>$(\"#a\").c... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5464/"
] | I have a div with `id="a"` that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works:
```
$("#a").removeClass("bg*");
``` | With jQuery, the actual DOM element is at index zero, this should work
```
$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');
``` |
57,840 | <p>I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code?</p>
<p>This is the wrapper that I have which calls GetData() defined in a C++ file:</p>
<pre><code> [DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl,
EntryPoint = "GetData", BestFitMapping = false)]
public static extern String GetData(String url);
</code></pre>
<p>The code is crashing and I want to investigate the root cause.</p>
<p>Thanks,
Nikhil</p>
| [
{
"answer_id": 57862,
"author": "Lou",
"author_id": 4341,
"author_profile": "https://Stackoverflow.com/users/4341",
"pm_score": 6,
"selected": true,
"text": "<p>Check the Debug tab on your project's properties page. There should be an \"Enable unmanaged code debugging\" checkbox. This wo... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5734/"
] | I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code?
This is the wrapper that I have which calls GetData() defined in a C++ file:
```
[DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl,
EntryPoint = "GetData", BestFitMapping = false)]
public static extern String GetData(String url);
```
The code is crashing and I want to investigate the root cause.
Thanks,
Nikhil | Check the Debug tab on your project's properties page. There should be an "Enable unmanaged code debugging" checkbox. This worked for me when we developed a new .NET UI for our old c++ DLLs.
If your unmanaged DLL is being built from another project (for a while ours were being built using VS6) just make sure you have the DLL's pdb file handy for the debugging.
The other approach is to use the C# exe as the target exe to run from the DLL project, you can then debug your DLL normally. |
57,849 | <p>There doesn't seem to be a way to change the padding (or row height) for all rows in a .NET ListView. Does anybody have an elegant hack-around?</p>
| [
{
"answer_id": 57975,
"author": "Joel Lucsy",
"author_id": 645,
"author_profile": "https://Stackoverflow.com/users/645",
"pm_score": 3,
"selected": false,
"text": "<p>A workaround is to use an ImageList that is as tall as you want the items to be. Just fill a blank image with the backgro... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There doesn't seem to be a way to change the padding (or row height) for all rows in a .NET ListView. Does anybody have an elegant hack-around? | I know this post is fairly old, however, if you never found the best option, I've got a [blog post](http://qdevblog.blogspot.co.uk/2011/11/c-listview-item-spacing.html) that may help, it involves utilizing LVM\_SETICONSPACING.
**According to my blog,**
Initially, you'll need to add:
```
using System.Runtime.InteropServices;
```
Next, you'll need to import the DLL, so that you can utilize SendMessage, to modify the ListView parameters.
```
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
```
Once that is complete, create the following two functions:
```
public int MakeLong(short lowPart, short highPart)
{
return (int)(((ushort)lowPart) | (uint)(highPart << 16));
}
public void ListViewItem_SetSpacing(ListView listview, short leftPadding, short topPadding)
{
const int LVM_FIRST = 0x1000;
const int LVM_SETICONSPACING = LVM_FIRST + 53;
SendMessage(listview.Handle, LVM_SETICONSPACING, IntPtr.Zero, (IntPtr)MakeLong(leftPadding, topPadding));
}
```
Then to use the function, just pass in your ListView, and set the values. In the example, 64 pixels is the image width, and 32 pixels is my horizontal spacing/padding, 100 pixels is the image height, and 16 pixels is my vertical spacing/padding, and both parameters require a minimum of 4 pixels.
```
ListViewItem_SetSpacing(this.listView1, 64 + 32, 100 + 16);
``` |
57,854 | <p>How can I close a browser window without receiving the <em>Do you want to close this window</em> prompt?</p>
<p>The prompt occurs when I use the <code>window.close();</code> function.</p>
| [
{
"answer_id": 57857,
"author": "Derek",
"author_id": 5440,
"author_profile": "https://Stackoverflow.com/users/5440",
"pm_score": -1,
"selected": false,
"text": "<p>The best solution I have found is:</p>\n\n<pre><code>this.focus();\nself.opener=this;\nself.close();\n</code></pre>\n"
},... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5440/"
] | How can I close a browser window without receiving the *Do you want to close this window* prompt?
The prompt occurs when I use the `window.close();` function. | My friend... there is a way but "hack" does not begin to describe it. You have to basically exploit a bug in IE 6 & 7.
Works every time!
Instead of calling `window.close()`, redirect to another page.
Opening Page:
```
alert("No whammies!");
window.open("closer.htm", '_self');
```
Redirect to another page. This fools IE into letting you close the browser on this page.
Closing Page:
```
<script type="text/javascript">
window.close();
</script>
```
Awesome huh?! |
57,855 | <p>I'm troubleshooting a problem with creating Vista shortcuts.</p>
<p>I want to make sure that our Installer is reading the Programs folder from the right registry key.</p>
<p>It's reading it from:</p>
<pre><code>HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Programs
</code></pre>
<p>And it's showing this directory for Programs:</p>
<pre><code>C:\Users\NonAdmin2 UAC OFF\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
</code></pre>
<p>From what I've read, this seems correct, but I wanted to double check.</p>
| [
{
"answer_id": 57866,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds correct to me.</p>\n"
},
{
"answer_id": 57869,
"author": "Tadmas",
"author_id": 3750,
"author_p... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
] | I'm troubleshooting a problem with creating Vista shortcuts.
I want to make sure that our Installer is reading the Programs folder from the right registry key.
It's reading it from:
```
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Programs
```
And it's showing this directory for Programs:
```
C:\Users\NonAdmin2 UAC OFF\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
```
From what I've read, this seems correct, but I wanted to double check. | use windows installer properties. will probably be easier.
<http://msdn.microsoft.com/en-us/library/aa370905(VS.85).aspx#system_folder_properties> |
57,912 | <p>I'm currently updating a legacy system which allows users to dictate part of the schema of one of its tables. Users can create and remove columns from the table through this interface. This legacy system is using ADO 2.8, and is using SQL Server 2005 as its database (you don't even WANT to know what database it was using before the attempt to modernize this beast began... but I digress. =) )</p>
<p>In this same editing process, users can define (and change) a list of valid values that can be stored in these user created fields (if the user wants to limit what can be in the field).</p>
<p>When the user changes the list of valid entries for a field, if they remove one of the valid values, they are allowed to choose a new "valid value" to map any rows that have this (now invalid) value in it, so that they now have a valid value again.</p>
<p>In looking through the old code, I noticed that it is extremely vulnerable to putting the system into an invalid state, because the changes mentioned above are not done within a transaction (so if someone else came along halfway through the process mentioned above and made their own changes... well, you can imagine the problems that might cause).</p>
<p>The problem is, I've been trying to get them to update under a single transaction, but whenever the code gets to the part where it changes the schema of that table, all of the other changes (updating values in rows, be it in the table where the schema changed or not... they can be completely unrelated tables even) made up to that point in the transaction appear to be silently dropped. I receive no error message indicating that they were dropped, and when I commit the transaction at the end no error is raised... but when I go to look in the tables that were supposed to be updated in the transaction, only the new columns are there. None of the non-schema changes made are saved.</p>
<p>Looking on the net for answers has, thus far, proved to be a waste of a couple hours... so I turn here for help. Has anyone ever tried to perform a transaction through ADO that both updates the schema of a table and updates rows in tables (be it that same table, or others)? Is it not allowed? Is there any documentation out there that could be helpful in this situation?</p>
<p>EDIT:</p>
<p>Okay, I did a trace, and these commands were sent to the database (explanations in parenthesis)</p>
<p><strong>(I don't know what's happening here, looks like it's creating a temporary stored procedure...?)</strong></p>
<pre><code>
declare @p1
int set @p1=180150003 declare @p3 int
set @p3=2 declare @p4 int set @p4=4
declare @p5 int set @p5=-1
</code></pre>
<p><strong>(Retreiving the table that holds definition information for the user-generated fields)</strong></p>
<pre><code>
exec sp_cursoropen @p1 output,N'SELECT * FROM CustomFieldDefs ORDER BY Sequence',@p3 output,@p4 output,@p5 output select @p1, @p3, @p4, @p5
go
</code></pre>
<p><strong>(I think my code was iterating through the list of them here, grabbing the current information)</strong></p>
<pre><code>
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,1025,1,1
go
exec sp_cursorfetch 180150003,1028,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
</code></pre>
<p><strong>(This appears to be where I'm entering the modified data for the definitions, I go through each and update any changes that occurred in the definitions for the custom fields themselves)</strong></p>
<pre><code>
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=1,@Description='asdf',@Format='U|',@IsLookUp=1,@Length=50,@Properties='U|',@Required=1,@Title='__asdf',@Type='',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=2,@Description='give',@Format='Y',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_give',@Type='B',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=3,@Description='up',@Format='###-##-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_up',@Type='N',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=4,@Description='Testy',@Format='',@IsLookUp=0,@Length=50,@Properties='',@Required=0,@Title='_Testy',@Type='',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=5,@Description='you',@Format='U|',@IsLookUp=0,@Length=250,@Properties='U|',@Required=0,@Title='_you',@Type='',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=6,@Description='never',@Format='mm/dd/yyyy',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_never',@Type='D',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=7,@Description='gonna',@Format='###-###-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_gonna',@Type='C',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
</code></pre>
<p><strong>(This is where my code removes the deleted through the interface before this saving began]... it is also the ONLY thing as far as I can tell that actually happens during this transaction)</strong> </p>
<pre><code>
ALTER TABLE CustomizableTable DROP COLUMN _weveknown;
</code></pre>
<p><strong>(Now if any of the definitions were altered in such a way that the user-created column's properties need to be changed or indexes on the columns need to be added/removed, it is done here, along with giving a default value to any rows that didn't have a value yet for the given column... note that, as far as I can tell, NONE of this actually happens when the stored procedure finishes.)</strong></p>
<p><code><pre>
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '__asdf'
go
ALTER TABLE CustomizableTable ALTER COLUMN __asdf VarChar(50) NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON CustomizableTable (
__asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF);
go
select * from IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON
CustomizableTable ( __asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF);
go
UPDATE CustomizableTable SET [__asdf] = '' WHERE [__asdf] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_give'
go
ALTER TABLE CustomizableTable ALTER COLUMN _give Bit NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__give') DROP INDEX idx__give ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_give] = 0 WHERE [_give] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_up'
go
ALTER TABLE CustomizableTable ALTER COLUMN _up Int NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__up') DROP INDEX idx__up ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_up] = 0 WHERE [_up] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_Testy'
go
ALTER TABLE CustomizableTable ADD _Testy VarChar(50) NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__Testy') DROP INDEX idx__Testy ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_Testy] = '' WHERE [_Testy] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_you'
go
ALTER TABLE CustomizableTable ALTER COLUMN _you VarChar(250) NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__you') DROP INDEX idx__you ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_you] = '' WHERE [_you] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_never'
go
ALTER TABLE CustomizableTable ALTER COLUMN _never DateTime NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__never') DROP INDEX idx__never ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_never] = '1/1/1900' WHERE [_never] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_gonna'
go
ALTER TABLE CustomizableTable ALTER COLUMN _gonna Money NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__gonna') DROP INDEX idx__gonna ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_gonna] = 0 WHERE [_gonna] IS NULL
go
</pre></code></p>
<p><strong>(Closing the Transaction...?)</strong></p>
<p><code><pre>
exec sp_cursorclose 180150003
go
</pre></code></p>
<p>After all that ado above, only the deletion of the column occurs. Everything before and after it in the transaction appears to be ignored, and there were no messages in the SQL Trace to indicate that something went wrong during the transaction.</p>
| [
{
"answer_id": 57922,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 0,
"selected": false,
"text": "<p>The behavior you describe is allowed. How is the code making the schema changes? Building SQL on the fly and executing t... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3068/"
] | I'm currently updating a legacy system which allows users to dictate part of the schema of one of its tables. Users can create and remove columns from the table through this interface. This legacy system is using ADO 2.8, and is using SQL Server 2005 as its database (you don't even WANT to know what database it was using before the attempt to modernize this beast began... but I digress. =) )
In this same editing process, users can define (and change) a list of valid values that can be stored in these user created fields (if the user wants to limit what can be in the field).
When the user changes the list of valid entries for a field, if they remove one of the valid values, they are allowed to choose a new "valid value" to map any rows that have this (now invalid) value in it, so that they now have a valid value again.
In looking through the old code, I noticed that it is extremely vulnerable to putting the system into an invalid state, because the changes mentioned above are not done within a transaction (so if someone else came along halfway through the process mentioned above and made their own changes... well, you can imagine the problems that might cause).
The problem is, I've been trying to get them to update under a single transaction, but whenever the code gets to the part where it changes the schema of that table, all of the other changes (updating values in rows, be it in the table where the schema changed or not... they can be completely unrelated tables even) made up to that point in the transaction appear to be silently dropped. I receive no error message indicating that they were dropped, and when I commit the transaction at the end no error is raised... but when I go to look in the tables that were supposed to be updated in the transaction, only the new columns are there. None of the non-schema changes made are saved.
Looking on the net for answers has, thus far, proved to be a waste of a couple hours... so I turn here for help. Has anyone ever tried to perform a transaction through ADO that both updates the schema of a table and updates rows in tables (be it that same table, or others)? Is it not allowed? Is there any documentation out there that could be helpful in this situation?
EDIT:
Okay, I did a trace, and these commands were sent to the database (explanations in parenthesis)
**(I don't know what's happening here, looks like it's creating a temporary stored procedure...?)**
```
declare @p1
int set @p1=180150003 declare @p3 int
set @p3=2 declare @p4 int set @p4=4
declare @p5 int set @p5=-1
```
**(Retreiving the table that holds definition information for the user-generated fields)**
```
exec sp_cursoropen @p1 output,N'SELECT * FROM CustomFieldDefs ORDER BY Sequence',@p3 output,@p4 output,@p5 output select @p1, @p3, @p4, @p5
go
```
**(I think my code was iterating through the list of them here, grabbing the current information)**
```
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursorfetch 180150003,1025,1,1
go
exec sp_cursorfetch 180150003,1028,1,1
go
exec sp_cursorfetch 180150003,32,1,1
go
```
**(This appears to be where I'm entering the modified data for the definitions, I go through each and update any changes that occurred in the definitions for the custom fields themselves)**
```
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=1,@Description='asdf',@Format='U|',@IsLookUp=1,@Length=50,@Properties='U|',@Required=1,@Title='__asdf',@Type='',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=2,@Description='give',@Format='Y',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_give',@Type='B',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=3,@Description='up',@Format='###-##-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_up',@Type='N',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=4,@Description='Testy',@Format='',@IsLookUp=0,@Length=50,@Properties='',@Required=0,@Title='_Testy',@Type='',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=5,@Description='you',@Format='U|',@IsLookUp=0,@Length=250,@Properties='U|',@Required=0,@Title='_you',@Type='',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=6,@Description='never',@Format='mm/dd/yyyy',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_never',@Type='D',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
exec sp_cursor 180150003,33,1,N'[CustomFieldDefs]',@Sequence=7,@Description='gonna',@Format='###-###-####',@IsLookUp=0,@Length=0,@Properties='',@Required=0,@Title='_gonna',@Type='C',@_Version=1
go
exec sp_cursorfetch 180150003,32,1,1
go
```
**(This is where my code removes the deleted through the interface before this saving began]... it is also the ONLY thing as far as I can tell that actually happens during this transaction)**
```
ALTER TABLE CustomizableTable DROP COLUMN _weveknown;
```
**(Now if any of the definitions were altered in such a way that the user-created column's properties need to be changed or indexes on the columns need to be added/removed, it is done here, along with giving a default value to any rows that didn't have a value yet for the given column... note that, as far as I can tell, NONE of this actually happens when the stored procedure finishes.)**
````
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '__asdf'
go
ALTER TABLE CustomizableTable ALTER COLUMN __asdf VarChar(50) NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON CustomizableTable (
__asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF);
go
select * from IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx___asdf') CREATE NONCLUSTERED INDEX idx___asdf ON
CustomizableTable ( __asdf ASC) WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF);
go
UPDATE CustomizableTable SET [__asdf] = '' WHERE [__asdf] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_give'
go
ALTER TABLE CustomizableTable ALTER COLUMN _give Bit NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__give') DROP INDEX idx__give ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_give] = 0 WHERE [_give] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_up'
go
ALTER TABLE CustomizableTable ALTER COLUMN _up Int NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__up') DROP INDEX idx__up ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_up] = 0 WHERE [_up] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_Testy'
go
ALTER TABLE CustomizableTable ADD _Testy VarChar(50) NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__Testy') DROP INDEX idx__Testy ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_Testy] = '' WHERE [_Testy] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_you'
go
ALTER TABLE CustomizableTable ALTER COLUMN _you VarChar(250) NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__you') DROP INDEX idx__you ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_you] = '' WHERE [_you] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_never'
go
ALTER TABLE CustomizableTable ALTER COLUMN _never DateTime NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__never') DROP INDEX idx__never ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_never] = '1/1/1900' WHERE [_never] IS NULL
go
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'CustomizableTable') AND name = '_gonna'
go
ALTER TABLE CustomizableTable ALTER COLUMN _gonna Money NULL
go
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomizableTable]') AND name = N'idx__gonna') DROP INDEX idx__gonna ON CustomizableTable WITH ( ONLINE = OFF );
go
UPDATE CustomizableTable SET [_gonna] = 0 WHERE [_gonna] IS NULL
go
````
**(Closing the Transaction...?)**
````
exec sp_cursorclose 180150003
go
````
After all that ado above, only the deletion of the column occurs. Everything before and after it in the transaction appears to be ignored, and there were no messages in the SQL Trace to indicate that something went wrong during the transaction. | The code is using a server-side cursor, that's what those calls are for. The first set of calls is preparing/opening the cursor. Then fetching rows from the cursor. Finally closing the cursor. Those sprocs are analogous to the OPEN CURSOR, FETCH NEXT, CLOSE CURSOR T-SQL statements.
I'd have to take a closer look (which I will), but my guess is there is something going on with the server-side cursor, the encapsulating transaction, and the DDL.
Some more questions:
1. Are you meaning to use server-side cursors in this case?
2. Are the ADO Commands all using the same active connection?
**Update:**
I'm not exactly sure what's going on.
It looks like you're using server-side cursors so you can use Recordset.Update() to push changes back to the server, in addition to executing generated SQL statements to alter schema and update data in the dynamic table(s). Using the same connection, inside an explicit transaction.
I'm not sure what effect the cursor operations will have on the rest of the transaction, or vice-versa, and to be honest I'm surprised this isn't working.
I don't know how large of a change it would be, but I would recommend moving away from the server-side cursors and building the UPDATE statements for your table updates.
Sorry I couldn't be of more help.
BTW- I found the following information on the sp\_cursor calls:
<http://jtds.sourceforge.net/apiCursors.html> |
57,918 | <p>We have a whole bunch of queries that "search" for clients, customers, etc. You can search by first name, email, etc. We're using LIKE statements in the following manner: </p>
<pre><code>SELECT *
FROM customer
WHERE fname LIKE '%someName%'
</code></pre>
<p>Does full-text indexing help in the scenario? We're using SQL Server 2005.</p>
| [
{
"answer_id": 57930,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 6,
"selected": true,
"text": "<p>It will depend upon your DBMS. I believe that most systems will not take advantage of the full-text index unless you use ... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] | We have a whole bunch of queries that "search" for clients, customers, etc. You can search by first name, email, etc. We're using LIKE statements in the following manner:
```
SELECT *
FROM customer
WHERE fname LIKE '%someName%'
```
Does full-text indexing help in the scenario? We're using SQL Server 2005. | It will depend upon your DBMS. I believe that most systems will not take advantage of the full-text index unless you use the full-text functions. (e.g. [MATCH/AGAINST](http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html) in mySQL or FREETEXT/CONTAINS in MS SQL)
Here is two good articles on when, why, and how to use full-text indexing in SQL Server:
1. [How To Use SQL Server Full-Text Searching](https://www.developer.com/database/sql-server-full-text-searching/)
2. [Solving Complex SQL Problems with Full-Text Indexing](https://www.developer.com/guides/solving-complex-sql-problems-with-full-text-indexing/) |
57,927 | <p>I have an excel spreadsheet in a format similar to the following...</p>
<pre><code>| NAME | CLUB | STATUS | SCORE |
| Fred | a | Gent | 145 |
| Bert | a | Gent | 150 |
| Harry | a | Gent | 195 |
| Jim | a | Gent | 150 |
| Clare | a | Lady | 99 |
| Simon | a | Junior | 130 |
| John | b | Junior | 130 |
:
:
| Henry | z | Gent | 200 |
</code></pre>
<p>I need to convert this table into a list of the "Top Ten" teams. The rules are</p>
<ul>
<li>Each team score is taken from the sum of four members of that club.</li>
<li>These totals should be of the best four scores except...
<ul>
<li>Each team must consist of at least one Junior or Lady</li>
</ul></li>
</ul>
<p>For example in the table above the team score for club A would be 625 <strong>not</strong> 640 as you would take the scores for Harry(190), Bert(150), Jim(150), and Simon(130). You could not take Fred's(145) score as that would give you only Gents.</p>
<p>My question is, can this be done easily as a series of Excel formula, or will I need to resort to using something more procedural?</p>
<p>Ideally the solution needs to be automatic in the team selections, I don't want to have to create separate hand crafted formula for each team. I also will not necessarily have a neatly ordered list of each clubs members. Although I could probably generate the list via an extra calculation sheet.</p>
| [
{
"answer_id": 57955,
"author": "Knox",
"author_id": 4873,
"author_profile": "https://Stackoverflow.com/users/4873",
"pm_score": 0,
"selected": false,
"text": "<p>Use a pivot table which will act as a database query on the data you have. Pivot so that the teams go down the columns and t... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3720/"
] | I have an excel spreadsheet in a format similar to the following...
```
| NAME | CLUB | STATUS | SCORE |
| Fred | a | Gent | 145 |
| Bert | a | Gent | 150 |
| Harry | a | Gent | 195 |
| Jim | a | Gent | 150 |
| Clare | a | Lady | 99 |
| Simon | a | Junior | 130 |
| John | b | Junior | 130 |
:
:
| Henry | z | Gent | 200 |
```
I need to convert this table into a list of the "Top Ten" teams. The rules are
* Each team score is taken from the sum of four members of that club.
* These totals should be of the best four scores except...
+ Each team must consist of at least one Junior or Lady
For example in the table above the team score for club A would be 625 **not** 640 as you would take the scores for Harry(190), Bert(150), Jim(150), and Simon(130). You could not take Fred's(145) score as that would give you only Gents.
My question is, can this be done easily as a series of Excel formula, or will I need to resort to using something more procedural?
Ideally the solution needs to be automatic in the team selections, I don't want to have to create separate hand crafted formula for each team. I also will not necessarily have a neatly ordered list of each clubs members. Although I could probably generate the list via an extra calculation sheet. | ```
Public Function TopTen(Club As String, Scores As Range)
Dim i As Long
Dim vaScores As Variant
Dim bLady As Boolean
Dim lCnt As Long
Dim lTotal As Long
vaScores = FilterOnClub(Scores.Value, Club)
vaScores = SortOnScore(vaScores)
For i = LBound(vaScores, 2) To UBound(vaScores, 2)
If lCnt = 3 And Not bLady Then
If vaScores(3, i) <> "Gent" Then
lTotal = lTotal + vaScores(4, i)
bLady = True
lCnt = lCnt + 1
End If
Else
lTotal = lTotal + vaScores(4, i)
lCnt = lCnt + 1
If vaScores(3, i) <> "Gent" Then bLady = True
End If
If lCnt = 4 Then Exit For
Next i
TopTen = lTotal
End Function
Private Function FilterOnClub(vaScores As Variant, sClub As String) As Variant
Dim i As Long, j As Long
Dim aTemp() As Variant
For i = LBound(vaScores, 1) To UBound(vaScores, 1)
If vaScores(i, 2) = sClub Then
j = j + 1
ReDim Preserve aTemp(1 To 4, 1 To j)
aTemp(1, j) = vaScores(i, 1)
aTemp(2, j) = vaScores(i, 2)
aTemp(3, j) = vaScores(i, 3)
aTemp(4, j) = vaScores(i, 4)
End If
Next i
FilterOnClub = aTemp
End Function
Private Function SortOnScore(vaScores As Variant) As Variant
Dim i As Long, j As Long, k As Long
Dim aTemp(1 To 4) As Variant
For i = 1 To UBound(vaScores, 2) - 1
For j = i To UBound(vaScores, 2)
If vaScores(4, i) < vaScores(4, j) Then
For k = 1 To 4
aTemp(k) = vaScores(k, j)
vaScores(k, j) = vaScores(k, i)
vaScores(k, i) = aTemp(k)
Next k
End If
Next j
Next i
SortOnScore = vaScores
End Function
```
Use as `=TopTen(H2,$B$2:$E$30)` where `H2` contains the club letter. |
57,947 | <p>I'm really confused by the various configuration options for .Net configuration of dll's, ASP.net websites etc in .Net v2 - especially when considering the impact of a config file at the UI / end-user end of the chain.</p>
<p>So, for example, some of the applications I work with use settings which we access with:</p>
<pre><code>string blah = AppLib.Properties.Settings.Default.TemplatePath;
</code></pre>
<p>Now, this option seems cool because the members are stongly typed, and I won't be able to type in a property name that doesn't exist in the Visual Studio 2005 IDE. We end up with lines like this in the App.Config of a command-line executable project:</p>
<pre><code><connectionStrings>
<add name="AppConnectionString" connectionString="XXXX" />
<add name="AppLib.Properties.Settings.AppConnectionString" connectionString="XXXX" />
</connectionStrings>
</code></pre>
<p>(If we don't have the second setting, someone releasing a debug dll to the live box could have built with the debug connection string embedded in it - eek)</p>
<p>We also have settings accessed like this:</p>
<pre><code>string blah = System.Configuration.ConfigurationManager.AppSettings["TemplatePath_PDF"];
</code></pre>
<p>Now, these seem cool because we can access the setting from the dll code, or the exe / aspx code, and all we need in the Web or App.config is:</p>
<pre><code><appSettings>
<add key="TemplatePath_PDF" value="xxx"/>
</appSettings>
</code></pre>
<p>However, the value of course may not be set in the config files, or the string name may be mistyped, and so we have a different set of problems.</p>
<p>So... if my understanding is correct, the former methods give strong typing but bad sharing of values between the dll and other projects. The latter provides better sharing, but weaker typing.</p>
<p>I feel like I must be missing something. For the moment, I'm not even concerned with the application being able to write-back values to the configuration files, encryption or anything like that. Also, I had decided that the best way to store any non-connection strings was in the DB... and then the very next thing that I have to do is store phone numbers to text people in case of DB connection issues, so they must be stored outside the DB!</p>
| [
{
"answer_id": 57953,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<p>I think your confusion comes from the fact that it looks like your first example is a home-brewed library, not part of .NE... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6004/"
] | I'm really confused by the various configuration options for .Net configuration of dll's, ASP.net websites etc in .Net v2 - especially when considering the impact of a config file at the UI / end-user end of the chain.
So, for example, some of the applications I work with use settings which we access with:
```
string blah = AppLib.Properties.Settings.Default.TemplatePath;
```
Now, this option seems cool because the members are stongly typed, and I won't be able to type in a property name that doesn't exist in the Visual Studio 2005 IDE. We end up with lines like this in the App.Config of a command-line executable project:
```
<connectionStrings>
<add name="AppConnectionString" connectionString="XXXX" />
<add name="AppLib.Properties.Settings.AppConnectionString" connectionString="XXXX" />
</connectionStrings>
```
(If we don't have the second setting, someone releasing a debug dll to the live box could have built with the debug connection string embedded in it - eek)
We also have settings accessed like this:
```
string blah = System.Configuration.ConfigurationManager.AppSettings["TemplatePath_PDF"];
```
Now, these seem cool because we can access the setting from the dll code, or the exe / aspx code, and all we need in the Web or App.config is:
```
<appSettings>
<add key="TemplatePath_PDF" value="xxx"/>
</appSettings>
```
However, the value of course may not be set in the config files, or the string name may be mistyped, and so we have a different set of problems.
So... if my understanding is correct, the former methods give strong typing but bad sharing of values between the dll and other projects. The latter provides better sharing, but weaker typing.
I feel like I must be missing something. For the moment, I'm not even concerned with the application being able to write-back values to the configuration files, encryption or anything like that. Also, I had decided that the best way to store any non-connection strings was in the DB... and then the very next thing that I have to do is store phone numbers to text people in case of DB connection issues, so they must be stored outside the DB! | Nij, our difference in thinking comes from our different perspectives. I'm thinking about developing enterprise apps that predominantly use WinForms clients. In this instance the business logic is contained on an application server. Each client would need to know the phone number to dial, but placing it in the App.config of each client poses a problem if that phone number changes. In that case it seems obvious to store application configuration information (or application wide settings) in a database and have each client read the settings from there.
The other, .NET way, (I make the distinction because we have, in the pre .NET days, stored application settings in DB tables) is to store application settings in the app.config file and access via way of the generated Settings class.
I digress. Your situation sounds different. If all different apps are on the same server, you could place the settings in a web.config at a higher level. However if they are not, you could also have a seperate "configuration service" that all three applications talk to get their shared settings. At least in this solution you're not replicating the code in three places, raising the potential of maintenance problems when adding settings. Sounds a bit over engineered though.
My personal preference is to use strong typed settings. I actually generate my own strongly typed settings class based on what it's my settings table in the database. That way I can have the best of both worlds. Intellisense to my settings and settings stored in the db (note: that's in the case where there's no app server).
I'm interested in learning other peoples strategies for this too :) |
57,958 | <p>I like HtmlControls because there is no HTML magic going on... the asp source looks similar to what the client sees. </p>
<p>I can't argue with the utility of GridView, Repeater, CheckBoxLists, etc, so I use them when I need that functionality. </p>
<p>Also, it looks weird to have code that mixes and matches:</p>
<pre><code><asp:Button id='btnOK' runat='server' Text='OK' />
<input id='btnCancel' runat='server' type='button' value='Cancel' />
</code></pre>
<p>(The above case in the event you wanted to bind a server-side event listener to OK but Cancel just runs a javascript that hides the current div)</p>
<p>Is there some definitive style guide out there? Should HtmlControls just be avoided? </p>
| [
{
"answer_id": 57961,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>well... i wouldn't use an html control if you don't need to do anything on it on the server. i would do</p>\n\n<pre><code>... | 2008/09/11 | [
"https://Stackoverflow.com/questions/57958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4435/"
] | I like HtmlControls because there is no HTML magic going on... the asp source looks similar to what the client sees.
I can't argue with the utility of GridView, Repeater, CheckBoxLists, etc, so I use them when I need that functionality.
Also, it looks weird to have code that mixes and matches:
```
<asp:Button id='btnOK' runat='server' Text='OK' />
<input id='btnCancel' runat='server' type='button' value='Cancel' />
```
(The above case in the event you wanted to bind a server-side event listener to OK but Cancel just runs a javascript that hides the current div)
Is there some definitive style guide out there? Should HtmlControls just be avoided? | It might be useful to think of HTML controls as an option when you want more control over the mark up that ends up getting emitted by your page. More control in the sense that you want EVERY browser to see exactly the same markup.
If you create System.Web.UI.HtmlControls like:
```
<input id='btnCancel' runat='server' type='button' value='Cancel' />
```
Then you know what kind of code is going to be emitted. Even though most of the time:
```
<asp:Button id='btnCancel' runat='server' Text='Cancel' />
```
will end up being the same markup. The same markup is not always emitted for all WebControls. Many WebControls have built in adaptive rendering that will render different HTML based on the browser user agent. As an example a DataGrid will look quite different in a mobile browser than it will in a desktop browser.
Using WebControls as opposed to HtmlControls also lets you take advantage of [ASP.NET v2.0 ControlAdapters](http://msdn.microsoft.com/en-us/library/67276kc5.aspx) which I believe only works with WebControls, this will allow you programatic config driven control over the markup that gets emitted.
This might seem more valuable when you consider that certain mobile browsers or WebTVs are going to want WML or completely different sets of markups. |
57,987 | <p>Does anyone know how to write to an excel file (.xls) via OLEDB in C#? I'm doing the following:</p>
<pre><code> OleDbCommand dbCmd = new OleDbCommand("CREATE TABLE [test$] (...)", connection);
dbCmd.CommandTimeout = mTimeout;
results = dbCmd.ExecuteNonQuery();
</code></pre>
<p>But I get an OleDbException thrown with message:</p>
<blockquote>
<p>"Cannot modify the design of table
'test$'. It is in a read-only
database."</p>
</blockquote>
<p>My connection seems fine and I can select data fine but I can't seem to insert data into the excel file, does anyone know how I get read/write access to the excel file via OLEDB?</p>
| [
{
"answer_id": 58162,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 1,
"selected": false,
"text": "<p>A couple questions: </p>\n\n<ul>\n<li>Does the user that executes your app (you?) have permission to write to the file? ... | 2008/09/12 | [
"https://Stackoverflow.com/questions/57987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39040/"
] | Does anyone know how to write to an excel file (.xls) via OLEDB in C#? I'm doing the following:
```
OleDbCommand dbCmd = new OleDbCommand("CREATE TABLE [test$] (...)", connection);
dbCmd.CommandTimeout = mTimeout;
results = dbCmd.ExecuteNonQuery();
```
But I get an OleDbException thrown with message:
>
> "Cannot modify the design of table
> 'test$'. It is in a read-only
> database."
>
>
>
My connection seems fine and I can select data fine but I can't seem to insert data into the excel file, does anyone know how I get read/write access to the excel file via OLEDB? | You need to add `ReadOnly=False;` to your connection string
```
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=fifa_ng_db.xls;Mode=ReadWrite;ReadOnly=false;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";
``` |
58,024 | <p>I'm trying to provide a link to my company's website from a Windows Form. I want to be well behaved and launch using the user's preferred browser.</p>
<p>What is the best way to open a URL in the user's default browser from a Windows Forms application?</p>
| [
{
"answer_id": 58032,
"author": "Aaron Wagner",
"author_id": 3909,
"author_profile": "https://Stackoverflow.com/users/3909",
"pm_score": 5,
"selected": false,
"text": "<pre><code>using System.Diagnostics;\n\nProcess.Start(\"http://www.google.com/\");\n</code></pre>\n\n<p>This approach ha... | 2008/09/12 | [
"https://Stackoverflow.com/questions/58024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148/"
] | I'm trying to provide a link to my company's website from a Windows Form. I want to be well behaved and launch using the user's preferred browser.
What is the best way to open a URL in the user's default browser from a Windows Forms application? | This [article](http://support.microsoft.com/kb/320478) will walk you through it.
Short answer:
```
ProcessStartInfo sInfo = new ProcessStartInfo("http://mysite.com/");
Process.Start(sInfo);
``` |
58,054 | <p>I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.</p>
| [
{
"answer_id": 58060,
"author": "parkerfath",
"author_id": 6027,
"author_profile": "https://Stackoverflow.com/users/6027",
"pm_score": 7,
"selected": true,
"text": "<p>Here is a solution I found. It doesn't seem very elegant, though:</p>\n\n<pre><code><%@ taglib prefix=\"fn\" uri=\"ht... | 2008/09/12 | [
"https://Stackoverflow.com/questions/58054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6027/"
] | I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility. | Here is a solution I found. It doesn't seem very elegant, though:
```
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<% pageContext.setAttribute("newLineChar", "\n"); %>
${fn:replace(item.comments, newLineChar, "; ")}
``` |
58,070 | <p>I remember back when MS released a forum sample application, the design of the application was like this:</p>
<p>/Classes/User.cs
/Classes/Post.cs
...
/Users.cs
/Posts.cs</p>
<p>So the classes folder had just the class i.e. properties and getters/setters.
The Users.cs, Post.cs, etc. have the actual methods that access the Data Access Layer, so Posts.cs might look like:</p>
<pre><code>public class Posts
{
public static Post GetPostByID(int postID)
{
SqlDataProvider dp = new SqlDataProvider();
return dp.GetPostByID(postID);
}
}
</code></pre>
<p>Another more traditional route would be to put all of the methods in Posts.cs into the class definition also (Post.cs).</p>
<p>Splitting things into 2 files makes it much more procedural doesn't it?
Isn't this breaking OOP rules since it is taking the behavior out of the class and putting it into another class definition?</p>
| [
{
"answer_id": 58080,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure the classes aren't partial classes. In which case they really aren't two classes, just a single class spre... | 2008/09/12 | [
"https://Stackoverflow.com/questions/58070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | I remember back when MS released a forum sample application, the design of the application was like this:
/Classes/User.cs
/Classes/Post.cs
...
/Users.cs
/Posts.cs
So the classes folder had just the class i.e. properties and getters/setters.
The Users.cs, Post.cs, etc. have the actual methods that access the Data Access Layer, so Posts.cs might look like:
```
public class Posts
{
public static Post GetPostByID(int postID)
{
SqlDataProvider dp = new SqlDataProvider();
return dp.GetPostByID(postID);
}
}
```
Another more traditional route would be to put all of the methods in Posts.cs into the class definition also (Post.cs).
Splitting things into 2 files makes it much more procedural doesn't it?
Isn't this breaking OOP rules since it is taking the behavior out of the class and putting it into another class definition? | If every method is just a static call straight to the data source, then the "Posts" class is really a Factory. You could certainly put the static methods in "Posts" into the "Post" class (this is how CSLA works), but they are still factory methods.
I would say that a more modern and accurate name for the "Posts" class would be "PostFactory" (assuming that all it has is static methods).
I guess I wouldn't say this is a "procedural" approach necessarily -- it's just a misleading name, you would assume in the modern OO world that a "Posts" object would be stateful and provide methods to manipulate and manage a set of "Post" objects. |
58,119 | <p>I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are? </p>
| [
{
"answer_id": 58129,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": true,
"text": "<p>Well, <code>re.compile</code> certainly may:</p>\n\n<pre><code>>>> import re\n>>> re.compile('he(lo'... | 2008/09/12 | [
"https://Stackoverflow.com/questions/58119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1892/"
] | I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are? | Well, `re.compile` certainly may:
```
>>> import re
>>> re.compile('he(lo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python25\lib\re.py", line 180, in compile
return _compile(pattern, flags)
File "C:\Python25\lib\re.py", line 233, in _compile
raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis
```
[The documentation](https://web.archive.org/web/20080913142948/http://docs.python.org/lib/node46.html) does support this, in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the `error` exception.
Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to [decompile](https://web.archive.org/web/20081004235506/http://www.depython.net/) them (if written in Python) or even [look at the source](http://www.python.org/download/), if they're in the standard library. |
58,123 | <p>This is actually a two part question. First,does the HttpContext.Current correspond to the current System.UI.Page object?</p>
<p>And the second question, which is probably related to the first, is why can't I use the following to see if the current page implements an interface:</p>
<pre><code>private IWebBase FindWebBase()
{
if (HttpContext.Current as IWebBase != null)
{
return (IWebBase)HttpContext.Current.;
}
throw new NotImplementedException("Crawling for IWebBase not implemented yet");
}
</code></pre>
<p>The general context is that some controls need to know whether they are executing as a SharePoint webpart, or as part of an Asp.Net framework.</p>
<p>I have solved the problem by requiring the control to pass a reference to itself, and checking the Page property of the control, but I'm still curious why the above does not work.</p>
<p>The compiler error is:
Cannot convert System.Web.HttpContext to ...IWebBase via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion or null type conversion.</p>
| [
{
"answer_id": 58128,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 5,
"selected": false,
"text": "<p>You're looking for <code>HttpContext.Handler</code>. Since Page implements IHttpHandler, you'll obtain a reference to th... | 2008/09/12 | [
"https://Stackoverflow.com/questions/58123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1685/"
] | This is actually a two part question. First,does the HttpContext.Current correspond to the current System.UI.Page object?
And the second question, which is probably related to the first, is why can't I use the following to see if the current page implements an interface:
```
private IWebBase FindWebBase()
{
if (HttpContext.Current as IWebBase != null)
{
return (IWebBase)HttpContext.Current.;
}
throw new NotImplementedException("Crawling for IWebBase not implemented yet");
}
```
The general context is that some controls need to know whether they are executing as a SharePoint webpart, or as part of an Asp.Net framework.
I have solved the problem by requiring the control to pass a reference to itself, and checking the Page property of the control, but I'm still curious why the above does not work.
The compiler error is:
Cannot convert System.Web.HttpContext to ...IWebBase via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion or null type conversion. | No, from MSDN on HttpContext.Current: "Gets or sets the HttpContext object for the current HTTP request."
In other words it is an HttpContext object, not a Page.
You can get to the Page object via HttpContext using:
```
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
// Use page instance.
}
``` |
58,207 | <p>To create a playlist for all of the music in a folder, I am using the following command in bash:</p>
<pre><code>ls > list.txt
</code></pre>
<p>I would like to use the result of the <code>pwd</code> command for the name of the playlist.</p>
<p>Something like:</p>
<pre><code>ls > ${pwd}.txt
</code></pre>
<p>That doesn't work though - can anyone tell me what syntax I need to use to do something like this?</p>
<p><strong>Edit:</strong> As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went!</p>
| [
{
"answer_id": 58212,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 8,
"selected": true,
"text": "<p>The best way to do this is with <code>\"$(command substitution)\"</code> (thanks, <a href=\"https://stackoverflow.com... | 2008/09/12 | [
"https://Stackoverflow.com/questions/58207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/840/"
] | To create a playlist for all of the music in a folder, I am using the following command in bash:
```
ls > list.txt
```
I would like to use the result of the `pwd` command for the name of the playlist.
Something like:
```
ls > ${pwd}.txt
```
That doesn't work though - can anyone tell me what syntax I need to use to do something like this?
**Edit:** As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went! | The best way to do this is with `"$(command substitution)"` (thanks, [Landon](https://stackoverflow.com/a/58233/1899640)):
```
ls > "$(pwd).txt"
```
You will sometimes also see people use the older backtick notation, but this has [several drawbacks](https://stackoverflow.com/questions/4708549/what-is-the-difference-between-command-and-command-in-shell-programming) in terms of nesting and escaping:
```
ls > "`pwd`.txt"
```
Note that the unprocessed substitution of `pwd` is an absolute path, so the above command creates a file with the same name in the same directory as the working directory, but with a `.txt` extension. Thomas Kammeyer pointed out that the `basename` command strips the leading directory, so this would create a text file in the current directory with the name of that directory:
```
ls > "$(basename "$(pwd)").txt"
```
Also thanks to erichui for bringing up the problem of spaces in the path. |