Question:
I've been trying to get up to speed on some of the newer features in C# and one of them that I haven't had occasion to use is anonymous types.

I understand the usage as it pertains to LINQ queries and I looked at this SO post which asked a similar question.  Most of the examples I've seen on the net are related to LINQ queries, which is cool.  I saw some somewhat contrived examples too but not really anything where I saw a lot of value.

Do you have a novel use for anonymous types where you think it really provides you some utility?

Answer:
The biggest use for anonymous types is LINQ, in fact that's why it was created.
I guess one reason for an anonymous type outside of linq is to create a temporary struct-like object, e.g.:
```
```
var x = new { a = 1, b = 2 };
```
```
That may make your life a little easier in some situations.


Question:
Can someone provide a regular expression for parsing name/value pairs from a string?  The pairs are separated by commas, and the value can optionally be enclosed in quotes.  For example:

AssemblyName=foo.dll,ClassName="SomeClass",Parameters="Some,Parameters"

Answer:
No escape:
```
```
/([^=,]*)=("[^"]*"|[^,"]*)/
```
```
Double quote escape for both key and value:
```
```
/((?:"[^"]*"|[^=,])*)=((?:"[^"]*"|[^=,])*)/

key=value,"key with "" in it"="value with "" in it",key=value" "with" "spaces
```
```
Backslash string escape:
```
```
/([^=,]*)=("(?:\\.|[^"\\]+)*"|[^,"]*)/

key=value,key="value",key="val\"ue"
```
```
Full backslash escape:
```
```
/((?:\\.|[^=,]+)*)=("(?:\\.|[^"\\]+)*"|(?:\\.|[^,"\\]+)*)/

key=value,key="value",key="val\"ue",ke\,y=val\,ue
```
```
Edit:
Added escaping alternatives.
Edit2:
Added another escaping alternative.
You would have to clean up the keys/values by removing any escape-characters and surrounding quotes.


Question:
I have a webpage that pulls information from a database, converts it to .csv format, and writes the file to the HTTPResponse.

string csv = GetCSV();
Response.Clear();
Response.ContentType = "text/csv";
Response.Write(csv);

This works fine, and the file is sent to the client with no problems.  However, when the file is sent to the client, the name of the current page is used, instead of a more friendly name (like "data.csv").

My question is, how can I change the name of the file that is written to the output stream without writing the file to disk and redirecting the client to the file's url?

EDIT:  Thanks for the responses guys.  I got 4 of the same response, so I just chose the first one as the answer.

Answer:
I believe this will work for you.
```
```
Response.AddHeader("content-disposition", "attachment; filename=NewFileName.csv");
```
```


Question: In a recent project the "lead" developer designed a database schema where "larger" tables would be split across two separate databases with a view on the main database which would union the two separate database-tables together.  The main database is what the application was driven off of so these tables looked and felt like ordinary tables (except some quirky things around updating).  This seemed like a HUGE performance problem.  We do see problems with performance around these tables but nothing to make him change his mind about his design.  Just wondering what is the best way to do this, or if it is even worth doing?

Answer:
Which version of SQL Server are you using? SQL Server 2005 has partitioned tables, but in 2000 (or 7.0) you needed to use partition views.
Also, what was the reasoning for putting the table partitions in a separate database?
When I've had to partition tables in the past (pre-2005), it's usually by a date column or something similar, with a view over the various partitions. Books Online has a section that talks about how to do this and all of the rules around it. You need to follow the  rules to make it work how it's supposed to work.
The key thing to remember is that your partitioning column must be part of the primary key and you want to try to always use that column in any access against the table so that the optimizer can ignore partitions that shouldn't be affected by the query.
Look up "partitioned table" in MSDN and you should be able to find a more complete tutorial for SQL Server 2005 partitioned tables as well as advice on how to set them up for maximum performance.


Question:
I find that quite often Visual Studio memory usage will average ~150-300 MB of RAM.

As a developer who very often needs to run with multiple instances of Visual Studio open, are there any performance tricks to optimize the amount of memory that VS uses?

I am running VS 2005 with one add-in (TFS)

Answer:
From
this blog post
:
[...]
These changes are all available from the Options dialog (Tools –> Options):
Environment
General
:
Disable “Animate environment tools”
Documents
:
Disable “Detect when file is changed outside the environment”
Keyboard
:
Remove the F1 key from the Help.F1Help command
Help\Online
:
Set “When loading Help content” to “Try local first, then online” or “Try local only, not online”
Startup
:
Change the “At startup” option to “Show empty environment”
Projects and Solutions
General
:
Disable “Track Active Item in Solution Explorer”
Text Editor
General
(for each language you want):
Disable “Navigation bar” (this is the toolbar that shows the objects and procedures drop down lists allowing you to choose a particular object in your code.
Disable “Track changes”
Windows Forms Designer
General
:
Set “AutotoolboxPopulate” to false.
Set “EnableRefactoringOnRename” to false.


Question: Is there a way to use .NET reflection to capture the values of all parameters/local variables?

Answer:
Reflection is not used to capture information from the stack.  It reads the Assembly.
You might want to take a look at StackTrace
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
Good article here:
http://www.codeproject.com/KB/trace/customtracelistener.aspx


Question:
I have run across an XML Schema with the following definition:

<xs:simpleType name="ClassRankType">
    <xs:restriction base="xs:integer">
        <xs:totalDigits value="4"/>
        <xs:minInclusive value="1"/>
        <xs:maxInclusive value="9999"/>
    </xs:restriction>
</xs:simpleType>

However, it seems to me that totalDigits is redundant.  I am somewhat new to XML Schema, and want to make sure I'm not missing something.

What is the actual behavior of totalDigits vs. maxInclusive?

Can totalDigits always be represented with a combination of minInclusive and MaxInclusive?

How does totalDigits affect negative numbers?

Answer:
can totalDigits always be represented with a combination of minInclusive and MaxInclusive?
In this case, yes. As you're dealing with an integer, the value must be a whole number, so you have a finite set of values between
```
minInclusive
```
and
```
maxInclusive
```
. If you had decimal values,
```
totalDigits
```
would tell you how many numbers in total that value could have.
How does totalDigits affect negative numbers?
It is the total number of digits allowed in the number, and is not affected by decimal points, minus signs, etc. From
auxy.com
:
The number specified by the value attribute of the
```
<xsd:totalDigits>
```
facet will restrict the total number of digits that are allowed in the number, on both sides of the decimal point.


Question: What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?

Answer:
I've done this in the past for a Python script to determine the last updated files in a directory:
```
```
import glob
import os

search_dir = "/mydir/"
# remove anything from the list that is not a file (directories, symlinks)
# thanks to J.F. Sebastion for pointing out that the requirement was a list
# of files (presumably not including directories)
files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
files.sort(key=lambda x: os.path.getmtime(x))
```
```
That should do what you're looking for based on file mtime.
EDIT
: Note that you can also use os.listdir() in place of glob.glob() if desired - the reason I used glob in my original code was that I was wanting to use glob to only search for files with a particular set of file extensions, which glob() was better suited to. To use listdir here's what it would look like:
```
```
import os

search_dir = "/mydir/"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))
```
```


Question:
For my current project, I need to request XML data over a tcp/ip socket connection.  For this, I am using the TcpClient class:

Dim client As New TcpClient()
client.Connect(server, port)

Dim stream As NetworkStream = client.GetStream()
stream.Write(request)
stream.Read(buffer, 0, buffer.length)

// Output buffer and return results...

Now this works fine and dandy for small responses.  However, when I start receiving larger blocks of data, it appears that the data gets pushed over the socket connection in bursts.  When this happens, the stream.Read call only reads the first burst, and thus I miss out on the rest of the response.

What's the best way to handle this issue?  Initially I tried to just loop until I had a valid XML document, but I found that in between stream.Read calls the underlying stream would sometimes get shut down and I would miss out on the last portion of the data.

Answer:
You create a loop for reading.
Stream.Read returns int for the bytes it read so far, or 0 if the end of stream is reached.
So, its like:
```
```
int bytes_read = 0;
while (bytes_read < buffer.Length)
   bytes_read += stream.Read(buffer, bytes_read, buffer.length - bytes_read);
