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 |
|---|---|---|---|---|---|---|
8,800 | <p>So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable?</p>
<pre><code>public class TokenTree
{
public TokenTree()
{
/* I must admit to not fully understanding this,
* I got it from msdn. As far as I can tell, IDictionary is an
* interface, and Dictionary is the default implementation of
* that interface, right?
*/
SubPairs = new Dictionary<string, string>();
}
public string Key;
public string Value;
public IDictionary<string, string> SubPairs;
}
</code></pre>
<p>It's only really a simple shunt for passing around data.</p>
| [
{
"answer_id": 8811,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 8,
"selected": true,
"text": "<p>There is an actual Data Type called KeyValuePair, use like this</p>\n\n<pre><code>KeyValuePair<string, string> myKeyV... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable?
```
public class TokenTree
{
public TokenTree()
{
/* I must admit to not fully understanding this,
* I got it from msdn. As far as I can tell, IDictionary is an
* interface, and Dictionary is the default implementation of
* that interface, right?
*/
SubPairs = new Dictionary<string, string>();
}
public string Key;
public string Value;
public IDictionary<string, string> SubPairs;
}
```
It's only really a simple shunt for passing around data. | There is an actual Data Type called KeyValuePair, use like this
```
KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue");
``` |
8,832 | <p>I hope I can explain this clearly enough, but if not let me know and I'll try to clarify.</p>
<p>I'm currently developing a site using ColdFusion and have a mod_rewrite rule in place to make it look like the site is using PHP. Any requests for index.php get processed by index.cfm (the rule maps *.php to *.cfm).</p>
<p>This works great - so far, so good. The problem is that I want to return a 404 status code if index.cfm (or any ColdFusion page) is requested directly.</p>
<p>If I try to block access to *.cfm files using mod_rewrite it also returns a 404 for requests to *.php.</p>
<p>I figure I might have to change my Apache config rather than use .htaccess</p>
| [
{
"answer_id": 8861,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 0,
"selected": false,
"text": "<p>Post the rules you already have as a starting point so people don't have to recreate it to help you.</p>\n\n<p>I would suggest t... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1025/"
] | I hope I can explain this clearly enough, but if not let me know and I'll try to clarify.
I'm currently developing a site using ColdFusion and have a mod\_rewrite rule in place to make it look like the site is using PHP. Any requests for index.php get processed by index.cfm (the rule maps \*.php to \*.cfm).
This works great - so far, so good. The problem is that I want to return a 404 status code if index.cfm (or any ColdFusion page) is requested directly.
If I try to block access to \*.cfm files using mod\_rewrite it also returns a 404 for requests to \*.php.
I figure I might have to change my Apache config rather than use .htaccess | You can use the `S` flag to skip the `404` rule, like this:
```
RewriteEngine on
# Do not separate these two rules so long as the first has S=1
RewriteRule (.*)\.php$ $1.cfm [S=1]
RewriteRule \.cfm$ - [R=404]
```
If you are also using the `Alias` option then you should also add the `PT` flag. See the [mod\_rewrite documentation](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html) for details. |
8,880 | <p>Using the Windows API, how can I get a list of domains on my network?</p>
| [
{
"answer_id": 8881,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>Answered my own question:</p>\n\n<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/aa370623(VS.85).aspx\" rel... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] | Using the Windows API, how can I get a list of domains on my network? | You will need to use some LDAP queries
Here is some code I have used in a previous script (it was taken off the net somewhere, and I've left in the copyright notices)
-------------------------------------------------------------------------------------------------------------------------------
```
' This VBScript code gets the list of the domains contained in the
' forest that the user running the script is logged into
' ---------------------------------------------------------------
' From the book "Active Directory Cookbook" by Robbie Allen
' Publisher: O'Reilly and Associates
' ISBN: 0-596-00466-4
' Book web site: http://rallenhome.com/books/adcookbook/code.html
' ---------------------------------------------------------------
set objRootDSE = GetObject("LDAP://RootDSE")
strADsPath = "<GC://" & objRootDSE.Get("rootDomainNamingContext") & ">;"
strFilter = "(objectcategory=domainDNS);"
strAttrs = "name;"
strScope = "SubTree"
set objConn = CreateObject("ADODB.Connection")
objConn.Provider = "ADsDSOObject"
objConn.Open "Active Directory Provider"
set objRS = objConn.Execute(strADsPath & strFilter & strAttrs & strScope)
objRS.MoveFirst
while Not objRS.EOF
Wscript.Echo objRS.Fields(0).Value
objRS.MoveNext
wend
```
---
[Also a C# version](http://www.janus-net.de/2005/11/18/getting-list-of-sub-domains-from-active-directory-with-c/) |
8,941 | <p><strong>Is there a way to enforce/limit the types that are passed to primitives?</strong> <em>(bool, int, string, etc.)</em></p>
<p>Now, I know you can limit the generic type parameter to a type or interface implementation via the <em>where</em> clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from <em>object</em> before someone says! :P).</p>
<p>So, my current thoughts are to just grit my teeth and do a big <em>switch</em> statement and throw an <em>ArgumentException</em> on failure.</p>
<hr />
<p><strong>EDIT 1:</strong></p>
<p>Just to clarify:</p>
<p>The code definition should be like this:</p>
<pre><code>public class MyClass<GenericType> ....
</code></pre>
<p>And instantiation:</p>
<pre><code>MyClass<bool> = new MyClass<bool>(); // Legal
MyClass<string> = new MyClass<string>(); // Legal
MyClass<DataSet> = new MyClass<DataSet>(); // Illegal
MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!)
</code></pre>
<hr />
<p><strong>EDIT 2</strong></p>
<p>@Jon Limjap - Good point, and something I was already considering. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type.</p>
<p>This could be useful in instantly removing a lot of the objects I don't want to deal with (but then you need to worry about the structs that are used such as <em>Size</em> ). Interesting problem no? :)</p>
<p>Here it is:</p>
<pre><code>where T: struct
</code></pre>
<p>Taken from <a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx" rel="nofollow noreferrer">MSDN</a>.</p>
<hr />
<p>I'm curious. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code.</p>
<p>What do you guys think?</p>
<p>The sad news is I am working in Framework 2!! :D</p>
<hr />
<p><strong>EDIT 3</strong></p>
<p>This was so simple following on from <a href="https://stackoverflow.com/questions/8941/generic-type-checking#8956">Jon Limjaps Pointer</a>.. So simple I almost want to cry, but it's great because the code works like a charm!</p>
<p>So here is what I did (you'll laugh!):</p>
<h2>Code added to the generic class</h2>
<pre><code>bool TypeValid()
{
// Get the TypeCode from the Primitive Type
TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType));
// All of the TypeCode Enumeration refer Primitive Types
// with the exception of Object and Empty (Null).
// Since I am willing to allow Null Types (at this time)
// all we need to check for is Object!
switch (code)
{
case TypeCode.Object:
return false;
default:
return true;
}
}
</code></pre>
<p>Then a little utility method to check the type and throw an exception,</p>
<pre><code>private void EnforcePrimitiveType()
{
if (!TypeValid())
throw new InvalidOperationException(
"Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name +
"' - this Class is Designed to Work with Primitive Data Types Only.");
}
</code></pre>
<p>All that then needs to be done is to call <em>EnforcePrimitiveType()</em> in the classes constructors. Job done! :-)</p>
<p>The only downside, it only throws an exception at runtime (obviously) rather than design time. But that's no big deal and could be picked up with utilities like <a href="http://en.wikipedia.org/wiki/FxCop" rel="nofollow noreferrer">FxCop</a> (which we don't use at work).</p>
<p>Special thanks to Jon Limjap on this one!</p>
| [
{
"answer_id": 8945,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 6,
"selected": false,
"text": "<pre><code>public class Class1<GenericType> where GenericType : struct\n{\n}\n</code></pre>\n\n<p>This one seemed to d... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | **Is there a way to enforce/limit the types that are passed to primitives?** *(bool, int, string, etc.)*
Now, I know you can limit the generic type parameter to a type or interface implementation via the *where* clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from *object* before someone says! :P).
So, my current thoughts are to just grit my teeth and do a big *switch* statement and throw an *ArgumentException* on failure.
---
**EDIT 1:**
Just to clarify:
The code definition should be like this:
```
public class MyClass<GenericType> ....
```
And instantiation:
```
MyClass<bool> = new MyClass<bool>(); // Legal
MyClass<string> = new MyClass<string>(); // Legal
MyClass<DataSet> = new MyClass<DataSet>(); // Illegal
MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!)
```
---
**EDIT 2**
@Jon Limjap - Good point, and something I was already considering. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type.
This could be useful in instantly removing a lot of the objects I don't want to deal with (but then you need to worry about the structs that are used such as *Size* ). Interesting problem no? :)
Here it is:
```
where T: struct
```
Taken from [MSDN](http://msdn.microsoft.com/en-us/library/d5x73970.aspx).
---
I'm curious. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code.
What do you guys think?
The sad news is I am working in Framework 2!! :D
---
**EDIT 3**
This was so simple following on from [Jon Limjaps Pointer](https://stackoverflow.com/questions/8941/generic-type-checking#8956).. So simple I almost want to cry, but it's great because the code works like a charm!
So here is what I did (you'll laugh!):
Code added to the generic class
-------------------------------
```
bool TypeValid()
{
// Get the TypeCode from the Primitive Type
TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType));
// All of the TypeCode Enumeration refer Primitive Types
// with the exception of Object and Empty (Null).
// Since I am willing to allow Null Types (at this time)
// all we need to check for is Object!
switch (code)
{
case TypeCode.Object:
return false;
default:
return true;
}
}
```
Then a little utility method to check the type and throw an exception,
```
private void EnforcePrimitiveType()
{
if (!TypeValid())
throw new InvalidOperationException(
"Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name +
"' - this Class is Designed to Work with Primitive Data Types Only.");
}
```
All that then needs to be done is to call *EnforcePrimitiveType()* in the classes constructors. Job done! :-)
The only downside, it only throws an exception at runtime (obviously) rather than design time. But that's no big deal and could be picked up with utilities like [FxCop](http://en.wikipedia.org/wiki/FxCop) (which we don't use at work).
Special thanks to Jon Limjap on this one! | Primitives appear to be specified in the [`TypeCode`](http://msdn.microsoft.com/en-us/library/system.typecode.aspx) enumeration:
Perhaps there is a way to find out if an object contains the `TypeCode enum` without having to cast it to an specific object or call `GetType()` or `typeof()`?
**Update** It was right under my nose. The code sample there shows this:
```
static void WriteObjectInfo(object testObject)
{
TypeCode typeCode = Type.GetTypeCode( testObject.GetType() );
switch( typeCode )
{
case TypeCode.Boolean:
Console.WriteLine("Boolean: {0}", testObject);
break;
case TypeCode.Double:
Console.WriteLine("Double: {0}", testObject);
break;
default:
Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject);
break;
}
}
}
```
It's still an ugly switch. But it's a good place to start! |
8,948 | <p>Is there a maintained package I can use to retrieve and set MP3 ID3 metadata using Python?</p>
| [
{
"answer_id": 8974,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 3,
"selected": false,
"text": "<p>A simple example from the book Dive Into Python works ok for me, <a href=\"http://www.diveintopython.org/download/diveintopyth... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] | Is there a maintained package I can use to retrieve and set MP3 ID3 metadata using Python? | I used [eyeD3](http://eyed3.nicfit.net/) the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to install using pip or download the tar and execute `python setup.py install` from the source folder.
Relevant examples from the website are below.
Reading the contents of an mp3 file containing either v1 or v2 tag info:
```
import eyeD3
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
print tag.getArtist()
print tag.getAlbum()
print tag.getTitle()
```
Read an mp3 file (track length, bitrate, etc.) and access it's tag:
```
if eyeD3.isMp3File(f):
audioFile = eyeD3.Mp3AudioFile(f)
tag = audioFile.getTag()
```
Specific tag versions can be selected:
```
tag.link("/some/file.mp3", eyeD3.ID3_V2)
tag.link("/some/file.mp3", eyeD3.ID3_V1)
tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION) # The default.
```
Or you can iterate over the raw frames:
```
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
for frame in tag.frames:
print frame
```
Once a tag is linked to a file it can be modified and saved:
```
tag.setArtist(u"Cro-Mags")
tag.setAlbum(u"Age of Quarrel")
tag.update()
```
If the tag linked in was v2 and you'd like to save it as v1:
```
tag.update(eyeD3.ID3_V1_1)
```
Read in a tag and remove it from the file:
```
tag.link("/some/file.mp3")
tag.remove()
tag.update()
```
Add a new tag:
```
tag = eyeD3.Tag()
tag.link('/some/file.mp3') # no tag in this file, link returned False
tag.header.setVersion(eyeD3.ID3_V2_3)
tag.setArtist('Fugazi')
tag.update()
``` |
8,966 | <p>I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem.</p>
<p>In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0.</p>
<p>Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different.</p>
<p>Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there?</p>
| [
{
"answer_id": 9026,
"author": "J Wynia",
"author_id": 1124,
"author_profile": "https://Stackoverflow.com/users/1124",
"pm_score": 0,
"selected": false,
"text": "<p>It doesn't <strong>need</strong> to be WIA. I was mostly looking at the WIA setup because it offers the same basic interfac... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124/"
] | I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem.
In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0.
Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different.
Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there? | To access WIA, you'll need to add a reference to the COM library, "Microsoft Windows Image Acquisition Library v2.0" (wiaaut.dll).
add a "using WIA;"
```
const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
CommonDialogClass wiaDiag = new CommonDialogClass();
WIA.ImageFile wiaImage = null;
wiaImage = wiaDiag.ShowAcquireImage(
WiaDeviceType.UnspecifiedDeviceType,
WiaImageIntent.GrayscaleIntent,
WiaImageBias.MaximizeQuality,
wiaFormatJPEG, true, true, false);
WIA.Vector vector = wiaImage.FileData;
```
(System.Drawing)
```
Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));
i.Save(filename)
```
Thats a basic way, works with my flatbed/doc feeder. If you need more than one document/page at a time though, there is probably a better way to do it (from what I could see, this only handles one image at a time, although I'm not entirely sure). While it is a WIA v1 doc, Scott Hanselman's [Coding4Fun article on WIA](http://blogs.msdn.com/coding4fun/archive/2006/10/31/912546.aspx) does contain some more info on how to do it for multiple pages, I think (I'm yet to go further than that myself)
If its for a paperless office system, you might want also check out MODI (Office Document Imaging) to do all the OCR for you. |
8,970 | <p>Is it possible to access the iSight camera on a macbook programmatically? By this I mean I would like to be able to just grab still frames from the iSight camera on command and then do something with them. If so, is it only accessible using objective c, or could other languages be used as well? </p>
| [
{
"answer_id": 8977,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": "<p>I don't have a Mac here, but there is some Documentation up here:</p>\n\n<p><a href=\"http://developer.apple.com/documenta... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | Is it possible to access the iSight camera on a macbook programmatically? By this I mean I would like to be able to just grab still frames from the iSight camera on command and then do something with them. If so, is it only accessible using objective c, or could other languages be used as well? | You should check out the [QTKit Capture documentation](http://developer.apple.com/documentation/QuickTime/Conceptual/QTKitCaptureProgrammingGuide/Introduction/chapter_1_section_1.html#//apple_ref/doc/uid/TP40004574-CH1-DontLinkElementID_41).
On Leopard, you can get at all of it over the RubyCocoa bridge:
```
require 'osx/cocoa'
OSX.require_framework("/System/Library/Frameworks/QTKit.framework")
OSX::QTCaptureDevice.inputDevices.each do |device|
puts device.localizedDisplayName
end
``` |
9,002 | <p>When I use the sp_send_dbmail stored procedure, I get a message saying that my mail was queued. However, it never seems to get delivered. I can see them in the queue if I run this SQL:</p>
<pre><code>SELECT * FROM msdb..sysmail_allitems WHERE sent_status = 'unsent'
</code></pre>
<p>This SQL returns a 1:</p>
<pre><code>SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'
</code></pre>
<p>This stored procedure returns STARTED:</p>
<pre><code>msdb.dbo.sysmail_help_status_sp
</code></pre>
<p>The appropriate accounts and profiles have been set up and the mail was functioning at one point. There are no errors in msdb.dbo.sysmail_event_log. </p>
| [
{
"answer_id": 9212,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried </p>\n\n<pre><code>sysmail_stop_sp\n</code></pre>\n\n<p>then </p>\n\n<pre><code>sysmail_start_sp\n</code></pre>\n"... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/162/"
] | When I use the sp\_send\_dbmail stored procedure, I get a message saying that my mail was queued. However, it never seems to get delivered. I can see them in the queue if I run this SQL:
```
SELECT * FROM msdb..sysmail_allitems WHERE sent_status = 'unsent'
```
This SQL returns a 1:
```
SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'
```
This stored procedure returns STARTED:
```
msdb.dbo.sysmail_help_status_sp
```
The appropriate accounts and profiles have been set up and the mail was functioning at one point. There are no errors in msdb.dbo.sysmail\_event\_log. | Could be oodles of things. For example, I've seen (yes, actually seen) this happen after:
* Domain controller reboot
* Exchange server reboot
* Router outage
* Service account changes
* SQL Server running out of disk space
So until it happens again, I wouldn't freak out over it. |
9,009 | <p>This snippet of Perl code in my program is giving the wrong result.</p>
<pre><code>$condition ? $a = 2 : $a = 3 ;
print $a;
</code></pre>
<p>No matter what the value of <code>$condition</code> is, the output is always 3, how come?</p>
| [
{
"answer_id": 9011,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "<p>This is explained in the Perl <a href=\"http://perldoc.perl.org/perlop.html#Conditional-Operator\" rel=\"noreferrer\">documentatio... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
] | This snippet of Perl code in my program is giving the wrong result.
```
$condition ? $a = 2 : $a = 3 ;
print $a;
```
No matter what the value of `$condition` is, the output is always 3, how come? | This is explained in the Perl [documentation](http://perldoc.perl.org/perlop.html#Conditional-Operator).
Because of Perl operator precedence the statement is being parsed as
```
($condition ? $a= 2 : $a ) = 3 ;
```
Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.
When $condition is true this means ($a=2)=3 giving $a=3
When $condition is false this means ($a)=3 giving $a=3
The correct way to write this is
```
$a = ( $condition ? 2 : 3 );
print $a;
```
We got bitten by this at work, so I am posting here hoping others will find it useful. |
9,018 | <p>I am working at a client site where there is a proxy server (<code>HTTP</code>) in place. If I do a hard reset of the emulator it forgets network connection settings for the emulator and settings in the hosted Windows Mobile OS. If I 'save state and exit' it will lose all of these settings. I need to do hard resets regularly which means that I lose this information and spend a lot of time setting:</p>
<ul>
<li>The emulators associated network card</li>
<li>DNS servers for network card in the WM OS.</li>
<li>Proxy servers in connection settings of WM OS.</li>
</ul>
<p>How can I make my life easier? Can I save this as defaults in the emulator, or create an installer easily?</p>
| [
{
"answer_id": 9011,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "<p>This is explained in the Perl <a href=\"http://perldoc.perl.org/perlop.html#Conditional-Operator\" rel=\"noreferrer\">documentatio... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | I am working at a client site where there is a proxy server (`HTTP`) in place. If I do a hard reset of the emulator it forgets network connection settings for the emulator and settings in the hosted Windows Mobile OS. If I 'save state and exit' it will lose all of these settings. I need to do hard resets regularly which means that I lose this information and spend a lot of time setting:
* The emulators associated network card
* DNS servers for network card in the WM OS.
* Proxy servers in connection settings of WM OS.
How can I make my life easier? Can I save this as defaults in the emulator, or create an installer easily? | This is explained in the Perl [documentation](http://perldoc.perl.org/perlop.html#Conditional-Operator).
Because of Perl operator precedence the statement is being parsed as
```
($condition ? $a= 2 : $a ) = 3 ;
```
Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.
When $condition is true this means ($a=2)=3 giving $a=3
When $condition is false this means ($a)=3 giving $a=3
The correct way to write this is
```
$a = ( $condition ? 2 : 3 );
print $a;
```
We got bitten by this at work, so I am posting here hoping others will find it useful. |
9,019 | <p>I have a stored procedure which takes as its parameter a <em>varchar</em> which needs to be cast as a <em>datetime</em> for later use:</p>
<pre><code>SET @the_date = CAST(@date_string AS DATETIME)
</code></pre>
<p>I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?</p>
<p><em>NB: using Sybase ASE 12.5.3, there is no ISDATE function</em></p>
| [
{
"answer_id": 9023,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Found <a href=\"http://blog.sqlauthority.com/2007/07/12/sql-server-validate-field-for-date-datatype-using-function-isdate/... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | I have a stored procedure which takes as its parameter a *varchar* which needs to be cast as a *datetime* for later use:
```
SET @the_date = CAST(@date_string AS DATETIME)
```
I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?
*NB: using Sybase ASE 12.5.3, there is no ISDATE function* | I'm having a similar issue. You might be able to do something like this:
```
SET arithabort arith_overflow off
SET @the_date = CAST(@date_string AS DATETIME)
IF @the_date is NULL
set @the_date = getdate()
SET arithabort arith_overflow on
```
However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch. |
9,022 | <p>Inside an asp.net page, should I use</p>
<pre><code><html><title>My page's title from México</title></html>
</code></pre>
<p>Or </p>
<pre><code><html><title>My page&rsquo;s title from M&eacute;xico</title></html>
</code></pre>
<p>Both examples have the same output. Since asp.net encodes all my pages to utf-8, there is no need to use html entities, is that right?</p>
| [
{
"answer_id": 9023,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Found <a href=\"http://blog.sqlauthority.com/2007/07/12/sql-server-validate-field-for-date-datatype-using-function-isdate/... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296/"
] | Inside an asp.net page, should I use
```
<html><title>My page's title from México</title></html>
```
Or
```
<html><title>My page’s title from México</title></html>
```
Both examples have the same output. Since asp.net encodes all my pages to utf-8, there is no need to use html entities, is that right? | I'm having a similar issue. You might be able to do something like this:
```
SET arithabort arith_overflow off
SET @the_date = CAST(@date_string AS DATETIME)
IF @the_date is NULL
set @the_date = getdate()
SET arithabort arith_overflow on
```
However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch. |
9,024 | <p>I'm using <code>IIS 5.1</code> in Windows XP on my development computer. I'm going to set up HTTPS on my company's web server, but I want to try doing it locally before doing it on a production system.</p>
<p>But when I go into the Directory Security tab of my web site's configuration section, the "Secure communication" groupbox is disabled. Is there something I need to do to make this groupbox enabled?</p>
| [
{
"answer_id": 9023,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Found <a href=\"http://blog.sqlauthority.com/2007/07/12/sql-server-validate-field-for-date-datatype-using-function-isdate/... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614/"
] | I'm using `IIS 5.1` in Windows XP on my development computer. I'm going to set up HTTPS on my company's web server, but I want to try doing it locally before doing it on a production system.
But when I go into the Directory Security tab of my web site's configuration section, the "Secure communication" groupbox is disabled. Is there something I need to do to make this groupbox enabled? | I'm having a similar issue. You might be able to do something like this:
```
SET arithabort arith_overflow off
SET @the_date = CAST(@date_string AS DATETIME)
IF @the_date is NULL
set @the_date = getdate()
SET arithabort arith_overflow on
```
However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch. |
9,033 | <p>This came to my mind after I learned the following from <a href="http://www.stackoverflow.com/questions/8941/generic-type-checking">this question</a>:</p>
<pre><code>where T : struct
</code></pre>
<p>We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.</p>
<p>Some of us even mastered the stuff like <a href="http://msdn.microsoft.com/en-us/library/512aeb7t.aspx" rel="nofollow noreferrer">Generics</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx" rel="nofollow noreferrer">anonymous types</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" rel="nofollow noreferrer">lambdas</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397676.aspx" rel="nofollow noreferrer">LINQ</a>, ...</p>
<p>But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?</p>
<h1>Here are the revealed features so far:</h1>
<p><br /></p>
<h2>Keywords</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx" rel="nofollow noreferrer"><code>yield</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><code>var</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><code>using()</code> statement by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li><code>readonly</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li><code>as</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9041#9041">Mike Stone</a></li>
<li><code>as</code> / <code>is</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9070#9070">Ed Swangren</a></li>
<li><code>as</code> / <code>is</code> (improved) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9092#9092">Rocketpants</a></li>
<li><code>default</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9639#9639">deathofrats</a></li>
<li><code>global::</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12152#12152">pzycoman</a></li>
<li><code>using()</code> blocks by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12316#12316">AlexCuse</a></li>
<li><code>volatile</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/59691#59691">Jakub Šturc</a></li>
<li><code>extern alias</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/37926#37926">Jakub Šturc</a></li>
</ul>
<h2>Attributes</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx" rel="nofollow noreferrer"><code>DefaultValueAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx" rel="nofollow noreferrer"><code>ObsoleteAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx" rel="nofollow noreferrer"><code>DebuggerDisplayAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9048#9048">Stu</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx" rel="nofollow noreferrer"><code>DebuggerBrowsable</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx" rel="nofollow noreferrer"><code>DebuggerStepThrough</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/33474#33474">bdukes</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx" rel="nofollow noreferrer"><code>ThreadStaticAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="nofollow noreferrer"><code>FlagsAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/21752#21752">Martin Clarke</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/4xssyw96.aspx" rel="nofollow noreferrer"><code>ConditionalAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/35342#35342">AndrewBurns</a></li>
</ul>
<h2>Syntax</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx" rel="nofollow noreferrer"><code>??</code></a> (coalesce nulls) operator by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li>Number flaggings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9038#9038">Nick Berardi</a></li>
<li><code>where T:new</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9067#9067">Lars Mæhlum</a></li>
<li>Implicit generics by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>One-parameter lambdas by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Auto properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Namespace aliases by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Verbatim string literals with @ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9114#9114">Patrick</a></li>
<li><code>enum</code> values by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/11738#11738">lfoust</a></li>
<li>@variablenames by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14088#14088">marxidad</a></li>
<li><code>event</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14277#14277">marxidad</a></li>
<li>Format string brackets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15321#15321">Portman</a></li>
<li>Property accessor accessibility modifiers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15715#15715">xanadont</a></li>
<li>Conditional (ternary) operator (<code>?:</code>) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16450#16450">JasonS</a></li>
<li><code>checked</code> and <code>unchecked</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/355991#355991">Binoj Antony</a></li>
<li><code>implicit and explicit</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/121470#121470">Flory</a></li>
</ul>
<h2>Language Features</h2>
<ul>
<li>Nullable types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9055#9055">Brad Barker</a></li>
<li>Anonymous types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li><code>__makeref __reftype __refvalue</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9125#9125">Judah Himango</a></li>
<li>Object initializers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9547#9547">lomaxx</a></li>
<li>Format strings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10207#10207">David in Dakota</a></li>
<li>Extension Methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li>
<li><code>partial</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16395#16395">Jon Erickson</a></li>
<li>Preprocessor directives by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16482#16482">John Asbeck</a></li>
<li><code>DEBUG</code> pre-processor directive by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/29081#29081">Robert Durgin</a></li>
<li>Operator overloading by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/24914#24914">SefBkn</a></li>
<li>Type inferrence by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/28811#28811">chakrit</a></li>
<li>Boolean operators <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm" rel="nofollow noreferrer">taken to next level</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/32148#32148">Rob Gough</a></li>
<li>Pass value-type variable as interface without boxing by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1820538#1820538">Roman Boiko</a></li>
<li>Programmatically determine declared variable type by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1789985#1789985">Roman Boiko</a></li>
<li>Static Constructors by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/100321#100321">Chris</a></li>
<li>Easier-on-the-eyes / condensed ORM-mapping using LINQ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/2026781#2026781">roosteronacid</a></li>
<li><code>__arglist</code> by <a href="https://stackoverflow.com/a/1836944/171819">Zac Bowling</a></li>
</ul>
<h2>Visual Studio Features</h2>
<ul>
<li>Select block of text in editor by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1699477#1699477" title="block text selecting with alt key">Himadri</a></li>
<li>Snippets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a> </li>
</ul>
<h2>Framework</h2>
<ul>
<li><code>TransactionScope</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>DependantTransaction</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>Nullable<T></code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9118#9118">IainMH</a></li>
<li><code>Mutex</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9181#9181">Diago</a></li>
<li><code>System.IO.Path</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9401#9401">ageektrapped</a></li>
<li><code>WeakReference</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14723#14723">Juan Manuel</a></li>
</ul>
<h2>Methods and Properties</h2>
<ul>
<li><code>String.IsNullOrEmpty()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>List.ForEach()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>BeginInvoke()</code>, <code>EndInvoke()</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9581#9581">Will Dean</a></li>
<li><code>Nullable<T>.HasValue</code> and <code>Nullable<T>.Value</code> properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15393#15393">Rismo</a></li>
<li><code>GetValueOrDefault</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/18158#18158">John Sheehan</a></li>
</ul>
<h2>Tips & Tricks</h2>
<ul>
<li>Nice method for event handlers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9282#9282">Andreas H.R. Nilsson</a></li>
<li>Uppercase comparisons by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12137#12137">John</a></li>
<li>Access anonymous types without reflection by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13441#13441">dp</a></li>
<li>A quick way to lazily instantiate collection properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/58945#58945">Will</a></li>
<li>JavaScript-like anonymous inline-functions by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1399130#1399130">roosteronacid</a></li>
</ul>
<h2>Other</h2>
<ul>
<li>netmodules by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a> </li>
<li><a href="http://www.albahari.com/nutshell/linqbridge.html" rel="nofollow noreferrer">LINQBridge</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10886#10886">Duncan Smart</a> </li>
<li><a href="http://msdn.microsoft.com/en-us/concurrency/default.aspx" rel="nofollow noreferrer">Parallel Extensions</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/31293#31293">Joel Coehoorn</a></li>
</ul>
| [
{
"answer_id": 9035,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 8,
"selected": false,
"text": "<p>\"<a href=\"http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx\" rel=\"nofollow noreferrer\">yield</a>\" would c... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | This came to my mind after I learned the following from [this question](http://www.stackoverflow.com/questions/8941/generic-type-checking):
```
where T : struct
```
We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.
Some of us even mastered the stuff like [Generics](http://msdn.microsoft.com/en-us/library/512aeb7t.aspx), [anonymous types](http://msdn.microsoft.com/en-us/library/bb397696.aspx), [lambdas](http://msdn.microsoft.com/en-us/library/bb397687.aspx), [LINQ](http://msdn.microsoft.com/en-us/library/bb397676.aspx), ...
But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?
Here are the revealed features so far:
======================================
Keywords
--------
* [`yield`](http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx) by [Michael Stum](https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035)
* `var` by [Michael Stum](https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035)
* `using()` statement by [kokos](https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036)
* `readonly` by [kokos](https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036)
* `as` by [Mike Stone](https://stackoverflow.com/questions/9033/hidden-features-of-c/9041#9041)
* `as` / `is` by [Ed Swangren](https://stackoverflow.com/questions/9033/hidden-features-of-c/9070#9070)
* `as` / `is` (improved) by [Rocketpants](https://stackoverflow.com/questions/9033/hidden-features-of-c/9092#9092)
* `default` by [deathofrats](https://stackoverflow.com/questions/9033/hidden-features-of-c/9639#9639)
* `global::` by [pzycoman](https://stackoverflow.com/questions/9033/hidden-features-of-c/12152#12152)
* `using()` blocks by [AlexCuse](https://stackoverflow.com/questions/9033/hidden-features-of-c/12316#12316)
* `volatile` by [Jakub Šturc](https://stackoverflow.com/questions/9033/hidden-features-of-c/59691#59691)
* `extern alias` by [Jakub Šturc](https://stackoverflow.com/questions/9033/hidden-features-of-c/37926#37926)
Attributes
----------
* [`DefaultValueAttribute`](http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx) by [Michael Stum](https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035)
* [`ObsoleteAttribute`](http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx) by [DannySmurf](https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037)
* [`DebuggerDisplayAttribute`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx) by [Stu](https://stackoverflow.com/questions/9033/hidden-features-of-c/9048#9048)
* [`DebuggerBrowsable`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx) and [`DebuggerStepThrough`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx) by [bdukes](https://stackoverflow.com/questions/9033/hidden-features-of-c/33474#33474)
* [`ThreadStaticAttribute`](http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx) by [marxidad](https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932)
* [`FlagsAttribute`](http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx) by [Martin Clarke](https://stackoverflow.com/questions/9033/hidden-features-of-c/21752#21752)
* [`ConditionalAttribute`](http://msdn.microsoft.com/en-us/library/4xssyw96.aspx) by [AndrewBurns](https://stackoverflow.com/questions/9033/hidden-features-of-c/35342#35342)
Syntax
------
* [`??`](http://msdn.microsoft.com/en-us/library/ms173224.aspx) (coalesce nulls) operator by [kokos](https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036)
* Number flaggings by [Nick Berardi](https://stackoverflow.com/questions/9033/hidden-features-of-c/9038#9038)
* `where T:new` by [Lars Mæhlum](https://stackoverflow.com/questions/9033/hidden-features-of-c/9067#9067)
* Implicit generics by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* One-parameter lambdas by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* Auto properties by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* Namespace aliases by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* Verbatim string literals with @ by [Patrick](https://stackoverflow.com/questions/9033/hidden-features-of-c/9114#9114)
* `enum` values by [lfoust](https://stackoverflow.com/questions/9033/hidden-features-of-c/11738#11738)
* @variablenames by [marxidad](https://stackoverflow.com/questions/9033/hidden-features-of-c/14088#14088)
* `event` operators by [marxidad](https://stackoverflow.com/questions/9033/hidden-features-of-c/14277#14277)
* Format string brackets by [Portman](https://stackoverflow.com/questions/9033/hidden-features-of-c/15321#15321)
* Property accessor accessibility modifiers by [xanadont](https://stackoverflow.com/questions/9033/hidden-features-of-c/15715#15715)
* Conditional (ternary) operator (`?:`) by [JasonS](https://stackoverflow.com/questions/9033/hidden-features-of-c/16450#16450)
* `checked` and `unchecked` operators by [Binoj Antony](https://stackoverflow.com/questions/9033/hidden-features-of-c/355991#355991)
* `implicit and explicit` operators by [Flory](https://stackoverflow.com/questions/9033/hidden-features-of-c/121470#121470)
Language Features
-----------------
* Nullable types by [Brad Barker](https://stackoverflow.com/questions/9033/hidden-features-of-c/9055#9055)
* Anonymous types by [Keith](https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099)
* `__makeref __reftype __refvalue` by [Judah Himango](https://stackoverflow.com/questions/9033/hidden-features-of-c/9125#9125)
* Object initializers by [lomaxx](https://stackoverflow.com/questions/9033/hidden-features-of-c/9547#9547)
* Format strings by [David in Dakota](https://stackoverflow.com/questions/9033/hidden-features-of-c/10207#10207)
* Extension Methods by [marxidad](https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932)
* `partial` methods by [Jon Erickson](https://stackoverflow.com/questions/9033/hidden-features-of-c/16395#16395)
* Preprocessor directives by [John Asbeck](https://stackoverflow.com/questions/9033/hidden-features-of-c/16482#16482)
* `DEBUG` pre-processor directive by [Robert Durgin](https://stackoverflow.com/questions/9033/hidden-features-of-c/29081#29081)
* Operator overloading by [SefBkn](https://stackoverflow.com/questions/9033/hidden-features-of-c/24914#24914)
* Type inferrence by [chakrit](https://stackoverflow.com/questions/9033/hidden-features-of-c/28811#28811)
* Boolean operators [taken to next level](http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm) by [Rob Gough](https://stackoverflow.com/questions/9033/hidden-features-of-c/32148#32148)
* Pass value-type variable as interface without boxing by [Roman Boiko](https://stackoverflow.com/questions/9033/hidden-features-of-c/1820538#1820538)
* Programmatically determine declared variable type by [Roman Boiko](https://stackoverflow.com/questions/9033/hidden-features-of-c/1789985#1789985)
* Static Constructors by [Chris](https://stackoverflow.com/questions/9033/hidden-features-of-c/100321#100321)
* Easier-on-the-eyes / condensed ORM-mapping using LINQ by [roosteronacid](https://stackoverflow.com/questions/9033/hidden-features-of-c/2026781#2026781)
* `__arglist` by [Zac Bowling](https://stackoverflow.com/a/1836944/171819)
Visual Studio Features
----------------------
* Select block of text in editor by [Himadri](https://stackoverflow.com/questions/9033/hidden-features-of-c/1699477#1699477 "block text selecting with alt key")
* Snippets by [DannySmurf](https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037)
Framework
---------
* `TransactionScope` by [KiwiBastard](https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042)
* `DependantTransaction` by [KiwiBastard](https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042)
* `Nullable<T>` by [IainMH](https://stackoverflow.com/questions/9033/hidden-features-of-c/9118#9118)
* `Mutex` by [Diago](https://stackoverflow.com/questions/9033/hidden-features-of-c/9181#9181)
* `System.IO.Path` by [ageektrapped](https://stackoverflow.com/questions/9033/hidden-features-of-c/9401#9401)
* `WeakReference` by [Juan Manuel](https://stackoverflow.com/questions/9033/hidden-features-of-c/14723#14723)
Methods and Properties
----------------------
* `String.IsNullOrEmpty()` method by [KiwiBastard](https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042)
* `List.ForEach()` method by [KiwiBastard](https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042)
* `BeginInvoke()`, `EndInvoke()` methods by [Will Dean](https://stackoverflow.com/questions/9033/hidden-features-of-c/9581#9581)
* `Nullable<T>.HasValue` and `Nullable<T>.Value` properties by [Rismo](https://stackoverflow.com/questions/9033/hidden-features-of-c/15393#15393)
* `GetValueOrDefault` method by [John Sheehan](https://stackoverflow.com/questions/9033/hidden-features-of-c/18158#18158)
Tips & Tricks
-------------
* Nice method for event handlers by [Andreas H.R. Nilsson](https://stackoverflow.com/questions/9033/hidden-features-of-c/9282#9282)
* Uppercase comparisons by [John](https://stackoverflow.com/questions/9033/hidden-features-of-c/12137#12137)
* Access anonymous types without reflection by [dp](https://stackoverflow.com/questions/9033/hidden-features-of-c/13441#13441)
* A quick way to lazily instantiate collection properties by [Will](https://stackoverflow.com/questions/9033/hidden-features-of-c/58945#58945)
* JavaScript-like anonymous inline-functions by [roosteronacid](https://stackoverflow.com/questions/9033/hidden-features-of-c/1399130#1399130)
Other
-----
* netmodules by [kokos](https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036)
* [LINQBridge](http://www.albahari.com/nutshell/linqbridge.html) by [Duncan Smart](https://stackoverflow.com/questions/9033/hidden-features-of-c/10886#10886)
* [Parallel Extensions](http://msdn.microsoft.com/en-us/concurrency/default.aspx) by [Joel Coehoorn](https://stackoverflow.com/questions/9033/hidden-features-of-c/31293#31293) | This isn't C# per se, but I haven't seen anyone who really uses `System.IO.Path.Combine()` to the extent that they should. In fact, the whole Path class is really useful, but **no one uses it!**
I'm willing to bet that every production app has the following code, even though it shouldn't:
```
string path = dir + "\\" + fileName;
``` |
9,044 | <p>I have a base class that represents a database test in TestNG, and I want to specify that all classes extending from this class are of a group "db-test", however I have found that this doesn't seem possible. I have tried the @Test annotation:</p>
<pre><code>@Test(groups = { "db-test" })
public class DBTestBase {
}
</code></pre>
<p>However, this doesn't work because the @Test annotation will try to make a bunch of methods into tests, and warnings/errors pop up in eclipse when the tests are run.</p>
<p>So I tried disabling the test, so at least the groups are assigned:</p>
<pre><code>@Test(enabled = false, groups = { "db-test" })
public class DBTestBase {
}
</code></pre>
<p>but then any @BeforeTest (and other similar annotations) ALSO get disabled... which is of course not what I want.</p>
<p>I would like some way to annotate a class as being of a particular type of group, but it doesn't quite seem possible in TestNG. Does anyone have any other ideas?</p>
| [
{
"answer_id": 9137,
"author": "Sam Merrell",
"author_id": 782,
"author_profile": "https://Stackoverflow.com/users/782",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure how the annotation inheritance works for TestNG but this <a href=\"http://web.archive.org/web/20100104232432... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I have a base class that represents a database test in TestNG, and I want to specify that all classes extending from this class are of a group "db-test", however I have found that this doesn't seem possible. I have tried the @Test annotation:
```
@Test(groups = { "db-test" })
public class DBTestBase {
}
```
However, this doesn't work because the @Test annotation will try to make a bunch of methods into tests, and warnings/errors pop up in eclipse when the tests are run.
So I tried disabling the test, so at least the groups are assigned:
```
@Test(enabled = false, groups = { "db-test" })
public class DBTestBase {
}
```
but then any @BeforeTest (and other similar annotations) ALSO get disabled... which is of course not what I want.
I would like some way to annotate a class as being of a particular type of group, but it doesn't quite seem possible in TestNG. Does anyone have any other ideas? | The answer is through a custom **org.testng.IMethodSelector**:
Its **includeMethod()** can exclude any method we want, like a public not-annotated method.
However, to register a custom *Java* MethodSelector, you must add it to the **XMLTest** instance managed by any TestRunner, which means you need your own **custom TestRunner**.
But, to build a custom TestRunner, you need to register a **TestRunnerFactory**, through the **-testrunfactory** option.
BUT that -testrunfactory is NEVER taken into account by **TestNG** class... so you need also to define a custom TestNG class :
* in order to override the configure(Map) method,
* so you can actually set the TestRunnerFactory
* TestRunnerFactory which will build you a custom TestRunner,
* TestRunner which will set to the XMLTest instance a custom XMLMethodSelector
* XMLMethodSelector which will build a custom IMethodSelector
* IMethodSelector which will exclude any TestNG methods of your choosing!
Ok... it's a nightmare. But it is also a code-challenge, so it must be a little challenging ;)
All the code is available at [**DZone snippets**](http://snippets.dzone.com/posts/show/6446).
As usual for a code challenge:
* one java class (and quite a few inner classes)
* copy-paste the class in a 'source/test' directory (since the package is 'test')
* run it (no arguments needed)
---
**Update from Mike Stone:**
I'm going to accept this because it sounds pretty close to what I ended up doing, but I figured I would add what I did as well.
Basically, I created a Groups annotation that behaves like the groups property of the Test (and other) annotations.
Then, I created a GroupsAnnotationTransformer, which uses IAnnotationTransformer to look at all tests and test classes being defined, then modifies the test to add the groups, which works perfectly with group exclusion and inclusion.
Modify the build to use the new annotation transformer, and it all works perfectly!
Well... the one caveat is that it doesn't add the groups to non-test methods... because at the time I did this, there was another annotation transformer that lets you transform ANYTHING, but it somehow wasn't included in the TestNG I was using for some reason... so it is a good idea to make your before/after annotated methods to alwaysRun=true... which is sufficient for me.
The end result is I can do:
```
@Groups({ "myGroup1", "myGroup2"})
public class MyTestCase {
@Test
@Groups("aMethodLevelGroup")
public void myTest() {
}
}
```
And I made the transformer work with subclassing and everything. |
9,052 | <p>I'm working on a spec for a piece of software for my company and as part of the auditing system I think it would be neat if there was a way to grab the current Active Directory user.</p>
<p>Hopefully something like:</p>
<pre><code>Dim strUser as String
strUser = ActiveDirectory.User()
MsgBox "Welcome back, " & strUser
</code></pre>
| [
{
"answer_id": 9054,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://bytes.com/forum/thread717576.html\" rel=\"nofollow noreferrer\">Try this article</a> - I have some code... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] | I'm working on a spec for a piece of software for my company and as part of the auditing system I think it would be neat if there was a way to grab the current Active Directory user.
Hopefully something like:
```
Dim strUser as String
strUser = ActiveDirectory.User()
MsgBox "Welcome back, " & strUser
``` | [Try this article](http://bytes.com/forum/thread717576.html) - I have some code at work that will erm, work if this doesn't...
Relevant quote:
>
>
> ```vba
> Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
> (ByVal IpBuffer As String, nSize As Long) As Long
> Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" _
> (ByVal lpBuffer As String, nSize As Long) As Long
>
> Function ThisUserName() As String
> Dim LngBufLen As Long
> Dim strUser As String
>
> strUser = String$(15, " ")
> LngBufLen = 15
>
> If GetUserName(strUser, LngBufLen) = 1 Then
> ThisUserName = Left(strUser, LngBufLen - 1)
> Else
> ThisUserName = "Unknown"
> End If
> End Function
>
> Function ThisComputerID() As String
> Dim LngBufLen As Long
> Dim strUser As String
>
> strUser = String$(15, " ")
> LngBufLen = 15
>
> If GetComputerName(strUser, LngBufLen) = 1 Then
> ThisComputerID = Left(strUser, LngBufLen)
> Else
> ThisComputerID = 0
> End If
> End Function
>
> ```
>
> |
9,081 | <p>How do I <code>grep</code> and show the preceding and following 5 lines surrounding each matched line?</p>
| [
{
"answer_id": 9083,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 13,
"selected": true,
"text": "<p>For <strong>BSD</strong> or <strong>GNU</strong> <code>grep</code> you can use <code>-B num</code> to set how many lines bef... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | How do I `grep` and show the preceding and following 5 lines surrounding each matched line? | For **BSD** or **GNU** `grep` you can use `-B num` to set how many lines before the match and `-A num` for the number of lines after the match.
```
grep -B 3 -A 2 foo README.txt
```
If you want the same number of lines before and after you can use `-C num`.
```
grep -C 3 foo README.txt
```
This will show 3 lines before and 3 lines after. |
9,104 | <p>I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes...</p>
<p>I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code. It would merely construct a URL based on the current date and then do a window.location = on that URL.</p>
<p>I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript. I could have sworn that this was possible years ago, but I can't find anything that tells me either way now.</p>
| [
{
"answer_id": 9105,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "<p>What you want is a <a href=\"http://en.wikipedia.org/wiki/Bookmarklet\" rel=\"noreferrer\">bookmarklet</a> they are easy to create... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] | I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes...
I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code. It would merely construct a URL based on the current date and then do a window.location = on that URL.
I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript. I could have sworn that this was possible years ago, but I can't find anything that tells me either way now. | What you want is a [bookmarklet](http://en.wikipedia.org/wiki/Bookmarklet) they are easy to create and should work in most major browsers.
Edit: Stack overflow seems not to allow creating bookmarklets in the context of the site, basically you can create a new bookmark and type the following in the location field
```
javascript:window.location='http://www.google.com/search?q='+Date()
```
to get a bookmarklet that searches google for the current date. |
9,122 | <p>I'm trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this?</p>
<p>EDIT: There are 53 columns in this table (NOT MY DESIGN)</p>
| [
{
"answer_id": 9123,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 5,
"selected": false,
"text": "<p>To the best of my knowledge, there isn't. You can do something like:</p>\n\n<pre><code>SELECT col1, col2, col3, col4 FRO... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44/"
] | I'm trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this?
EDIT: There are 53 columns in this table (NOT MY DESIGN) | Actually there is a way, you need to have permissions of course for doing this ...
```
SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;
```
Replacing `<table>, <database> and <columns_to_omit>` |
9,191 | <p>I'd like to ask a question then follow it up with my own answer, but also see what answers other people have.</p>
<p>We have two large files which we'd like to read from two separate threads concurrently. One thread will sequentially read fileA while the other thread will sequentially read fileB. There is no locking or communication between the threads, both are sequentially reading as fast as they can, and both are immediately discarding the data they read.</p>
<p>Our experience with this setup on Windows is very poor. The combined throughput of the two threads is in the order of 2-3 MiB/sec. The drive seems to be spending most of its time seeking backwards and forwards between the two files, presumably reading very little after each seek.</p>
<p>If we disable one of the threads and temporarily look at the performance of a single thread then we get much better bandwidth (~45 MiB/sec for this machine). So clearly the bad two-thread performance is an artefact of the OS disk scheduler.</p>
<p><strong>Is there anything we can do to improve the concurrent thread read performance?</strong> Perhaps by using different APIs or by tweaking the OS disk scheduler parameters in some way.</p>
<p>Some details:</p>
<p>The files are in the order of 2 GiB each on a machine with 2GiB of RAM. For the purpose of this question we consider them not to be cached and perfectly defragmented. We have used defrag tools and rebooted to ensure this is the case.</p>
<p>We are using no special APIs to read these files. The behaviour is repeatable across various bog-standard APIs such as Win32's CreateFile, C's fopen, C++'s std::ifstream, Java's FileInputStream, etc.</p>
<p>Each thread spins in a loop making calls to the read function. We have varied the number of bytes requested from the API each iteration from values between 1KiB up to 128MiB. Varying this has had no effect, so clearly the amount the OS is physically reading after each disk seek is not dictated by this number. This is exactly what should be expected.</p>
<p>The dramatic difference between one-thread and two-thread performance is repeatable across Windows 2000, Windows XP (32-bit and 64-bit), Windows Server 2003, and also with and without hardware RAID5.</p>
| [
{
"answer_id": 9193,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 3,
"selected": false,
"text": "<p>I'd like to add some further notes in my response. All other non-Microsoft operating systems we have tested do not suffer fr... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] | I'd like to ask a question then follow it up with my own answer, but also see what answers other people have.
We have two large files which we'd like to read from two separate threads concurrently. One thread will sequentially read fileA while the other thread will sequentially read fileB. There is no locking or communication between the threads, both are sequentially reading as fast as they can, and both are immediately discarding the data they read.
Our experience with this setup on Windows is very poor. The combined throughput of the two threads is in the order of 2-3 MiB/sec. The drive seems to be spending most of its time seeking backwards and forwards between the two files, presumably reading very little after each seek.
If we disable one of the threads and temporarily look at the performance of a single thread then we get much better bandwidth (~45 MiB/sec for this machine). So clearly the bad two-thread performance is an artefact of the OS disk scheduler.
**Is there anything we can do to improve the concurrent thread read performance?** Perhaps by using different APIs or by tweaking the OS disk scheduler parameters in some way.
Some details:
The files are in the order of 2 GiB each on a machine with 2GiB of RAM. For the purpose of this question we consider them not to be cached and perfectly defragmented. We have used defrag tools and rebooted to ensure this is the case.
We are using no special APIs to read these files. The behaviour is repeatable across various bog-standard APIs such as Win32's CreateFile, C's fopen, C++'s std::ifstream, Java's FileInputStream, etc.
Each thread spins in a loop making calls to the read function. We have varied the number of bytes requested from the API each iteration from values between 1KiB up to 128MiB. Varying this has had no effect, so clearly the amount the OS is physically reading after each disk seek is not dictated by this number. This is exactly what should be expected.
The dramatic difference between one-thread and two-thread performance is repeatable across Windows 2000, Windows XP (32-bit and 64-bit), Windows Server 2003, and also with and without hardware RAID5. | The problem seems to be in Windows I/O scheduling policy. According to what I found [here](http://engr.smu.edu/~kocan/7343/fall05/slides/chapter11.ppt "I/O management and disk scheduling") there are many ways for an O.S. to schedule disk requests. While Linux and others can choose between different policies, before Vista Windows was locked in a single policy: a FIFO queue, where all requests where splitted in 64 KB blocks. I believe that this policy is the cause for the problem you are experiencing: the scheduler will mix requests from the two threads, causing continuous seek between different areas of the disk.
Now, the good news is that according to [here](http://technet.microsoft.com/en-us/magazine/cc162494.aspx "Inside Windows Vista Kernel") and [here](http://widefox.pbwiki.com/IO "Kernel Comparison: Linux (2.6.22) versus Windows (Vista)"), Vista introduced a smarter disk scheduler, where you can set the priority of your requests and also allocate a minimum badwidth for your process.
The bad news is that I found no way to change disk policy or buffers size in previous versions of Windows. Also, even if raising disk I/O priority of your process will boost the performance against the other processes, you still have the problems of your threads competing against each other.
What I can suggest is to modify your software by introducing a self-made disk access policy.
For example, you could use a policy like this in your thread B (similar for Thread A):
```
if THREAD A is reading from disk then wait for THREAD A to stop reading or wait for X ms
Read for X ms (or Y MB)
Stop reading and check status of thread A again
```
You could use semaphores for status checking or you could use perfmon counters to get the status of the actual disk queue.
The values of X and/or Y could also be auto-tuned by checking the actual trasfer rates and slowly modify them, thus maximizing the throughtput when the application runs on different machines and/or O.S. You could find that cache, memory or RAID levels affect them in a way or the other, but with auto-tuning you will always get the best performance in every scenario. |
9,240 | <p>Say you have an application divided into 3-tiers: GUI, business logic, and data access. In your business logic layer you have described your business objects: getters, setters, accessors, and so on... you get the idea. The interface to the business logic layer guarantees safe usage of the business logic, so all the methods and accessors you call will validate input. </p>
<p>This great when you first write the UI code, because you have a neatly defined interface that you can trust.</p>
<p>But here comes the tricky part, when you start writing the data access layer, the interface to the business logic does not accommodate your needs. You need to have more accessors and getters to set fields which are/used to be hidden. Now you are forced to erode the interface of your business logic; now it is possible set fields from the UI layer, which the UI layer has no business setting. </p>
<p>Because of the changes needed for the data access layer, the interface to the business logic has eroded to the point where it is possible to even set the business logic with invalid data. Thus, the interface does not guarantee safe usage anymore.</p>
<p>I hope I explained the problem clearly enough. How do you prevent interface eroding, maintain information hiding and encapsulation, and yet still accommodate different interface needs among different layers? </p>
| [
{
"answer_id": 9250,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 0,
"selected": false,
"text": "<p>I always create a separate assembly that contains: </p>\n\n<ul>\n<li>A lot of small Interfaces (think ICreateRepository,... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Say you have an application divided into 3-tiers: GUI, business logic, and data access. In your business logic layer you have described your business objects: getters, setters, accessors, and so on... you get the idea. The interface to the business logic layer guarantees safe usage of the business logic, so all the methods and accessors you call will validate input.
This great when you first write the UI code, because you have a neatly defined interface that you can trust.
But here comes the tricky part, when you start writing the data access layer, the interface to the business logic does not accommodate your needs. You need to have more accessors and getters to set fields which are/used to be hidden. Now you are forced to erode the interface of your business logic; now it is possible set fields from the UI layer, which the UI layer has no business setting.
Because of the changes needed for the data access layer, the interface to the business logic has eroded to the point where it is possible to even set the business logic with invalid data. Thus, the interface does not guarantee safe usage anymore.
I hope I explained the problem clearly enough. How do you prevent interface eroding, maintain information hiding and encapsulation, and yet still accommodate different interface needs among different layers? | If I understand the question correctly, you've created a domain model and you would like to write an object-relational mapper to map between records in your database and your domain objects. However, you're concerned about polluting your domain model with the 'plumbing' code that would be necessary to read and write to your object's fields.
Taking a step back, you essentially have two choices of where to put your data mapping code - within the domain class itself or in an external mapping class.
The first option is often called the Active Record pattern and has the advantage that each object knows how to persist itself and has sufficient access to its internal structure to allow it to perform the mapping without needing to expose non-business related fields.
E.g
```
public class User
{
private string name;
private AccountStatus status;
private User()
{
}
public string Name
{
get { return name; }
set { name = value; }
}
public AccountStatus Status
{
get { return status; }
}
public void Activate()
{
status = AccountStatus.Active;
}
public void Suspend()
{
status = AccountStatus.Suspended;
}
public static User GetById(int id)
{
User fetchedUser = new User();
// Lots of database and error-checking code
// omitted for clarity
// ...
fetchedUser.name = (string) reader["Name"];
fetchedUser.status = (int)reader["statusCode"] == 0 ? AccountStatus.Suspended : AccountStatus.Active;
return fetchedUser;
}
public static void Save(User user)
{
// Code to save User's internal structure to database
// ...
}
}
```
In this example, we have an object that represents a User with a Name and an AccountStatus. We don't want to allow the Status to be set directly, perhaps because we want to check that the change is a valid status transition, so we don't have a setter. Fortunately, the mapping code in the GetById and Save static methods have full access to the object's name and status fields.
The second option is to have a second class that is responsible for the mapping. This has the advantage of seperating out the different concerns of business logic and persistence which can allow your design to be more testable and flexible. The challenge with this method is how to expose the name and status fields to the external class. Some options are:
1. Use reflection (which has no qualms about digging deep into your object's private parts)
2. Provide specially-named, public setters (e.g. prefix them with the word 'Private') and hope no one uses them accidentally
3. If your language suports it, make the setters internal but grant your data mapper module access. E.g. use the InternalsVisibleToAttribute in .NET 2.0 onwards or friend functions in C++
For more information, I'd recommend Martin Fowler's classic book 'Patterns of Enterprise Architecture'
However, as a word of warning, before going down the path of writing your own mappers I'd strongly recommend looking at using a 3rd-party object relational mapper (ORM) tool such as nHibernate or Microsoft's Entity Framework. I've worked on four different projects where, for various reasons, we wrote our own mapper and it is very easy to waste a lot of time maintaining and extending the mapper instead of writing code that provides end user value. I've used nHibernate on one project so far and, although it has quite a steep learning curve initially, the investment you put in early on pays off considerably. |
9,256 | <p>Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX.</p>
<p>They print fine in IE7, even IE6.</p>
<p>We need these charts to print, but they also have dynamic content. I don't really want to draw them again as images when the user prints - the Flex component should do it.</p>
<p>We've found a <a href="http://www.anychart.com/blog/2007/09/23/solving-problem-with-printing-flash-content-in-firefox-browser/" rel="nofollow noreferrer">potential workaround</a>, but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough).</p>
<p>Anyone know a workaround?</p>
| [
{
"answer_id": 16362,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 3,
"selected": true,
"text": "<p>Using the ACPrintManager I was able to get firefox 3 to print perfectly!</p>\n\n<p>The one thing I had to add to the examp... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX.
They print fine in IE7, even IE6.
We need these charts to print, but they also have dynamic content. I don't really want to draw them again as images when the user prints - the Flex component should do it.
We've found a [potential workaround](http://www.anychart.com/blog/2007/09/23/solving-problem-with-printing-flash-content-in-firefox-browser/), but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough).
Anyone know a workaround? | Using the ACPrintManager I was able to get firefox 3 to print perfectly!
The one thing I had to add to the example was to check if stage was null, and callLater if the stage was null.
```
private function initPrint():void {
//if we don't have a stage, wait until the next frame and try again
if ( stage == null ) {
callLater(initPrint);
return;
}
PrintManager.init(stage);
var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
data.draw(myDataGrid);
PrintManager.setPrintableContent(data);
}
``` |
9,275 | <p>I writing a report in Visual Studio that takes a user input parameter and runs against an ODBC datasource. I would like to write the query manually and have reporting services replace part of the where clause with the parameter value before sending it to the database. What seems to be happening is that the <code>@parmName</code> I am assuming will be replaced is actually being sent as part of the SQL statement. Am I missing a configuration setting somewhere or is this simply not possible?</p>
<p>I am not using the filter option in the tool because this appears to bring back the full dataset from the database and do the filtering on the SQL Server.</p>
| [
{
"answer_id": 9325,
"author": "Jorriss",
"author_id": 621,
"author_profile": "https://Stackoverflow.com/users/621",
"pm_score": 4,
"selected": true,
"text": "<p>It sounds like you'll need to treat the SQL Statement as an expression. For example:</p>\n\n<pre><code>=\"Select col1, col2 fr... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1104/"
] | I writing a report in Visual Studio that takes a user input parameter and runs against an ODBC datasource. I would like to write the query manually and have reporting services replace part of the where clause with the parameter value before sending it to the database. What seems to be happening is that the `@parmName` I am assuming will be replaced is actually being sent as part of the SQL statement. Am I missing a configuration setting somewhere or is this simply not possible?
I am not using the filter option in the tool because this appears to bring back the full dataset from the database and do the filtering on the SQL Server. | It sounds like you'll need to treat the SQL Statement as an expression. For example:
```
="Select col1, col2 from table 1 Where col3 = " & Parameters!Param1.Value
```
If the where clause is a string you would need to do the following:
```
="Select col1, col2 from table 1 Where col3 = '" & Parameters!Param1.Value & "'"
```
Important: Do not use line breaks in your SQL expression. If you do you will get an error.
Holla back if you need any more assistance. |
9,279 | <p>I absolutely love the <a href="http://winscp.net/eng/docs/task_keep_up_to_date" rel="noreferrer">Keep Remote Directory Up-to-date</a> feature in <a href="http://winscp.net/" rel="noreferrer">Winscp</a>. Unfortunately, I can't find anything as simple to use in OS X or Linux. I know the same thing can <em>theoretically</em> be accomplished using <a href="http://freshmeat.net/projects/changedfiles/" rel="noreferrer">changedfiles</a> or <a href="http://samba.anu.edu.au/rsync/" rel="noreferrer">rsync</a>, but I've always found the tutorials for both tools to be lacking and/or contradictory. </p>
<p>I basically just need a tool that works in OSX or Linux and keeps a remote directory in sync (mirrored) with a local directory while I make changes to the local directory.</p>
<hr>
<p><strong>Update</strong></p>
<p>Looking through the solutions, I see a couple which solve the general problem of keeping a remote directory in sync with a local directory <em>manually</em>. I know that I can set a cron task to run rsync every minute, and this should be fairly close to real time. </p>
<p>This is not the exact solution I was looking for as winscp does this and more: it detects file changes in a directory (while I work on them) and then automatically pushes the changes to the remote server. I know this is not the best solution (no code repository), but it allows me to very quickly test code on a server while I develop it. Does anyone know how to combine rsync with any other commands to get this functionality?</p>
| [
{
"answer_id": 9287,
"author": "dwj",
"author_id": 346,
"author_profile": "https://Stackoverflow.com/users/346",
"pm_score": 5,
"selected": true,
"text": "<p>How \"real-time\" do you want the syncing? I would still lean toward rsync since you know it is going to be fully supported on bot... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/302/"
] | I absolutely love the [Keep Remote Directory Up-to-date](http://winscp.net/eng/docs/task_keep_up_to_date) feature in [Winscp](http://winscp.net/). Unfortunately, I can't find anything as simple to use in OS X or Linux. I know the same thing can *theoretically* be accomplished using [changedfiles](http://freshmeat.net/projects/changedfiles/) or [rsync](http://samba.anu.edu.au/rsync/), but I've always found the tutorials for both tools to be lacking and/or contradictory.
I basically just need a tool that works in OSX or Linux and keeps a remote directory in sync (mirrored) with a local directory while I make changes to the local directory.
---
**Update**
Looking through the solutions, I see a couple which solve the general problem of keeping a remote directory in sync with a local directory *manually*. I know that I can set a cron task to run rsync every minute, and this should be fairly close to real time.
This is not the exact solution I was looking for as winscp does this and more: it detects file changes in a directory (while I work on them) and then automatically pushes the changes to the remote server. I know this is not the best solution (no code repository), but it allows me to very quickly test code on a server while I develop it. Does anyone know how to combine rsync with any other commands to get this functionality? | How "real-time" do you want the syncing? I would still lean toward rsync since you know it is going to be fully supported on both platforms (Windows, too, with cygwin) and you can run it via a cron job. I have a super-simple bash file that I run on my system (this does *not* remove old files):
```
#!/bin/sh
rsync -avrz --progress --exclude-from .rsync_exclude_remote . remote_login@remote_computer:remote_dir
# options
# -a archive
# -v verbose
# -r recursive
# -z compress
```
Your best bet is to set it up and try it out. The `-n (--dry-run)` option is your friend!
Keep in mind that rsync (at least in cygwin) does not support unicode file names (as of 16 Aug 2008). |
9,289 | <p>I would like to filter an array of items by using the <code>map()</code> function. Here is a code snippet:</p>
<pre><code>var filteredItems = items.map(function(item)
{
if( ...some condition... )
{
return item;
}
});
</code></pre>
<p>The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.</p>
<p>Any idea?</p>
<p>EDIT: Thanks, I forgot about <code>filter()</code>, what I wanted is actually a <code>filter()</code> then a <code>map()</code>.</p>
<p>EDIT2: Thanks for pointing that <code>map()</code> and <code>filter()</code> are not implemented in all browsers, although my specific code was not intended to run in a browser.</p>
| [
{
"answer_id": 9295,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 4,
"selected": false,
"text": "<p>That's not what map does. You really want <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268/"
] | I would like to filter an array of items by using the `map()` function. Here is a code snippet:
```
var filteredItems = items.map(function(item)
{
if( ...some condition... )
{
return item;
}
});
```
The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.
Any idea?
EDIT: Thanks, I forgot about `filter()`, what I wanted is actually a `filter()` then a `map()`.
EDIT2: Thanks for pointing that `map()` and `filter()` are not implemented in all browsers, although my specific code was not intended to run in a browser. | You should use the `filter` method rather than map unless you want to mutate the items in the array, in addition to filtering.
eg.
```
var filteredItems = items.filter(function(item)
{
return ...some condition...;
});
```
[Edit: Of course you could always do `sourceArray.filter(...).map(...)` to both filter and mutate] |
9,301 | <p>I'm having trouble with events in Internet Explorer 7.</p>
<p>When I have a form with <strong>two or more</strong> <code>input[type=text]</code> and I press enter, the events occurs in this order:</p>
<ol>
<li>submit button (<code>onClick</code>)</li>
<li>form (<code>onSubmit</code>)</li>
</ol>
<p>Sample code:</p>
<pre><code><form onSubmit="{alert('form::onSubmit'); return false;}">
<input type="text">
<input type="text">
<input type="submit" onClick="{alert('button::onClick');}">
</form>
</code></pre>
<p>If I have only <strong>one</strong> <code>input[type=text]</code> and I press enter the submit button <code>onClick</code> event doesn't fire. Sample code:</p>
<pre><code><form onSubmit="{alert('form::onSubmit'); return false;}">
<input type="text">
<input type="submit" onClick="{alert('button::onClick');}">
</form>
</code></pre>
| [
{
"answer_id": 9327,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 1,
"selected": false,
"text": "<p>If you want code to run when the user presses enter, <strong>just use the onSubmit handler.</strong></p>\n\n<p>If you want c... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] | I'm having trouble with events in Internet Explorer 7.
When I have a form with **two or more** `input[type=text]` and I press enter, the events occurs in this order:
1. submit button (`onClick`)
2. form (`onSubmit`)
Sample code:
```
<form onSubmit="{alert('form::onSubmit'); return false;}">
<input type="text">
<input type="text">
<input type="submit" onClick="{alert('button::onClick');}">
</form>
```
If I have only **one** `input[type=text]` and I press enter the submit button `onClick` event doesn't fire. Sample code:
```
<form onSubmit="{alert('form::onSubmit'); return false;}">
<input type="text">
<input type="submit" onClick="{alert('button::onClick');}">
</form>
``` | The button's onclick should (I think) only fire if the button is actually clicked (or when the focus is on it and the user clicks enter), unless you've added logic to change that.
Is the addition of the extra textbox possibly changing the tab order of your elements (perhaps making the button the default control in that case)? |
9,303 | <p>How do you retrieve selected text using Regex in C#?</p>
<p>I am looking for C# code that is equivalent to this Perl code:</p>
<pre><code>$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = $1;}
</code></pre>
| [
{
"answer_id": 9306,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 4,
"selected": true,
"text": "<pre><code>int indexVal = 0;\nRegex re = new Regex(@\"Index: (\\d*)\")\nMatch m = re.Match(s)\n\nif(m.Success)\n indexVal = int.... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | How do you retrieve selected text using Regex in C#?
I am looking for C# code that is equivalent to this Perl code:
```
$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = $1;}
``` | ```
int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)")
Match m = re.Match(s)
if(m.Success)
indexVal = int.TryParse(m.Groups[1].toString());
```
I might have the group number wrong, but you should be able to figure it out from here. |
9,304 | <p><em>Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.</em></p>
<p>I am used to create my properties in C# using a private and a public field:</p>
<pre><code>private string title;
public string Title
{
get { return title; }
set { title = value; }
}
</code></pre>
<p>Now, with <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> 3.0, we got auto-properties:</p>
<pre><code>public string Title { get; set; }
</code></pre>
<p>I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.</p>
<p>In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.</p>
<p>I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.</p>
<p>So, what am I missing here? Why would anyone actually want to use auto-properties?</p>
| [
{
"answer_id": 9308,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 5,
"selected": false,
"text": "<p>I personally love auto-properties. What's wrong with saving the lines of code? If you want to do stuff in getters or setters, the... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | *Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.*
I am used to create my properties in C# using a private and a public field:
```
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
```
Now, with [.NET](http://en.wikipedia.org/wiki/.NET_Framework) 3.0, we got auto-properties:
```
public string Title { get; set; }
```
I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.
In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.
I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.
So, what am I missing here? Why would anyone actually want to use auto-properties? | We use them all the time in Stack Overflow.
You may also be interested in a discussion of [Properties vs. Public Variables](http://blog.codinghorror.com/properties-vs-public-variables/). IMHO that's really what this is a reaction to, and for that purpose, it's great. |
9,314 | <p>I have a .NET 2.0 windows forms app, which makes heavy use of the <code>ListView</code> control.</p>
<p>I've subclassed the <code>ListView</code> class into a templated <code>SortableListView<T></code> class, so it can be a bit smarter about how it displays things, and sort itself.</p>
<p>Unfortunately this seems to break the Visual Studio Forms Designer, in both VS2005 and 2008.</p>
<p>The program compiles and runs fine, but when I try view the owning form in the designer, I get these Errors:</p>
<ul>
<li>Could not find type 'MyApp.Controls.SortableListView'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built.</li>
</ul>
<p>There is no stack trace or error line information available for this error </p>
<ul>
<li>The variable 'listViewImages' is either undeclared or was never assigned. </li>
</ul>
<p>At MyApp.Main.Designer.cs Line:XYZ Column:1</p>
<pre><code>Call stack:
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
</code></pre>
<p>The line of code in question is where it is actually added to the form, and is</p>
<pre><code>this.imagesTab.Controls.Add( this.listViewImages );
</code></pre>
<p>listViewImages is declared as</p>
<pre><code>private MyApp.Controls.SortableListView<Image> listViewImages;
</code></pre>
<p>and is instantiated in the <code>InitializeComponent</code> method as follows:</p>
<pre><code>this.listViewImages = new MyApp.Controls.SortableListView<Image>();
</code></pre>
<p>As mentioned earlier, the program compiles and runs perfectly, and I've tried shifting the <code>SortableListView</code> class out to a seperate assembly so it can be compiled seperately, but this makes no difference.</p>
<p>I have no idea where to go from here. Any help would be appreciated!</p>
| [
{
"answer_id": 9320,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 3,
"selected": false,
"text": "<p>I've had a problem like this (tho not the same) in the past where my control was in a different namespace to my form even tho ... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | I have a .NET 2.0 windows forms app, which makes heavy use of the `ListView` control.
I've subclassed the `ListView` class into a templated `SortableListView<T>` class, so it can be a bit smarter about how it displays things, and sort itself.
Unfortunately this seems to break the Visual Studio Forms Designer, in both VS2005 and 2008.
The program compiles and runs fine, but when I try view the owning form in the designer, I get these Errors:
* Could not find type 'MyApp.Controls.SortableListView'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built.
There is no stack trace or error line information available for this error
* The variable 'listViewImages' is either undeclared or was never assigned.
At MyApp.Main.Designer.cs Line:XYZ Column:1
```
Call stack:
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
```
The line of code in question is where it is actually added to the form, and is
```
this.imagesTab.Controls.Add( this.listViewImages );
```
listViewImages is declared as
```
private MyApp.Controls.SortableListView<Image> listViewImages;
```
and is instantiated in the `InitializeComponent` method as follows:
```
this.listViewImages = new MyApp.Controls.SortableListView<Image>();
```
As mentioned earlier, the program compiles and runs perfectly, and I've tried shifting the `SortableListView` class out to a seperate assembly so it can be compiled seperately, but this makes no difference.
I have no idea where to go from here. Any help would be appreciated! | >
> when you added the listview, did you add it to the toolbox and then add it to the form?
>
>
>
No, I just edited `Main.Designer.cs` and changed it from `System.Windows.Forms.ListView` to `MyApp.Controls.SortableListView<Image>`
Suspecting it might have been due to the generics led me to actually finding a solution.
For each class that I need to make a SortableListView for, I defined a 'stub class' like this
```
class ImagesListView : SortableListView<Image> { }
```
Then made the `Main.Designer.cs` file refer to these stub classes instead of the `SortableListView`.
It now works, hooray!
Thankfully I am able to do this because all my types are known up front, and I'm only using the `SortableListView` as a method of reducing duplicate code. |
9,321 | <p>How do you create a static class in C++? I should be able to do something like:</p>
<pre><code>cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
</code></pre>
<p>Assuming I created the <code>BitParser</code> class. What would the <code>BitParser</code> class definition look like?</p>
| [
{
"answer_id": 9326,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 4,
"selected": false,
"text": "<p>In C++ you want to create a static function of a class (not a static class).</p>\n\n<pre><code>class BitParser {\np... | 2008/08/12 | [
"https://Stackoverflow.com/questions/9321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | How do you create a static class in C++? I should be able to do something like:
```
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
```
Assuming I created the `BitParser` class. What would the `BitParser` class definition look like? | If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.
But the looks of your sample, you just need to create a public static method on your BitParser object. Like so:
**BitParser.h**
```
class BitParser
{
public:
static bool getBitAt(int buffer, int bitIndex);
// ...lots of great stuff
private:
// Disallow creating an instance of this object
BitParser() {}
};
```
**BitParser.cpp**
```
bool BitParser::getBitAt(int buffer, int bitIndex)
{
bool isBitSet = false;
// .. determine if bit is set
return isBitSet;
}
```
You can use this code to call the method in the same way as your example code. |
9,336 | <p>I'm trying to generate a sitemap.xml on the fly for a particular asp.net website.</p>
<p>I found a couple solutions:<br /></p>
<ol>
<li><a href="http://sitemap.chinookwebs.com/" rel="nofollow noreferrer">chinookwebs</a></li>
<li><a href="http://web.archive.org/web/20080307061444/http://www.cervoproject.info:80/sitemaps.aspx" rel="nofollow noreferrer">cervoproject</a></li>
<li><a href="http://www.codeplex.com/Sitemaps" rel="nofollow noreferrer">newtonking</a></li>
</ol>
<p>Chinookwebs is working great but seems a bit inactive right now and it's impossible to personalize the "priority" and the "changefreq" tags of each and every page, they all inherit the same value from the config file.</p>
<p>What solutions do you guys use?</p>
| [
{
"answer_id": 9360,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Custom handler to generate the sitemap. </p>\n"
},
{
"answer_id": 9382,
"author": "Matt Mitchell",
"autho... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296/"
] | I'm trying to generate a sitemap.xml on the fly for a particular asp.net website.
I found a couple solutions:
1. [chinookwebs](http://sitemap.chinookwebs.com/)
2. [cervoproject](http://web.archive.org/web/20080307061444/http://www.cervoproject.info:80/sitemaps.aspx)
3. [newtonking](http://www.codeplex.com/Sitemaps)
Chinookwebs is working great but seems a bit inactive right now and it's impossible to personalize the "priority" and the "changefreq" tags of each and every page, they all inherit the same value from the config file.
What solutions do you guys use? | Usually you'll use an [HTTP Handler](http://www.google.com/search?q=HTTPHandler+ASP.NET&spell=1) for this. Given a request for...
>
> <http://www.yoursite.com/sitemap.axd>
>
>
>
...your handler will respond with a formatted XML sitemap. Whether that sitemap is generated on the fly, from a database, or some other method is up to the HTTP Handler implementation.
Here's roughly what it would look like:
```
void IHttpHandler.ProcessRequest(HttpContext context)
{
//
// Important to return qualified XML (text/xml) for sitemaps
//
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "text/xml";
//
// Create an XML writer
//
XmlTextWriter writer = new XmlTextWriter(context.Response.Output);
writer.WriteStartDocument();
writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
//
// Now add entries for individual pages..
//
writer.WriteStartElement("url");
writer.WriteElementString("loc", "http://www.codingthewheel.com");
// use W3 date format..
writer.WriteElementString("lastmod", postDate.ToString("yyyy-MM-dd"));
writer.WriteElementString("changefreq", "daily");
writer.WriteElementString("priority", "1.0");
writer.WriteEndElement();
//
// Close everything out and go home.
//
result.WriteEndElement();
result.WriteEndDocument();
writer.Flush();
}
```
This code can be improved but that's the basic idea. |
9,338 | <p>One of the articles I really enjoyed reading recently was <a href="http://blog.last.fm/2008/08/01/quality-control" rel="nofollow noreferrer">Quality Control by Last.FM</a>. In the spirit of this article, I was wondering if anyone else had favorite monitoring setups for web type applications. Or maybe if you don't believe in Log Monitoring, why?<br>
I'm looking for a mix of opinion slash experience here I guess.</p>
| [
{
"answer_id": 9360,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Custom handler to generate the sitemap. </p>\n"
},
{
"answer_id": 9382,
"author": "Matt Mitchell",
"autho... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063/"
] | One of the articles I really enjoyed reading recently was [Quality Control by Last.FM](http://blog.last.fm/2008/08/01/quality-control). In the spirit of this article, I was wondering if anyone else had favorite monitoring setups for web type applications. Or maybe if you don't believe in Log Monitoring, why?
I'm looking for a mix of opinion slash experience here I guess. | Usually you'll use an [HTTP Handler](http://www.google.com/search?q=HTTPHandler+ASP.NET&spell=1) for this. Given a request for...
>
> <http://www.yoursite.com/sitemap.axd>
>
>
>
...your handler will respond with a formatted XML sitemap. Whether that sitemap is generated on the fly, from a database, or some other method is up to the HTTP Handler implementation.
Here's roughly what it would look like:
```
void IHttpHandler.ProcessRequest(HttpContext context)
{
//
// Important to return qualified XML (text/xml) for sitemaps
//
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "text/xml";
//
// Create an XML writer
//
XmlTextWriter writer = new XmlTextWriter(context.Response.Output);
writer.WriteStartDocument();
writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
//
// Now add entries for individual pages..
//
writer.WriteStartElement("url");
writer.WriteElementString("loc", "http://www.codingthewheel.com");
// use W3 date format..
writer.WriteElementString("lastmod", postDate.ToString("yyyy-MM-dd"));
writer.WriteElementString("changefreq", "daily");
writer.WriteElementString("priority", "1.0");
writer.WriteEndElement();
//
// Close everything out and go home.
//
result.WriteEndElement();
result.WriteEndDocument();
writer.Flush();
}
```
This code can be improved but that's the basic idea. |
9,341 | <p>Simple ASP.NET application.</p>
<p>I have two drop-down controls. On the first-drop down I have a JavaScript <code>onChange</code> event. The JavaScript enables the second drop-down and removes a value from it (the value selected in the first drop-down). If they click the blank first value of the drop-down, then the second drop-down will be disabled (and the options reset).</p>
<p>I also have code in the <code>OnPreRender</code> method that will enable or disable the second drop-down based on the value of the first drop-down. This is so that the value of the first drop-down can be selected in code (loading user settings).</p>
<p>My problem is:</p>
<ol>
<li>The user selects something in the first drop-down. The second drop-down will become enabled through JavaScript. </li>
<li>They then change a third drop-down that initiates a post back. After the post back the drop-downs are in the correct state (first value selected, second drop-down enabled).</li>
<li>If they then click the back button, the second drop-down will no longer be enabled although it should be since there's something selected in the first drop-down.</li>
</ol>
<p>I've tried adding a startup script (that will set the correct state of the second-drop down) through <code>ClientScript.RegisterStartupScript</code>, however when this gets called the first drop-down has a <code>selectedIndex</code> of <code>0</code>, not what it actually is. My guess is that the value of the selection gets set after my start script (but still doesn't call the <code>onChange</code> script).</p>
<p>Any ideas on what to try?</p>
| [
{
"answer_id": 9343,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>If the second dropdown is initially enabled through javascript (I'm assuming this is during a javascript onchange, s... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
] | Simple ASP.NET application.
I have two drop-down controls. On the first-drop down I have a JavaScript `onChange` event. The JavaScript enables the second drop-down and removes a value from it (the value selected in the first drop-down). If they click the blank first value of the drop-down, then the second drop-down will be disabled (and the options reset).
I also have code in the `OnPreRender` method that will enable or disable the second drop-down based on the value of the first drop-down. This is so that the value of the first drop-down can be selected in code (loading user settings).
My problem is:
1. The user selects something in the first drop-down. The second drop-down will become enabled through JavaScript.
2. They then change a third drop-down that initiates a post back. After the post back the drop-downs are in the correct state (first value selected, second drop-down enabled).
3. If they then click the back button, the second drop-down will no longer be enabled although it should be since there's something selected in the first drop-down.
I've tried adding a startup script (that will set the correct state of the second-drop down) through `ClientScript.RegisterStartupScript`, however when this gets called the first drop-down has a `selectedIndex` of `0`, not what it actually is. My guess is that the value of the selection gets set after my start script (but still doesn't call the `onChange` script).
Any ideas on what to try? | ```
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void indexChanged(object sender, EventArgs e)
{
Label1.Text = " I did something! ";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Page</title>
</head>
<body>
<script type="text/javascript">
function firstChanged() {
if(document.getElementById("firstSelect").selectedIndex != 0)
document.getElementById("secondSelect").disabled = false;
else
document.getElementById("secondSelect").disabled = true;
}
</script>
<form id="form1" runat="server">
<div>
<select id="firstSelect" onchange="firstChanged()">
<option value="0"></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="secondSelect" disabled="disabled">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<asp:DropDownList ID="DropDownList1" AutoPostBack="true" OnSelectedIndexChanged="indexChanged" runat="server">
<asp:ListItem Text="One" Value="1"></asp:ListItem>
<asp:ListItem Text="Two" Value="2"></asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
<script type="text/javascript">
window.onload = function() {firstChanged();}
</script>
</body>
</html>
```
Edit: Replaced the whole code. This should work even in your user control.
I believe that Register.ClientScriptBlock is not working because the code you write in that block is executed *before* window.onload is called. And, I assume (I am not sure of this point) that the DOM objects do not have their values set at that time. And, this is why you are getting selectedIndex as always 0. |
9,355 | <p>I can display and select a single file in windows explorer like this:</p>
<pre><code>explorer.exe /select, "c:\path\to\file.txt"
</code></pre>
<p>However, I can't work out how to select more than one file. None of the permutations of select I've tried work.</p>
<p>Note: I looked at these pages for docs, neither helped.</p>
<p><a href="https://support.microsoft.com/kb/314853" rel="nofollow noreferrer">https://support.microsoft.com/kb/314853</a><br />
<a href="http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm" rel="nofollow noreferrer">http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm</a></p>
| [
{
"answer_id": 9359,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>it cannot be done through explorer.exe</p>\n"
},
{
"answer_id": 9497,
"author": "bruceatk",
"author_id": 7... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | I can display and select a single file in windows explorer like this:
```
explorer.exe /select, "c:\path\to\file.txt"
```
However, I can't work out how to select more than one file. None of the permutations of select I've tried work.
Note: I looked at these pages for docs, neither helped.
<https://support.microsoft.com/kb/314853>
<http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm> | This should be possible with the shell function [`SHOpenFolderAndSelectItems`](http://msdn.microsoft.com/en-us/library/bb762232(VS.85).aspx)
**EDIT**
Here is some sample code showing how to use the function in C/C++, without error checking:
```
//Directory to open
ITEMIDLIST *dir = ILCreateFromPath(_T("C:\\"));
//Items in directory to select
ITEMIDLIST *item1 = ILCreateFromPath(_T("C:\\Program Files\\"));
ITEMIDLIST *item2 = ILCreateFromPath(_T("C:\\Windows\\"));
const ITEMIDLIST* selection[] = {item1,item2};
UINT count = sizeof(selection) / sizeof(ITEMIDLIST);
//Perform selection
SHOpenFolderAndSelectItems(dir, count, selection, 0);
//Free resources
ILFree(dir);
ILFree(item1);
ILFree(item2);
``` |
9,409 | <p>I have a datagrid getting bound to a dataset, and I want to display the average result in the footer for a column populated with integers.</p>
<p>The way I figure, there's 2 ways I can think of:</p>
<p>1."Use the <strong>Source</strong>, Luke"<br>
In the code where I'm calling DataGrid.DataBind(), use the DataTable.Compute() method (<em>or in my case DataSet.DataTable(0).Compute()</em>). For example: </p>
<pre><code>Dim strAverage = DataTable.Compute("Avg(ColumnName)", "")
</code></pre>
<p>But once I have this, how can I insert it into the footer?</p>
<p>2."<strong>Bound</strong> for Glory"<br>
Using the DataGrid.ItemDataBound event, and calculating a running total from every ListItemType.Item and ListItemType.AlternatingItem, finally displaying in ListItemType.Footer. For example: </p>
<pre><code>Select Case e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
runningTotal += CInt(e.Item.Cells(2).Text)
Case ListItemType.Footer
e.Item.Cells(2).Text = runningTotal/DataGrid.Items.Count
End Select
</code></pre>
<p>This just feels wrong, plus I would have to make sure the runningTotal is reset on every DataBind. </p>
<p>Is there a better way?</p>
| [
{
"answer_id": 9384,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 4,
"selected": true,
"text": "<p>See this KB Article. <a href=\"http://support.microsoft.com/default.aspx?scid=kb;EN-US;914277\" rel=\"noreferrer\">How to configur... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952/"
] | I have a datagrid getting bound to a dataset, and I want to display the average result in the footer for a column populated with integers.
The way I figure, there's 2 ways I can think of:
1."Use the **Source**, Luke"
In the code where I'm calling DataGrid.DataBind(), use the DataTable.Compute() method (*or in my case DataSet.DataTable(0).Compute()*). For example:
```
Dim strAverage = DataTable.Compute("Avg(ColumnName)", "")
```
But once I have this, how can I insert it into the footer?
2."**Bound** for Glory"
Using the DataGrid.ItemDataBound event, and calculating a running total from every ListItemType.Item and ListItemType.AlternatingItem, finally displaying in ListItemType.Footer. For example:
```
Select Case e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
runningTotal += CInt(e.Item.Cells(2).Text)
Case ListItemType.Footer
e.Item.Cells(2).Text = runningTotal/DataGrid.Items.Count
End Select
```
This just feels wrong, plus I would have to make sure the runningTotal is reset on every DataBind.
Is there a better way? | See this KB Article. [How to configure SQL Server 2005 to allow remote connections](http://support.microsoft.com/default.aspx?scid=kb;EN-US;914277).
Oh, and remember that the SQLServer name will probably be MyMachineName\SQLExpress |
9,410 | <p>I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?</p>
| [
{
"answer_id": 9411,
"author": "saint_groceon",
"author_id": 59,
"author_profile": "https://Stackoverflow.com/users/59",
"pm_score": 2,
"selected": false,
"text": "<p>You need to pass a <a href=\"http://www.newty.de/fpt/fpt.html#passPtr\" rel=\"nofollow noreferrer\">function pointer</a>.... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C? | **Declaration**
A prototype for a function which takes a function parameter looks like the following:
```
void func ( void (*f)(int) );
```
This states that the parameter `f` will be a pointer to a function which has a `void` return type and which takes a single `int` parameter. The following function (`print`) is an example of a function which could be passed to `func` as a parameter because it is the proper type:
```
void print ( int x ) {
printf("%d\n", x);
}
```
**Function Call**
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
```
func(print);
```
would call `func`, passing the print function to it.
**Function Body**
As with any parameter, `func` can now use the parameter's name in the function body to access the value of the parameter. Let's say that `func` will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
```
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
```
Since `func`'s parameter declaration says that `f` is the name for a pointer to the desired function, we recall first that if `f` is a pointer then `*f` is the thing that `f` points to (i.e. the function `print` in this case). As a result, just replace every occurrence of print in the loop above with `*f`:
```
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
```
[Source](http://math.hws.edu/bridgeman/courses/331/f05/handouts/c-c++-notes.html) |
9,434 | <p>In my ASP.NET User Control I'm adding some JavaScript to the <code>window.onload</code> event:</p>
<pre><code>if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName))
Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName,
"window.onload = function() {myFunction();};", true);
</code></pre>
<p>My problem is, if there is already something in the <code>onload</code> event, than this overwrites it. How would I go about allowing two user controls to each execute JavaScript in the <code>onload</code> event?</p>
<p><strong>Edit:</strong> Thanks for the info on third party libraries. I'll keep them in mind. </p>
| [
{
"answer_id": 9440,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know a lot about ASP.NET, but why not write a custom function for the onload event that in turn calls both functio... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
] | In my ASP.NET User Control I'm adding some JavaScript to the `window.onload` event:
```
if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName))
Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName,
"window.onload = function() {myFunction();};", true);
```
My problem is, if there is already something in the `onload` event, than this overwrites it. How would I go about allowing two user controls to each execute JavaScript in the `onload` event?
**Edit:** Thanks for the info on third party libraries. I'll keep them in mind. | Most of the "solutions" suggested are Microsoft-specific, or require bloated libraries. Here's one good way. This works with W3C-compliant browsers and with Microsoft IE.
```
if (window.addEventListener) // W3C standard
{
window.addEventListener('load', myFunction, false); // NB **not** 'onload'
}
else if (window.attachEvent) // Microsoft
{
window.attachEvent('onload', myFunction);
}
``` |
9,486 | <p>I could swear I've seen people typing function headers and then hitting some key combination to auto-create function braces and insert the cursor between them like so:</p>
<pre><code>void foo()_
</code></pre>
<p>to</p>
<pre><code>void foo()
{
_
}
</code></pre>
<p>Is this a built-in feature?</p>
| [
{
"answer_id": 9488,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>It can be achieved by using code snippets, some are already built in (try typing \"svm\" and hitting TAB-TAB)..</p>\n\n<p>... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | I could swear I've seen people typing function headers and then hitting some key combination to auto-create function braces and insert the cursor between them like so:
```
void foo()_
```
to
```
void foo()
{
_
}
```
Is this a built-in feature? | Check out [Resharper](http://www.jetbrains.com/resharper/documentation/feature_map.html) - it is a Visual Studio add-on with this feature, among many other development helps.
Also see [C# Completer](http://www.knowdotnet.com/articles/csharpcompleter.html), another add-on.
If you want to roll your own, check out [this article](http://www.developer.com/net/cplus/article.php/3347271). Insane that one should have to do that, though. |
9,614 | <p>Suppose we have a table A:</p>
<pre><code>itemid mark
1 5
2 3
</code></pre>
<p>and table B:</p>
<pre><code>itemid mark
1 3
3 5
</code></pre>
<p>I want to join A*B on A.itemid=B.itemid both right and left ways. i.e. result:</p>
<pre><code>itemid A.mark B.mark
1 5 3
2 3 NULL
3 NULL 5
</code></pre>
<p>Is there a way to do it in one query in MySQL?</p>
| [
{
"answer_id": 9625,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 2,
"selected": false,
"text": "<p>Could do with some work but here is some sql</p>\n\n<pre><code>select distinct T.itemid, A.mark as \"A.mark\", B.mark as \"B.mark... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844/"
] | Suppose we have a table A:
```
itemid mark
1 5
2 3
```
and table B:
```
itemid mark
1 3
3 5
```
I want to join A\*B on A.itemid=B.itemid both right and left ways. i.e. result:
```
itemid A.mark B.mark
1 5 3
2 3 NULL
3 NULL 5
```
Is there a way to do it in one query in MySQL? | It's called a full outer join and it's not supported natively in MySQL, judging from its [docs](http://dev.mysql.com/doc/refman/4.1/en/join.html). You can work around this limitation using UNION as described in the comments to the page I linked to.
[edit] Since others posted snippets, here you go. You can see explanation on the linked page.
```
SELECT *
FROM A LEFT JOIN B ON A.id = B.id
UNION ALL
SELECT *
FROM A RIGHT JOIN B ON A.id = B.id
WHERE A.id IS NULL
``` |
9,632 | <p>Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background.</p>
<p>I know this works well:</p>
<pre><code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBox ContextMenu="{x:Null}"/>
</Page>
</code></pre>
<p>But this doesn't work:</p>
<pre><code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu" Value="{x:Null}"/>
</Style>
</Page.Resources>
<TextBox/>
</Page>
</code></pre>
<p>Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF?</p>
| [
{
"answer_id": 9864,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Try removing the x:Key attribute from the Style resource, leaving TargetType. I know, you're supposed to have that x:Key for... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/900/"
] | Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background.
I know this works well:
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBox ContextMenu="{x:Null}"/>
</Page>
```
But this doesn't work:
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu" Value="{x:Null}"/>
</Style>
</Page.Resources>
<TextBox/>
</Page>
```
Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF? | Due to a late bug report we discovered that we cannot use the ApplicationComands Cut Paste and Copy directly in a partial trusted application. Therefor, using these commands in any Commmand of your controls will do absolutely nothing when executed.
So in essence Brads answer was almost there, it sure looked the right way i.e. no black background, but did not fix the problem.
We decided to "remove" the menu based on Brads answer, like so:
```
<ContextMenu x:Key="TextBoxContextMenu" Width="0" Height="0" />
```
And use this empty context menu like so:
```
<Style TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu" Value="{StaticResource TextBoxContextMenu}" />
</Style>
``` |
9,666 | <p>I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write.</p>
<p>However, I was looking through System.Web.Security.Membership using Reflector and found code like this:</p>
<pre><code>public static class Membership
{
private static bool s_Initialized = false;
private static object s_lock = new object();
private static MembershipProvider s_Provider;
public static MembershipProvider Provider
{
get
{
Initialize();
return s_Provider;
}
}
private static void Initialize()
{
if (s_Initialized)
return;
lock(s_lock)
{
if (s_Initialized)
return;
// Perform initialization...
s_Initialized = true;
}
}
}
</code></pre>
<p>Why is the s_Initialized field read outside of the lock? Couldn't another thread be trying to write to it at the same time? <strong>Are reads and writes of variables atomic?</strong> </p>
| [
{
"answer_id": 9682,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>I thought they were - I'm not sure of the point of the lock in your example unless you're also doing something to s_Provider at... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016/"
] | I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write.
However, I was looking through System.Web.Security.Membership using Reflector and found code like this:
```
public static class Membership
{
private static bool s_Initialized = false;
private static object s_lock = new object();
private static MembershipProvider s_Provider;
public static MembershipProvider Provider
{
get
{
Initialize();
return s_Provider;
}
}
private static void Initialize()
{
if (s_Initialized)
return;
lock(s_lock)
{
if (s_Initialized)
return;
// Perform initialization...
s_Initialized = true;
}
}
}
```
Why is the s\_Initialized field read outside of the lock? Couldn't another thread be trying to write to it at the same time? **Are reads and writes of variables atomic?** | For the definitive answer go to the spec. :)
Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size."
So that confirms that s\_Initialized will never be unstable, and that read and writes to primitve types smaller than 32 bits are atomic.
In particular, `double` and `long` (`Int64` and `UInt64`) are **not** guaranteed to be atomic on a 32-bit platform. You can use the methods on the `Interlocked` class to protect these.
Additionally, while reads and writes are atomic, there is a race condition with addition, subtraction, and incrementing and decrementing primitive types, since they must be read, operated on, and rewritten. The interlocked class allows you to protect these using the `CompareExchange` and `Increment` methods.
Interlocking creates a memory barrier to prevent the processor from reordering reads and writes. The lock creates the only required barrier in this example. |
9,667 | <p>Given a handle of type <code>HWND</code> is it possible to confirm that the handle represents a real window?</p>
| [
{
"answer_id": 9670,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 5,
"selected": true,
"text": "<p>There is a function <code>IsWindow</code> which does exactly what you asked for.</p>\n\n<pre><code>BOOL isRealHandle = IsWindo... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887/"
] | Given a handle of type `HWND` is it possible to confirm that the handle represents a real window? | There is a function `IsWindow` which does exactly what you asked for.
```
BOOL isRealHandle = IsWindow(unknwodnHandle);
```
Look at [this link](http://msdn.microsoft.com/en-us/library/ms633528(VS.85).aspx) for more information. |
9,673 | <p>I have been working with a <code>string[]</code> array in C# that gets returned from a function call. I could possibly cast to a <code>Generic</code> collection, but I was wondering if there was a better way to do it, possibly by using a temp array.</p>
<p><strong>What is the best way to remove duplicates from a C# array?</strong></p>
| [
{
"answer_id": 9677,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 4,
"selected": false,
"text": "<p>If you needed to sort it, then you could implement a sort that also removes duplicates.</p>\n\n<p>Kills two birds w... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | I have been working with a `string[]` array in C# that gets returned from a function call. I could possibly cast to a `Generic` collection, but I was wondering if there was a better way to do it, possibly by using a temp array.
**What is the best way to remove duplicates from a C# array?** | You could possibly use a LINQ query to do this:
```
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
``` |
9,687 | <p>I'm looking for a pattern for performing a dynamic search on multiple tables.</p>
<p>I have no control over the legacy (and poorly designed) database table structure.</p>
<p>Consider a scenario similar to a resume search where a user may want to perform a search against any of the data in the resume and get back a list of resumes that match their search criteria. Any field can be searched at anytime and in combination with one or more other fields.</p>
<p>The actual sql query gets created dynamically depending on which fields are searched. Most solutions I've found involve complicated if blocks, but I can't help but think there must be a more elegant solution since this must be a solved problem by now.</p>
<hr>
<p>Yeah, so I've started down the path of dynamically building the sql in code. Seems godawful. If I really try to support the requested ability to query any combination of any field in any table this is going to be one MASSIVE set of if statements. <em>shiver</em></p>
<hr>
<p>I believe I read that COALESCE only works if your data does not contain NULLs. Is that correct? If so, no go, since I have NULL values all over the place.</p>
| [
{
"answer_id": 9889,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>As far as I understand (and I'm also someone who has written against a horrible legacy database), there is no such thing as d... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097/"
] | I'm looking for a pattern for performing a dynamic search on multiple tables.
I have no control over the legacy (and poorly designed) database table structure.
Consider a scenario similar to a resume search where a user may want to perform a search against any of the data in the resume and get back a list of resumes that match their search criteria. Any field can be searched at anytime and in combination with one or more other fields.
The actual sql query gets created dynamically depending on which fields are searched. Most solutions I've found involve complicated if blocks, but I can't help but think there must be a more elegant solution since this must be a solved problem by now.
---
Yeah, so I've started down the path of dynamically building the sql in code. Seems godawful. If I really try to support the requested ability to query any combination of any field in any table this is going to be one MASSIVE set of if statements. *shiver*
---
I believe I read that COALESCE only works if your data does not contain NULLs. Is that correct? If so, no go, since I have NULL values all over the place. | As far as I understand (and I'm also someone who has written against a horrible legacy database), there is no such thing as dynamic WHERE clauses. It has NOT been solved.
Personally, I prefer to generate my dynamic searches in code. Makes testing convenient. Note, when you create your sql queries in code, don't concatenate in user input. Use your @variables!
The only alternative is to use the COALESCE operator. Let's say you have the following table:
```
Users
-----------
Name nvarchar(20)
Nickname nvarchar(10)
```
and you want to search optionally for name or nickname. The following query will do this:
```
SELECT Name, Nickname
FROM Users
WHERE
Name = COALESCE(@name, Name) AND
Nickname = COALESCE(@nick, Nickname)
```
If you don't want to search for something, just pass in a null. For example, passing in "brian" for @name and null for @nick results in the following query being evaluated:
```
SELECT Name, Nickname
FROM Users
WHERE
Name = 'brian' AND
Nickname = Nickname
```
The coalesce operator turns the null into an identity evaluation, which is always true and doesn't affect the where clause. |
9,702 | <p>As part of our current database work, we are looking at a dealing with the process of updating databases.</p>
<p>A point which has been brought up recurrently, is that of dealing with system vs. user values; in our project user and system vals are stored together. For example...</p>
<p>We have a list of templates.</p>
<pre><code>1, <system template>
2, <system template>
3, <system template>
</code></pre>
<p>These are mapped in the app to an enum (1, 2, 3)</p>
<p>Then a user comes in and adds...</p>
<pre><code>4, <user template>
</code></pre>
<p>...and...</p>
<pre><code>5, <user template>
</code></pre>
<p>Then.. we issue an upgrade.. and insert as part of our upgrade scripts...</p>
<pre><code><new id> [6], <new system template>
</code></pre>
<p>THEN!!... we find a bug in the new system template and need to update it... The problem is how? We cannot update record using ID6 (as we may have inserted it as 9, or 999, so we have to identify the record using some other mechanism)</p>
<p>So, we've come to two possible solutions for this.</p>
<h2><strong>In the red corner (speed)....</strong></h2>
<p>We simply start user Ids at 5000 (or some other value) and test data at 10000 (or some other value). This would allow us to make modifications to system values and test them up to the lower limit of the next ID range. </p>
<p>Advantage...Quick and easy to implement, </p>
<p>Disadvantage... could run out of values if we don't choose a big enough range!</p>
<h2><strong>In the blue corner (scalability)...</strong></h2>
<p>We store, system and user data separately, use GUIDs as Ids and merge the two lists using a view.</p>
<p>Advantage...Scalable..No limits w/regard to DB size. </p>
<p>Disadvantage.. More complicated to implement. (many to one updatable views etc.)</p>
<hr>
<p>I plump squarely for the first option, but looking for some ammo to back me up!</p>
<p>Does anyone have any thoughts on these approaches, or even one(s) that we've missed?</p>
| [
{
"answer_id": 9707,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe I didn't get it, but couldn't you use GUIDs as Ids and still have user and system data together? Then you can a... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1193/"
] | As part of our current database work, we are looking at a dealing with the process of updating databases.
A point which has been brought up recurrently, is that of dealing with system vs. user values; in our project user and system vals are stored together. For example...
We have a list of templates.
```
1, <system template>
2, <system template>
3, <system template>
```
These are mapped in the app to an enum (1, 2, 3)
Then a user comes in and adds...
```
4, <user template>
```
...and...
```
5, <user template>
```
Then.. we issue an upgrade.. and insert as part of our upgrade scripts...
```
<new id> [6], <new system template>
```
THEN!!... we find a bug in the new system template and need to update it... The problem is how? We cannot update record using ID6 (as we may have inserted it as 9, or 999, so we have to identify the record using some other mechanism)
So, we've come to two possible solutions for this.
**In the red corner (speed)....**
---------------------------------
We simply start user Ids at 5000 (or some other value) and test data at 10000 (or some other value). This would allow us to make modifications to system values and test them up to the lower limit of the next ID range.
Advantage...Quick and easy to implement,
Disadvantage... could run out of values if we don't choose a big enough range!
**In the blue corner (scalability)...**
---------------------------------------
We store, system and user data separately, use GUIDs as Ids and merge the two lists using a view.
Advantage...Scalable..No limits w/regard to DB size.
Disadvantage.. More complicated to implement. (many to one updatable views etc.)
---
I plump squarely for the first option, but looking for some ammo to back me up!
Does anyone have any thoughts on these approaches, or even one(s) that we've missed? | I have never had problems (performance or development - TDD & unit testing included) using GUIDs as the ID for my databases, and I've worked on some pretty big ones. Have a look [here](http://www.sql-server-performance.com/articles/per/guid_performance_p2.aspx), [here](http://weblogs.asp.net/wwright/archive/2007/11/04/the-gospel-of-the-guid-and-why-it-matters.aspx) and [here](http://weblogs.asp.net/wwright/archive/2007/11/11/gospel-of-the-guid-answers-to-your-burning-questions-comments-and-insults.aspx) if you want to find out more about using GUIDs (and the potential GOTCHAS involved) as your primary keys - but I can't recommend it highly enough since moving data around safely and DB synchronisation becomes as easy as brushing your teeth in the morning :-)
For your question above, I would either recommend a third column (if possible) that indicates whether or not the template is user or system based, or you can at the very least generate GUIDs for system templates as you insert them and keep a list of those on hand, so that if you need to update the template, you can just target that same GUID in your DEV, UAT and /or PRODUCTION databases without fear of overwriting other templates. The third column would come in handy though for selecting all system or user templates at will, without the need to seperate them into two tables (this is overkill IMHO).
I hope that helps,
Rob G |
9,734 | <p>Why does C#.Net allow the declaration of the string object to be case-insensitive?</p>
<pre><code>String sHello = "Hello";
string sHello = "Hello";
</code></pre>
<p>Both the lower-case and upper-case S of the word String are acceptable and this seems to be the only object that allows this.</p>
<p>Can anyone explain why?</p>
| [
{
"answer_id": 9739,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 2,
"selected": false,
"text": "<p>\"String\" is the name of the class. \"string\" is keyword that maps this class.</p>\n\n<p>it's the same like</p>\n\n<ul>... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | Why does C#.Net allow the declaration of the string object to be case-insensitive?
```
String sHello = "Hello";
string sHello = "Hello";
```
Both the lower-case and upper-case S of the word String are acceptable and this seems to be the only object that allows this.
Can anyone explain why? | **`string`** is a language keyword while `System.String` is the type it aliases.
Both compile to exactly the same thing, similarly:
* **`int`** is `System.Int32`
* **`long`** is `System.Int64`
* **`float`** is `System.Single`
* **`double`** is `System.Double`
* **`char`** is `System.Char`
* **`byte`** is `System.Byte`
* **`short`** is `System.Int16`
* **`ushort`** is `System.UInt16`
* **`uint`** is `System.UInt32`
* **`ulong`** is `System.UInt64`
I think in most cases this is about code legibility - all the basic system value types have aliases, I think the lower case `string` might just be for consistency. |
9,750 | <p>I was reading Joel's book where he was suggesting as interview question:</p>
<blockquote>
<p>Write a program to reverse the "ON" bits in a given byte.</p>
</blockquote>
<p>I only can think of a solution using C. </p>
<p>Asking here so you can show me how to do in a Non C way (if possible)</p>
| [
{
"answer_id": 9752,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>What specifically does that question mean?</p>\n\n<p>Does <em>reverse</em> mean setting 1's to 0's and vice versa?</... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] | I was reading Joel's book where he was suggesting as interview question:
>
> Write a program to reverse the "ON" bits in a given byte.
>
>
>
I only can think of a solution using C.
Asking here so you can show me how to do in a Non C way (if possible) | >
> What specifically does that question mean?
>
>
>
Good question. If reversing the "ON" bits means reversing only the bits that are "ON", then you will always get 0, no matter what the input is. If it means reversing *all* the bits, i.e. changing all 1s to 0s and all 0s to 1s, which is how I initially read it, then that's just a bitwise NOT, or complement. C-based languages have a complement operator, `~`, that does this. For example:
```
unsigned char b = 102; /* 0x66, 01100110 */
unsigned char reverse = ~b; /* 0x99, 10011001 */
``` |
9,805 | <p>I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop:</p>
<pre><code>var iWeeks = 6;
for (int w = 0; w < iWeeks; w++) {
</code></pre>
<p>This works fine, however, some month will only have 5 weeks and in some rare cases, 4.</p>
<p>How can I calculate the number of rows that will be required for a particular month?</p>
<p>This is an example of what I am creating:</p>
<p><img src="https://i.stack.imgur.com/NkxN7.png" alt="enter image description here"></p>
<p>As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.</p>
<p><strong><em>Image found on google</em></strong></p>
<hr>
<p>This is an example of what I am creating:</p>
<p><img src="https://i.stack.imgur.com/NkxN7.png" alt="enter image description here"></p>
<p>As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.</p>
<p><strong><em>Image found on google</em></strong></p>
| [
{
"answer_id": 9806,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>How about checking which week the first and last days will be in?</p>\n"
},
{
"answer_id": 9810,
"author... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop:
```
var iWeeks = 6;
for (int w = 0; w < iWeeks; w++) {
```
This works fine, however, some month will only have 5 weeks and in some rare cases, 4.
How can I calculate the number of rows that will be required for a particular month?
This is an example of what I am creating:

As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.
***Image found on google***
---
This is an example of what I am creating:

As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.
***Image found on google*** | Here is the method that does it:
```
public int GetWeekRows(int year, int month)
{
DateTime firstDayOfMonth = new DateTime(year, month, 1);
DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
int lastWeek = calendar.GetWeekOfYear(lastDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
int firstWeek = calendar.GetWeekOfYear(firstDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return lastWeek - firstWeek + 1;
}
```
You can customize the calendar week rule by modifying the System.Globalization.CalendarWeekRule.FirstFourDayWeek part. I hope the code is self explanatory. |
9,831 | <p>I've asked this question to the forums on the Mootools website and one person said that my class selection was corrupted before an admin came along and changed my post status to invalid. Needless to say this did not help much. I then posted to a google group for Mootools with no response. My question is why doesn't the 'enter', 'leave', 'drop' events fire for my '.drop' elements? The events for the .drag elements are working.</p>
<pre><code><title>Untitled Page</title>
<script type="text/javascript" src="/SDI/includes/mootools-1.2.js"></script>
<script type="text/javascript" src="/SDI/includes/mootools-1.2-more.js"></script>
<script type="text/javascript" charset="utf-8">
window.addEvent('domready', function() {
var fx = [];
$$('#draggables div').each(function(drag){
new Drag.Move(drag, {
droppables: $$('#droppables div'),
onDrop: function(element, droppable){
if(!droppable) {
}
else {
element.setStyle('background-color', '#1d1d20');
}
element.dispose();
},
onEnter: function(element, droppable){
element.setStyle('background-color', '#ffffff');
},
onLeave: function(element, droppable){
element.setStyle('background-color', '#000000');
}
});
});
$$('#droppables div').each(function(drop, index){
drop.addEvents({
'enter': function(el, obj){
drop.setStyle('background-color', '#78ba91');
},
'leave': function(el, obj){
drop.setStyle('background-color', '#1d1d20');
},
'drop': function(el, obj){
el.remove();
}
});
});
});
</script>
<form id="form1" runat="server">
<div>
<div id="draggables">
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
</div>
<div id="droppables">
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
</div>
</div>
</form>
</code></pre>
| [
{
"answer_id": 12910,
"author": "maxsilver",
"author_id": 1477,
"author_profile": "https://Stackoverflow.com/users/1477",
"pm_score": 3,
"selected": true,
"text": "<p>Ok, it looks like there are a couple of issues here. As far as I can tell, there is no such thing as a \"droppable\" in m... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491425/"
] | I've asked this question to the forums on the Mootools website and one person said that my class selection was corrupted before an admin came along and changed my post status to invalid. Needless to say this did not help much. I then posted to a google group for Mootools with no response. My question is why doesn't the 'enter', 'leave', 'drop' events fire for my '.drop' elements? The events for the .drag elements are working.
```
<title>Untitled Page</title>
<script type="text/javascript" src="/SDI/includes/mootools-1.2.js"></script>
<script type="text/javascript" src="/SDI/includes/mootools-1.2-more.js"></script>
<script type="text/javascript" charset="utf-8">
window.addEvent('domready', function() {
var fx = [];
$$('#draggables div').each(function(drag){
new Drag.Move(drag, {
droppables: $$('#droppables div'),
onDrop: function(element, droppable){
if(!droppable) {
}
else {
element.setStyle('background-color', '#1d1d20');
}
element.dispose();
},
onEnter: function(element, droppable){
element.setStyle('background-color', '#ffffff');
},
onLeave: function(element, droppable){
element.setStyle('background-color', '#000000');
}
});
});
$$('#droppables div').each(function(drop, index){
drop.addEvents({
'enter': function(el, obj){
drop.setStyle('background-color', '#78ba91');
},
'leave': function(el, obj){
drop.setStyle('background-color', '#1d1d20');
},
'drop': function(el, obj){
el.remove();
}
});
});
});
</script>
<form id="form1" runat="server">
<div>
<div id="draggables">
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
</div>
<div id="droppables">
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
</div>
</div>
</form>
``` | Ok, it looks like there are a couple of issues here. As far as I can tell, there is no such thing as a "droppable" in mootools. This means your events like 'enter', 'leave' and 'drop' won't work. (These are events on the drag object)
If you change those names to events that elements in mootools have (as in, DOM events) your code works perfectly. For instance, if you change 'enter' and 'leave' to 'mouseover' and 'mouseout', your events fire with no problem. (Opera 9.51 on Windows Vista)
This appears to be the revelant line in the documentation for this, which stats to use DOM events.
<http://docs.mootools.net/Element/Element.Event#Element:addEvents>
Also, on that page, is a link to the events that regular elements can have
<http://www.w3schools.com/html/html_eventattributes.asp>
However, [the advice "TG in SD" gave you in the nabble forums](http://mootools-users.660466.n2.nabble.com/Drag-and-drop-problem-I-m-having-td686391.html) is probably best. If you can, don't bother using these events. Put whatever it is you need to do in the draggable object, and save yourself all this hassle. |
9,882 | <p>I am working on a project that requires the parsing of log files. I am looking for a fast algorithm that would take groups messages like this:</p>
<blockquote>
<p>The temperature at P1 is 35F.</p>
<p>The temperature at P1 is 40F.</p>
<p>The temperature at P3 is 35F.</p>
<p>Logger stopped.</p>
<p>Logger started.</p>
<p>The temperature at P1 is 40F.</p>
</blockquote>
<p>and puts out something in the form of a printf():</p>
<pre><code>"The temperature at P%d is %dF.", Int1, Int2"
{(1,35), (1, 40), (3, 35), (1,40)}
</code></pre>
<p>The algorithm needs to be generic enough to recognize almost any data load in message groups.</p>
<p>I tried searching for this kind of technology, but I don't even know the correct terms to search for.</p>
| [
{
"answer_id": 9886,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 4,
"selected": false,
"text": "<p>I think you might be overlooking and missed fscanf() and sscanf(). Which are the opposite of fprintf() and sprintf().</p>... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am working on a project that requires the parsing of log files. I am looking for a fast algorithm that would take groups messages like this:
>
> The temperature at P1 is 35F.
>
>
> The temperature at P1 is 40F.
>
>
> The temperature at P3 is 35F.
>
>
> Logger stopped.
>
>
> Logger started.
>
>
> The temperature at P1 is 40F.
>
>
>
and puts out something in the form of a printf():
```
"The temperature at P%d is %dF.", Int1, Int2"
{(1,35), (1, 40), (3, 35), (1,40)}
```
The algorithm needs to be generic enough to recognize almost any data load in message groups.
I tried searching for this kind of technology, but I don't even know the correct terms to search for. | Overview:
A **naïve!!** algorithm keeps track of the frequency of words in a per-column manner, where one can assume that each line can be separated into columns with a delimiter.
Example input:
>
> The dog jumped over the moon
>
> The cat jumped over the moon
>
> The moon jumped over the moon
>
> The car jumped over the moon
>
>
>
Frequencies:
```
Column 1: {The: 4}
Column 2: {car: 1, cat: 1, dog: 1, moon: 1}
Column 3: {jumped: 4}
Column 4: {over: 4}
Column 5: {the: 4}
Column 6: {moon: 4}
```
We could partition these frequency lists further by grouping based on the total number of fields, but in this simple and convenient example, we are only working with a fixed number of fields (6).
The next step is to iterate through lines which generated these frequency lists, so let's take the first example.
1. **The**: meets some hand-wavy criteria and the algorithm decides it must be static.
2. **dog**: doesn't appear to be static based on the rest of the frequency list, and thus it must be dynamic as opposed to static text. We loop through a few pre-defined regular expressions and come up with `/[a-z]+/i`.
3. **over**: same deal as #1; it's static, so leave as is.
4. **the**: same deal as #1; it's static, so leave as is.
5. **moon**: same deal as #1; it's static, so leave as is.
Thus, just from going over the first line we can put together the following regular expression:
```
/The ([a-z]+?) jumps over the moon/
```
Considerations:
* Obviously one can choose to scan part or the whole document for the first pass, as long as one is confident the frequency lists will be a sufficient sampling of the entire data.
* False positives may creep into the results, and it will be up to the filtering algorithm (hand-waving) to provide the best threshold between static and dynamic fields, or some human post-processing.
* The overall idea is probably a good one, but the actual implementation will definitely weigh in on the speed and efficiency of this algorithm. |
9,928 | <p>I am working on a small webapp and I want to use Groovy to write some unit testing for my app. Most of my coding is done on Eclipse and I really want to run all the unit testing with the graphical test runner within Eclipse (I really like the green bar :) )</p>
<p>Sadly, after 4 hours of try-and-error, I'm still not able to setup properly. I tried to use the Eclipse Junit4 test runner to run a Groovy file with method annotated for testing using <code>@Test</code>. But it keeps complaining <code>NoClassDefFoundException</code></p>
<p>Anyone can help? </p>
<p>Here is content of my groovy file, named simpleTest.groovy</p>
<pre><code>import org.junit.Test
import static org.junit.Assert.assertEquals
class simpleTest{
@Test
void trial(){
assertEquals 6, 3+3
}
}
</code></pre>
<p>Anyone can help?</p>
| [
{
"answer_id": 55705,
"author": "Kivus",
"author_id": 5590,
"author_profile": "https://Stackoverflow.com/users/5590",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, the Groovy Eclipse plugin is pretty horrible at giving actual helpful information to let you know what is goi... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am working on a small webapp and I want to use Groovy to write some unit testing for my app. Most of my coding is done on Eclipse and I really want to run all the unit testing with the graphical test runner within Eclipse (I really like the green bar :) )
Sadly, after 4 hours of try-and-error, I'm still not able to setup properly. I tried to use the Eclipse Junit4 test runner to run a Groovy file with method annotated for testing using `@Test`. But it keeps complaining `NoClassDefFoundException`
Anyone can help?
Here is content of my groovy file, named simpleTest.groovy
```
import org.junit.Test
import static org.junit.Assert.assertEquals
class simpleTest{
@Test
void trial(){
assertEquals 6, 3+3
}
}
```
Anyone can help? | You might want to give the updated plugin a try, see the [the recent blog post](http://blog.springsource.com/2009/07/30/a-groovier-eclipse-experience) for more details. The theme of this alpha release is *providing an optimized edit/save/compile/test experience*, which seems to be your exact use case.
 |
9,938 | <p>I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list.</p>
<p>The custom list defines an iterator;</p>
<pre><code>class Iterator: public std::iterator<std::forward_iterator_tag, T> {
// ...
}
Iterator begin() {
return (Iterator(root));
}
Iterator end() {
return (Iterator(NULL));
}
</code></pre>
<p>with the appropriate operators overloaded. </p>
<p>Ideally, I would like to do this;</p>
<pre><code>class Foo {
public:
Foo() {
std::list<int> x;
std::vector<int> y;
custom_list<int> z;
iter = x.begin(); // OR
iter = y.begin(); // OR
iter = z.begin();
// ...
};
private:
std::iterator<int> iter;
};
</code></pre>
<p>But obviously these are all iterators of different types. I can assume all the containers are of the same type however.</p>
<p>Is there an elegant way to solve this problem?</p>
| [
{
"answer_id": 9972,
"author": "David Sykes",
"author_id": 259,
"author_profile": "https://Stackoverflow.com/users/259",
"pm_score": 5,
"selected": true,
"text": "<p>Here are some articles you might find of interest</p>\n\n<p><a href=\"http://accu.org/index.php/journals/479\" rel=\"noref... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/263/"
] | I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list.
The custom list defines an iterator;
```
class Iterator: public std::iterator<std::forward_iterator_tag, T> {
// ...
}
Iterator begin() {
return (Iterator(root));
}
Iterator end() {
return (Iterator(NULL));
}
```
with the appropriate operators overloaded.
Ideally, I would like to do this;
```
class Foo {
public:
Foo() {
std::list<int> x;
std::vector<int> y;
custom_list<int> z;
iter = x.begin(); // OR
iter = y.begin(); // OR
iter = z.begin();
// ...
};
private:
std::iterator<int> iter;
};
```
But obviously these are all iterators of different types. I can assume all the containers are of the same type however.
Is there an elegant way to solve this problem? | Here are some articles you might find of interest
[Giving STL Iterators a Base Class](http://accu.org/index.php/journals/479)
[Type Erasure for C++ Iterators](http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/start_page.html)
[any\_iterator Class Reference](http://stlab.adobe.com/classadobe_1_1any__iterator.html) |
9,974 | <p>This is a question I asked on another forum which received some decent answers, but I wanted to see if anyone here has more insight.</p>
<p>The problem is that you have one of your pages in a web application timing out when it gets to a stored procedure call, so you use Sql Profiler, or your application trace logs, to find the query and you paste it into management studio to figure our why it's running slow. But you run it from there and it just blazes along, returning in less than a second each time.</p>
<p>My particular case was using ASP.NET 2.0 and Sql Server 2005, but I think the problem could apply to any RDBMS system.</p>
| [
{
"answer_id": 9982,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": "<p>Try changing the SelectCommand timeout value:</p>\n\n<pre><code>DataAdapter.SelectCommand.CommandTimeout = 120;\n</code><... | 2008/08/13 | [
"https://Stackoverflow.com/questions/9974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | This is a question I asked on another forum which received some decent answers, but I wanted to see if anyone here has more insight.
The problem is that you have one of your pages in a web application timing out when it gets to a stored procedure call, so you use Sql Profiler, or your application trace logs, to find the query and you paste it into management studio to figure our why it's running slow. But you run it from there and it just blazes along, returning in less than a second each time.
My particular case was using ASP.NET 2.0 and Sql Server 2005, but I think the problem could apply to any RDBMS system. | This is what I've learned so far from my research.
.NET sends in connection settings that are not the same as what you get when you log in to management studio. Here is what you see if you sniff the connection with Sql Profiler:
```
-- network protocol: TCP/IP
set quoted_identifier off
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls off
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language us_english
set dateformat mdy
set datefirst 7
set transaction isolation level read committed
```
I am now pasting those setting in above every query that I run when logged in to sql server, to make sure the settings are the same.
For this case, I tried each setting individually, after disconnecting and reconnecting, and found that changing arithabort from off to on reduced the problem query from 90 seconds to 1 second.
The most probable explanation is related to parameter sniffing, which is a technique Sql Server uses to pick what it thinks is the most effective query plan. When you change one of the connection settings, the query optimizer might choose a different plan, and in this case, it apparently chose a bad one.
But I'm not totally convinced of this. I have tried comparing the actual query plans after changing this setting and I have yet to see the diff show any changes.
Is there something else about the arithabort setting that might cause a query to run slowly in some cases?
The solution seemed simple: Just put set arithabort on into the top of the stored procedure. But this could lead to the opposite problem: change the query parameters and suddenly it runs faster with 'off' than 'on'.
For the time being I am running the procedure 'with recompile' to make sure the plan gets regenerated each time. It's Ok for this particular report, since it takes maybe a second to recompile, and this isn't too noticeable on a report that takes 1-10 seconds to return (it's a monster).
But it's not an option for other queries that run much more frequently and need to return as quickly as possible, in just a few milliseconds. |
10,042 | <p>What's the best way to make a linked list in Java?</p>
| [
{
"answer_id": 10050,
"author": "dlinsin",
"author_id": 198,
"author_profile": "https://Stackoverflow.com/users/198",
"pm_score": 6,
"selected": false,
"text": "<p>Java has a <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html\" rel=\"noreferrer\">LinkedList</a> i... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
] | What's the best way to make a linked list in Java? | The obvious solution to developers familiar to Java is to use the **LinkedList** class already provided in **java.util**. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. **Enhancements** to this implementation include making it a **double-linked list**, adding methods to **insert** and **delete** from the middle or end, and by adding **get** and **sort** methods as well.
**Note**: In the example, the Link object doesn't actually contain another Link object - *nextLink* is actually only a reference to another link.
```
class Link {
public int data1;
public double data2;
public Link nextLink;
//Link constructor
public Link(int d1, double d2) {
data1 = d1;
data2 = d2;
}
//Print Link data
public void printLink() {
System.out.print("{" + data1 + ", " + data2 + "} ");
}
}
class LinkList {
private Link first;
//LinkList constructor
public LinkList() {
first = null;
}
//Returns true if list is empty
public boolean isEmpty() {
return first == null;
}
//Inserts a new Link at the first of the list
public void insert(int d1, double d2) {
Link link = new Link(d1, d2);
link.nextLink = first;
first = link;
}
//Deletes the link at the first of the list
public Link delete() {
Link temp = first;
if(first == null){
return null;
//throw new NoSuchElementException(); // this is the better way.
}
first = first.nextLink;
return temp;
}
//Prints list data
public void printList() {
Link currentLink = first;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
class LinkListTest {
public static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1, 1.01);
list.insert(2, 2.02);
list.insert(3, 3.03);
list.insert(4, 4.04);
list.insert(5, 5.05);
list.printList();
while(!list.isEmpty()) {
Link deletedLink = list.delete();
System.out.print("deleted: ");
deletedLink.printLink();
System.out.println("");
}
list.printList();
}
}
``` |
10,071 | <p>I'm working on an app that grabs and installs a bunch of updates off an an external server, and need some help with threading. The user follows this process:</p>
<ul>
<li>Clicks button</li>
<li>Method checks for updates, count is returned.</li>
<li>If greater than 0, then ask the user if they want to install using MessageBox.Show().</li>
<li>If yes, it runs through a loop and call BeginInvoke() on the run() method of each update to run it in the background.</li>
<li>My update class has some events that are used to update a progress bar etc. </li>
</ul>
<p>The progress bar updates are fine, but the MessageBox is not fully cleared from the screen because the update loop starts right after the user clicks yes (see screenshot below).</p>
<ul>
<li>What should I do to make the messagebox disappear instantly before the update loop starts?</li>
<li>Should I be using Threads instead of BeginInvoke()?</li>
<li>Should I be doing the initial update check on a separate thread and calling MessageBox.Show() from that thread?</li>
</ul>
<p><strong>Code</strong></p>
<pre><code>// Button clicked event handler code...
DialogResult dlgRes = MessageBox.Show(
string.Format("There are {0} updates available.\n\nInstall these now?",
um2.Updates.Count), "Updates Available",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2
);
if (dlgRes == DialogResult.Yes)
{
ProcessAllUpdates(um2);
}
// Processes a bunch of items in a loop
private void ProcessAllUpdates(UpdateManager2 um2)
{
for (int i = 0; i < um2.Updates.Count; i++)
{
Update2 update = um2.Updates[i];
ProcessSingleUpdate(update);
int percentComplete = Utilities.CalculatePercentCompleted(i, um2.Updates.Count);
UpdateOverallProgress(percentComplete);
}
}
// Process a single update with IAsyncResult
private void ProcessSingleUpdate(Update2 update)
{
update.Action.OnStart += Action_OnStart;
update.Action.OnProgress += Action_OnProgress;
update.Action.OnCompletion += Action_OnCompletion;
//synchronous
//update.Action.Run();
// async
IAsyncResult ar = this.BeginInvoke((MethodInvoker)delegate() { update.Action.Run(); });
}
</code></pre>
<p><strong>Screenshot</strong></p>
<p><a href="http://www.flickr.com/photos/brianly/2760435228/" rel="nofollow noreferrer" title="Windows Mobile Bug by BrianLy, on Flickr"><img src="https://farm4.static.flickr.com/3043/2760435228_1af7dbf365_o.gif" width="233" height="266" alt="Windows Mobile Bug" /></a></p>
| [
{
"answer_id": 10116,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried putting a </p>\n\n<pre><code>Application.DoEvents()\n</code></pre>\n\n<p>in here</p>\n\n<pre><code>if (... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | I'm working on an app that grabs and installs a bunch of updates off an an external server, and need some help with threading. The user follows this process:
* Clicks button
* Method checks for updates, count is returned.
* If greater than 0, then ask the user if they want to install using MessageBox.Show().
* If yes, it runs through a loop and call BeginInvoke() on the run() method of each update to run it in the background.
* My update class has some events that are used to update a progress bar etc.
The progress bar updates are fine, but the MessageBox is not fully cleared from the screen because the update loop starts right after the user clicks yes (see screenshot below).
* What should I do to make the messagebox disappear instantly before the update loop starts?
* Should I be using Threads instead of BeginInvoke()?
* Should I be doing the initial update check on a separate thread and calling MessageBox.Show() from that thread?
**Code**
```
// Button clicked event handler code...
DialogResult dlgRes = MessageBox.Show(
string.Format("There are {0} updates available.\n\nInstall these now?",
um2.Updates.Count), "Updates Available",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2
);
if (dlgRes == DialogResult.Yes)
{
ProcessAllUpdates(um2);
}
// Processes a bunch of items in a loop
private void ProcessAllUpdates(UpdateManager2 um2)
{
for (int i = 0; i < um2.Updates.Count; i++)
{
Update2 update = um2.Updates[i];
ProcessSingleUpdate(update);
int percentComplete = Utilities.CalculatePercentCompleted(i, um2.Updates.Count);
UpdateOverallProgress(percentComplete);
}
}
// Process a single update with IAsyncResult
private void ProcessSingleUpdate(Update2 update)
{
update.Action.OnStart += Action_OnStart;
update.Action.OnProgress += Action_OnProgress;
update.Action.OnCompletion += Action_OnCompletion;
//synchronous
//update.Action.Run();
// async
IAsyncResult ar = this.BeginInvoke((MethodInvoker)delegate() { update.Action.Run(); });
}
```
**Screenshot**
[](http://www.flickr.com/photos/brianly/2760435228/ "Windows Mobile Bug by BrianLy, on Flickr") | Your UI isn't updating because all the work is happening in the user interface thread.
Your call to:
```
this.BeginInvoke((MethodInvoker)delegate() {update.Action.Run(); })
```
is saying invoke update.Action.Run() on the thread that created "this" (your form), which is the user interface thread.
```
Application.DoEvents()
```
will indeed give the UI thread the chance to redraw the screen, but I'd be tempted to create new delegate, and call BeginInvoke on that.
This will execute the update.Action.Run() function on a seperate thread allocated from the thread pool. You can then keep checking the IAsyncResult until the update is complete, querying the update object for its progress after every check (because you can't have the other thread update the progress bar/UI), then calling Application.DoEvents().
You also are supposed to call EndInvoke() afterwards otherwise you may end up leaking resources
I would also be tempted to put a cancel button on the progress dialog, and add a timeout, otherwise if the update gets stuck (or takes too long) then your application will have locked up forever. |
10,123 | <p>I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:</p>
<blockquote>
<p>a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.</p>
</blockquote>
<p>How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet:</p>
<pre><code>(pid,status) = os.wait()
(exitstatus, signum) = decode(status)
</code></pre>
| [
{
"answer_id": 10129,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": true,
"text": "<p>This will do what you want:</p>\n\n<pre><code>signum = status & 0xff\nexitstatus = (status & 0xff00) >> 8... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:
>
> a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.
>
>
>
How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet:
```
(pid,status) = os.wait()
(exitstatus, signum) = decode(status)
``` | This will do what you want:
```
signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
``` |
10,149 | <p>For context, I am something of an emacs newbie. I haven't used it for very long, but have been using it more and more (I like it a lot). Also I'm comfortable with lisp, but not super familiar with elisp.</p>
<p>What I need to do is bind a regular expression to a keyboard combination because I use this particular regex so often.</p>
<p>What I've been doing: </p>
<pre><code>M-C-s ^.*Table\(\(.*\n\)*?GO\)
</code></pre>
<p>Note, I used newline above, but I've found that for <code>isearch-forward-regexp</code>, you really need to replace the <code>\n</code> in the regular expression with the result of <kbd>C-q Q-j</kbd>. This inserts a literal newline (without ending the command) enabling me to put a newline into the expression and match across lines.</p>
<p>How can I bind this to a key combination? </p>
<p>I vaguely understand that I need to create an elisp function which executes <code>isearch-forward-regexp</code> with the expression, but I'm fuzzy on the details. I've searched google and found most documentation to be a tad confusing.</p>
<p><em>How can I bind a regular expression to a key combination in emacs?</em></p>
<hr>
<p><strong>Mike Stone had the best answer so far -- not <em>exactly</em> what I was looking for but it worked for what I needed</strong> </p>
<p>Edit - this sort of worked, but after storing the macro, when I went back to use it later, I couldn't use it with <kbd>C-x e</kbd>. (i.e., if I reboot emacs and then type <kbd>M-x macro-name</kbd>, and then <kbd>C-x e</kbd>, I get a message in the minibuffer like 'no last kbd macro' or something similar)</p>
<hr>
<p>@Mike Stone - Thanks for the information. I tried creating a macro like so:</p>
<pre><code>C-x( M-C-s ^.*Table\(\(.*C-q C-J\)*?GO\) C-x)
</code></pre>
<p>This created my macro, but when I executed my macro I didn't get the same highlighting that I ordinarily get when I use <code>isearch-forward-regexp</code>. Instead it just jumped to the end of the next match of the expression. So that doesn't really work for what I need. Any ideas?</p>
<p>Edit: It looks like I <em>can</em> use macros to do what I want, I just have to think outside the box of <code>isearch-forward-regexp</code>. I'll try what you suggested.</p>
| [
{
"answer_id": 10161,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": true,
"text": "<p>You can use macros, just do <kbd>C-x (</kbd> then do everything for the macro, then <kbd>C-x )</kbd> to end the macro, the... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92/"
] | For context, I am something of an emacs newbie. I haven't used it for very long, but have been using it more and more (I like it a lot). Also I'm comfortable with lisp, but not super familiar with elisp.
What I need to do is bind a regular expression to a keyboard combination because I use this particular regex so often.
What I've been doing:
```
M-C-s ^.*Table\(\(.*\n\)*?GO\)
```
Note, I used newline above, but I've found that for `isearch-forward-regexp`, you really need to replace the `\n` in the regular expression with the result of `C-q Q-j`. This inserts a literal newline (without ending the command) enabling me to put a newline into the expression and match across lines.
How can I bind this to a key combination?
I vaguely understand that I need to create an elisp function which executes `isearch-forward-regexp` with the expression, but I'm fuzzy on the details. I've searched google and found most documentation to be a tad confusing.
*How can I bind a regular expression to a key combination in emacs?*
---
**Mike Stone had the best answer so far -- not *exactly* what I was looking for but it worked for what I needed**
Edit - this sort of worked, but after storing the macro, when I went back to use it later, I couldn't use it with `C-x e`. (i.e., if I reboot emacs and then type `M-x macro-name`, and then `C-x e`, I get a message in the minibuffer like 'no last kbd macro' or something similar)
---
@Mike Stone - Thanks for the information. I tried creating a macro like so:
```
C-x( M-C-s ^.*Table\(\(.*C-q C-J\)*?GO\) C-x)
```
This created my macro, but when I executed my macro I didn't get the same highlighting that I ordinarily get when I use `isearch-forward-regexp`. Instead it just jumped to the end of the next match of the expression. So that doesn't really work for what I need. Any ideas?
Edit: It looks like I *can* use macros to do what I want, I just have to think outside the box of `isearch-forward-regexp`. I'll try what you suggested. | You can use macros, just do `C-x (` then do everything for the macro, then `C-x )` to end the macro, then `C-x e` will execute the last defined macro. Then, you can name it using `M-x name-last-kbd-macro` which lets you assign a name to it, which you can then invoke with `M-x TESTIT`, then store the definition using `M-x insert-kbd-macro` which will put the macro into your current buffer, and then you can store it in your `.emacs` file.
Example:
```
C-x( abc *return* C-x)
```
Will define a macro to type "abc" and press return.
```
C-xeee
```
Executes the above macro immediately, 3 times (first e executes it, then following 2 e's will execute it twice more).
```
M-x name-last-kbd-macro testit
```
Names the macro to "testit"
```
M-x testit
```
Executes the just named macro (prints "abc" then return).
```
M-x insert-kbd-macro
```
Puts the following in your current buffer:
```
(fset 'testit
[?a ?b ?c return])
```
Which can then be saved in your `.emacs` file to use the named macro over and over again after restarting emacs. |
10,158 | <p>What's the easiest way to do an "instring" type function with a regex? For example, how could I reject a whole string because of the presence of a single character such as <code>:</code>? For example: </p>
<ul>
<li><code>this</code> - okay</li>
<li><code>there:is</code> - not okay because of <code>:</code></li>
</ul>
<p>More practically, how can I match the following string: </p>
<pre><code>//foo/bar/baz[1]/ns:foo2/@attr/text()
</code></pre>
<p>For any node test on the xpath that doesn't include a namespace?</p>
<pre><code>(/)?(/)([^:/]+)
</code></pre>
<p>Will match the node tests but includes the namespace prefix which makes it faulty.</p>
| [
{
"answer_id": 10168,
"author": "Adam Lerman",
"author_id": 673,
"author_profile": "https://Stackoverflow.com/users/673",
"pm_score": 0,
"selected": false,
"text": "<p>I dont know regex syntax very well but could you not do:</p>\n\n<p><code>[any alpha numeric]\\*:[any alphanumeric]\\*</c... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64/"
] | What's the easiest way to do an "instring" type function with a regex? For example, how could I reject a whole string because of the presence of a single character such as `:`? For example:
* `this` - okay
* `there:is` - not okay because of `:`
More practically, how can I match the following string:
```
//foo/bar/baz[1]/ns:foo2/@attr/text()
```
For any node test on the xpath that doesn't include a namespace?
```
(/)?(/)([^:/]+)
```
Will match the node tests but includes the namespace prefix which makes it faulty. | I'm still not sure whether you just wanted to detect if the Xpath contains a namespace, or whether you want to remove the references to the namespace. So here's some sample code (in C#) that does both.
```
class Program
{
static void Main(string[] args)
{
string withNamespace = @"//foo/ns2:bar/baz[1]/ns:foo2/@attr/text()";
string withoutNamespace = @"//foo/bar/baz[1]/foo2/@attr/text()";
ShowStuff(withNamespace);
ShowStuff(withoutNamespace);
}
static void ShowStuff(string input)
{
Console.WriteLine("'{0}' does {1}contain namespaces", input, ContainsNamespace(input) ? "" : "not ");
Console.WriteLine("'{0}' without namespaces is '{1}'", input, StripNamespaces(input));
}
static bool ContainsNamespace(string input)
{
// a namspace must start with a character, but can have characters and numbers
// from that point on.
return Regex.IsMatch(input, @"/?\w[\w\d]+:\w[\w\d]+/?");
}
static string StripNamespaces(string input)
{
return Regex.Replace(input, @"(/?)\w[\w\d]+:(\w[\w\d]+)(/?)", "$1$2$3");
}
}
```
Hope that helps! Good luck. |
10,190 | <p>Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results.</p>
<p>What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user?</p>
<p>Does LINQ simplify the solution?</p>
| [
{
"answer_id": 10194,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 5,
"selected": true,
"text": "<p>On MS SQL Server 2005 and above, <a href=\"http://msdn.microsoft.com/en-us/library/ms186734.aspx\" rel=\"noreferrer\">ROW_... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] | Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results.
What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user?
Does LINQ simplify the solution? | On MS SQL Server 2005 and above, [ROW\_NUMBER()](http://msdn.microsoft.com/en-us/library/ms186734.aspx) seems to work:
[T-SQL: Paging with ROW\_NUMBER()](http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx)
```
DECLARE @PageNum AS INT;
DECLARE @PageSize AS INT;
SET @PageNum = 2;
SET @PageSize = 10;
WITH OrdersRN AS
(
SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum
,OrderID
,OrderDate
,CustomerID
,EmployeeID
FROM dbo.Orders
)
SELECT *
FROM OrdersRN
WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1
AND @PageNum * @PageSize
ORDER BY OrderDate
,OrderID;
``` |
10,205 | <p>I'm looking at parsing a delimited string, something on the order of</p>
<p>a,b,c</p>
<p>But this is a very simple example, and parsing delimited data can get complex; for instance</p>
<p>1,"Your simple algorithm, it fails",True</p>
<p>would blow your naiive string.Split implementation to bits. Is there anything I can freely use/steal/copy and paste that offers a relatively bulletproof solution to parsing delimited text? .NET, plox.</p>
<p><em>Update:</em> I decided to go with the <a href="http://msdn.microsoft.com/en-us/library/f68t4563.aspx" rel="nofollow noreferrer">TextFieldParser</a>, which is part of VB.NET's pile of goodies hidden away in Microsoft.VisualBasic.DLL.</p>
| [
{
"answer_id": 10210,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 0,
"selected": false,
"text": "<p>I am thinking that a generic framework would need to specify between two things:\n1. What are the delimiting characters.\n2.... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm looking at parsing a delimited string, something on the order of
a,b,c
But this is a very simple example, and parsing delimited data can get complex; for instance
1,"Your simple algorithm, it fails",True
would blow your naiive string.Split implementation to bits. Is there anything I can freely use/steal/copy and paste that offers a relatively bulletproof solution to parsing delimited text? .NET, plox.
*Update:* I decided to go with the [TextFieldParser](http://msdn.microsoft.com/en-us/library/f68t4563.aspx), which is part of VB.NET's pile of goodies hidden away in Microsoft.VisualBasic.DLL. | I use this to read from a file
```
string filename = @textBox1.Text;
string[] fields;
string[] delimiter = new string[] {"|"};
using (Microsoft.VisualBasic.FileIO.TextFieldParser parser =
new Microsoft.VisualBasic.FileIO.TextFieldParser(filename)) {
parser.Delimiters = delimiter;
parser.HasFieldsEnclosedInQuotes = false;
while (!parser.EndOfData) {
fields = parser.ReadFields();
//Do what you need
}
}
```
I am sure someone here can transform this to parser a string that is in memory. |
10,229 | <p>Consider this problem: I have a program which should fetch (let's say) 100 records from a database, and then for each one it should get updated information from a web service. There are two ways to introduce parallelism in this scenario:</p>
<ol>
<li><p>I start each request to the web service on a new Thread. The number of simultaneous threads is controlled by some external parameter (or dynamically adjusted somehow).</p></li>
<li><p>I create smaller batches (let's say of 10 records each) and launch each batch on a separate thread (so taking our example, 10 threads).</p></li>
</ol>
<p>Which is a better approach, and why do you think so?</p>
| [
{
"answer_id": 10264,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>Two things to consider.</p>\n<h3>1. How long will it take to process a record?</h3>\n<p>If record processing is very quic... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] | Consider this problem: I have a program which should fetch (let's say) 100 records from a database, and then for each one it should get updated information from a web service. There are two ways to introduce parallelism in this scenario:
1. I start each request to the web service on a new Thread. The number of simultaneous threads is controlled by some external parameter (or dynamically adjusted somehow).
2. I create smaller batches (let's say of 10 records each) and launch each batch on a separate thread (so taking our example, 10 threads).
Which is a better approach, and why do you think so? | Option 3 is the best:
Use Async IO.
Unless your request processing is complex and heavy, your program is going to spend 99% of it's time waiting for the HTTP requests.
This is exactly what Async IO is designed for - Let the windows networking stack (or .net framework or whatever) worry about all the waiting, and just use a single thread to dispatch and 'pick up' the results.
Unfortunately the .NET framework makes it a right pain in the ass. It's easier if you're just using raw sockets or the Win32 api. Here's a (tested!) example using C#3 anyway:
```
using System.Net; // need this somewhere
// need to declare an class so we can cast our state object back out
class RequestState {
public WebRequest Request { get; set; }
}
static void Main( string[] args ) {
// stupid cast neccessary to create the request
HttpWebRequest request = WebRequest.Create( "http://www.stackoverflow.com" ) as HttpWebRequest;
request.BeginGetResponse(
/* callback to be invoked when finished */
(asyncResult) => {
// fetch the request object out of the AsyncState
var state = (RequestState)asyncResult.AsyncState;
var webResponse = state.Request.EndGetResponse( asyncResult ) as HttpWebResponse;
// there we go;
Debug.Assert( webResponse.StatusCode == HttpStatusCode.OK );
Console.WriteLine( "Got Response from server:" + webResponse.Server );
},
/* pass the request through to our callback */
new RequestState { Request = request }
);
// blah
Console.WriteLine( "Waiting for response. Press a key to quit" );
Console.ReadKey();
}
```
EDIT:
In the case of .NET, the 'completion callback' actually gets fired in a ThreadPool thread, not in your main thread, so you will still need to lock any shared resources, but it still saves you all the trouble of managing threads. |
10,314 | <p>Being new to Objective-C (but a long term C/++) programmer I'm looking for advice/recommendations on naming conventions for variables.</p>
<p>My personal preference would be to utilize a prefix for instance variables both for clarity within functions and to prevent shadowing of function parameters. However I'm a fan of properties which rules out prefixes (unless you also prefix your property names, which doesn't work too well and looks daft). Similarly I could use the "self.variable" convention, but only if I make EVERYTHING a property.</p>
<p>So given the code below what's your preferred naming style for instance/function variables? And if you don't bother, how do you deal with shadowing on function params?</p>
<pre><code>@interface GridItem : NSObject
{
CGRect _rect;
...
}
@end
-(void) initFromRect:(CGRect)rect
{
_rect = rect;
...
}
</code></pre>
<p>Cheers!</p>
| [
{
"answer_id": 10342,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 1,
"selected": false,
"text": "<p>I don't like using underscores as prefixes for any identifiers, because C and C++ both reserve certain undersco... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] | Being new to Objective-C (but a long term C/++) programmer I'm looking for advice/recommendations on naming conventions for variables.
My personal preference would be to utilize a prefix for instance variables both for clarity within functions and to prevent shadowing of function parameters. However I'm a fan of properties which rules out prefixes (unless you also prefix your property names, which doesn't work too well and looks daft). Similarly I could use the "self.variable" convention, but only if I make EVERYTHING a property.
So given the code below what's your preferred naming style for instance/function variables? And if you don't bother, how do you deal with shadowing on function params?
```
@interface GridItem : NSObject
{
CGRect _rect;
...
}
@end
-(void) initFromRect:(CGRect)rect
{
_rect = rect;
...
}
```
Cheers! | Most Cocoa projects use underbar as a non-`IBOutlet` instance variable prefix, and use no prefix for `IBOutlet` instance variables.
The reason I don't use underbars for `IBOutlet` instance variables is that when a nib file is loaded, if you have a setter method for a connected outlet, that setter will be called. *However* this mechanism does *not* use Key-Value Coding, so an IBOutlet whose name is prefixed with an underbar (*e.g.* `_myField`) will *not* be set unless the setter is named exactly like the outlet (*e.g.* `set_myField:`), which is non-standard and gross.
Also, be aware that using properties like `self.myProp` is **not** the same as accessing instance variables. You are **sending a message** when you use a property, just like if you used bracket notation like `[self myProp]`. All properties do is give you a concise syntax for specifying both the getter and setter in a single line, and allow you to synthesize their implementation; they do not actually short-circuit the message dispatch mechanism. If you want to access an instance variable directly but prefix it with `self` you need to treat `self` as a pointer, like `self->myProp` which really is a C-style field access.
Finally, never use Hungarian notation when writing Cocoa code, and shy away from other prefixes like "f" and "m\_" — that will mark the code as having been written by someone who doesn't "get it" and will cause it to be viewed by suspicion by other Cocoa developers.
In general, follow the advice in the [Coding Guidelines for Cocoa](http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/index.html "Coding Guidelines for Cocoa") document at the [Apple Developer Connection](http://developer.apple.com/ "Apple Developer Connection"), and other developers will be able to pick up and understand your code, and your code will work well with all of the Cocoa features that use runtime introspection.
Here's what a window controller class might look like, using my conventions:
```
// EmployeeWindowController.h
#import <AppKit/NSWindowController.h>
@interface EmployeeWindowController : NSWindowController {
@private
// model object this window is presenting
Employee *_employee;
// outlets connected to views in the window
IBOutlet NSTextField *nameField;
IBOutlet NSTextField *titleField;
}
- (id)initWithEmployee:(Employee *)employee;
@property(readwrite, retain) Employee *employee;
@end
// EmployeeWindowController.m
#import "EmployeeWindowController.h"
@implementation EmployeeWindowController
@synthesize employee = _employee;
- (id)initWithEmployee:(Employee *)employee {
if (self = [super initWithWindowNibName:@"Employee"]) {
_employee = [employee retain];
}
return self;
}
- (void)dealloc {
[_employee release];
[super dealloc];
}
- (void)windowDidLoad {
// populates the window's controls, not necessary if using bindings
[nameField setStringValue:self.employee.name];
[titleField setStringValue:self.employee.title];
}
@end
```
You'll see that I'm using the instance variable that references an `Employee` directly in my `-init` and `-dealloc` method, while I'm using the property in other methods. That's generally a good pattern with properties: Only ever touch the underlying instance variable for a property in initializers, in `-dealloc`, and in the getter and setter for the property. |
10,323 | <p>I recently read a nice <a href="http://macdevelopertips.com/ruby/using-a-string-as-a-file-in-ruby.html" rel="noreferrer">post</a> on using <code>StringIO</code> in Ruby. What the author doesn't mention, though, is that <code>StringIO</code> is just an "I." There's no "O." You <em>can't</em> do this, for example:</p>
<pre><code>s = StringIO.new
s << 'foo'
s << 'bar'
s.to_s
# => should be "foo\nbar"
# => really is ''`
</code></pre>
<p>Ruby really needs a StringBuffer just like the one Java has. StringBuffers serve two important purposes. First, they let you test the output half of what Ruby's StringIO does. Second, they are useful for building up long strings from small parts -- something that Joel reminds us over and over again is otherwise very very slow.</p>
<p>Is there a good replacement?</p>
<p>It's true that Strings in Ruby are mutable, but that doesn't mean we should always rely on that functionality. If <code>stuff</code> is large, the performance and memory requirements of this, for example, is really bad.</p>
<pre><code>result = stuff.map(&:to_s).join(' ')
</code></pre>
<p>The "correct" way to do this in Java is:</p>
<pre><code>result = StringBuffer.new("")
for(String s : stuff) {
result.append(s);
}
</code></pre>
<p>Though my Java is a bit rusty.</p>
| [
{
"answer_id": 10335,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>Well, a StringBuffer is not quite as necessary in Ruby, mainly because Strings in Ruby are mutable... thus you can build ... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | I recently read a nice [post](http://macdevelopertips.com/ruby/using-a-string-as-a-file-in-ruby.html) on using `StringIO` in Ruby. What the author doesn't mention, though, is that `StringIO` is just an "I." There's no "O." You *can't* do this, for example:
```
s = StringIO.new
s << 'foo'
s << 'bar'
s.to_s
# => should be "foo\nbar"
# => really is ''`
```
Ruby really needs a StringBuffer just like the one Java has. StringBuffers serve two important purposes. First, they let you test the output half of what Ruby's StringIO does. Second, they are useful for building up long strings from small parts -- something that Joel reminds us over and over again is otherwise very very slow.
Is there a good replacement?
It's true that Strings in Ruby are mutable, but that doesn't mean we should always rely on that functionality. If `stuff` is large, the performance and memory requirements of this, for example, is really bad.
```
result = stuff.map(&:to_s).join(' ')
```
The "correct" way to do this in Java is:
```
result = StringBuffer.new("")
for(String s : stuff) {
result.append(s);
}
```
Though my Java is a bit rusty. | I looked at the ruby documentation for `StringIO`, and it looks like what you want is [`StringIO#string`](http://ruby-doc.org/stdlib/libdoc/stringio/rdoc/classes/StringIO.html#method-i-string), not `StringIO#to_s`
Thus, change your code to:
```
s = StringIO.new
s << 'foo'
s << 'bar'
s.string
``` |
10,349 | <p>I'm sure there is a good (or at least decent) reason for this. What is it?</p>
| [
{
"answer_id": 10354,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 1,
"selected": false,
"text": "<p>It is so that you don't have two things trying to update the control at the same time. (This could happen if the CPU swit... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] | I'm sure there is a good (or at least decent) reason for this. What is it? | Because you can easily end up with a deadlock (among other issues).
For exmaple, your secondary thread could be trying to update the UI control, but the UI control will be waiting for a resource locked by the secondary thread to be released, so both threads end up waiting for each other to finish. As others have commented this situation is not unique to UI code, but is particularly common.
In other languages such as C++ you are free to try and do this (without an exception being thrown as in WinForms), but your application may freeze and stop responding should a deadlock occur.
Incidentally, you can easily tell the UI thread that you want to update a control, just create a delegate, then call the (asynchronous) BeginInvoke method on that control passing it your delegate. E.g.
```
myControl.BeginInvoke(myControl.UpdateFunction);
```
This is the equivalent to doing a C++/MFC PostMessage from a worker thread |
10,366 | <p>I have an absolutely positioned <code>div</code> that I want to show when the user clicks a link. The <code>onclick</code> of the link calls a js function that sets the display of the div to block (also tried: "", <code>inline</code>, <code>table-cell</code>, <code>inline-table</code>, etc). This works great in IE7, not at all in every other browser I've tried (FF2, FF3, Opera 9.5, Safari).</p>
<p>I've tried adding alerts before and after the call, and they show that the display has changed from <code>none</code> to <code>block</code> but the <code>div</code> does not display.</p>
<p>I can get the <code>div</code> to display in FF3 if I change the display value using Firebug's HTML inspector (but not by running javascript through Firebug's console) - so I know it's not just showing up off-screen, etc.</p>
<p>I've tried everything I can think of, including:</p>
<ul>
<li>Using a different doctype (XHTML 1, HTML 4, etc)</li>
<li>Using visibility visible/hidden instead of display block/none</li>
<li>Using inline javascript instead of a function call</li>
<li>Testing from different machines</li>
</ul>
<p>Any ideas about what could cause this?</p>
| [
{
"answer_id": 10368,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 1,
"selected": false,
"text": "<p>Check the error console (Tools Menu > Error Console in Firefox 3) to make sure that there isn't another error happe... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521/"
] | I have an absolutely positioned `div` that I want to show when the user clicks a link. The `onclick` of the link calls a js function that sets the display of the div to block (also tried: "", `inline`, `table-cell`, `inline-table`, etc). This works great in IE7, not at all in every other browser I've tried (FF2, FF3, Opera 9.5, Safari).
I've tried adding alerts before and after the call, and they show that the display has changed from `none` to `block` but the `div` does not display.
I can get the `div` to display in FF3 if I change the display value using Firebug's HTML inspector (but not by running javascript through Firebug's console) - so I know it's not just showing up off-screen, etc.
I've tried everything I can think of, including:
* Using a different doctype (XHTML 1, HTML 4, etc)
* Using visibility visible/hidden instead of display block/none
* Using inline javascript instead of a function call
* Testing from different machines
Any ideas about what could cause this? | Since setting the properties with javascript never seemed to work, but setting using Firebug's inspect did, I started to suspect that the javascript ID selector was broken - maybe there were multiple items in the DOM with the same ID? The source didn't show that there were, but looping through all divs using javascript I found that that was the case. Here's the function I ended up using to show the popup:
```
function openPopup(popupID)
{
var divs = getObjectsByTagAndClass('div','popupDiv');
if (divs != undefined && divs != null)
{
for (var i = 0; i < divs.length; i++)
{
if (divs[i].id == popupID)
divs[i].style.display = 'block';
}
}
}
```
(utility function getObjectsByTagAndClass not listed)
Ideally I'll find out why the same item is being inserted multiple times, but I don't have control over the rendering platform, just its inputs.
So when debugging issues like this, **remember to check for duplicate IDs in the DOM, which can break getElementById**.
To everyone who answered, thanks for your help! |
10,435 | <p>I have a website that works correctly under IIS 6.0: It authenticates users with windows credentials, and then when talking to the service that hits the DB, it passes the credentials.</p>
<p>In IIS 7.0, the same config settings do not pass the credentials, and the DB gets hit with NT AUTHORITY\ANONYMOUS.</p>
<p>Is there something I'm missing? I've turned ANONYMOUS access off in my IIS 7.0 website, but I can't get the thing to work.</p>
<p>These are the settings that I'm using on both IIS 6.0 and 7.0:</p>
<pre><code><authentication mode="Windows">
<identity impersonate="true">
</code></pre>
<p>What changed from 6.0 to 7.0?</p>
| [
{
"answer_id": 10444,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting... I have the opposite problem - <strong>Not being able</strong> to get the authentication to be passed from the cli... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] | I have a website that works correctly under IIS 6.0: It authenticates users with windows credentials, and then when talking to the service that hits the DB, it passes the credentials.
In IIS 7.0, the same config settings do not pass the credentials, and the DB gets hit with NT AUTHORITY\ANONYMOUS.
Is there something I'm missing? I've turned ANONYMOUS access off in my IIS 7.0 website, but I can't get the thing to work.
These are the settings that I'm using on both IIS 6.0 and 7.0:
```
<authentication mode="Windows">
<identity impersonate="true">
```
What changed from 6.0 to 7.0? | There has been changes between IIS7 and IIS6.0. I found for you one blog post that might actually help you ([click here to see it](http://mvolo.com/blogs/serverside/archive/2007/12/08/IIS-7.0-Breaking-Changes-ASP.NET-2.0-applications-Integrated-mode.aspx)).
Are you running your application in Integrated Mode or in Classic Mode? From what I saw, putting the Impersonate attribute at true should display you a 500 error with the following error message:
>
> Internal Server Error. This is HTTP
> Error 500.19: The requested page
> cannot be accessed because the related
> configuration data for the page is
> invalid.
>
>
>
Here is the workaround that is proposed:
>
> Workaround:
>
>
> 1) If your application does not rely
> on impersonating the requesting user
> in the BeginRequest and
> AuthenticateRequest stages (the only
> stages where impersonation is not
> possible in Integrated mode), ignore
> this error by adding the following to
> your application’s web.config:
>
>
>
>
> ```
> <validation validateIntegratedModeConfiguration="false"
>
> ```
>
> />
>
>
>
> 2) If your application does rely on
> impersonation in BeginRequest and
> AuthenticateRequest, or you are not
> sure, move to classic mode.
>
>
>
I hoped that was useful to understand how IIS 7.0 now works. |
10,443 | <p>I have this program, we'll call it Host. Host does all kinds of good stuff, but it needs to be able to accept input through the command line <strong>while it's running</strong>. This means it has to somehow send its other process data and then quit. For example, I need to be able to do this:</p>
<pre><code>./Host --blahblah 3 6 3 5
</code></pre>
<p>This should somehow end up calling some function in Host called</p>
<pre><code>handleBlahBlah(int x1, int y1, int x2, int y2){
//do some more sweet stuff
}
</code></pre>
<p>Host is a C program, and does not need to support multiple instances.</p>
<p>An example of this is Amarok music player. With Amarok running and playing, you can type "amarok --pause" and it will pause the music.</p>
<p>I need to be able to do this in Linux or Windows. Preferably Linux.</p>
<p>What is the cleanest way to implement this?</p>
| [
{
"answer_id": 10445,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": -1,
"selected": false,
"text": "<p>So, I may be missing the point here, but by deafult a C program's main function takes two arguments; argc, a count of the n... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | I have this program, we'll call it Host. Host does all kinds of good stuff, but it needs to be able to accept input through the command line **while it's running**. This means it has to somehow send its other process data and then quit. For example, I need to be able to do this:
```
./Host --blahblah 3 6 3 5
```
This should somehow end up calling some function in Host called
```
handleBlahBlah(int x1, int y1, int x2, int y2){
//do some more sweet stuff
}
```
Host is a C program, and does not need to support multiple instances.
An example of this is Amarok music player. With Amarok running and playing, you can type "amarok --pause" and it will pause the music.
I need to be able to do this in Linux or Windows. Preferably Linux.
What is the cleanest way to implement this? | If you were on Windows, I'd tell you to use a hidden window to receive the messages, but since you used `./`, I assume you want something Unix-based.
In that case, I'd go with a [named pipe](http://en.wikipedia.org/wiki/Named_pipe). Sun has a [tutorial](http://developers.sun.com/solaris/articles/named_pipes.html) about named pipes that might be useful.
The program would probably create the pipe and listen. You could have a separate command-line script which would open the pipe and just echo its command-line arguments to it.
You *could* modify your program to support the command-line sending instead of using a separate script. You'd do the same basic thing in that case. Your program would look at it's command-line arguments, and if applicable, open the pipe to the "main" instance of the program, and send the arguments through. |
10,456 | <p>The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus.</p>
<p>Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta.</p>
<pre><code>using System;
using Microsoft.Win32;
namespace HowTo
{
class WebClickSound
{
/// <summary>
/// Enables or disables the web browser navigating click sound.
/// </summary>
public static bool Enabled
{
get
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string keyValue = (string)key.GetValue(null);
return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
}
set
{
string keyValue;
if (value)
{
keyValue = "%SystemRoot%\\Media\\";
if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
{
// XP
keyValue += "Windows XP Start.wav";
}
else if (Environment.OSVersion.Version.Major == 6)
{
// Vista
keyValue += "Windows Navigation Start.wav";
}
else
{
// Don't know the file name so I won't be able to re-enable it
return;
}
}
else
{
keyValue = "\"\"";
}
// Open and set the key that points to the file
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, keyValue, RegistryValueKind.ExpandString);
isEnabled = value;
}
}
}
}
</code></pre>
<p>Then in the main form we use the above code in these 3 events: </p>
<ul>
<li>Activated </li>
<li>Deactivated </li>
<li><p>FormClosing</p>
<pre><code>private void Form1_Activated(object sender, EventArgs e)
{
// Disable the sound when the program has focus
WebClickSound.Enabled = false;
}
private void Form1_Deactivate(object sender, EventArgs e)
{
// Enable the sound when the program is out of focus
WebClickSound.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Enable the sound on app exit
WebClickSound.Enabled = true;
}
</code></pre></li>
</ul>
<p>The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that.</p>
<p>What do you guys think? Is this a good solution? What improvements can be made?</p>
| [
{
"answer_id": 10463,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": true,
"text": "<p>I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1147/"
] | The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus.
Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta.
```
using System;
using Microsoft.Win32;
namespace HowTo
{
class WebClickSound
{
/// <summary>
/// Enables or disables the web browser navigating click sound.
/// </summary>
public static bool Enabled
{
get
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string keyValue = (string)key.GetValue(null);
return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
}
set
{
string keyValue;
if (value)
{
keyValue = "%SystemRoot%\\Media\\";
if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
{
// XP
keyValue += "Windows XP Start.wav";
}
else if (Environment.OSVersion.Version.Major == 6)
{
// Vista
keyValue += "Windows Navigation Start.wav";
}
else
{
// Don't know the file name so I won't be able to re-enable it
return;
}
}
else
{
keyValue = "\"\"";
}
// Open and set the key that points to the file
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, keyValue, RegistryValueKind.ExpandString);
isEnabled = value;
}
}
}
}
```
Then in the main form we use the above code in these 3 events:
* Activated
* Deactivated
* FormClosing
```
private void Form1_Activated(object sender, EventArgs e)
{
// Disable the sound when the program has focus
WebClickSound.Enabled = false;
}
private void Form1_Deactivate(object sender, EventArgs e)
{
// Enable the sound when the program is out of focus
WebClickSound.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Enable the sound on app exit
WebClickSound.Enabled = true;
}
```
The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that.
What do you guys think? Is this a good solution? What improvements can be made? | I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen.
So instead of this:
```
webBrowser1.DocumentText = "<h1>Hello, world!</h1>";
```
try this:
```
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write("<h1>Hello, world!</h1>");
``` |
10,499 | <p>Sometimes I get Oracle connection problems because I can't figure out which tnsnames.ora file my database client is using.</p>
<p>What's the best way to figure this out? ++happy for various platform solutions. </p>
| [
{
"answer_id": 10501,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "<p>For linux:</p>\n\n<pre><code>$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'open.*tnsnames.ora'\n</code></... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | Sometimes I get Oracle connection problems because I can't figure out which tnsnames.ora file my database client is using.
What's the best way to figure this out? ++happy for various platform solutions. | Oracle provides a utility called `tnsping`:
```
R:\>tnsping someconnection
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:38:07
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
TNS-03505: Failed to resolve name
R:\>
R:\>tnsping entpr01
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:39:22
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)
(PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0
1)))
OK (40 msec)
R:\>
```
This should show what file you're using. The utility sits in the Oracle `bin` directory. |
10,506 | <p>I am having a strange DB2 issue when I run DBUnit tests. My DBUnit tests are highly customized, but I don't think it is the issue. When I run the tests, I get a failure: </p>
<blockquote>
<p>SQLCODE: -1084, SQLSTATE: 57019</p>
</blockquote>
<p><a href="https://www1.columbia.edu/sec/acis/db2/db2m0/sql1000.htm" rel="nofollow noreferrer">which translates to</a> </p>
<blockquote>
<p>SQL1084C Shared memory segments cannot be allocated.</p>
</blockquote>
<p>It sounds like a weird memory issue, though here's the big strange thing. If I ssh to the test database server, then go in to db2 and do "connect to MY_DB", the tests start succeeding! This seems to have no relation to the supposed memory error that is being reported.</p>
<p>I have 2 tests, and the first one actually succeeds, the second one is the one that fails. However, it fails in the DBUnit setup code, when it is obtaining the connection to the DB server to load my xml dataset.</p>
<p>Any ideas what might be going on?</p>
| [
{
"answer_id": 10501,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "<p>For linux:</p>\n\n<pre><code>$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'open.*tnsnames.ora'\n</code></... | 2008/08/13 | [
"https://Stackoverflow.com/questions/10506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I am having a strange DB2 issue when I run DBUnit tests. My DBUnit tests are highly customized, but I don't think it is the issue. When I run the tests, I get a failure:
>
> SQLCODE: -1084, SQLSTATE: 57019
>
>
>
[which translates to](https://www1.columbia.edu/sec/acis/db2/db2m0/sql1000.htm)
>
> SQL1084C Shared memory segments cannot be allocated.
>
>
>
It sounds like a weird memory issue, though here's the big strange thing. If I ssh to the test database server, then go in to db2 and do "connect to MY\_DB", the tests start succeeding! This seems to have no relation to the supposed memory error that is being reported.
I have 2 tests, and the first one actually succeeds, the second one is the one that fails. However, it fails in the DBUnit setup code, when it is obtaining the connection to the DB server to load my xml dataset.
Any ideas what might be going on? | Oracle provides a utility called `tnsping`:
```
R:\>tnsping someconnection
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:38:07
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
TNS-03505: Failed to resolve name
R:\>
R:\>tnsping entpr01
TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:39:22
Copyright (c) 1997 Oracle Corporation. All rights reserved.
Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)
(PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0
1)))
OK (40 msec)
R:\>
```
This should show what file you're using. The utility sits in the Oracle `bin` directory. |
10,533 | <p>Here's a problem I ran into recently. I have attributes strings of the form</p>
<pre><code>"x=1 and y=abc and z=c4g and ..."
</code></pre>
<p>Some attributes have numeric values, some have alpha values, some have mixed, some have dates, etc.</p>
<p>Every string is <em>supposed</em> to have "<code>x=someval and y=anotherval</code>" at the beginning, but some don't. I have three things I need to do. </p>
<ol>
<li>Validate the strings to be certain that they have <code>x</code> and <code>y</code>. </li>
<li>Actually parse the values for <code>x</code> and <code>y</code>.</li>
<li>Get the rest of the string.</li>
</ol>
<p>Given the example at the top, this would result in the following variables:</p>
<pre><code>$x = 1;
$y = "abc";
$remainder = "z=c4g and ..."
</code></pre>
<p>My question is: Is there a (reasonably) simple way to parse these <em>and</em> validate with a single regular expression? i.e.:</p>
<pre><code>if ($str =~ /someexpression/)
{
$x = $1;
$y = $2;
$remainder = $3;
}
</code></pre>
<p>Note that the string may consist of <em>only</em> <code>x</code> and <code>y</code> attributes. This is a valid string.</p>
<p>I'll post my solution as an answer, but it doesn't meet my single-regex preference.</p>
| [
{
"answer_id": 10537,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "<p>Here's basically what I did to solve this:</p>\n\n<pre><code>($x_str, $y_str, $remainder) = split(/ and /, $str, 3);\n\ni... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/872/"
] | Here's a problem I ran into recently. I have attributes strings of the form
```
"x=1 and y=abc and z=c4g and ..."
```
Some attributes have numeric values, some have alpha values, some have mixed, some have dates, etc.
Every string is *supposed* to have "`x=someval and y=anotherval`" at the beginning, but some don't. I have three things I need to do.
1. Validate the strings to be certain that they have `x` and `y`.
2. Actually parse the values for `x` and `y`.
3. Get the rest of the string.
Given the example at the top, this would result in the following variables:
```
$x = 1;
$y = "abc";
$remainder = "z=c4g and ..."
```
My question is: Is there a (reasonably) simple way to parse these *and* validate with a single regular expression? i.e.:
```
if ($str =~ /someexpression/)
{
$x = $1;
$y = $2;
$remainder = $3;
}
```
Note that the string may consist of *only* `x` and `y` attributes. This is a valid string.
I'll post my solution as an answer, but it doesn't meet my single-regex preference. | I'm not the best at regular expressions, but this seems pretty close to what you're looking for:
```
/x=(.+) and y=([^ ]+)( and (.*))?/
```
Except you use $1, $2, and $4. In use:
```
my @strs = ("x=1 and y=abc and z=c4g and w=v4l",
"x=yes and y=no",
"z=nox and w=noy");
foreach (@strs) {
if ($_ =~ /x=(.+) and y=([^ ]+)( and (.*))?/) {
$x = $1;
$y = $2;
$remainder = $4;
print "x: $x; y: $y; remainder: $remainder\n";
} else {
print "Failed.\n";
}
}
```
Output:
```
x: 1; y: abc; remainder: z=c4g and w=v4l
x: yes; y: no; remainder:
Failed.
```
This of course leaves out plenty of error checking, and I don't know everything about your inputs, but this seems to work. |
10,564 | <p>I'm trying out <strong>Git on Windows</strong>. I got to the point of trying "git commit" and I got this error:</p>
<blockquote>
<p>Terminal is dumb but no VISUAL nor
EDITOR defined. Please supply the
message using either -m or -F option.</p>
</blockquote>
<p>So I figured out I need to have an environment variable called EDITOR. No problem. I set it to point to Notepad. That worked, almost. The default commit message opens in Notepad. But Notepad doesn't support bare line feeds. I went out and got <a href="http://notepad-plus.sourceforge.net/uk/site.htm" rel="noreferrer">Notepad++</a>, but I can't figure out how to get Notepad++ set up as the <code>%EDITOR%</code> in such a way that it works with Git as expected.</p>
<p>I'm not married to Notepad++. At this point I don't mind what editor I use. I just want to be able to <strong>type commit messages in an editor</strong> rather than the command line (with <code>-m</code>).</p>
<p>Those of you using Git on Windows: What tool do you use to edit your commit messages, and what did you have to do to make it work?</p>
| [
{
"answer_id": 10574,
"author": "J Wynia",
"author_id": 1124,
"author_profile": "https://Stackoverflow.com/users/1124",
"pm_score": 1,
"selected": false,
"text": "<p>I've had difficulty getting Git to cooperate with <a href=\"http://en.wikipedia.org/wiki/WordPad\" rel=\"nofollow noreferr... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] | I'm trying out **Git on Windows**. I got to the point of trying "git commit" and I got this error:
>
> Terminal is dumb but no VISUAL nor
> EDITOR defined. Please supply the
> message using either -m or -F option.
>
>
>
So I figured out I need to have an environment variable called EDITOR. No problem. I set it to point to Notepad. That worked, almost. The default commit message opens in Notepad. But Notepad doesn't support bare line feeds. I went out and got [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm), but I can't figure out how to get Notepad++ set up as the `%EDITOR%` in such a way that it works with Git as expected.
I'm not married to Notepad++. At this point I don't mind what editor I use. I just want to be able to **type commit messages in an editor** rather than the command line (with `-m`).
Those of you using Git on Windows: What tool do you use to edit your commit messages, and what did you have to do to make it work? | Update September 2015 (6 years later)
The [last release of git-for-Windows (2.5.3)](https://github.com/git-for-windows/git/releases/tag/v2.5.3.windows.1) now includes:
>
> By configuring **`git config core.editor notepad`**, users [can now use `notepad.exe` as their default editor](https://github.com/git-for-windows/git/issues/381).
>
> Configuring `git config format.commitMessageColumns 72` will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it.
>
>
>
See [commit 69b301b](https://github.com/git-for-windows/build-extra/commit/69b301bbd7c18226c63d83638991cb2b7f84fb64) by [Johannes Schindelin (`dscho`)](https://github.com/dscho).
And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editor
opens to a hidden window or somewhere obscure and the user gets
lost.
See [commit abfb04d](https://github.com/git/git/commit/abfb04d0c74cde804c734015ff5868a88c84fb6f) (07 Dec 2017), and [commit a64f213](https://github.com/git/git/commit/a64f213d3fa13fa01e582b6734fe7883ed975dc9) (29 Nov 2017) by [Lars Schneider (`larsxschneider`)](https://github.com/larsxschneider).
Helped-by: [Junio C Hamano (`gitster`)](https://github.com/gitster).
(Merged by [Junio C Hamano -- `gitster` --](https://github.com/gitster) in [commit 0c69a13](https://github.com/git/git/commit/0c69a132cb1adf0ce9f31e6631f89321e437cb76), 19 Dec 2017)
>
> `launch_editor()`: indicate that Git waits for user input
> ---------------------------------------------------------
>
>
> When a graphical `GIT_EDITOR` is spawned by a Git command that opens
> and waits for user input (e.g. "`git rebase -i`"), then the editor window
> might be obscured by other windows.
>
> The user might be left staring at
> the original Git terminal window without even realizing that s/he needs
> to interact with another window before Git can proceed. To this user Git
> appears hanging.
>
>
> Print a message that Git is waiting for editor input in the original
> terminal and get rid of it when the editor returns, if the terminal
> supports erasing the last line
>
>
>
---
Original answer
I just tested it with git version 1.6.2.msysgit.0.186.gf7512 and Notepad++5.3.1
I prefer to *not* have to set an EDITOR variable, so I tried:
```bash
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""
# or
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\" %*"
```
That always gives:
```
C:\prog\git>git config --global --edit
"c:\Program Files\Notepad++\notepad++.exe" %*: c:\Program Files\Notepad++\notepad++.exe: command not found
error: There was a problem with the editor '"c:\Program Files\Notepad++\notepad++.exe" %*'.
```
If I define a npp.bat including:
```
"c:\Program Files\Notepad++\notepad++.exe" %*
```
and I type:
```
C:\prog\git>git config --global core.editor C:\prog\git\npp.bat
```
It just works from the DOS session, **but not from the git shell**.
(not that with the core.editor configuration mechanism, a script with "`start /WAIT...`" in it would not work, but only open a new DOS window)
---
[Bennett's answer](https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/1431003#1431003) mentions the possibility to avoid adding a script, but to reference directly the program itself **between simple quotes**. Note the direction of the slashes! Use `/` NOT `\` to separate folders in the path name!
```bash
git config --global core.editor \
"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
```
Or if you are in a 64 bit system:
```bash
git config --global core.editor \
"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
```
But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a `git config`.
---
The actual solution (with a script) was to realize that:
**what you refer to in the config file is actually a shell (`/bin/sh`) script**, not a DOS script.
So what does work is:
```
C:\prog\git>git config --global core.editor C:/prog/git/npp.bat
```
with `C:/prog/git/npp.bat`:
```bash
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"
```
or
```bash
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$*"
```
With that setting, I can do '`git config --global --edit`' from DOS or Git Shell, or I can do '`git rebase -i ...`' from DOS or Git Shell.
Bot commands will trigger a new instance of notepad++ (hence the `-multiInst`' option), and wait for that instance to be closed before going on.
Note that I use only '/', not `\`'. And I [installed msysgit using option 2.](https://stackoverflow.com/questions/623518/msysgit-on-windows-what-should-i-be-aware-of-if-any) (Add the `git\bin` directory to the `PATH` environment variable, but without overriding some built-in windows tools)
The fact that the notepad++ wrapper is called .bat is not important.
It would be better to name it 'npp.sh' and to put it in the `[git]\cmd` directory though (or in any directory referenced by your PATH environment variable).
---
See also:
* [How do I view ‘git diff’ output with visual diff program?](https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/255212#255212) for the general theory
* [How do I setup DiffMerge with msysgit / gitk?](https://stackoverflow.com/questions/780425/how-do-i-setup-diffmerge-with-msysgit-gitk/783667#783667) for another example of external tool (DiffMerge, and WinMerge)
---
[lightfire228](https://stackoverflow.com/users/2716305/lightfire228) adds [in the comments](https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/773973#comment74027740_773973):
>
> For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see "[Aborting commit due to empty message](https://stackoverflow.com/q/30085970/6309)": change your `.bat` or `.sh` file to say:
>
>
>
```
"<path-to-n++" .git/COMMIT_EDITMSG -<arguments>.
```
>
> That will tell notepad++ to open the temp commit file, rather than a blank new one.
>
>
> |
10,616 | <p>I'm an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> developer who has used <code>Microsoft SQL Server</code> for all my database needs (both at work and for personal projects). </p>
<p>I am considering trying out the <a href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29" rel="noreferrer">LAMP</a> stack for some of my personal projects. </p>
<p>What are some of the main differences between <code>MySQL</code> and <code>SQL Server</code>? Is using <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">stored procedures</a> a common practice in <code>MySQL</code>? </p>
<p>Any advice or resources you'd recommend to help me with the switch? </p>
<p>To those who have experience with both, are there any missing features from <code>MySQL</code>?</p>
| [
{
"answer_id": 10623,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 8,
"selected": true,
"text": "<p>One thing you have to watch out for is the fairly severe differences in the way SQL Server and MySQL implement the SQL s... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285/"
] | I'm an [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) developer who has used `Microsoft SQL Server` for all my database needs (both at work and for personal projects).
I am considering trying out the [LAMP](http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29) stack for some of my personal projects.
What are some of the main differences between `MySQL` and `SQL Server`? Is using [stored procedures](http://en.wikipedia.org/wiki/Stored_procedure) a common practice in `MySQL`?
Any advice or resources you'd recommend to help me with the switch?
To those who have experience with both, are there any missing features from `MySQL`? | One thing you have to watch out for is the fairly severe differences in the way SQL Server and MySQL implement the SQL syntax.
Here's a nice [Comparison of Different SQL Implementations](http://troels.arvin.dk/db/rdbms/).
For example, take a look at the top-n section. In MySQL:
```
SELECT age
FROM person
ORDER BY age ASC
LIMIT 1 OFFSET 2
```
In SQL Server (T-SQL):
```
SELECT TOP 3 WITH TIES *
FROM person
ORDER BY age ASC
``` |
10,635 | <p>I wrote a simple batch file as a PowerShell script, and I am getting errors when they run.</p>
<p>It's in a scripts directory in my path. This is the error I get:</p>
<blockquote>
<p>Cannot be loaded because the execution of scripts is disabled on this system.
Please see "get-help about-signing".</p>
</blockquote>
<p>I looked in the help, but it's less than helpful.</p>
| [
{
"answer_id": 10638,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 8,
"selected": true,
"text": "<p>It could be PowerShell's default security level, which (IIRC) will only run signed scripts.</p>\n\n<p>Try typing this:<... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
] | I wrote a simple batch file as a PowerShell script, and I am getting errors when they run.
It's in a scripts directory in my path. This is the error I get:
>
> Cannot be loaded because the execution of scripts is disabled on this system.
> Please see "get-help about-signing".
>
>
>
I looked in the help, but it's less than helpful. | It could be PowerShell's default security level, which (IIRC) will only run signed scripts.
Try typing this:
```none
set-executionpolicy remotesigned
```
That will tell PowerShell to allow local (that is, on a local drive) unsigned scripts to run.
Then try executing your script again. |
10,668 | <p>I've been trying to understand how to read the memory of other processes on Mac OS X, but I'm not having much luck. I've seen many examples online using <code>ptrace</code> with <code>PEEKDATA</code> and such, however it doesn't have that option on BSD <sup>[<a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man2/ptrace.2.html" rel="noreferrer"><code>man ptrace</code></a>]</sup>.</p>
<pre><code>int pid = fork();
if (pid > 0) {
// mess around with child-process's memory
}
</code></pre>
<p>How is it possible to read from and write to the memory of another process on Mac OS X?</p>
| [
{
"answer_id": 10676,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": false,
"text": "<p>Matasano Chargen had a good post a while back on porting some debugging code to OS X, which included learning how to read... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114/"
] | I've been trying to understand how to read the memory of other processes on Mac OS X, but I'm not having much luck. I've seen many examples online using `ptrace` with `PEEKDATA` and such, however it doesn't have that option on BSD [[`man ptrace`](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man2/ptrace.2.html)].
```
int pid = fork();
if (pid > 0) {
// mess around with child-process's memory
}
```
How is it possible to read from and write to the memory of another process on Mac OS X? | Matasano Chargen had a good post a while back on porting some debugging code to OS X, which included learning how to read and write memory in another process (among other things).
[It has to work, otherwise GDB wouldn't](http://replay.web.archive.org/20090627062246/http://www.matasano.com/log/1100/what-ive-been-doing-on-my-summer-vacation-or-it-has-to-work-otherwise-gdb-wouldnt/):
>
> It turns out Apple, in their infinite wisdom, had gutted `ptrace()`. The OS X man page lists the following request codes:
>
>
> * `PT_ATTACH` — to pick a process to debug
> * `PT_DENY_ATTACH` — so processes can stop themselves from being debugged
>
> [...]
>
>
> No mention of reading or writing memory or registers. Which would have been discouraging if the man page had not also mentioned `PT_GETREGS`, `PT_SETREGS`, `PT_GETFPREGS`, and `PT_SETFPREGS` in the error codes section. So, I checked `ptrace.h`. There I found:
>
>
> * `PT_READ_I` — to read instruction words
> * `PT_READ_D` — to read data words
> * `PT_READ_U` — to read U area data if you’re old enough to remember what the U area is
>
> [...]
>
>
> There’s one problem solved. I can read and write memory for breakpoints. But I still can’t get access to registers, and I need to be able to mess with EIP.
>
>
> |
10,680 | <p>Is there any difference between</p>
<pre><code> int on_exit(void (*function)(int , void *), void *arg);
</code></pre>
<p>and</p>
<pre><code> int atexit(void (*function)(void));
</code></pre>
<p>other than the fact that the function used by on_exit gets the exit status?</p>
<p>That is, if I don't care about the exit status, is there any reason to use one or the other?</p>
<p><strong>Edit:</strong> Many of the answers warned against <code>on_exit</code> because it's non-standard. If I'm developing an app that is for internal corporate use and guaranteed to run on specific configurations, should I worry about this? </p>
| [
{
"answer_id": 10684,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": false,
"text": "<p>You should use <code>atexit()</code> if possible. <code>on_exit()</code> is nonstandard and less common. For example, i... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] | Is there any difference between
```
int on_exit(void (*function)(int , void *), void *arg);
```
and
```
int atexit(void (*function)(void));
```
other than the fact that the function used by on\_exit gets the exit status?
That is, if I don't care about the exit status, is there any reason to use one or the other?
**Edit:** Many of the answers warned against `on_exit` because it's non-standard. If I'm developing an app that is for internal corporate use and guaranteed to run on specific configurations, should I worry about this? | According to [this link](http://www.delorie.com/gnu/docs/glibc/libc_560.html) I found, it seems there are a few differences. `on_exit` will let you pass in an argument that is passed in to the `on_exit` function when it is called... which might let you set up some pointers to do some cleanup work on when it is time to exit.
Furthermore, it appears that `on_exit` was a SunOS specific function that may not be compatible on all platforms... so you may want to stick with atexit, despite it being more restrictive. |
10,752 | <p>I know the so-called textbook definition of unit tests and integration tests. What I am curious about is when it is time to write unit tests... I will write them to cover as many sets of classes as possible.</p>
<p>For example, if I have a <code>Word</code> class, I will write some unit tests for the <code>Word</code> class. Then, I begin writing my <code>Sentence</code> class, and when it needs to interact with the <code>Word</code> class, I will often write my unit tests such that they test both <code>Sentence</code> and <code>Word</code>... at least in the places where they interact.</p>
<p><em>Have these tests essentially become integration tests because they now test the integration of these 2 classes, or is it just a unit test that spans 2 classes?</em></p>
<p>In general, because of this uncertain line, I will rarely actually write integration tests... or is my using the finished product to see if all the pieces work properly the actual integration tests, even though they are manual and rarely repeated beyond the scope of each individual feature?</p>
<p>Am I misunderstanding integration tests, or is there really just very little difference between integration and unit tests?</p>
| [
{
"answer_id": 10756,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 4,
"selected": false,
"text": "<p>using Single responsibility design, its black and white. More than 1 responsibility, its an integration test. </p>... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I know the so-called textbook definition of unit tests and integration tests. What I am curious about is when it is time to write unit tests... I will write them to cover as many sets of classes as possible.
For example, if I have a `Word` class, I will write some unit tests for the `Word` class. Then, I begin writing my `Sentence` class, and when it needs to interact with the `Word` class, I will often write my unit tests such that they test both `Sentence` and `Word`... at least in the places where they interact.
*Have these tests essentially become integration tests because they now test the integration of these 2 classes, or is it just a unit test that spans 2 classes?*
In general, because of this uncertain line, I will rarely actually write integration tests... or is my using the finished product to see if all the pieces work properly the actual integration tests, even though they are manual and rarely repeated beyond the scope of each individual feature?
Am I misunderstanding integration tests, or is there really just very little difference between integration and unit tests? | The key difference, to me, is that **integration tests** reveal if a feature is working or is broken, since they stress the code in a scenario close to reality. They invoke one or more software methods or features and test if they act as expected.
On the opposite, a **Unit test** testing a single method relies on the (often wrong) assumption that the rest of the software is correctly working, because it explicitly mocks every dependency.
Hence, when a unit test for a method implementing some feature is green, it does **not** mean the feature is working.
Say you have a method somewhere like this:
```
public SomeResults DoSomething(someInput) {
var someResult = [Do your job with someInput];
Log.TrackTheFactYouDidYourJob();
return someResults;
}
```
`DoSomething` is very important to your customer: it's a feature, the only thing that matters. That's why you usually write a Cucumber specification asserting it: you wish to *verify* and *communicate* the feature is working or not.
```
Feature: To be able to do something
In order to do something
As someone
I want the system to do this thing
Scenario: A sample one
Given this situation
When I do something
Then what I get is what I was expecting for
```
No doubt: if the test passes, you can assert you are delivering a working feature. This is what you can call **Business Value**.
If you want to write a unit test for `DoSomething` you should pretend (using some mocks) that the rest of the classes and methods are working (that is: that, all dependencies the method is using are correctly working) and assert your method is working.
In practice, you do something like:
```
public SomeResults DoSomething(someInput) {
var someResult = [Do your job with someInput];
FakeAlwaysWorkingLog.TrackTheFactYouDidYourJob(); // Using a mock Log
return someResults;
}
```
You can do this with Dependency Injection, or some Factory Method or any Mock Framework or just extending the class under test.
Suppose there's a bug in `Log.DoSomething()`.
Fortunately, the Gherkin spec will find it and your end-to-end tests will fail.
The feature won't work, because `Log` is broken, not because `[Do your job with someInput]` is not doing its job. And, by the way, `[Do your job with someInput]` is the sole responsibility for that method.
Also, suppose `Log` is used in 100 other features, in 100 other methods of 100 other classes.
Yep, 100 features will fail. But, fortunately, 100 end-to-end tests are failing as well and revealing the problem. And, yes: **they are telling the truth**.
It's very useful information: I know I have a broken product. It's also very confusing information: it tells me nothing about where the problem is. It communicates me the symptom, not the root cause.
Yet, `DoSomething`'s unit test is green, because it's using a fake `Log`, built to never break. And, yes: **it's clearly lying**. It's communicating a broken feature is working. How can it be useful?
(If `DoSomething()`'s unit test fails, be sure: `[Do your job with someInput]` has some bugs.)
Suppose this is a system with a broken class:

A single bug will break several features, and several integration tests will fail.

On the other hand, the same bug will break just one unit test.

Now, compare the two scenarios.
The same bug will break just one unit test.
* All your features using the broken `Log` are red
* All your unit tests are green, only the unit test for `Log` is red
Actually, unit tests for all modules using a broken feature are green because, by using mocks, they removed dependencies. In other words, they run in an ideal, completely fictional world. And this is the only way to isolate bugs and seek them. Unit testing means mocking. If you aren't mocking, you aren't unit testing.
The difference
--------------
Integration tests tell **what**'s not working. But they are of no use in **guessing where** the problem could be.
Unit tests are the sole tests that tell you **where** exactly the bug is. To draw this information, they must run the method in a mocked environment, where all other dependencies are supposed to correctly work.
That's why I think that your sentence "Or is it just a unit test that spans 2 classes" is somehow displaced. A unit test should never span 2 classes.
This reply is basically a summary of what I wrote here: [Unit tests lie, that's why I love them](http://arialdomartini.wordpress.com/2011/10/21/unit-tests-lie-thats-why-i-love-them/). |
10,793 | <p>I'm dynamically loading user controls adding them to the Controls collection of the web form.</p>
<p>I'd like to hide user controls if they cause a unhandled exception while rendering.</p>
<p>So, I tried hooking to the Error event of each UserControl but it seems that this event never fires for the UserControls as it does for Page class. </p>
<p>Did some googling around and it doesn't seem promising. Any ideas here?</p>
| [
{
"answer_id": 10797,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 0,
"selected": false,
"text": "<p>Global.asax and Application_Error?</p>\n\n<p><a href=\"http://www.15seconds.com/issue/030102.htm\" rel=\"nofollow norefer... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269/"
] | I'm dynamically loading user controls adding them to the Controls collection of the web form.
I'd like to hide user controls if they cause a unhandled exception while rendering.
So, I tried hooking to the Error event of each UserControl but it seems that this event never fires for the UserControls as it does for Page class.
Did some googling around and it doesn't seem promising. Any ideas here? | mmilic, following on from [your response](https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#10910) to my [previous idea](https://stackoverflow.com/questions/10793/catching-unhandled-exceptions-in-aspnet-usercontrols#10815)..
No additional logic required! That's the point, your doing nothing to the classes in question, just wrapping them in some instantiation bubble-wrap! :)
OK, I was going to just bullet point but I wanted to see this work for myself, so I cobbled together some *very* rough code but the concept is there and it seems to work.
**APOLOGIES FOR THE LONG POST**
The SafeLoader
--------------
This will basically be the "bubble" I mentioned.. It will get the controls HTML, catching any errors that occur during Rendering.
```
public class SafeLoader
{
public static string LoadControl(Control ctl)
{
// In terms of what we could do here, its down
// to you, I will just return some basic HTML saying
// I screwed up.
try
{
// Get the Controls HTML (which may throw)
// And store it in our own writer away from the
// actual Live page.
StringWriter writer = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
ctl.RenderControl(htmlWriter);
return writer.GetStringBuilder().ToString();
}
catch (Exception)
{
string ctlType = ctl.GetType().Name;
return "<span style=\"color: red; font-weight:bold; font-size: smaller;\">" +
"Rob + Controls = FAIL (" +
ctlType + " rendering failed) Sad face :(</span>";
}
}
}
```
And Some Controls..
-------------------
Ok I just mocked together two controls here, one will throw the other will render junk. Point here, I don't give a crap. These will be replaced with your custom controls..
### BadControl
```
public class BadControl : WebControl
{
protected override void Render(HtmlTextWriter writer)
{
throw new ApplicationException("Rob can't program controls");
}
}
```
### GoodControl
```
public class GoodControl : WebControl
{
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<b>Holy crap this control works</b>");
}
}
```
The Page
--------
OK, so lets look at the "test" page.. Here I simply instantiate the controls, grab their html and output it, I will follow with thoughts on designer support etc..
### Page Code-Behind
```
protected void Page_Load(object sender, EventArgs e)
{
// Create some controls (BadControl will throw)
string goodHtml = SafeLoader.LoadControl(new BadControl());
Response.Write(goodHtml);
string badHtml = SafeLoader.LoadControl(new GoodControl());
Response.Write(badHtml);
}
```
### Thoughts
OK, I know what you are thinking, "these controls are instantiated programatically, what about designer support? I spent freaking hours getting these controls nice for the designer, now you're messing with my mojo".
OK, so I havent really tested this yet (probably will do in a min!) but the idea here is to override the CreateChildControls method for the page, and take the instance of each control added on the form and run it through the SafeLoader. If the code passes, you can add it to the Controls collection as normal, if not, then you can create erroneous literals or something, up to you my friend.
Finally..
---------
Again, sorry for the long post, but I wanted to get the code here so we can discuss this :)
I hope this helps demonstrate my idea :)
Update
------
Tested by chucking a control in on the designer and overriding the CreateChildControls method with this, works fine, may need some clean up to make things better looking, but I'll leave that to you ;)
```
protected override void CreateChildControls()
{
// Pass each control through the Loader to check
// its not lame
foreach (Control ctl in Controls)
{
string s = SafeLoader.LoadControl(ctl);
// If its bad, smack it downnnn!
if (s == string.Empty)
{
ctl.Visible = false; // Prevent Rendering
string ctlType = ctl.GetType().Name;
Response.Write("<b>Problem Occurred Rendering " +
ctlType + " '" + ctl.ID + "'.</b>");
}
}
}
```
Enjoy! |
10,808 | <p>Ok, so I've been refactoring my code in my little Rails app in an effort to remove duplication, and in general make my life easier (as I like an easy life). Part of this refactoring, has been to move code that's common to two of my models to a module that I can include where I need it.</p>
<p>So far, so good. Looks like it's going to work out, but I've just hit a problem that I'm not sure how to get around. The module (which I've called sendable), is just going to be the code that handles faxing, e-mailing, or printing a PDF of the document. So, for example, I have a purchase order, and I have Internal Sales Orders (imaginatively abbreviated to ISO).</p>
<p>The problem I've struck, is that I want some variables initialised (initialized for people who don't spell correctly :P ) after the object is loaded, so I've been using the <strong>after_initialize</strong> hook. No problem... until I start adding some more mixins.</p>
<p>The problem I have, is that I can have an <strong><code>after_initialize</code></strong> in any one of my mixins, so I need to include a <strong>super</strong> call at the start to make sure the other mixin <strong><code>after_initialize</code></strong> calls get called. Which is great, until I end up calling super and I get an error because there is no super to call.</p>
<p>Here's a little example, in case I haven't been confusing enough:</p>
<pre><code>class Iso < ActiveRecord::Base
include Shared::TracksSerialNumberExtension
include Shared::OrderLines
extend Shared::Filtered
include Sendable::Model
validates_presence_of :customer
validates_associated :lines
owned_by :customer
order_lines :despatched # Mixin
tracks_serial_numbers :items # Mixin
sendable :customer # Mixin
attr_accessor :address
def initialize( params = nil )
super
self.created_at ||= Time.now.to_date
end
end
</code></pre>
<p>So, if each one of the mixins have an after_initialize call, with a <strong>super</strong> call, how can I stop that last <strong>super</strong> call from raising the error? How can I test that the super method exists before I call it?</p>
| [
{
"answer_id": 11719,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than checking if the super method exists, you can just define it</p>\n\n<pre><code>class ActiveRecord::Base\n ... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
] | Ok, so I've been refactoring my code in my little Rails app in an effort to remove duplication, and in general make my life easier (as I like an easy life). Part of this refactoring, has been to move code that's common to two of my models to a module that I can include where I need it.
So far, so good. Looks like it's going to work out, but I've just hit a problem that I'm not sure how to get around. The module (which I've called sendable), is just going to be the code that handles faxing, e-mailing, or printing a PDF of the document. So, for example, I have a purchase order, and I have Internal Sales Orders (imaginatively abbreviated to ISO).
The problem I've struck, is that I want some variables initialised (initialized for people who don't spell correctly :P ) after the object is loaded, so I've been using the **after\_initialize** hook. No problem... until I start adding some more mixins.
The problem I have, is that I can have an **`after_initialize`** in any one of my mixins, so I need to include a **super** call at the start to make sure the other mixin **`after_initialize`** calls get called. Which is great, until I end up calling super and I get an error because there is no super to call.
Here's a little example, in case I haven't been confusing enough:
```
class Iso < ActiveRecord::Base
include Shared::TracksSerialNumberExtension
include Shared::OrderLines
extend Shared::Filtered
include Sendable::Model
validates_presence_of :customer
validates_associated :lines
owned_by :customer
order_lines :despatched # Mixin
tracks_serial_numbers :items # Mixin
sendable :customer # Mixin
attr_accessor :address
def initialize( params = nil )
super
self.created_at ||= Time.now.to_date
end
end
```
So, if each one of the mixins have an after\_initialize call, with a **super** call, how can I stop that last **super** call from raising the error? How can I test that the super method exists before I call it? | You can use this:
```
super if defined?(super)
```
Here is an example:
```
class A
end
class B < A
def t
super if defined?(super)
puts "Hi from B"
end
end
B.new.t
``` |
10,810 | <p>I'm doing a authorization check from a WinForms application with the help of the AzMan authorization provider from Enterprise Library and am receiving the the following error:</p>
<blockquote>
<p>Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Practices.EnterpriseLibrary.Security.AzMan) </p>
<hr>
<p>Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Interop.Security.AzRoles) </p>
</blockquote>
<p>The AzMan store is hosted in ADAM on another computer in the same domain. Other computers and users do not have this problem. The user making the call has read access to both ADAM and the AzMan store. The computer running the WinForms app and the computer running ADAM are both on Windows XP SP2.</p>
<p>I've had access problems with AzMan before that I've resolved, but this is a new one... What am I missing?</p>
| [
{
"answer_id": 11719,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than checking if the super method exists, you can just define it</p>\n\n<pre><code>class ActiveRecord::Base\n ... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/966/"
] | I'm doing a authorization check from a WinForms application with the help of the AzMan authorization provider from Enterprise Library and am receiving the the following error:
>
> Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Practices.EnterpriseLibrary.Security.AzMan)
>
>
>
>
> ---
>
>
> Unable to update the password. The value provided as the current password is incorrect. (Exception from HRESULT: 0x8007052B) (Microsoft.Interop.Security.AzRoles)
>
>
>
The AzMan store is hosted in ADAM on another computer in the same domain. Other computers and users do not have this problem. The user making the call has read access to both ADAM and the AzMan store. The computer running the WinForms app and the computer running ADAM are both on Windows XP SP2.
I've had access problems with AzMan before that I've resolved, but this is a new one... What am I missing? | You can use this:
```
super if defined?(super)
```
Here is an example:
```
class A
end
class B < A
def t
super if defined?(super)
puts "Hi from B"
end
end
B.new.t
``` |
10,819 | <p>For certain types of sql queries, an auxiliary table of numbers can be very useful. It may be created as a table with as many rows as you need for a particular task or as a user defined function that returns the number of rows required in each query.</p>
<p>What is the optimal way to create such a function?</p>
| [
{
"answer_id": 39122,
"author": "mrdenny",
"author_id": 4197,
"author_profile": "https://Stackoverflow.com/users/4197",
"pm_score": 4,
"selected": false,
"text": "<p>The most optimal function would be to use a table instead of a function. Using a function causes extra CPU load to create... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/224/"
] | For certain types of sql queries, an auxiliary table of numbers can be very useful. It may be created as a table with as many rows as you need for a particular task or as a user defined function that returns the number of rows required in each query.
What is the optimal way to create such a function? | Heh... sorry I'm so late responding to an old post. And, yeah, I had to respond because the most popular answer (at the time, the Recursive CTE answer with the link to 14 different methods) on this thread is, ummm... performance challenged at best.
First, the article with the 14 different solutions is fine for seeing the different methods of creating a Numbers/Tally table on the fly but as pointed out in the article and in the cited thread, there's a *very* important quote...
>
> "suggestions regarding efficiency and
> performance are often subjective.
> Regardless of how a query is being
> used, the physical implementation
> determines the efficiency of a query.
> Therefore, rather than relying on
> biased guidelines, it is imperative
> that you test the query and determine
> which one performs better."
>
>
>
Ironically, the article itself contains many subjective statements and "biased guidelines" such as *"a recursive CTE can generate a number listing **pretty efficiently**"* and *"This is **an efficient method** of using WHILE loop from a newsgroup posting by Itzik Ben-Gen"* (which I'm sure he posted just for comparison purposes). C'mon folks... Just mentioning Itzik's good name may lead some poor slob into actually using that horrible method. The author should practice what (s)he preaches and should do a little performance testing before making such ridiculously incorrect statements especially in the face of any scalablility.
With the thought of actually doing some testing before making any subjective claims about what any code does or what someone "likes", here's some code you can do your own testing with. Setup profiler for the SPID you're running the test from and check it out for yourself... just do a "Search'n'Replace" of the number 1000000 for your "favorite" number and see...
```
--===== Test for 1000000 rows ==================================
GO
--===== Traditional RECURSIVE CTE method
WITH Tally (N) AS
(
SELECT 1 UNION ALL
SELECT 1 + N FROM Tally WHERE N < 1000000
)
SELECT N
INTO #Tally1
FROM Tally
OPTION (MAXRECURSION 0);
GO
--===== Traditional WHILE LOOP method
CREATE TABLE #Tally2 (N INT);
SET NOCOUNT ON;
DECLARE @Index INT;
SET @Index = 1;
WHILE @Index <= 1000000
BEGIN
INSERT #Tally2 (N)
VALUES (@Index);
SET @Index = @Index + 1;
END;
GO
--===== Traditional CROSS JOIN table method
SELECT TOP (1000000)
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS N
INTO #Tally3
FROM Master.sys.All_Columns ac1
CROSS JOIN Master.sys.ALL_Columns ac2;
GO
--===== Itzik's CROSS JOINED CTE method
WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
E02(N) AS (SELECT 1 FROM E00 a, E00 b),
E04(N) AS (SELECT 1 FROM E02 a, E02 b),
E08(N) AS (SELECT 1 FROM E04 a, E04 b),
E16(N) AS (SELECT 1 FROM E08 a, E08 b),
E32(N) AS (SELECT 1 FROM E16 a, E16 b),
cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)
SELECT N
INTO #Tally4
FROM cteTally
WHERE N <= 1000000;
GO
--===== Housekeeping
DROP TABLE #Tally1, #Tally2, #Tally3, #Tally4;
GO
```
While we're at it, here's the numbers I get from SQL Profiler for the values of 100, 1000, 10000, 100000, and 1000000...
```
SPID TextData Dur(ms) CPU Reads Writes
---- ---------------------------------------- ------- ----- ------- ------
51 --===== Test for 100 rows ============== 8 0 0 0
51 --===== Traditional RECURSIVE CTE method 16 0 868 0
51 --===== Traditional WHILE LOOP method CR 73 16 175 2
51 --===== Traditional CROSS JOIN table met 11 0 80 0
51 --===== Itzik's CROSS JOINED CTE method 6 0 63 0
51 --===== Housekeeping DROP TABLE #Tally 35 31 401 0
51 --===== Test for 1000 rows ============= 0 0 0 0
51 --===== Traditional RECURSIVE CTE method 47 47 8074 0
51 --===== Traditional WHILE LOOP method CR 80 78 1085 0
51 --===== Traditional CROSS JOIN table met 5 0 98 0
51 --===== Itzik's CROSS JOINED CTE method 2 0 83 0
51 --===== Housekeeping DROP TABLE #Tally 6 15 426 0
51 --===== Test for 10000 rows ============ 0 0 0 0
51 --===== Traditional RECURSIVE CTE method 434 344 80230 10
51 --===== Traditional WHILE LOOP method CR 671 563 10240 9
51 --===== Traditional CROSS JOIN table met 25 31 302 15
51 --===== Itzik's CROSS JOINED CTE method 24 0 192 15
51 --===== Housekeeping DROP TABLE #Tally 7 15 531 0
51 --===== Test for 100000 rows =========== 0 0 0 0
51 --===== Traditional RECURSIVE CTE method 4143 3813 800260 154
51 --===== Traditional WHILE LOOP method CR 5820 5547 101380 161
51 --===== Traditional CROSS JOIN table met 160 140 479 211
51 --===== Itzik's CROSS JOINED CTE method 153 141 276 204
51 --===== Housekeeping DROP TABLE #Tally 10 15 761 0
51 --===== Test for 1000000 rows ========== 0 0 0 0
51 --===== Traditional RECURSIVE CTE method 41349 37437 8001048 1601
51 --===== Traditional WHILE LOOP method CR 59138 56141 1012785 1682
51 --===== Traditional CROSS JOIN table met 1224 1219 2429 2101
51 --===== Itzik's CROSS JOINED CTE method 1448 1328 1217 2095
51 --===== Housekeeping DROP TABLE #Tally 8 0 415 0
```
As you can see, **the Recursive CTE method is the second worst only to the While Loop for Duration and CPU and has 8 times the memory pressure in the form of logical reads than the While Loop**. It's RBAR on steroids and should be avoided, at all cost, for any single row calculations just as a While Loop should be avoided. **There are places where recursion is quite valuable but this ISN'T one of them**.
As a side bar, Mr. Denny is absolutely spot on... a correctly sized permanent Numbers or Tally table is the way to go for most things. What does correctly sized mean? Well, most people use a Tally table to generate dates or to do splits on VARCHAR(8000). If you create an 11,000 row Tally table with the correct clustered index on "N", you'll have enough rows to create more than 30 years worth of dates (I work with mortgages a fair bit so 30 years is a key number for me) and certainly enough to handle a VARCHAR(8000) split. Why is "right sizing" so important? If the Tally table is used a lot, it easily fits in cache which makes it blazingly fast without much pressure on memory at all.
Last but not least, every one knows that if you create a permanent Tally table, it doesn't much matter which method you use to build it because 1) it's only going to be made once and 2) if it's something like an 11,000 row table, all of the methods are going to run "good enough". **So why all the indigination on my part about which method to use???**
The answer is that some poor guy/gal who doesn't know any better and just needs to get his or her job done might see something like the Recursive CTE method and decide to use it for something much larger and much more frequently used than building a permanent Tally table and I'm trying to **protect those people, the servers their code runs on, and the company that owns the data on those servers**. Yeah... it's that big a deal. It should be for everyone else, as well. Teach the right way to do things instead of "good enough". Do some testing before posting or using something from a post or book... the life you save may, in fact, be your own especially if you think a recursive CTE is the way to go for something like this. ;-)
Thanks for listening... |
10,822 | <p>What would be a very fast way to determine if your connectionstring lets you connect to a database?</p>
<p>Normally a connection attempt keeps the user waiting a long time before notifying the attempt was futile anyway.</p>
| [
{
"answer_id": 10823,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>Shorten the timeout on the connection string and execute something trivial.</p>\n\n<p>The wait should be about the same as the... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271/"
] | What would be a very fast way to determine if your connectionstring lets you connect to a database?
Normally a connection attempt keeps the user waiting a long time before notifying the attempt was futile anyway. | You haven't mentioned what database you are connecting to, however. In [SQL Server 2005](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005), from .NET, you can specify a connection timeout in your connection string like so:
```
server=<server>;database=<database>;uid=<user>;password=<password>;Connect Timeout=3
```
This will try to connect to the server and if it doesn't do so in three seconds, it will throw a timeout error. |
10,825 | <p>In SQL Server I have a <code>DATETIME</code> column which includes a time element.</p>
<p>Example: </p>
<pre><code>'14 AUG 2008 14:23:019'
</code></pre>
<p>What is the <strong>best</strong> method to only select the records for a particular day, ignoring the time part?</p>
<p>Example: (Not safe, as it does not match the time part and returns no rows)</p>
<pre><code>DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime = @p_date
</code></pre>
<p><em>Note: Given this site is also about jotting down notes and techniques you pick up and then forget, I'm going to post my own answer to this question as DATETIME stuff in MSSQL is probably the topic I lookup most in SQLBOL.</em></p>
<hr>
<p><strong>Update</strong> Clarified example to be more specific.</p>
<hr>
<p><strong>Edit</strong> Sorry, But I've had to down-mod WRONG answers (answers that return wrong results).</p>
<p>@Jorrit: <code>WHERE (date>'20080813' AND date<'20080815')</code> will return the 13th and the 14th.</p>
<p>@wearejimbo: <em>Close, but no cigar!</em> badge awarded to you. You missed out records written at 14/08/2008 23:59:001 to 23:59:999 (i.e. Less than 1 second before midnight.)</p>
| [
{
"answer_id": 10826,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 6,
"selected": true,
"text": "<p>Technique 1:</p>\n\n<pre><code> DECLARE @p_date DATETIME\n SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )\n\n SELECT ... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993/"
] | In SQL Server I have a `DATETIME` column which includes a time element.
Example:
```
'14 AUG 2008 14:23:019'
```
What is the **best** method to only select the records for a particular day, ignoring the time part?
Example: (Not safe, as it does not match the time part and returns no rows)
```
DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime = @p_date
```
*Note: Given this site is also about jotting down notes and techniques you pick up and then forget, I'm going to post my own answer to this question as DATETIME stuff in MSSQL is probably the topic I lookup most in SQLBOL.*
---
**Update** Clarified example to be more specific.
---
**Edit** Sorry, But I've had to down-mod WRONG answers (answers that return wrong results).
@Jorrit: `WHERE (date>'20080813' AND date<'20080815')` will return the 13th and the 14th.
@wearejimbo: *Close, but no cigar!* badge awarded to you. You missed out records written at 14/08/2008 23:59:001 to 23:59:999 (i.e. Less than 1 second before midnight.) | Technique 1:
```
DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime >= @p_date
AND column_datetime < DATEADD(d, 1, @p_date)
```
The advantage of this is that it will use any index on 'column\_datetime' if it exists. |
10,855 | <p>I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:</p>
<pre><code>var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
</code></pre>
<p>This is not allowed. How do I get something like this working?</p>
<p>I'm amazed that LINQ queries are not allowed on DataTables!</p>
| [
{
"answer_id": 10856,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 6,
"selected": false,
"text": "<p>It's not that they were deliberately not allowed on DataTables, it's just that DataTables pre-date the IQueryable and gen... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445/"
] | I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:
```
var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
```
This is not allowed. How do I get something like this working?
I'm amazed that LINQ queries are not allowed on DataTables! | You can't query against the `DataTable`'s *Rows* collection, since `DataRowCollection` doesn't implement `IEnumerable<T>`. You need to use the `AsEnumerable()` extension for `DataTable`. Like so:
```
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;
```
And as [@Keith](https://stackoverflow.com/a/10893/5519709) says, you'll need to add a reference to [System.Data.DataSetExtensions](http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx)
`AsEnumerable()` returns `IEnumerable<DataRow>`. If you need to convert `IEnumerable<DataRow>` to a `DataTable`, use the `CopyToDataTable()` extension.
Below is query with Lambda Expression,
```
var result = myDataTable
.AsEnumerable()
.Where(myRow => myRow.Field<int>("RowNo") == 1);
``` |
10,870 | <p>Once I've called <code>DragManager.acceptDrag</code> is there any way to "unaccept" the drag? Say that I have a view which can accept drag and drop, but only in certain areas. Once the user drags over one of these areas I call <code>DragManager.acceptDrag(this)</code> (from a <code>DragEvent.DRAG_OVER</code> handler), but if the user then moves out of this area I'd like to change the status of the drag to not accepted and show the <code>DragManager.NONE</code> feedback. However, neither calling <code>DragManager.acceptDrag(null)</code> nor <code>DragManager.showFeedback(DragManager.NONE)</code> seems to have any effect. Once I've accepted the drag an set the feedback type I can't seem to change it.</p>
<p>Just to make it clear: the areas where the user should be able to drop are not components or even display objects, in fact they are just ranges in the text of a text field (like the selection). Had they been components of their own I could have solved it by making each of them accept drag events individually. I guess I could create proxy components that float over the text to emulate it, but I'd rather not if it isn't necessary.</p>
<hr>
<p>I've managed to get it working in both AIR and the browser now, but only by putting proxy components on top of the ranges of text where you should be able to drop things. That way I get the right feedback and drops are automatically unaccepted on drag exit.</p>
<p>This is the oddest thing about D&D in AIR:</p>
<pre><code>DragManager.doDrag(initiator, source, event, dragImage, offsetX, offsetY);
</code></pre>
<p>In browser-based Flex, <code>offsetX</code> and <code>offsetY</code> should be negative (so says the documentation, and it works fine). However, when running <em>exactly the same code</em> in AIR you have to make the offsets positive. The same numbers, but positive. That is very, very weird.</p>
<hr>
<p>I've tested some more and what <a href="https://stackoverflow.com/questions/10870/how-can-i-unaccept-a-drag-in-flex#11209">@maclema</a> works, but not if you run in AIR. It seems like drag and drop in AIR is different. It's really, really weird because not only is the feedback not showing correctly, and it's not possible to unaccept, but the coordinates are also completely off. I just tried my application in a browser instead of AIR and dragging and dropping is completely broken.</p>
<p>Also, skipping the <code>dragEnter</code> handler works fine in AIR, but breaks everything when running in a browser.</p>
| [
{
"answer_id": 11209,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 3,
"selected": false,
"text": "<p>Are you using only the dragEnter method? If you are trying to reject the drag while still dragging over the same componen... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1109/"
] | Once I've called `DragManager.acceptDrag` is there any way to "unaccept" the drag? Say that I have a view which can accept drag and drop, but only in certain areas. Once the user drags over one of these areas I call `DragManager.acceptDrag(this)` (from a `DragEvent.DRAG_OVER` handler), but if the user then moves out of this area I'd like to change the status of the drag to not accepted and show the `DragManager.NONE` feedback. However, neither calling `DragManager.acceptDrag(null)` nor `DragManager.showFeedback(DragManager.NONE)` seems to have any effect. Once I've accepted the drag an set the feedback type I can't seem to change it.
Just to make it clear: the areas where the user should be able to drop are not components or even display objects, in fact they are just ranges in the text of a text field (like the selection). Had they been components of their own I could have solved it by making each of them accept drag events individually. I guess I could create proxy components that float over the text to emulate it, but I'd rather not if it isn't necessary.
---
I've managed to get it working in both AIR and the browser now, but only by putting proxy components on top of the ranges of text where you should be able to drop things. That way I get the right feedback and drops are automatically unaccepted on drag exit.
This is the oddest thing about D&D in AIR:
```
DragManager.doDrag(initiator, source, event, dragImage, offsetX, offsetY);
```
In browser-based Flex, `offsetX` and `offsetY` should be negative (so says the documentation, and it works fine). However, when running *exactly the same code* in AIR you have to make the offsets positive. The same numbers, but positive. That is very, very weird.
---
I've tested some more and what [@maclema](https://stackoverflow.com/questions/10870/how-can-i-unaccept-a-drag-in-flex#11209) works, but not if you run in AIR. It seems like drag and drop in AIR is different. It's really, really weird because not only is the feedback not showing correctly, and it's not possible to unaccept, but the coordinates are also completely off. I just tried my application in a browser instead of AIR and dragging and dropping is completely broken.
Also, skipping the `dragEnter` handler works fine in AIR, but breaks everything when running in a browser. | Are you using only the dragEnter method? If you are trying to reject the drag while still dragging over the same component you need to use both the dragEnter and dragOver methods.
Check out this example:
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.core.DragSource;
import mx.managers.DragManager;
import mx.events.DragEvent;
private function onDragEnter(e:DragEvent):void {
if ( e.target == lbl ) {
if ( e.localX < lbl.width/2 ) {
trace("accept");
DragManager.acceptDragDrop(this);
}
else {
DragManager.acceptDragDrop(null);
}
}
}
private function doStartDrag(e:MouseEvent):void {
if ( e.buttonDown ) {
var ds:DragSource = new DragSource();
ds.addData("test", "text");
DragManager.doDrag(btn, ds, e);
}
}
]]>
</mx:Script>
<mx:Label id="lbl" text="hello world!" left="10" top="10" dragEnter="onDragEnter(event)" dragOver="onDragEnter(event)" />
<mx:Button id="btn" x="47" y="255" label="Button" mouseMove="doStartDrag(event)"/>
</mx:Application>
``` |
10,877 | <p>How can I left-align the numbers in an ordered list?</p>
<pre><code>1. an item
// skip some items for brevity
9. another item
10. notice the 1 is under the 9, and the item contents also line up
</code></pre>
<p>Change the character after the number in an ordered list?</p>
<pre><code>1) an item
</code></pre>
<p>Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.</p>
<p>I am mostly interested in answers that work on Firefox 3.</p>
| [
{
"answer_id": 10887,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 5,
"selected": false,
"text": "<p>The CSS for styling lists is <a href=\"http://www.w3.org/TR/REC-CSS2/generate.html#lists\" rel=\"noreferrer\">here<... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] | How can I left-align the numbers in an ordered list?
```
1. an item
// skip some items for brevity
9. another item
10. notice the 1 is under the 9, and the item contents also line up
```
Change the character after the number in an ordered list?
```
1) an item
```
Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.
I am mostly interested in answers that work on Firefox 3. | This is the solution I have working in Firefox 3, Opera and Google Chrome. The list still displays in IE7 (but without the close bracket and left align numbers):
```css
ol {
counter-reset: item;
margin-left: 0;
padding-left: 0;
}
li {
display: block;
margin-bottom: .5em;
margin-left: 2em;
}
li::before {
display: inline-block;
content: counter(item) ") ";
counter-increment: item;
width: 2em;
margin-left: -2em;
}
```
```html
<ol>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li>Eight</li>
<li>Nine<br>Items</li>
<li>Ten<br>Items</li>
</ol>
```
**EDIT:** Included multiple line fix by strager
>
> Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.
>
>
>
Refer to [list-style-type](http://www.w3.org/TR/CSS2/generate.html#lists) CSS property. Or when using counters the second argument accepts a list-style-type value. For example the following will use upper roman:
```
li::before {
content: counter(item, upper-roman) ") ";
counter-increment: item;
/* ... */
``` |
10,905 | <p>You should be able to create a generic form:</p>
<pre><code>public partial class MyGenericForm<T> :
Form where T : class
{
/* form code */
public List<T> TypedList { get; set; }
}
</code></pre>
<p>Is valid C#, and compiles. However the designer won't work and the form will throw a runtime exception if you have any images stating that it cannot find the resource.</p>
<p>I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name.</p>
| [
{
"answer_id": 10906,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>I have a hack to workaround this, which works but isn't ideal:</p>\n\n<p>Add a new class to the project that inherits the form... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | You should be able to create a generic form:
```
public partial class MyGenericForm<T> :
Form where T : class
{
/* form code */
public List<T> TypedList { get; set; }
}
```
Is valid C#, and compiles. However the designer won't work and the form will throw a runtime exception if you have any images stating that it cannot find the resource.
I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name. | Yes you can! Here's a blog post I made a while ago with the trick:
[Designing Generic Forms](http://www.madprops.org/blog/designing-generic-forms/)
Edit: Looks like you're already doing it this way. This method works fine so I wouldn't consider it too hacky. |
10,915 | <p>Warning - I am very new to NHibernate. I know this question seems simple - and I'm sure there's a simple answer, but I've been spinning my wheels for some time on this one. I am dealing with a legacy db which really can't be altered structurally. I have a details table which lists payment plans that have been accepted by a customer. Each payment plan has an ID which links back to a reference table to get the plan's terms, conditions, etc. In my object model, I have an AcceptedPlan class, and a Plan class. Originally, I used a many-to-one relationship from the detail table back to the ref table to model this relationship in NHibernate. I also created a one-to-many relationship going in the opposite direction from the Plan class over to the AcceptedPlan class. This was fine while I was simply reading data. I could go to my Plan object, which was a property of my AcceptedPlan class to read the plan's details. My problem arose when I had to start inserting new rows to the details table. From my reading, it seems the only way to create a new child object is to add it to the parent object and then save the session. But I don't want to have to create a new parent Plan object every time I want to create a new detail record. This seems like unnecessary overhead. Does anyone know if I am going about this in the wrong way?</p>
| [
{
"answer_id": 10993,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 0,
"selected": false,
"text": "<p>The approach I'd take to model this is as follows:</p>\n\n<p>Customer object contains an ICollection <PaymentPlan&... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] | Warning - I am very new to NHibernate. I know this question seems simple - and I'm sure there's a simple answer, but I've been spinning my wheels for some time on this one. I am dealing with a legacy db which really can't be altered structurally. I have a details table which lists payment plans that have been accepted by a customer. Each payment plan has an ID which links back to a reference table to get the plan's terms, conditions, etc. In my object model, I have an AcceptedPlan class, and a Plan class. Originally, I used a many-to-one relationship from the detail table back to the ref table to model this relationship in NHibernate. I also created a one-to-many relationship going in the opposite direction from the Plan class over to the AcceptedPlan class. This was fine while I was simply reading data. I could go to my Plan object, which was a property of my AcceptedPlan class to read the plan's details. My problem arose when I had to start inserting new rows to the details table. From my reading, it seems the only way to create a new child object is to add it to the parent object and then save the session. But I don't want to have to create a new parent Plan object every time I want to create a new detail record. This seems like unnecessary overhead. Does anyone know if I am going about this in the wrong way? | I'd steer away from having child object containing their logical parent, it can get very messy and very recursive pretty quickly when you do that. I'd take a look at how you're intending to use the domain model before you do that sort of thing. You can easily still have the ID references in the tables and just leave them unmapped.
Here are two example mappings that might nudge you in the right direction, I've had to adlib table names etc but it could possibly help. I'd probably also suggest mapping the StatusId to an enumeration.
Pay attention to the way the bag effectivly maps the details table into a collection.
```
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping default-cascade="save-update" xmlns="urn:nhibernate-mapping-2.2">
<class lazy="false" name="Namespace.Customer, Namespace" table="Customer">
<id name="Id" type="Int32" unsaved-value="0">
<column name="CustomerAccountId" length="4" sql-type="int" not-null="true" unique="true" index="CustomerPK"/>
<generator class="native" />
</id>
<bag name="AcceptedOffers" inverse="false" lazy="false" cascade="all-delete-orphan" table="details">
<key column="CustomerAccountId" foreign-key="AcceptedOfferFK"/>
<many-to-many
class="Namespace.AcceptedOffer, Namespace"
column="AcceptedOfferFK"
foreign-key="AcceptedOfferID"
lazy="false"
/>
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping default-cascade="save-update" xmlns="urn:nhibernate-mapping-2.2">
<class lazy="false" name="Namespace.AcceptedOffer, Namespace" table="AcceptedOffer">
<id name="Id" type="Int32" unsaved-value="0">
<column name="AcceptedOfferId" length="4" sql-type="int" not-null="true" unique="true" index="AcceptedOfferPK"/>
<generator class="native" />
</id>
<many-to-one
name="Plan"
class="Namespace.Plan, Namespace"
lazy="false"
cascade="save-update"
>
<column name="PlanFK" length="4" sql-type="int" not-null="false"/>
</many-to-one>
<property name="StatusId" type="Int32">
<column name="StatusId" length="4" sql-type="int" not-null="true"/>
</property>
</class>
</hibernate-mapping>
``` |
10,926 | <p>I'm building a listing/grid control in a <code>Flex</code> application and using it in a <code>.NET</code> web application. To make a really long story short I am getting XML from a webservice of serialized objects. I have a page limit of how many things can be on a page. I've taken a data grid and made it page, sort across pages, and handle some basic filtering. </p>
<p>In regards to paging I'm using a Dictionary keyed on the page and storing the XML for that page. This way whenever a user comes back to a page that I've saved into this dictionary I can grab the XML from local memory instead of hitting the webservice. Basically, I'm caching the data retrieved from each call to the webservice for a page of data.</p>
<p>There are several things that can expire my cache. Filtering and sorting are the main reason. However, a user may edit a row of data in the grid by opening an editor. The data they edit could cause the data displayed in the row to be stale. I could easily go to the webservice and get the whole page of data, but since the page size is set at runtime I could be looking at a large amount of records to retrieve.</p>
<p>So let me now get to the heart of the issue that I am experiencing. In order to prevent getting the whole page of data back I make a call to the webservice asking for the completely updated record (the editor handles saving its data).</p>
<p>Since I'm using custom objects I need to serialize them on the server to XML (this is handled already for other portions of our software). All data is handled through XML in e4x. The cache in the Dictionary is stored as an XMLList.</p>
<p><strong>Now let me show you my code...</strong></p>
<pre><code>var idOfReplacee:String = this._WebService.GetSingleModelXml.lastResult.*[0].*[0].@Id;
var xmlToReplace:XMLList = this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee);
if(xmlToReplace.length() > 0)
{
delete (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]);
this._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0];
}
</code></pre>
<p>Basically, I get the id of the node I want to replace. Then I find it in the cache's Data property (<code>XMLList</code>). I make sure it exists since the filter on the second line returns the <code>XMLList</code>.</p>
<p>The problem I have is with the delete line. I cannot make that line delete that node from the list. The line following the delete line works. I've added the node to the list.</p>
<p>How do I replace or delete that node (meaning the node that I find from the filter statement out of the .Data property of the cache)???</p>
<p>Hopefully the underscores for all of my variables do not stay escaped when this is posted! otherwise <code>this.&#95 == this</code>._</p>
| [
{
"answer_id": 11048,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 0,
"selected": false,
"text": "<p>I don't immediately see the problem, so I can only venture a guess. The <code>delete</code> line that you've got is lo... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1290/"
] | I'm building a listing/grid control in a `Flex` application and using it in a `.NET` web application. To make a really long story short I am getting XML from a webservice of serialized objects. I have a page limit of how many things can be on a page. I've taken a data grid and made it page, sort across pages, and handle some basic filtering.
In regards to paging I'm using a Dictionary keyed on the page and storing the XML for that page. This way whenever a user comes back to a page that I've saved into this dictionary I can grab the XML from local memory instead of hitting the webservice. Basically, I'm caching the data retrieved from each call to the webservice for a page of data.
There are several things that can expire my cache. Filtering and sorting are the main reason. However, a user may edit a row of data in the grid by opening an editor. The data they edit could cause the data displayed in the row to be stale. I could easily go to the webservice and get the whole page of data, but since the page size is set at runtime I could be looking at a large amount of records to retrieve.
So let me now get to the heart of the issue that I am experiencing. In order to prevent getting the whole page of data back I make a call to the webservice asking for the completely updated record (the editor handles saving its data).
Since I'm using custom objects I need to serialize them on the server to XML (this is handled already for other portions of our software). All data is handled through XML in e4x. The cache in the Dictionary is stored as an XMLList.
**Now let me show you my code...**
```
var idOfReplacee:String = this._WebService.GetSingleModelXml.lastResult.*[0].*[0].@Id;
var xmlToReplace:XMLList = this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee);
if(xmlToReplace.length() > 0)
{
delete (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]);
this._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0];
}
```
Basically, I get the id of the node I want to replace. Then I find it in the cache's Data property (`XMLList`). I make sure it exists since the filter on the second line returns the `XMLList`.
The problem I have is with the delete line. I cannot make that line delete that node from the list. The line following the delete line works. I've added the node to the list.
How do I replace or delete that node (meaning the node that I find from the filter statement out of the .Data property of the cache)???
Hopefully the underscores for all of my variables do not stay escaped when this is posted! otherwise `this._ == this`.\_ | Thanks for the answers guys.
@Theo:
I tried the replace several different ways. For some reason it would never error, but never update the list.
@Matt:
I figured out a solution. The issue wasn't coming from what you suggested, but from how the delete works with Lists (at least how I have it in this instance).
The Data property of the \_DataPages dictionary object is list of the definition nodes (was arrived at by a previous filtering of another XML document).
```
<Models>
<Definition Id='1' />
<Definition Id='2' />
</Models>
```
I ended up doing this little deal:
```
//gets the index of the node to replace from the same filter
var childIndex:int = (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]).childIndex();
//deletes the node from the list
delete this._DataPages[this._Options.PageIndex].Data[childIndex];
//appends the new node from the webservice to the list
this._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0];
```
So basically I had to get the index of the node in the XMLList that is the Data property. From there I could use the delete keyword to remove it from the list. The += adds my new node to the list.
I'm so used to using the ActiveX or Mozilla XmlDocument stuff where you call "SelectSingleNode" and then use "replaceChild" to do this kind of stuff. Oh well, at least this is in some forum where someone else can find it. I do not know the procedure for what happens when I answer my own question. Perhaps this insight will help someone else come along and help answer the question better! |
10,985 | <p>Does anyone know how I can, in platform-independent C++ code prevent an object from being created on the heap? That is, for a class "Foo", I want to prevent users from doing this:</p>
<pre><code>Foo *ptr = new Foo;
</code></pre>
<p>and only allow them to do this:</p>
<pre><code>Foo myfooObject;
</code></pre>
<p>Does anyone have any ideas?</p>
<p>Cheers,</p>
| [
{
"answer_id": 11000,
"author": "David",
"author_id": 381,
"author_profile": "https://Stackoverflow.com/users/381",
"pm_score": 0,
"selected": false,
"text": "<p>You could declare a function called \"operator new\" inside the Foo class which would block the access to the normal form of n... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
] | Does anyone know how I can, in platform-independent C++ code prevent an object from being created on the heap? That is, for a class "Foo", I want to prevent users from doing this:
```
Foo *ptr = new Foo;
```
and only allow them to do this:
```
Foo myfooObject;
```
Does anyone have any ideas?
Cheers, | [Nick's answer](https://stackoverflow.com/questions/10985/how-to-prevent-an-object-being-created-on-the-heap#11003) is a good starting point, but incomplete, as you actually need to overload:
```
private:
void* operator new(size_t); // standard new
void* operator new(size_t, void*); // placement new
void* operator new[](size_t); // array new
void* operator new[](size_t, void*); // placement array new
```
(Good coding practice would suggest you should also overload the delete and delete[] operators -- I would, but since they're not going to get called it isn't *really* necessary.)
[Pauldoo](https://stackoverflow.com/questions/10985/how-to-prevent-an-object-being-created-on-the-heap#11018) is also correct that this doesn't survive aggregating on Foo, although it does survive inheriting from Foo. You could do some template meta-programming magic to HELP prevent this, but it would not be immune to "evil users" and thus is probably not worth the complication. Documentation of how it should be used, and code review to ensure it is used properly, are the only ~100% way. |
10,990 | <p>Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.</p>
<p>I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such:</p>
<pre><code>chown apache:apache -R uploads/
chmod 755 -R uploads/
</code></pre>
<p>The only problem now is that the FTP user can not modify the uploaded files at all.</p>
<p>Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user?</p>
| [
{
"answer_id": 11005,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 7,
"selected": true,
"text": "<p>You can create a new group with both the apache user and FTP user as members and then make the permission on the upload fol... | 2008/08/14 | [
"https://Stackoverflow.com/questions/10990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1153/"
] | Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.
I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such:
```
chown apache:apache -R uploads/
chmod 755 -R uploads/
```
The only problem now is that the FTP user can not modify the uploaded files at all.
Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user? | You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them. |
11,028 | <p>When I'm joining three or more tables together by a common column, I'd write my query like this:</p>
<pre><code>SELECT *
FROM a, b, c
WHERE a.id = b.id
AND b.id = c.id
</code></pre>
<p>a colleague recently asked my why I didn't do explicit <em>Join Transitive Closure</em> in my queries like this:</p>
<pre><code>SELECT *
FROM a, b, c
WHERE a.id = b.id
AND b.id = c.id
AND c.id = a.id
</code></pre>
<p>are the really any advantages to this? Surely the optimiser can imply this for itself?</p>
<p><em>edit: I know it's evil syntax, but it's a quick and dirty example of legitimate legacy code +1 @<a href="https://stackoverflow.com/questions/11028/what-are-the-advantages-of-explicit-join-transitive-closure-in-sql#11114">Stu</a> for cleaning it up</em></p>
| [
{
"answer_id": 11031,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>No this syntax stems from the days before joins were in the language. Not sure of the problems associated with it, but t... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | When I'm joining three or more tables together by a common column, I'd write my query like this:
```
SELECT *
FROM a, b, c
WHERE a.id = b.id
AND b.id = c.id
```
a colleague recently asked my why I didn't do explicit *Join Transitive Closure* in my queries like this:
```
SELECT *
FROM a, b, c
WHERE a.id = b.id
AND b.id = c.id
AND c.id = a.id
```
are the really any advantages to this? Surely the optimiser can imply this for itself?
*edit: I know it's evil syntax, but it's a quick and dirty example of legitimate legacy code +1 @[Stu](https://stackoverflow.com/questions/11028/what-are-the-advantages-of-explicit-join-transitive-closure-in-sql#11114) for cleaning it up* | You don't need to do this in todays database engines, but there was a time when things like that would give the query optimizer more hints as to possible index paths and thus to speedier results.
These days that entire syntax is going out anyway. |
11,043 | <p>What are the pros and cons of using table aliases in SQL? I personally try to avoid them, as I think they make the code less readable (especially when reading through large where/and statements), but I'd be interested in hearing any counter-points to this. When is it generally a good idea to use table aliases, and do you have any preferred formats?</p>
| [
{
"answer_id": 11049,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": false,
"text": "<p>Well, there are some cases you <em>must</em> use them, like when you need to join to the same table twice in one qu... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/637/"
] | What are the pros and cons of using table aliases in SQL? I personally try to avoid them, as I think they make the code less readable (especially when reading through large where/and statements), but I'd be interested in hearing any counter-points to this. When is it generally a good idea to use table aliases, and do you have any preferred formats? | Table aliases are a necessary evil when dealing with highly normalized schemas. For example, and I'm not the architect on this DB so bear with me, it can take 7 joins in order to get a clean and complete record back which includes a person's name, address, phone number and company affiliation.
Rather than the somewhat standard single character aliases, I tend to favor short word aliases so the above example's SQL ends up looking like:
```
select person.FirstName
,person.LastName
,addr.StreetAddress
,addr.City
,addr.State
,addr.Zip
,phone.PhoneNumber
,company.CompanyName
from tblPeople person
left outer join tblAffiliations affl on affl.personID = person.personID
left outer join tblCompany company on company.companyID = affl.companyID
```
... etc |
11,045 | <p>How can I get a user-defined function to re-evaluate itself based on changed data in the spreadsheet?</p>
<p>I tried <strong><kbd>F9</kbd></strong> and <strong><kbd>Shift</kbd>+<kbd>F9</kbd></strong>.</p>
<p>The only thing that seems to work is editing the cell with the function call and then pressing Enter.</p>
| [
{
"answer_id": 11061,
"author": "Brian Sullivan",
"author_id": 767,
"author_profile": "https://Stackoverflow.com/users/767",
"pm_score": 4,
"selected": false,
"text": "<p>Okay, found this one myself. You can use <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>F9</kbd> to accomplish this.</p>\n"
}... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767/"
] | How can I get a user-defined function to re-evaluate itself based on changed data in the spreadsheet?
I tried **`F9`** and **`Shift`+`F9`**.
The only thing that seems to work is editing the cell with the function call and then pressing Enter. | You should use `Application.Volatile` in the top of your function:
```
Function doubleMe(d)
Application.Volatile
doubleMe = d * 2
End Function
```
It will then reevaluate whenever the workbook changes (if your calculation is set to automatic). |
11,085 | <p>In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class. When you use the ref() function on an unblessed reference, you are told what data type the reference points to. However, when you call ref() on a blessed reference, you are returned the name of the package that reference has been blessed into. </p>
<p>I want to know the actual underlying type of the blessed reference. How can I determine this?</p>
| [
{
"answer_id": 42237,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 2,
"selected": false,
"text": "<p>And my first thought on this was: \"Objects in Perl are always hash refs, so what the hack?\"</p>\n\n<p>But, Scalar::Util::... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/166/"
] | In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class. When you use the ref() function on an unblessed reference, you are told what data type the reference points to. However, when you call ref() on a blessed reference, you are returned the name of the package that reference has been blessed into.
I want to know the actual underlying type of the blessed reference. How can I determine this? | `Scalar::Util::reftype()` is the cleanest solution. The [`Scalar::Util`](http://search.cpan.org/dist/Scalar-List-Utils/lib/Scalar/Util.pm) module was added to the Perl core in version 5.7 but is available for older versions (5.004 or later) from CPAN.
You can also probe with `UNIVERSAL::isa()`:
```
$x->isa('HASH') # if $x is known to be an object
UNIVERSAL::isa($x, 'HASH') # if $x might not be an object or reference
```
Obviously, you'd also have to check for `ARRAY` and `SCALAR` types. The UNIVERSAL module (which serves as the base class for all objects) has been part of the core since Perl 5.003.
Another way -- easy but a little dirty -- is to stringify the reference. Assuming that the class hasn't overloaded stringification you'll get back something resembling `Class=HASH(0x1234ABCD)`, which you can parse to extract the underlying data type:
```
my $type = ($object =~ /=(.+)\(0x[0-9a-f]+\)$/i);
``` |
11,088 | <p>In Java, there is no such thing as an unsigned byte.</p>
<p>Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign.</p>
<p>What's a good way to work around this? (Saying don't use Java is not an option)</p>
| [
{
"answer_id": 11092,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "<p>I guess you could just use a short to store them. Not very efficient, but really the only option besides some herculean... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1309/"
] | In Java, there is no such thing as an unsigned byte.
Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign.
What's a good way to work around this? (Saying don't use Java is not an option) | When reading any single value from the array copy it into something like a short or an int and manually convert the negative number into the positive value it should be.
```
byte[] foobar = ..;
int value = foobar[10];
if (value < 0) value += 256 // Patch up the 'falsely' negative value
```
You can do a similar conversion when writing into the array. |
11,099 | <p>In the case of languages that support single decision and action without brackets, such as the following example:</p>
<pre><code>if (var == true)
doSomething();
</code></pre>
<p>What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example:</p>
<pre><code>if (var == 1)
doSomething(1);
else if (var > 1 && var < 10)
doSomething(2);
else
{
validate(var);
doSomething(var);
}
</code></pre>
| [
{
"answer_id": 11102,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't really matter, as long as you're consistent with it.</p>\n\n<p>There does seem to be a tendency to demand sameness wi... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | In the case of languages that support single decision and action without brackets, such as the following example:
```
if (var == true)
doSomething();
```
What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example:
```
if (var == 1)
doSomething(1);
else if (var > 1 && var < 10)
doSomething(2);
else
{
validate(var);
doSomething(var);
}
``` | There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like
```
if ( a == b) {
doSomething();
}
else {
doSomething();
}
```
but this is a holy war. |
11,112 | <p>Most wiki software I've presents lots of "features" on their pages. This is fine for desktop users, but is annoying when using an iPhone or other mobile device. <br /><br />I'd prefer pages that just had the content, along with maybe an Edit button and a Search button. The editors are also often too fancy for mobile users; a simple multi-line edit field would be better for mobile users than a bunch of formatting controls.</p>
<p>What is a good wiki package for mobile users?</p>
| [
{
"answer_id": 11102,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't really matter, as long as you're consistent with it.</p>\n\n<p>There does seem to be a tendency to demand sameness wi... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] | Most wiki software I've presents lots of "features" on their pages. This is fine for desktop users, but is annoying when using an iPhone or other mobile device.
I'd prefer pages that just had the content, along with maybe an Edit button and a Search button. The editors are also often too fancy for mobile users; a simple multi-line edit field would be better for mobile users than a bunch of formatting controls.
What is a good wiki package for mobile users? | There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like
```
if ( a == b) {
doSomething();
}
else {
doSomething();
}
```
but this is a holy war. |
11,141 | <p>Recently I have been investigating the possibilities of caching in ASP.NET.</p>
<p>I rolled my own "Cache", because I didn't know any better, it looked a bit like this:</p>
<pre><code>public class DataManager
{
private static DataManager s_instance;
public static DataManager GetInstance()
{
}
private Data[] m_myData;
private DataTime m_cacheTime;
public Data[] GetData()
{
TimeSpan span = DateTime.Now.Substract(m_cacheTime);
if(span.TotalSeconds > 10)
{
// Do SQL to get data
m_myData = data;
m_cacheTime = DateTime.Now;
return m_myData;
}
else
{
return m_myData;
}
}
}
</code></pre>
<p>So the values are stored for a while in a singleton, and when the time expires, the values are renewed. If time has not expired, and a request for the data is done, the stored values in the field are returned.</p>
<p>What are the benefits over using the real method (<a href="http://msdn.microsoft.com/en-us/library/aa478965.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa478965.aspx</a>) instead of this?</p>
| [
{
"answer_id": 11146,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": true,
"text": "<p>I think the maxim \"let the computer do it; it's smarter than you\" applies here. Just like memory management and ot... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Recently I have been investigating the possibilities of caching in ASP.NET.
I rolled my own "Cache", because I didn't know any better, it looked a bit like this:
```
public class DataManager
{
private static DataManager s_instance;
public static DataManager GetInstance()
{
}
private Data[] m_myData;
private DataTime m_cacheTime;
public Data[] GetData()
{
TimeSpan span = DateTime.Now.Substract(m_cacheTime);
if(span.TotalSeconds > 10)
{
// Do SQL to get data
m_myData = data;
m_cacheTime = DateTime.Now;
return m_myData;
}
else
{
return m_myData;
}
}
}
```
So the values are stored for a while in a singleton, and when the time expires, the values are renewed. If time has not expired, and a request for the data is done, the stored values in the field are returned.
What are the benefits over using the real method (<http://msdn.microsoft.com/en-us/library/aa478965.aspx>) instead of this? | I think the maxim "let the computer do it; it's smarter than you" applies here. Just like memory management and other complicated things, the computer is a lot more informed about what it's doing than your are; consequently, able to get more performance than you are.
Microsoft has had a team of engineers working on it and they've probably managed to squeeze much more performance out of the system than would be possible for you to. It's also likely that ASP.NET's built-in caching operates at a different level (which is inaccessible to your application), making it much faster. |
11,194 | <p>We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?</p>
| [
{
"answer_id": 11201,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>Just use C#'s && operator:</p>\n\n<pre><code>var items = dc.Users.Where(l => l.Date == DateTime.Today &a... | 2008/08/14 | [
"https://Stackoverflow.com/questions/11194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1204/"
] | We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses? | if you want to only filter if certain criteria is passed, do something like this
```
var logs = from log in context.Logs
select log;
if (filterBySeverity)
logs = logs.Where(p => p.Severity == severity);
if (filterByUser)
logs = logs.Where(p => p.User == user);
```
Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less. |