```
```
EDIT: now, the question is how you determine the size of the buffer. If your server first sends the size, that's ok, you can use the above snippet. But if you have to read until the server closes the connection, then you have to use try/catch (which is good idea even if you know the size), and use bytes_read to determine what you received.
```
```
int bytes_read = 0;
try
{
   int i = 0;
   while ( 0 < (i = stream.Read(buffer, bytes_read, buffer.Length - bytes_read) )
      bytes_read += i;
}
catch  (Exception e)
{
//recover
}
finally
{
if (stream != null)
   stream.Close();
}
```
```


Question:
I have a personal wiki that I take notes on.  The wiki's pages are in a subversion working copy directory, "pages", and I set their permissions to 664, owned by www-data:www-data.  My username is in the "www-data" group, so I can checkin and mess with the pages manually.

For a while, I had an issue because every time I ran a checkin, the files would be owned by me:www-data instead of www-data:www-data, and I would no longer be able to change the wiki files through my web interface!  I solved the issue by flipping the setgid bit on the "pages" directory, but I'm still confused as to why this happened in the first place:

Every time I check something into subversion, it appears as if svn deletes it and recreates it.  Why?  Does this behavior support some functionality that I'm not aware of?  Is there a way to change it?

Thanks!

Answer:
I think you are using it wrong. What you could do is still have everything in subversion and have your local working copy separate from the www directory which you develop on.
Then just have the www working-copy auto-updated (or exported if you don't want the .svn directories in the www foldeR) for the www-user by some script (perhaps as a
post-commit
hook) which then setups permissions accordingly.
Work flow would be:
edit files in /home/youruser/yourwiki-working-copy/
do svn commit
post-commit hook updates the files in /var/www/ (or wherever the wiki is located)
goto 1.
This way, you don't have to worry about permissions and you can even have more than one person work on the web site with all the benefits of version control.


Question: How do you post data to an iframe?

Answer:
Depends what you mean by "post data". You can use the HTML
```
target=""
```
attribute on a
```
<form />
```
tag, so it could be as simple as:
```
```
<form action="do_stuff.aspx" method="post" target="my_iframe">
  <input type="submit" value="Do Stuff!">
</form>

<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
```
```
If that's not it, or you're after something more complex, please edit your question to include more detail.
There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a
work-around here
), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.
I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.
default.asp
```
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <form action="do_stuff.asp" method="post" target="my_frame">
    <input type="text" name="someText" value="Some Text">
    <input type="submit">
  </form>
  <iframe name="my_frame" src="do_stuff.asp">
  </iframe>
  </body>
</html>
```
```
do_stuff.asp
```
```
<%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <% if (Request.Form.Count) { %>
  You typed: <%=Request.Form("someText").Item%>
  <% } else { %>
  (not submitted)
  <% } %>
  </body>
</html>
```
```
I would be very interested to hear of any browser that doesn't run these examples correctly.


Question:
Since length is a JavaScript property, does it matter whether I use

for( var i = 0; i < myArray.length; i++ )

OR

var myArrayLength = myArray.length;
for( var i = 0; i < myArrayLength ; i++ )

Answer:
```
```
for(var i = 0, iLen = myArray.length; i < iLen; i++)
```
```
See
http://blogs.oracle.com/greimer/resource/loop-test.html
for benchmarks of various Javascript loop constructs.


Question:
I've only started playing with both ASP.Net MVC and the new-to-VS2008 Dynamic Data Website Templates.  I note that they both use routing in their URL handling, and I'm given to understand that because of routing, ASP.Net MVC won't work under IIS6.  However my DynamicData site works just fine on IIS6.

I've had to temporarily abandon my exploration of ASP.Net MVC for an upcoming project due to the IIS7 requirement, and I'm wondering what the essential difference between the two is under the hood, i.e. what makes DynamicData sites work on IIS6 and MVC not?

Answer:
ASP.NET MVC does indeed work under
IIS6
(and IIS5 for that matter) as long as you
enable wildcard mappings
to ASP.NET. I have deployed MVC applications to production using IIS6, so I can guarantree that it's possible.
The key difference is that all URLs in DynamicData end in a file with an ASPX extension so, regardless of physical existance, the ASP.NET runtime is invoked (because ASPX is associated with ASP.NET), whereas most ASP.NET MVC requests to not have an extension (or have an MVC extension, which is not mapped by default) and thus IIS configuration is required before it will work.
IIS7 works automatically because IIS7 itself is managed and thus there is no separation between IIS/ASP.NET.


Question:
I didn't realize until recently that Perl 5.10 had significant new features and I was wondering if anyone could give me some good resources for learning about those.  I searched for them on Google and all I found was some slides and a quick overview.  Some of the features (to me at least) would be nice if they had more explanation.

Any links would be appreciated.

-fREW

Answer:
The
perldelta
manpage has all the nitty-gritty details. There's a brief (but informative) slide presentation,
Perl 5.10 for people who aren't totally insane
. And a good
PerlMonks discussion
on the issue.


Question: How can I display a tooltip over a button using Windows Forms?

Answer:
Sure, just handle the mousehover event and tell it to display a tool tip.
t is a tooltip defined either in the globals or in the constructor using:
```
```
ToolTip t = new ToolTip();
```
```
then the event handler:
```
```
private void control_MouseHover(object sender, EventArgs e)
{
  t.Show("Text", (Control)sender);
}
```
```


Question:
tempfile.mkstemp() returns:

a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.

How do I convert that OS-level handle to a file object?

The documentation for os.open() states:

To wrap a file descriptor in a "file
  object", use fdopen().

So I tried:

>>> import tempfile
>>> tup = tempfile.mkstemp()
>>> import os
>>> f = os.fdopen(tup[0])
>>> f.write('foo\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 9] Bad file descriptor

Answer:
You can use
```
```
os.write(tup[0], "foo\n")
```
```
to write to the handle.
If you want to open the handle for writing you need to add the
"w"
mode
```
```
f = os.fdopen(tup[0], "w")
f.write("foo")
```
```


Question:
I can do this:

$ find .
.
./b
./b/foo
./c
./c/foo

And this:

$ find . -type f -exec cat {} \;
This is in b.
This is in c.

But not this:

$ find . -type f -exec cat > out.txt {} \;

Why not?

Answer:
find's -exec argument runs the command you specify once for each file it finds. Try:
```
```
$ find . -type f -exec cat {} \; > out.txt
```
```
or:
```
```
$ find . -type f | xargs cat > out.txt
```
```
xargs converts its standard input into command-line arguments for the command you specify. If you're worried about embedded spaces in filenames, try:
```
```
$ find . -type f -print0 | xargs -0 cat > out.txt
```
```


Question: I am creating some build scripts that interact with Perforce and I would like to mark for delete a few files. What exactly is the P4 syntax using the command line?

Answer:
```
```
p4 delete filename
```
```
(output of p4 help delete)
delete -- Open an existing file to delete it from the depot
p4 delete [ -c changelist# ] [ -n ] file ...
```
```
Opens a file that currently exists in the depot for deletion.
If the file is present on the client it is removed.  If a pending
changelist number is given with the -c flag the opened file is
associated with that changelist, otherwise it is associated with
the 'default' pending changelist.

Files that are deleted generally do not appear on the have list.

The -n flag displays what would be opened for delete without actually
changing any files or metadata.
```
```


Question: I want to start working with TDD but I don't know really where to start. We coding with .NET (C#/ASP.NET).

Answer:
See the questions
Why should I practice Test Driven Development and how should I start?
,
Moving existing code to Test Driven Development
,
What is unit testing?
and
What is TDD?


Question:
I have a table with one column and about ten rows.  The first column has rows with text as row headers, "header 1", "header 2".  The second column contains fields for the user to type data (textboxes and checkboxes).

I want to have a button at the top labelled "Add New...", and have it create a third column, with the same fields as the first column.  If the user clicks it again, it will create another blank column with fields (as in the second column).

Does anyone know of an effective way to manipulate the DOM to achieve this?

I'm experimenting with div's and TABLES but i'm on my third day of doing this, and it feels harder than it should be.

Answer:
Something along the lines of
```
```
function(table)
{
  for(var i=0;i<table.rows.length;i++)
  {
    newcell = table.rows[i].cells[0].cloneNode(true);
    table.rows[i].appendChild(newcell);
  }
}
```
```


Question: Given a table or a temp table, I'd like to run a procedure that will output a SQL script (i.e. a bunch of INSERT statements) that would populate the table.  Is this possible in MS SQL Server 2000?

Answer:
Something along the lines of
```
```
function(table)
{
  for(var i=0;i<table.rows.length;i++)
  {
    newcell = table.rows[i].cells[0].cloneNode(true);
    table.rows[i].appendChild(newcell);
  }
}
```
```


Question:
How would you go about introducing acceptance tests into a team using the .NET framework?  What tools are available for this purpose?

Thanks!

Answer:
You might want to take a look at FitNesse, which is meant to be a way for Acceptance tests to look like a wiki document (so that they can be read and written by QA or project managers)
http://fitnesse.org/
Here's a good intro
http://ablog.apress.com/?p=735


Question:
I have a table on SQL2000 with a numeric column and I need the select to return a 01, 02, 03...

It currently returns 1,2,3,...10,11...

Thanks.

Answer:
Does this work?
```
```
SELECT REPLACE(STR(mycolumn, 2), ' ', '0')
```
```
From
http://foxtricks.blogspot.com/2007/07/zero-padding-numeric-value-in-transact.html


Question:
Can anyone recommend for/against the time-travel functions in postgresql's contrib/spi module?  Is there an example available anywhere?

Tnx

Answer:
The argument for time-travel would be being able to look at tables that are updated often at an earlier insertion/deletion point. Say a table of stock prices for a firms investment portfolio.
The argument against would be the extra storage space it eats up.
Here is an
Example
of use.


Question: I have an third-party applet that requires JRE v1.5_12 to work correctly.  THe user is installing JRE v1.6.07 or better.  It used to be with 1.5 and below, that I could have multiple JRE's on the machine and specify which one to use - but with 1.6 that apepars to be broken.  How do I tell the browser I want to use v1.5_12 instead of the latest one installed?

Answer:
For security reasons, you can no longer force it to use older JRE's. Say release 12 has a huge security hole, and everyone installs release 13 to patch it. Evil java applets could just say "run with release 12 please" and then carry out their exploits, rendering the patches useless.
Most likely you have some code with security holes that the newer JRE is blocking, because it would cause a security risk. Fix your code, should be pretty minor changes, then you wont have to worry.
See
this page
for more info on the change.


Question:
A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in Python 2.6), for instance, are found in the collections module.

The Library Documentation page will give you all the modules in the language, but newcomers to Python are likely to find themselves saying "Oh, I didn't know I could have done it this way using Python!" unless the important features in the language are pointed out by the experienced developers.

I'm not specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.

Answer:
May be
PEP 0631
and
What's new in 2.6
can provide elements of answer. This last article explains the new features in Python 2.6, released on October 1 2008.


Question:
I wish to perform an experiment many different times.  After every trial, I am left with a "large" set of output statistics -- let's say, 1000.  I would like to store the outputs of my experiments in a table, but what's the best way...?

Option 1

Have a table with 1000 columns.  Seems like a bad idea.  What if the number of statistics one day exceeds the maximum number of columns?

Option 2

Have a table with three columns.  Let's say, ID, StatisticType, and StatisticValue.  That way, you can have as many statistics as you want.  However, reading a single experiments statistics becomes more complicated.  Moreover, what if different statistics are different data types??

Any suggestions?

Answer:
Option 2, with ID, TrialID, StatisticID, StatisticValue
With proper indexing, it will perform fairly well (you can use PIVOT to get the values out on columns fairly easily in SQL Server 2005).
When the statistics are different datatypes, the problem becomes more interesting, but in many cases, I just up-size the datatype (sometimes ints just end up in the money field).  For other non-compatible types, the best design in my mind is really separate tables for each type, but I've also seen multiple columns or a free-form text column.


Question:
I'm porting a Java library to C#. I'm using Visual Studio 2008, so I don't have the discontinued Microsoft Java Language Conversion Assistant program (JLCA).

My approach is to create a new solution with a similar project structure to the Java library, and to then copy the java code into a c# file and convert it to valid c# line-by-line. Considering that I find Java easy to read, the subtle differences in the two languages have surprised me.

Some things are easy to port (namespaces, inheritance etc.) but some things have been unexpectedly different, such as visibility of private members in nested classes, overriding virtual methods and the behaviour of built-in types. I don't fully understand these things and I'm sure there are lots of other differences I haven't seen yet.

I've got a long way to go on this project. What rules-of-thumb I can apply during this conversion to manage the language differences correctly?

Answer:
Your doing it in the only sane way you can...the biggest help will be this document from Dare Obasanjo that lists the differences between the two languages:
http://www.25hoursaday.com/CsharpVsJava.html
BTW, change all getter and setter methods into properties...No need to have the C# library function just the same as the java library unless you are going for perfect interface compatibility.


Question:
I am trying to visualize some values on a form. They range from 0 to 200 and I would like the ones around 0 be green and turn bright red as they go to 200.

Basically the function should return color based on the value inputted. Any ideas ?

Answer:
```
```
red = (float)val / 200 * 255;

green = (float)(200 - val) / 200 * 255;

blue = 0;

return red << 16 + green << 8 + blue;
```
```


Question:
Is it more performant to have a bidimensional array (type[,]) or an array of arrays (type[][]) in C#?

Particularly for initial allocation and item access

Answer:
I believe that [,] can allocate one contiguous chunk of memory, while [][] is N+1 chunk allocations where N is the size of the first dimension. So I would guess that [,] is faster on initial allocation.
Access is probably about the same, except that [][] would involve one extra dereference. Unless you're in an exceptionally tight loop it's probably a wash. Now, if you're doing something like image processing where you are referencing
between
rows rather than traversing row by row, locality of reference will play a big factor and [,] will probably edge out [][] depending on your cache size.
As Marc Gravell mentioned, usage is key to evaluating the performance...


Question:
Let's say I've got two strings in JavaScript:

var date1 = '2008-10-03T20:24Z'
var date2 = '2008-10-04T12:24Z'

How would I come to a result like so:

'4 weeks ago'

or

'in about 15 minutes'

(should support past and future).

There are solutions out there for the past diffs, but I've yet to find one with support for future time diffs as well.

These are the solutions I tried:

John Resig's Pretty Date and Zach Leatherman's modification

Bonus points for a jQuery solution.

Answer:
Looking at the solutions you linked... it is actually as simple as my frivolous comment!
Here's a version of the Zach Leatherman code that prepends "In " for future dates for you. As you can see, the changes are very minor.
```
```
function humane_date(date_str){
      var time_formats = [
          [60, 'Just Now'],
          [90, '1 Minute'], // 60*1.5
          [3600, 'Minutes', 60], // 60*60, 60
          [5400, '1 Hour'], // 60*60*1.5
          [86400, 'Hours', 3600], // 60*60*24, 60*60
          [129600, '1 Day'], // 60*60*24*1.5
          [604800, 'Days', 86400], // 60*60*24*7, 60*60*24
          [907200, '1 Week'], // 60*60*24*7*1.5
          [2628000, 'Weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
          [3942000, '1 Month'], // 60*60*24*(365/12)*1.5
          [31536000, 'Months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
          [47304000, '1 Year'], // 60*60*24*365*1.5
          [3153600000, 'Years', 31536000], // 60*60*24*365*100, 60*60*24*365
          [4730400000, '1 Century'], // 60*60*24*365*100*1.5
      ];

      var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
          dt = new Date,
          seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
          token = ' Ago',
          prepend = '',
          i = 0,
          format;

      if (seconds < 0) {
          seconds = Math.abs(seconds);
          token = '';
          prepend = 'In ';
      }

      while (format = time_formats[i++]) {
          if (seconds < format[0]) {
              if (format.length == 2) {
                  return (i>1?prepend:'') + format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
              } else {
                  return prepend + Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
              }
          }
      }

      // overflow for centuries
      if(seconds > 4730400000)
          return Math.round(seconds / 4730400000) + ' Centuries' + token;

      return date_str;
  };
```
```


Question:
Ok, I'm using the term "Progressive Enhancement" kind of loosely here but basically I have a Flash-based website that supports deep linking and loads content dynamically - what I'd like to do is provide alternate content (text) for those either not having Flash and for search engine bots. So, for a user with flash they would navigate to:

http://www.samplesite.com/#specific_page

and they would see a flash site that would navigate to the "specific_page."  Those without flash would see the "specific_page" rendered in text in the alternative content section.

Basically, I would use php/mysql to create a backend to handle all of this since the swf is also using dynamic data. The question is, does something out there that does this already exist?

Answer:
Looking at the solutions you linked... it is actually as simple as my frivolous comment!
Here's a version of the Zach Leatherman code that prepends "In " for future dates for you. As you can see, the changes are very minor.
```
```
function humane_date(date_str){
      var time_formats = [
          [60, 'Just Now'],
          [90, '1 Minute'], // 60*1.5
          [3600, 'Minutes', 60], // 60*60, 60
          [5400, '1 Hour'], // 60*60*1.5
          [86400, 'Hours', 3600], // 60*60*24, 60*60
          [129600, '1 Day'], // 60*60*24*1.5
          [604800, 'Days', 86400], // 60*60*24*7, 60*60*24
          [907200, '1 Week'], // 60*60*24*7*1.5
          [2628000, 'Weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
          [3942000, '1 Month'], // 60*60*24*(365/12)*1.5
          [31536000, 'Months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
          [47304000, '1 Year'], // 60*60*24*365*1.5
          [3153600000, 'Years', 31536000], // 60*60*24*365*100, 60*60*24*365
          [4730400000, '1 Century'], // 60*60*24*365*100*1.5
      ];

      var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
          dt = new Date,
          seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
          token = ' Ago',
          prepend = '',
          i = 0,
          format;

      if (seconds < 0) {
          seconds = Math.abs(seconds);
          token = '';
          prepend = 'In ';
      }

      while (format = time_formats[i++]) {
          if (seconds < format[0]) {
              if (format.length == 2) {
                  return (i>1?prepend:'') + format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
              } else {
                  return prepend + Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
              }
          }
      }

      // overflow for centuries
      if(seconds > 4730400000)
          return Math.round(seconds / 4730400000) + ' Centuries' + token;

      return date_str;
  };
```
```


Question:
I need a (php) regex to match Yahoo's username rules:

Use 4 to 32 characters and start with a letter. You may use letters, numbers, underscores, and one dot (.).

Answer:
A one dot limit?  That's tricky.
I'm no regex expert, but I think this would get it, except for that:
```
```
[A-Za-z][A-Za-z0-9_.]{3,31}
```
```
Maybe you could check for the . requirement separately?


Question:
I have the following code making a GET request on a URL:

$('#searchButton').click(function() {
    $('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val());
});

But the returned result is not always reflected. For example, I made a change in the response that spit out a stack trace but the stack trace did not appear when I clicked on the search button. I looked at the underlying PHP code that controls the ajax response and it had the correct code and visiting the page directly showed the correct result but the output returned by .load was old.

If I close the browser and reopen it it works once and then starts to return the stale information. Can I control this by jQuery or do I need to have my PHP script output headers to control caching?

Answer:
One way is to add a unique number to the end of the url:
```
```
$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&uid='+uniqueId());
```
```
Where you write uniqueId() to return something different each time it's called.


Question:
I'm trying to display a series of titles varying from 60 characters to 160 or so and the capitalization varies, some of it all caps, some half caps.  When it's mostly lowercase the whole 160 characters of text fits in the width I want, but when it starts getting more caps (they must be wider), it starts over flowing.

Is there a way to use an attractive fixed witdh font (upper and lowercase widths the same too), or dynamically shrink the text to fit, or otherwise recognize how much space the text is going to take on the server side, and cut off the end dynamically?  Or do you folks have a better solution?

Answer:
You could fix the width and hide the overflow,
```
style="width: Xpx; overflow: hidden;"
```
That will limit the width and cut off the end if it's too wide.


Question:
I'm trying to write a regex that will parse out the directory and filename of a fully qualified path using matching groups.

so...

/var/log/xyz/10032008.log

would recognize group 1 to be "/var/log/xyz" and group 2 to be "10032008.log"

Seems simple but I can't get the matching groups to work for the life of me.

NOTE:  As pointed out by some of the respondents this is probably not a good use of regular expressions.  Generally I'd prefer to use the file API of the language I was using.  What I'm actually trying to do is a little more complicated than this but would have been much more difficult to explain, so I chose a domain that everyone would be familiar with in order to most succinctly describe the root problem.

Answer:
What language? and why use regex for this simple task?
If you
must
:
```
```
^(.*)/([^/]*)$
```
```
gives you the two parts you wanted. You might need to quote the parentheses:
```
```
^\(.*\)/\([^/]*\)$
```
```
depending on your preferred language syntax.
But I suggest you just use your language's string search function that finds the last "/" character, and split the string on that index.


Question:
Every time I call this method my NSMutableData is leaking and I cannot figure out how to plug it. theData's retain count is upped by one after the decoder is allocated and initialized and I have no idea why. I am stuck with a retain count of 2 at the end of the method and attempting to release it causes an app crash.

- (void)readVenueArchiveFile:(NSString *)inFile key:(NSString *)inKey
{
    NSMutableData *theData;
    NSKeyedUnarchiver *decoder;

    theData = [NSData dataWithContentsOfFile:inFile];

    decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];

    venueIOList = [[decoder decodeObjectForKey:inKey] mutableCopy];

    [decoder finishDecoding];

    [decoder release];
}

Answer:
Don't worry about retain counts, worry about balance within a method.  What you're doing in this method looks correct, assuming
```
venueIOList
```
is an instance variable.
To expand on my answer a little bit:  The unarchiver might be retaining your data during the unarchive operation, and then sending the data
```
-autorelease
```
when it's done instead of
```
-release
```
.  Since that's not something
you
did, it's not something
you
have to care about.


Question: My development environment is running in JDK1.6, and I need to compile some classes so they are compatible with a client running JDK1.5.  How would I do this with the 'javac' ant target?

Answer:
Command line : javac -target 1.5 sourcefiles
Ant:
```
< javac srcdir="${src} destdir="${build}" target="1.5" />
```


Question:
I've got a Win32 C++ app with a suite of unit tests.  After the unit tests have finished running, I'd like a human-readable report on any unfreed memory to be automatically generated.  Ideally, the report will have a stack with files & line number info for each unfreed allocation.  It would be nice to have them generated in a consistent order to make it easy to diff it from one run to the next.  (Basically, I would like the results of valgrind --leak-check=full, but on windows).

I've had success with UMDH getting this kind of info from running processes, but that tool only seems to work if you attach to an existing process.  I want this to happen automatically every time I run my unit tests.

Is there a tool that can do this?  If so, how do I use it?

Thanks!

Answer:
If you're using MSVC, Microsoft's Debug heap functions can be used to generate the report you want, but it may not be as automatic as you'd like (you may need to write some custom code):
```
```
_CrtSetReportMode
_CrtSetReportFile
_CrtMemState
_CrtMemCheckpoint
_CrtMemDumpStatistics
_CrtSetReportFile
_CrtSetDbgFlag
```
```


Question: How do I write a decorator that restores the current working directory to what it was before the decorated function was called?  In other words, if I use the decorator on a function that does an os.chdir(), the cwd will not be changed after the function is called.

Answer:
```
```
def preserve_cwd(function):
   def decorator(*args, **kwargs):
      cwd = os.getcwd()
      result = function(*args, **kwargs)
      os.chdir(cwd)
      return result
   return decorator
```
```
Here's how it's used:
```
```
@preserve_cwd
def test():
  print 'was:',os.getcwd()
  os.chdir('/')
  print 'now:',os.getcwd()

>>> print os.getcwd()
/Users/dspitzer
>>> test()
was: /Users/dspitzer
now: /
>>> print os.getcwd()
/Users/dspitzer
```
```


Question:
I'd like to be able to toggle easily between two values for "maximum number of parallel project builds" in Visual Studio 2008 (in Tools->Options->Projects and Solutions->Build and Run). (When I'm planning on doing concurrent work I'd like to reduce it from 4 to 3.) I'm not too well versed in writing macros for the IDE. When I try recording a macro, and perform all the actions (open the dialog, change the setting, click OK), the only thing that gets recorded is this:

DTE.ExecuteCommand ("Tools.Options")

Is my goal unattainable?

Answer:
It appears to be impossible, according to the MSDN page for
Determining Names of Property Items in Tools Options Pages
If it
was
possible, it would have been something like this:
```
```
Dim p = DTE.Properties("ProjectsAndSolutions","BuildAndRun")
p.Item("MaxNumParallelBuilds")
```
```


Question:
I have a type (System.Type) of an enum and a string containing enumeration value to set.

E.g. given:

enum MyEnum { A, B, C };

I have typeof(MyEnum) and "B".

How do I create MyEnum object set to MyEnum.B?

Answer:
```
```
MyEnum enumValue = (MyEnum)Enum.Parse(typeof(MyEnum), "B");
```
```
You also have a case-insensitive overload.


Question: When I try to bind port 80 to a socket in c, i always get the error, that I don't have permission to use this port. is there an easy way to get this permission?

Answer:
Usually only the superuser (root) can bind to 'privileged' ports (i.e. those port numbers below 1024).
This means that you either have to run your program as root or make your executable 'suid root'.
Both of these have security consequences so you may want to consider using the suid approach and relinquishing superuser privileges once the bind call has been made.


Question:
I am having a very hard time finding a standard pattern / best practice that deals with rendering child controls inside a composite based on a property value.

Here is a basic scenario. I have a Composite Control that has two child controls, a textbox and a dropdown. Lets say there is a property that toggles which child to render.

so:

myComposite.ShowDropdown = true;

If true, it shows a dropdown, otherwise it shows the textbox.

The property value should be saved across postbacks, and the the correct control should be displayed based on the postback value.

Any good examples out there?

Answer:
I would think something like:
```
```
public bool ShowDropDown
{
    get{ return (bool)ViewState["ShowDropDown"]; }
    set{ ViewState["ShowDropDown"]; }
}

private  void Page_Load(object sender, EventArgs e)
{
    DropDaownControl.Visible = ShowDropDown;
    TextBoxControl.Visible = !ShowDropDown;
}
/* some more code */
```
```


Question:
There is a way to keep the scroll on bottom for a multi line textbox?

Something like in the vb6

txtfoo.selstart=len(txtfoo.text)

I'm trying with txtfoo.selectionstart=txtfoo.text.length without success.

Regards.

Answer:
Ok, I found that the solution was to use
```
```
txtfoo.AppendText
```
```
instead of
```
```
txtfoo.text+="something"
```
```


Question:
I have an RFID reader connected to an Arduino board. I'd like to connect to it over its serial interface, and whenever the RFID reader omits a signal ( when it has read an (RF)ID ), I'd like to retrieve it in my C++ program.

I already have the code for simply printing the RFID to serial from the Arduino.

What I don't know, is how to read it from C++ in Linux ?

I have looked at libserial, which looks straightforward. However, how can I have the C++ program react to a signal and then read the RFID, instead of listening continously? Is this necessary?

EDIT: In most examples I have read, the (c++) program sends input, and recieves output. I just want to listen and recieve output from the Arduino.

Answer:
The
Communications
part of the Interface section in the Arduino Playground has several examples of interfacing, including one with the Arduino as Linux TTY.
Try the
Syntax and Programs
forum and the
Software Development
forum on the Arduino site. There have been discussions about interfacing to many different languages and computers in the past.
And finally check out the
Processing
and
Wiring
sites. The Arduino IDE is based on the Processing language, and the Wiring environment and dev board is related to Arduino. Both sites have lots more examples and links to even more resources.
Edit:
I just realized that I didn't answer your actual question. These are all general communications resources, but some may have hints towards how to alert the computer of a new RFID input.


Question:
In ActionScript 3.0, is there an automatic way to calculate the number of days, hours, minutes and seconds between two specified dates?

Basicly, what I need is the ActionScript equivalent of the .NET Timespan class.

Any idea?

Answer:
You can covert the two date times into milliseconds since the epoch, perform your math and then use the resultant milliseconds to calculate these higher timespan numbers.
```
```
var someDate:Date = new Date(...);
var anotherDate:Date = new Date(...);
var millisecondDifference:int = anotherDate.valueOf() - someDate.valueOf();
var seconds:int = millisecondDifference / 1000;
....
```
```
The
LiveDocs
are useful for this type of thing too. Sorry if the ActionScript is a bit off, but it has been a while.
I'd also recommend creating a set of static class methods that can perform these operations if you're doing a lot of this type of math. Sadly, this basic functionality doesn't really exist in the standard APIs.


Question: As kind of a follow up to this question about prefixes, I agree with most people on the thread that prefixes are bad. But what about if you are using getters and setters? Then you need to differeniate the publicly accessible getter name from the privately stored variable. I normally just use an underscore, but is there a better way?

Answer:
In a case sensitive language I just use:
```
```
private int myValue;

public int MyValue
{
    get { return myValue; }
}
```
```
Otherwise I would use an underscore
```
```
Private _myValue As Integer

Public ReadOnly Property MyValue As Integer
    Get
        Return _myValue
    End Get
End Property
```
```


Question:
In SQL Server you can use the IsNull() function to check if a value is null, and if it is, return another value. Now I am wondering if there is anything similar in C#.

For example, I want to do something like:

myNewValue = IsNull(myValue, new MyValue());

instead of:

if (myValue == null)
  myValue = new MyValue();
myNewValue = myValue;

Thanks.

Answer:
It's called the null coalescing (
```
??
```
) operator:
```
```
myNewValue = myValue ?? new MyValue();
```
```


Question:
I'm used to writing classes like this:

public class foo {
  private string mBar = "bar";
  public string Bar {
    get { return mBar; }
    set { mBar = value; }
  }
  //... other methods, no constructor ...
}

Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?

public class foo2theRevengeOfFoo {
  //private string mBar = "bar";
  public string Bar { get; set; }
  //... other methods, no constructor ...
  //behavior has changed.
}

You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.

Something like this would make more sense to me:

public string Bar { get; set; } = "bar";

Answer:
In the default constructor (and any non-default ones if you have any too of course):
```
```
public foo() {
    Bar = "bar";
}
```
```
This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.


Question:
http://thedailywtf.com/Articles/The-Hot-Room.aspx

You see how at the bottom there're links to the next and previous articles ("Unprepared For Divide_By_Zero" and "A Completely Different Game")? How do I do that, but selecting the next and previous non-private articles? This works for selecting the next article:

SELECT * FROM articles WHERE id > ? AND private IS NULL

But I cannot find a way to select the previous article.

What is the proper/efficient way to do this, preferably in one query?

Answer:
Here's how I would do it:
```
```
-- next
SELECT * FROM articles WHERE id > ? AND private IS NULL ORDER BY id ASC LIMIT 1

-- previous
SELECT * FROM articles WHERE id < ? AND private IS NULL ORDER BY id DESC LIMIT 1
```
```
I'm not sure how to do it in one query. The only thing I can think of is possibly getting both the article you're displaying and the next article in one query, but that might be too confusing.


Question:
I have two databases with the same structure. The tables have an integer as a primary key as used in Rails.

If I have a patients table, I will have one patient using primary key 123 in one database and another patient using the same primary key in the other database.

What would you suggest for merging the data from both databases?

Answer:
Set both your databases up with entries in config/database.yml, then generate a new migration.
Use ActiveRecord::Base.establish_connection to switch between the two databases in the migration like this:
```
```
def self.up
  ActiveRecord::Base.establish_connection :development
  patients = Patient.find(:all)
  ActiveRecord::Base.establish_connection :production
  patients.each { |patient| Patient.create patient.attributes.except("id") }
end
```
```
YMMV depending on the number of records and the associations between models.


Question:
I have seen Jetbrain's ReSharper tool on many "must-have" tool lists. I've installed it on a few occasions over the last few years and it's turned my Visual Studio sluggish and erratic. I generally uninstall it after a week or two because it make VS flaky, I want to like it, but I can't get past the instability.

So what's the deal? Am I having bad luck? Does the tool have issues but the usefulness out weighs the issues? Anyone else out there have trouble with it? Are there some troublesome options to turn off?

Answer:
I've experienced a lot of what you're talking about over the years as well, but I have to say having recently moved to the 4.0 version of ReSharper, a lot of that overhead has been cut down dramatically and it seems to be quite a bit more functional to boot.
Try it again. What's the worst that can happen? You'll uninstall it again? No big loss.


Question:
After maintaining lots of code littered with #region (in both C# and VB.NET), it seems to me that this construct is just a bunch of "make work" for the programmer. It's work to PUT the dang things into the code, and then they make searching and reading code very annoying.

What are the benefits? Why do coders go to the extra trouble to put this in their code.

Make me a believer!

Answer:
Often times, both partials and #regions are used as a crutch for bad design (e.g. class is too big or tries to do too many things).
The
best
use I've had for #regions so far is the grouping of functionality that is seen in many different classes. For example, value objects that have getters, setters, constructors and supporting fields. I might very well group those ideas into regions. Its a matter of opinion, however, as to whether that makes code cleaner or harder to read.


Question:
Is there a Generics Friendly way of using Collection.EMPTY_LIST in my Java Program.

I know I could just declare one myself, but I'm just curious to know if there's a way in the JDK to do this.

Something like users = Collections<User>.EMPTY_LIST;

Answer:
By doing the following:
```
```
List<User> users = Collections.emptyList();
```
```
The type of the returned list from
```
Collections.emptyList();
```
will be
inferred
as a
```
String
```
due to the left-hand-side of the assignment.  However, if you prefer to not have this inference, you can define it explicitly by doing the following:
```
```
List<User> users = Collections.<User>emptyList();
```
```
In this particular instance, this may appear as redundant to most people (in fact, I've seen very little code out in the wild that makes use of explicit type arguments), however for a method with the signature:
```
void doStuff(List<String> users)
```
it would be perfectly clean for one to invoke
```
doStuff()
```
with an explicit type argument as follows:
```
```
doStuff(Collections.<String>emptyList());
```
```


Question:
How do I get modrewrite to ENTIRELY ignore the /vip/ directory so that all requests pass directly to the folder?

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^vip/.$ - [PT]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

See also How do I ignore a directory in mod_rewrite?  -- reposting because I wasn't sufficiently clear about the problem first time around.

Answer:
Replace:
```
```
RewriteRule ^vip/.$ - [PT]
```
```
with:
```
```
RewriteRule ^vip/.*$ - [PT,L]
```
```


Question:
Does anyone have a good resource on dlls and how they are used / generated in Visual Studio?  A few questions I'm rather hazy on specifically are:

How refresh files work

How dll version numbers are generated

The difference between adding a reference by project vs browsing for the specific dll

Any other tips are welcome as well.

Answer:
See the question on
DLL information
for some background.
Version numbers for unmanaged DLLs are stored in the DLL's rc file, same as for an exe.  For managed DLLs I believe it uses AssemblyFileInfo attribute, usually in AssemblyInfo.cs for a Visual Studio generated project:
```
```
[assembly: AssemblyFileVersion("1.0.0.0")]
```
```
If you add the reference by project then VS will be able to copy the correct flavour (debug/release) of the referenced assembly to your output directory. It can also use this information to implicitly add a dependency between the projects so it builds then in the right order.


Question:
Is there a way to get stored procedures from a SQL Server 2005 Express database using C#? I would like to export all of this data in the same manner that you can script it our using SQL Server Management Studio, without having to install the GUI.

I've seen some references to do thing via the PowerShell but in the end a C# console app is what I really want.

To clarify....

I'd like to script out the stored procedures. The list via the Select * from sys.procedures is helpful, but in the end I need to script out each of these.

Answer:
This blog post
suggests running this against your database:
```
```
select * from sys.procedures
```
```


Question:
I want to use a timer in my simple .NET application written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console application.

Is there a C# timer (or timer like) class for use in console applications?

Answer:
System.Timers.Timer
And as MagicKat says:
System.Threading.Timer
You can see the differences here:
http://intellitect.com/system-windows-forms-timer-vs-system-threading-timer-vs-system-timers-timer/
And you can see MSDN examples here:
http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx
And here:
http://msdn.microsoft.com/en-us/library/system.threading.timer(VS.80).aspx


Question:
I'm writing an implementation of the XXTEA encryption algorithm that works on "streams", ie, can be used like: crypt mykey < myfile > output.

One of the requisites is that it doesn't have access to the file at all (it only reads an fixed size block until find an EOF). The algorithm needs that the data bytes is multiple of 4, so its needed to add a padding.

For plain text a good solution is to pad with NULLs, and in the decryption just ignore the NULLs, but the same strategy cannot be used for binary streams (that can contain embedded NULLs).

I've read the common solutions, like padding with the number of missing chars (if it miss 3 chars, then append an 3, 3, 3 at the end) and etc, but I wonder: theres a more elegant solution?

Answer:
Read:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.paddingmode.aspx
It has a list of common padding methods, like:
PKCS7 - The PKCS #7 padding string consists of a sequence of bytes, each of which is equal to the total number of padding bytes added.
The ANSIX923 padding string consists of a sequence of bytes filled with zeros before the length.
The ISO10126 padding string consists of random data before the length.
Examples:
Raw data: 01 01 01 01 01
PKCS #7: 01 01 01 01 01 03 03 03
ANSIX923 01 01 01 01 01 00 00 03
ISO10126: 01 01 01 01 01 CD A9 03


Question: I would like to compress a folder and all its sub-folders/files, and email the zip file as an attachment. What would be the best way to achieve this with Python?

Answer:
Look at
zipfile
for compressing a folder and it's subfolders.
Look at
smtplib
for an email client.


Question:
In a related question I asked about creating a generic container. Using polymorphic templates seems like the right way to go.

However, I can't for the life of me figure out how a destructor should be written. I want the owner of the memory allocated to be the containers even if the example constructor takes in an array of T (along with its dimensions), allocated at some other point.

I would like to be able to do something like

MyContainer<float> blah();
...
delete blah;

and

MyContainer<ComplexObjectType*> complexBlah();
...
delete complexBlah;`

Can I do something like this? Can I do it without smart pointers?

Again, thanks for your input.

Answer:
It can be done, but this is pretty advanced stuff.
You'll need to use something like the boost MPL library (
http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/index.html
) so that you can get MyContainer's destructor to select the right kind of destructing it will need to do on individual items on the container. And you can use the boost TypeTraits library to decide what kind of deleting is required (
http://www.boost.org/doc/libs/1_36_0/libs/type_traits/doc/html/index.html
). I'm sure it will have a trait that will let you decide if your contained type is a pointer or not, and thus decide how it needs to be destructed. You may need to implement traits yourself for any other types you want to use in MyContainer that have any other specific deletion requirements. Good luck with it! If you solve it, show us how you did it.


Question: I like having my warning level set at W4 but all new projects start at W3.  Is there some way to change the default value for warning levels for new projects?

Answer:
I don't know how to do it at the IDE but you cand always edit the new project templates at:
```
```
%PROGRAM_FILES%\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\
```
```
If you're using the express version there could be a minor variation in the path:
```
```
%PROGRAM_FILES%\Microsoft Visual Studio 9.0\Common7\IDE\{Version}\ProjectTemplates\
```
```
Where {Version} is the express flavor you are using, VCSExpress, VBExpress, etc.
The templates are zip files, just edit the project changing:
```
```
<WarningLevel>3</WarningLevel>
```
```
to
```
```
<WarningLevel>4</WarningLevel>
```
```


Question:
this code always returns 0 in PHP 5.2.5 for microseconds:

<?php
$dt = new DateTime();
echo $dt->format("Y-m-d\TH:i:s.u") . "\n";
?>

Output:

[root@www1 ~]$ php date_test.php
2008-10-03T20:31:26.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:27.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:27.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:28.000000

Any ideas?

Answer:
This seems to work, although it seems illogical that
http://us.php.net/date
documents the microsecond specifier yet doesn't really support it:
```
```
function getTimestamp()
{
        return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8);
}
```
```


Question:
I have a form with many input fields.

When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?

Answer:
Associative? Not without some work, but you can use generic selectors:
```
```
var items = new Array();

$('#form_id:input').each(function (el) {
    items[el.name] = el;
});
```
```


Question:
How do I iterate over a range of numbers in Bash when the range is given by a variable?

I know I can do this (called "sequence expression" in the Bash documentation):

 for i in {1..5}; do echo $i; done

Which gives:

1

  2

  3

  4

  5

Yet, how can I replace either of the range endpoints with a variable? This doesn't work:

END=5
for i in {1..$END}; do echo $i; done

Which prints:

{1..5}

Answer:
You can use
```
```
for i in $(seq $END); do echo $i; done
```
```


Question:
Greetings,

I need to include a property in my class which is a collection of System.IO.FileInfo objects.  I am not really sure how to do this and how I would add and removed objects from an instance of the the class (I would assume like any other collection).

Please let me know if I need to add more information.

Thank you

Update: Am I approaching this the wrong way? I have read comments that adding to a collection which is a property is bad practice.  If this is true what is good practice?  I have a bunch of objects I need to store in a collection.  The collection will be added to and removed from before a final action will be taken on it.  Is this a correct approach or am I missing something?

Answer:
```
File
```
is a static class. So let's assume you meant
```
FileInfo
```
.
There are lots of ways, you can:
Expose a private field
Use Iterators
Expose a private field through a ReadOnlyCollection<>
For example,
```
```
class Foo {
    public IEnumerable<FileInfo> LotsOfFile {
        get {
            for (int i=0; i < 100; i++) {
                yield return new FileInfo("C:\\" + i + ".txt");
            }
        }
    }
    private List<FileInfo> files = new List<FileInfo>();
    public List<FileInfo> MoreFiles {
        get {
            return files;
        }
    }
    public ReadOnlyCollection<FileInfo> MoreFilesReadOnly {
        get {
            return files.AsReadOnly();
        }
    }

}
```
```
With this code, you can easily add to the property
```
MoreFiles
```
:
```
```
Foo f = new Foo();
f.MoreFiles.Add(new FileInfo("foo.txt"));
f.MoreFiles.Add(new FileInfo("BAR.txt"));
f.MoreFiles.Add(new FileInfo("baz.txt"));
Console.WriteLine(f.MoreFiles.Count);
```
```


Question:
I was looking into sorting tables by a column designated given some input, and from what I've found, there is no easy way to do this. The best I've found is a switch statement:

SELECT Column1, Column2, Column3, Column4
FROM Table
ORDER BY CASE WHEN @OrderBY = 'Column1' THEN Column1
              WHEN @OrderBY = 'Column2' THEN Column2
              WHEN @OrderBY = 'Column3' THEN Column3
              WHEN @OrderBY = 'Column4' THEN Column4

Is it possible to do this without having a CASE statement like that? If the table gets bigger and more columns need to be sorted by, this could become messy.

The only way I've been able to do this is by just concatenating a big SQL string, which sort of defeats the advantages of Stored Procedures, and makes the SQL hard to write and maintain.

Answer:
I generally convert the stored procedure to a function that returns a table ( so you can select FROM it ... and add the dynamic order by columns to it in the application code:
```
```
Select
    *
From
   myTableFUnction()
Order by
   1, 2, 3, 6  <-- defined by application code in the SQL for the query
```
```
Ron


Question: I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.

Answer:
```
(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?
```
That's a (slightly modified) version of the official URI parsing regexp from
RFC 2396
. It allows for
```
#fragments
```
and
```
?querystrings
```
to appear after the filename, which may or may not be what you want. It also matches any valid domain, including
```
localhost
```
, which again might not be what you want, but it could be modified.
A more traditional regexp for this might look like the below.
```
^https?://(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$
          |-------- domain -----------|--- path ---|-- extension ---|
```
EDIT
See my
other comment
, which although isn't answering the question as completely as this one, I feel it's probably a more useful in this case. However, I'm leaving this here for
karma-whoring
completeness reasons.


Question:
When I retrieve a record using LINQ that has a DateTime field only the ToString() is available.

Where are all the other DateTime methods?

I have to Convert.ToDateTime the DateTime? that the Field returns?

What is the difference between (DateTime) and (DateTime?)

Answer:
The namespace collision aside, I know that SQL's datetime has a different epoch (and therefore a different range of valid dates) than C# datetime.
Try to send a
```
new DateTime()
```
to a stored procedure and see what I mean.


Question:
Is it possible, in Java, to enforce that a class have a specific set of subclasses and no others? For example:

public abstract class A {}
public final class B extends A {}
public final class C extends A {}
public final class D extends A {}

Can I somehow enforce that no other subclasses of A can ever be created?

Answer:
Give class
```
A
```
a constructor with package-level accessibility (and no other constructors).
Thanks, Dave L., for the bit about no other constructors.


Question:
What is the best way to persist/save printer settings in .Net?
There used to be a bug in .Net 1.1 in the serialization of the PrinterSetting object and there were some workarounds but I'm wondering if there isn't a better or easier way of doing this in the more recent versions of the framework.

The main use case is to allow a user to define, using the standard printer setting user interfaces, all print details (including printer-specific options) for a given printer and have these saved so they get restored the next time the user prints to that printer.

Answer:
You should use the class
```
PrinterSettings
```
.


Question:
I keep hearing that Flex is open source and I figured that a great way to learn about the inner workings would be to look at it. I can easily find the Flex SDK (http://opensource.adobe.com/wiki/display/flexsdk/Get+Source+Code), but I'm wanting to look at the class definitions for the MXML core library (like NumericStepper). Have I misunderstood, or is this kind of thing available somewhere?

Note, I'm looking for the source of some core MXML components so I can see how they work internally, not for the compiler's source. Does what I've linked above have what I'm looking for and I just can't find it in the director structure?

Answer:
The open source stuff appears to be at:
```
```
http://opensource.adobe.com/wiki/display/flexsdk/Downloads
```
```
I don't know if everything is available there yet, there may be issues with third-party stuff.


Question: I'm looking for a word processing component for .NET that would act like an embedded MS Word in my WinForm/WPF .NET app.  The main goal being for users to be able to create rich formatted text.  I don't really want to have to write a highly custom RichTextBox component.  Any suggestions?

Answer:
Obviously I have no idea what your particular project requirements are, but
ScintillaNET
is a fabulous control and is flexible enough to do a lot more than just syntax highlighting.  I can foresee cases where it certainly wouldn't be appropriate, but it is at least worth investigating.  After a fair amount of searching it has perfectly filled a void in an application of mine where I need to do extensive contextual highlighting of prose.
Edit
I'm revoking this comment because I've thought about it a minute longer and the finite number of styles that Scintilla provides would make it inappropriate for rich text editing.  However, it is still an excellent solution for any situation where you can determine programmatically how styling will be applied.


Question:
In Javascript, I have an object:

obj = { one: "foo", two: "bar" };

Now, I want do do this

var a = 'two';
if(confirm('Do you want One'))
{
  a = 'one';
}

alert(obj.a);

But of course it doesn't work.  What would be the correct way of referencing this object dynamically?

Answer:
Like this:
```
```
obj[a]
```
```


Question: What's the best .NET communication component or protocol for very low bandwidth and intermittently connected communication (i.e.: < 10 kilobits/sec)?

Answer:
Probably
```
System.Net.Sockets.
```
```
Socket
```
. There is also a
```
TcpClient
```
and
```
UdpClient
```
in that namespace.


Question:
I am totally new to SQL. I have a simple select query similar to this:

SELECT COUNT(col1) FROM table1

There are some 120 records in the table and shown on the GUI.
For some reason, this query always returns a number which is less than the actual count.

Can somebody please help me?

Answer:
Try
```
```
select count(*) from table1
```
```
Edit:
To explain further,
```
count(*)
```
gives you the rowcount for a table, including duplicates and nulls.
```
count(isnull(col1,0))
```
will do the same thing, but
slightly
slower, since
```
isnull
```
must be evaluated for each row.


Question:
I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this.

When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically.

I've been trying to use JPanels like usercontrols in C#. I created a JPanel form called BlurbEditor. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event.

Here is the code that I thought would work:

mainPanel.add(new BlurbEditor());
mainPanel.revalidate();
//I've also tried all possible combinations of these too
//mainPanel.repaint();
//mainPanel.validate();

This unfortunately is not working. What am I doing wrong?

Answer:
Try
```
mainPanel.invalidate()
```
and then if necessary,
```
mainPanel.validate()
```
.  It also might be worth checking that you're doing this all in the event dispatch thread, otherwise your results will be spotty and (generally) non-deterministic.


Question:
I'm writing a simulator in Python, and am curious about options and opinions regarding basic 2D animations. By animation, I'm referring to rendering on the fly, not displaying prerendered images.

I'm currently using matplotlib (Wxagg backend), and it's possible that I'll be able to continue using it, but I suspect it won't be able to sufficiently scale in terms of performance or capabilities.

Requirements are:

Cross-platform (Linux, MacOS X,
Windows)

Low complexity overhead

Plays well with wxpython (at least won't step on each other's toes unduly)

Interactivity. Detect when objects are clicked on, moused over, etc.

Note that high performance isn't on the list, but the ability to handle ~100 bitmap objects on the screen would be good.

Your thoughts?

Answer:
I am a fan of
pyglet
which is a completely self contained library for doing graphical work under win32, linux, and OS X.
It has very low overhead, and you can see this for yourself from the tutorial on the website. It
should
play well with wxpython, or at least I seem to recall posts to the mailing list about wxpython and pyglet being used together.
It however does not offer selection of objects via mouse clicks - this you will have to handle yourself. Generally speaking for a 2D application this is not too difficult to do.
mactorii
is an OS X application of mine written in pure python+pyglet, and has some basic animation (scrolling) and click detection. It doesn't use wxpython, but perhaps it will give you an idea of what is involved. Note however mactorii is using the old pyglet api, so the run loop I have in there is obsolete. I will get around to updating it one day... :P


Question:
In the same spirit of other platforms, it seemed logical to follow up with this question: What are common non-obvious mistakes in Java? Things that seem like they ought to work, but don't.

I won't give guidelines as to how to structure answers, or what's "too easy" to be considered a gotcha, since that's what the voting is for.

See also:

Perl - Common gotchas

.NET - Common gotchas

Answer:
Going first, here's one I caught today. It had to do with
```
Long
```
/
```
long
```
confusion.
```
```
public void foo(Object obj) {
    if (grass.isGreen()) {
        Long id = grass.getId();
        foo(id);
    }
}
private void foo(long id) {
    Lawn lawn = bar.getLawn(id);
    if (lawn == null) {
        throw new IllegalStateException("grass should be associated with a lawn");
    }
}
```
```
Obviously, the names have been changed to protect the innocent :)


Question:
I'm thinking the answer is no, but I'd love it it anybody had any insight into how to crawl a tree structure to any depth in SQL (MySQL), but with a single query

More specifically, given a tree structured table (id, data, data, parent_id), and one row in the table, is it possible to get all descendants (child/grandchild/etc), or for that matter all ancestors (parent/grandparent/etc) without knowing how far down or up it will go, using a single query?

Or is using some kind of recursion require, where I keep querying deeper until there are no new results?

Specifically, I'm using Ruby and Rails, but I'm guessing that's not very relevant.

Answer:
You're almost definitely going to want to employ some recursion for that. And if you're doing that, then it would be trivial (in fact easier) to get the entire tree rather than bits of it to a fixed depth.
In really rough pseudo-code you'll want something along these lines:
```
```
getChildren(parent){
    children = query(SELECT * FROM table WHERE parent_id = parent.id)
    return children
}

printTree(root){
    print root
    children = getChildren(root)
    for child in children {
        printTree(child)
    }
}
```
```
Although in practice you'd rarely want to do something like this. It will be rather inefficient since it's making one request for every row in the table, so it'll only be sensible for either small tables, or trees that aren't nested too deeply. To be honest, in either case you probably want to limit the depth.
However, given the popularity of these kinds of data structure, there may very well be some MySQL stuff to help you with this, specifically to cut down on the numbers of queries you need to make.
Edit: Having thought about it, it makes very little sense to make all these queries. If you're reading the entire table anyway, then you can just slurp the whole thing into RAM - assuming it's small enough!


Question: I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window.  I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work.  Any ideas?

Answer:
```
```
myWindow.document.writeln(documentString)
```
```


Question: I'm not looking for a full implementation, I'm more interested in how they do it.  I know they use GWT, but I'd like a more low level answer.  Naively, I would start by thinking when you click the popout link they simply open a new window and copy content into it.  There are lots of reasons why that won't work out well, so I'm wondering if anyone knows or has ideas on how they do this or how it could be done.

Answer:
I recently needed to solve exactly this problem in an app. I ended up using this great little jQuery plugin to do the trick: WindowMsg (see link at bottom) While I'm sure there are other ways to accomplish the same task, that plugin does works thusly:
first you create a new child window from your original window using window.open
you save a reference to the window object returned by window.open
you call a library method in the child window that adds a hidden form for the library to store data in
you call a library method in the parent window that uses window.document.forms to populate form fields on the child window (the library abstracts all of this stuff so you wouldn't even know there was a form involved unless you looked at the source) window.document.forms works the same on all major browsers so this abstraction in x-browser compatible
finally, the child window refers back to its parent window using window.opener and can communicate back via a parallel hidden form on the parent
the library implements a convenient helper that takes a callback function to run on each side to make the callback chain easy to deal with
In my experience working with the library, it would have also been quite nice if they had included the JSON 2 lib from JSON.org. Out of the box, WindowMsg only allows you to send string messages between windows, but with some pretty simple use of the JSON 2 lib, I was able to hack it to allow the sending of full JSON objects between windows. I bet more mature libraries (such as whatever google uses) include that kind of serialization and de-serialization baked in.
I am putting this link here because for some reason, the Stack Overflow formatter turns it into an anchor link with no closing tag and I don't want my whole post to be one giant hyperlink!
WindowMsg:
http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/


Question:
There's another post on SO relating to .NET -- not us.  Pure PHP.  Trying to find the best way/process to deploy stable version of our PHP app.  I've seen an article on Capistrano, but am curious what else is out there.  Aside from the obvious reasons, I'm also looking to add some scripting so that the SVN rev number gets added in there as well.

Much thanks.

Answer:
I've used a home-grown script for quite some time. It will (based on an application configuration file):
Run
```
svn export
```
on the repository based on a tag.
Package the export into a tar or zip file, which includes the tag in the name.
Use
```
scp
```
to copy the package to the appropriate server (QA or release).
Connect to the server with
```
ssh
```
to install the package and run post-install scripts.
The application configuration file is part of the project. It can tell the script (at step 2) to strip paths and otherwise process specified files. It also specifies server names and how to handle externals.
I've recently migrated the script to support Git as well as Subversion. I'm also probably going to migrate it to PHP since we're now running in a mixed (Linux and Windows) set up, with Linux now in the minority.
I have plans to automatically call the script with post-commit hooks, but haven't had the need to implement that just yet.


Question:
I tried to package a Twisted program with py2exe, but once I run the exe file I built, I got a "No module named resource" error.

And I found the py2exe said:

The following modules appear to be missing ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', 'email.Utils', 'pkg_resources', 'pywintypes', 'resource', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security']

So how do I solve this problem?

Thanks.

Answer:
I've seen this before... py2exe, for some reason, is not detecting that these modules are needed inside the ZIP archive and is leaving them out.
You can explicitly specify modules to include on the py2exe command line:
```
```
python setup.py py2exe -p win32com -i twisted.web.resource
```
```
Something like that. Read up on the options and experiment.


Question: I want to write a script which cleans the 'run' dialogue automatically every log off. Where is the history stored?

Answer:
```
```
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
```
```


Question: I need to encode a 100KB+ string as base64 in VBA. Are there any built-in functions or COM objects available which will do this as a pure VBA approach is either complex or doesn't scale well at these volumes (see links from dbb and marxidad)?

Answer:
You can use the MSXML Base64 encoding functionality as described at
www.nonhostile.com/howto-encode-decode-base64-vb6.asp
:
```
```
Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As MSXML2.DOMDocument
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = Replace(objNode.Text, vbLf, "")

  Set objNode = Nothing
  Set objXML = Nothing
End Function
```
```


Question:
I want to convert a string into a double and after doing some math on it, convert it back to a string.

How do I do this in Objective-C?

Is there a way to round a double to the nearest integer too?

Answer:
You can convert an NSString into a double with
```
```
double myDouble = [myString doubleValue];
```
```
Rounding to the nearest int can then be done as
```
```
int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))
```
```
I'm honestly not sure if there's a more streamlined way to convert back into a string than
```
```
NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];
```
```


Question:
I'm wondering what's a reasonable size for iPhone Apps. Right now I'm working on an iPhone game, and of course it loads fast into my device since I'm connected directly to it through a USB cable, but I've no idea how long it would actually take to download from the App Store.

In my case it's about 2mb in size, which is reasonable for a desktop or even a flash game, but I've no idea if this is reasonable size for the iPhone.

My other concern is what's the non-wifi download limit of the App Store? Occasionally there are Apps that won't download unless you've got a wifi connection. And personally I've never downloaded such apps, since it gives me a bad impression. So I'd definitely want to stay below that limit.

Also since I'm already asking about app sizes, it would be probably be useful to collect good sizes for other types of apps as well.

Thanks!

Answer:
The 3g network is fast.  I wouldn't limit your development based on this - do exactly what you need to do to make your game as good as it can be, and people will download it even if it takes a tiny bit longer.  I've downloaded 10MB+ applications from the store over 3g and it might as well be a slow wi-fi connection, it's just that fast.
Also remember that many people purchase on their computers (hence a fast connection) and then just sync to the iPhone, especially those that are in areas with slower cellular networks.
Bottom line, size won't affect downloads, ratings will.


Question:
Per this Adobe KB tech note is there any way around having to place the FLVPlayback skin SWF in same directory as HTML file the container SWF is loaded from?  It pains me to have to put a SWF in my site's root directory.

I think loading the Flash video in an iframe would solve this problem, but is that a good practice?  I generally shy away from using iframes because of padding, margin, and sizing issues between browsers.  Maybe that's not an issue anymore with CSS.

Answer:
Well, you can place the skin in another directory as long as you specify the path (relative to the loading HTML) in the "skin" parameter for your FLV playback component in the component inspector. Troubleshooting is very easy if you use the Net panel in Firebug or a similar tool.
Using an iframe works and don't cause rendering problems as long as you take care that there's no margin or padding inside the iframe. However, you will need another HTML file which can make maintaining your site more of a hassle.
If you are publishing a lot of video files, you might find that it's more convenient to use a standalone player such as the
JW Media Player
.


Question:
Let's say:

<div>
  pre text
  <div class="remove-just-this">
    <p>child foo</p>
    <p>child bar</p>
    nested text
  </div>
  post text
</div>

to this:

<div>
  pre text
  <p>child foo</p>
  <p>child bar</p>
  nested text
  post text
</div>

I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this.

Answer:
Using
jQuery
you can do this:
```
```
var cnt = $(".remove-just-this").contents();
$(".remove-just-this").replaceWith(cnt);
```
```
Quick links to the documentation:
contents
( ) :
jQuery
replaceWith
(
content
: [
String
|
Element
|
jQuery
] ) :
jQuery


Question: While Scrum is easy in theory and hard in practice, I wanted to hear your definition of Done; i.e. what are the gates (unit test, code coverage > 80%, code reviews, load tests, perf.test, functional tests, etc.) your product has to go through before you can label the product "Done"

Answer:
There are three nice articles by
Mitch Lacey
,
Dhaval Panchal
and
Mayank Gupta
on this on the ScrumAlliance website.
EDIT:
Basically the whole point is that
done is defined on a project-by-project basis by the team
. The basic need is to agree on the definition, not what the definition is.


Question:
I'm trying to make things simpler. Here is my code:

    If Threading.Monitor.TryEnter(syncRoot) Then
        Try
            'do something
        Finally
            Threading.Monitor.Exit(syncRoot)
        End Try
    Else
        'do something else
    End If

This is even worse than the ReaderWriterLock in terms of noise.
I can use C# or VB, so answers applying to either will be welcome.

Answer:
This is very similar to your
last post
, and I would expect a similar answer. The only significant difference is that you might return "null" from your method if the timeout fails - then the "Dispose()" is not called, and you can easily check the value:
```
```
using(var token = GetLock(syncLock, timeout)) {
  if(token != null) { ... }
}
```
```
The only real glitch is that you don't necessarily want to add an extension method to "object" (or even "T where T : class")...
Jon Skeet
has looked at this in the past -
worth a look
.


Question:
 <DataTemplate x:Key="Genre_DataTemplate">
        <RadioButton GroupName="One" Content="{Binding...
 </DataTemplate>

Above code is the ItemTemplate of my ItemsControl, I want all the Radiobuttons instantiated should behave as if it is in a group, I know the reason because the generated RadioButtons are not adjacent in the visualtree.

Any solution or workaround to group them together?. GroupName property also doesn't have any effect here.

[Update] I am trying this in Silverlight

Answer:
I think the problem is somewhere else in the control tree. Can you post more details?
Here is a sample xaml code that works as expected:
```
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <Grid>
    <Grid.Resources>
       <XmlDataProvider x:Key="flickrdata" Source="http://api.flickr.com/services/feeds/photos_public.gne?tags=flower&lang=en-us&format=rss_200">
          <XmlDataProvider.XmlNamespaceManager>
             <XmlNamespaceMappingCollection>
                <XmlNamespaceMapping Prefix="media" Uri="http://search.yahoo.com/mrss/"/>
             </XmlNamespaceMappingCollection>
          </XmlDataProvider.XmlNamespaceManager>
       </XmlDataProvider>
       <DataTemplate x:Key="itemTemplate">
        <RadioButton GroupName="One">
          <Image Width="75" Height="75" Source="{Binding Mode=OneWay, XPath=media:thumbnail/@url}"/>
        </RadioButton>
       </DataTemplate>
       <ControlTemplate x:Key="controlTemplate" TargetType="{x:Type ItemsControl}">
          <WrapPanel IsItemsHost="True" Orientation="Horizontal"/>
       </ControlTemplate>
    </Grid.Resources>
    <ItemsControl
       Width="375"
       ItemsSource="{Binding Mode=Default, Source={StaticResource flickrdata}, XPath=/rss/channel/item}"
       ItemTemplate="{StaticResource itemTemplate}"
       Template="{StaticResource controlTemplate}">
    </ItemsControl>
 </Grid>

</Page>
```
```
P.S.: In order grouping to work elements radio buttons should have same parent (as they usually have when generated from ItemsControl)


Question:
SQL Server profiler is great for profiling SQL Server performance for web apps. However, when I'm testing my webapp I'd like a summary of database hits/duration per page.

Does anybody know of any utilities for giving you this kind of information?

Answer:
I think the problem is somewhere else in the control tree. Can you post more details?
Here is a sample xaml code that works as expected:
```
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <Grid>
    <Grid.Resources>
       <XmlDataProvider x:Key="flickrdata" Source="http://api.flickr.com/services/feeds/photos_public.gne?tags=flower&lang=en-us&format=rss_200">
          <XmlDataProvider.XmlNamespaceManager>
             <XmlNamespaceMappingCollection>
                <XmlNamespaceMapping Prefix="media" Uri="http://search.yahoo.com/mrss/"/>
             </XmlNamespaceMappingCollection>
          </XmlDataProvider.XmlNamespaceManager>
       </XmlDataProvider>
       <DataTemplate x:Key="itemTemplate">
        <RadioButton GroupName="One">
          <Image Width="75" Height="75" Source="{Binding Mode=OneWay, XPath=media:thumbnail/@url}"/>
        </RadioButton>
       </DataTemplate>
       <ControlTemplate x:Key="controlTemplate" TargetType="{x:Type ItemsControl}">
          <WrapPanel IsItemsHost="True" Orientation="Horizontal"/>
       </ControlTemplate>
    </Grid.Resources>
    <ItemsControl
       Width="375"
       ItemsSource="{Binding Mode=Default, Source={StaticResource flickrdata}, XPath=/rss/channel/item}"
       ItemTemplate="{StaticResource itemTemplate}"
       Template="{StaticResource controlTemplate}">
    </ItemsControl>
 </Grid>

</Page>
```
```
P.S.: In order grouping to work elements radio buttons should have same parent (as they usually have when generated from ItemsControl)


Question:
What criteria should I use to decide whether I write VBA code like this:

Set xmlDocument = New MSXML2.DOMDocument

or like this:

Set xmlDocument = CreateObject("MSXML2.DOMDocument")

?

Answer:
For the former you need to have a reference to the type library in your application.  It will typically use early binding (assuming you declare your variable as MSXML2.DOMDocument rather than as Object, which you probably will), so will generally be faster and will give you intellisense support.
The latter can be used to create an instance of an object using its ProgId without needing the type library.  Typically you will be using late binding.
Normally it's better to use "As New" if you have a type library, and benefit from early binding.


Question:
I've gone to http://sourceforge.net/project/showfiles.php?group_id=2435, downloaded the Automated MinGW Installer for MinGW 5.1.4 and at the same time the GNU Source-Level Debugger Release Candidate: GDB 6.8-3. I've then installed MinGW base tools into C:\MinGW. No problem so far.

However when I come to install the gdb debugger it has a lot of files and folders with the same names as some already installed but the files are different to those already installed. e.g C:\MinGW\include\bfd.h is 171 KB but gdb-6.8-mingw-3\include\bfd.h is 184 KB.

How do I add gdb to MinGW without breaking what's already installed?

Answer:
The
Current Release
(5.2.1) version of gdb at the
project files page
has always worked for me. The download is a stand-alone .exe, you don't need anything else.
But I'll bet the .exe in the 6.8 package will work, too. I'd try using just the .exe, and then if there are problems, try extracting the other files from the 6.8 package. (Though that may cause problems with the rest of the MinGW installation.)
Update: There seems to be a 7.something version. I haven't tested it thoroughly, but it seems to work, even with gcc 3.


Question: Hi are there any pros / cons relating to the speed that a stored procedure executes when using an IF statement or choosing to use a CASE statement instead?

Answer:
Have you considered simply validating resource access through an HTTP request to the server after the swf loads?
Where I work we provide online trainings to users through flash but rather than verify the HTTP request itself, we allow the swf's to load first and then make a request to the server to verify that the user should have access to the swf and that they are accessing the swf from within our site and not from another location.
If any step of validation fails (either it fails to find an auth file in the necessary location or the user does not have a valid session or does not have access to the particular training) then they receive an error within flash and none of the important content ever loads.
As another note, if you do decide that you want to strictly limit access to the files so that they can only be loaded by those who should have access, then I would probably suggest using your second option of storing the files in a separate, non-public location and then using a handler script to load the swf.


Question:
How do I add the Swedish interactive user,

NT INSTANS\INTERAKTIV

or the English interactive user,

NT AUTHORITY\INTERACTIVE

or any other localised user group with write permissions to a program folder's ACL?

Is this question actually "How do I use secureObject"? I cannot use the LockPermissions Table because I undestand inheritance is removed. secureObject permissions seem to require CreateDirectory rather than Directory...

Answer:
There is no way
as such
to add both account names to an ACL since they are one and the same. The name you see corresponds to a SID, and that SID is identical in both the English and Swedish localizations. In the case of the INTERACTIVE group, that SID is
```
S-1-5-4
```
.
I haven't followed WiX in a long while, but I expect there has to be a way to specify SIDs for ACLs instead of account names. You should never, ever rely on the account name for well-known accounts unless there is absolutely no way to avoid it. Here is a
list of well-known SIDs
for reference.
Edit:
This post
seems to provide a solution to your problem using a custom action to translate the SIDs to account names - apparently WiX doesn't out of the box support using SIDs for Permission or PermissionEx objects.
Here is a more authoritative list of well-known SIDs in
Q243330
of the Microsoft Knownledge Base.


Question:
I was previously taught today how to set parameters in a SQL query in .NET in this answer (click).

Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter.

e.g.

Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn)

If actLimit.ToLower() = "unlimited" Then
    ' It's not nulling :(
    dc.Parameters.Add(New SqlParameter("Limit", Nothing))
Else
    dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit)))
End If

Is there something I'm missing? Am I doing it wrong?

Answer:
Try setting it to
```
DbNull.Value
```
.


Question:
What is the minimal conventional directory structure for a Java web app? What do I need to put in a build.xml file to get ant to build it and make a WAR file?

My goal is to deploy a Wicket app to Tomcat without using an IDE. I want to do it with only ant and my favourite text editor.

Answer:
Ours look like this:
```
```
web/
web/WEB-INF/   (sometimes we use a conf/ dir at the top level but this is minimal)
src/
lib/
```
```
The build.xml has three targets:
jsp: copies everything from web/ into the tomcat webapp folder and from lib/ into WEB-INF/lib
compile: compiles everything from src/ into WEB-INF/classes in the webapp
war: runs compile, jsp, and then zips the contents of the tomcat webapp into a warfile
This structure is a little bit informal and you can do it more cleanly by having a separate build directory for the warfile, and/or a separate compile directory, etc. Some people don't like the idea of deploying directly to the webapp instead of building a war first. But to get something up and running quickly, the above will do nicely.


Question:
Creating hashes of hashes in Ruby allows for convenient two (or more) dimensional lookups.  However, when inserting one must always check if the first index already exists in the hash. For example:

h = Hash.new
h['x'] = Hash.new if not h.key?('x')
h['x']['y'] = value_to_insert

It would be preferable to do the following where the new Hash is created automatically:

h = Hash.new
h['x']['y'] = value_to_insert

Similarly, when looking up a value where the first index doesn't already exist, it would be preferable if nil is returned rather than receiving an undefined method for '[]' error.

looked_up_value = h['w']['z']

One could create a Hash wrapper class that has this behavior, but is there an existing a Ruby idiom for accomplishing this task?

Answer:
You can pass the
```
Hash.new
```
function a block that is executed to yield a default value in case the queried value doesn't exist yet:
```
```
h = Hash.new { |h, k| h[k] = Hash.new }
```
```
Of course, this can be done recursively. There's
an article explaining the details
.
For the sake of completeness, here's the solution from the article for arbitrary depth hashes:
```
```
hash = Hash.new(&(p = lambda{|h, k| h[k] = Hash.new(&p)}))
```
```
The person to originally come up with this solution is
Kent Sibilev
.


Question:
I am trying to set myself up on a mac to learn Ruby on Rails, however I seem to be having some problems. If I try to run commands such as ./script/server, i get this:

Rails requires RubyGems >= 0.9.4 (you have 0.9.2). Please gem update --system and try again.

When I run "gem update.." I get this:

Updating RubyGems...
  Attempting remote update of rubygems-update
  ERROR:  While executing gem ... (Errno::EACCES)
      Permission denied - /opt/local/lib/ruby/gems/1.8/cache/rubygems-update-1.3.0.gem

Answer:
got it.
sudo gem update --system


Question:
Is there a mode, some switch or a programmatic way that I can ask MSBuild to display or output it's calculated dependencies for a given build file?

Some background -
I have a large project that requires splitting up to speed up the build time and want to remove the slow changing infrastructure code into it's own release area.  Not all of the information is contained in the build file itself, as some sub-projects are referenced by their vcproj or csproj files.

I'd really like to see what MSBuild thinks needs doing (either worse-case [rebuild all] and perhaps for a make) without actually doing the rebuild.

Answer:
The
MSBuild Profiler
project should be able to help you in seeing where time is being taken on the build.  It doesn't directly show dependencies.  With or without build dependencies, just profiling the builds can probably give some insight and help speed up the process.
I did just come across this application, but I have not used it myself yet,
Dependency Visualizer
that looks to have just added MSBuild-compatible project files.  There have also been posts about doing this previously, but no code (see
A
,
B
).


Question:
I would like to execute a stored procedure within a stored procedure, e.g.

EXEC SP1

BEGIN

EXEC SP2
END

But I only want SP1 to finish after SP2 has finished running so I need to find a way for SP1 to wait for SP2 to finish before SP1 ends.

SP2 is being executed as part of SP1 so I have something like:

CREATE PROCEDURE SP1
AS
BEGIN

EXECUTE SP2

END

Answer:
Thats how it works stored procedures run in order, you don't need begin just something like
```
```
exec dbo.sp1
exec dbo.sp2
```
```