q: What's the simplest way to connect and query a database for a set of records in C#?

[A]
Very roughly and from memory since I don't have code on this laptop:
```
```
using (OleDBConnection conn = new OleDbConnection())
{
  conn.ConnectionString = "Whatever connection string";

  using (OleDbCommand cmd = new OleDbCommand())
  {
    cmd.Connection = conn;
    cmd.CommandText = "Select * from CoolTable";

    using (OleDbDataReader dr = cmd.ExecuteReader())
    {
      while (dr.Read())
      {
        // do something like Console.WriteLine(dr["column name"] as String);
      }
    }
  }
}
```
```


q:
Attempting to insert an escape character into a table results in a warning.

For example:

create table EscapeTest (text varchar(50));

insert into EscapeTest (text) values ('This is the first part \n And this is the second');

Produces the warning:

WARNING:  nonstandard use of escape in a string literal

(Using PSQL 8.2)

Anyone know how to get around this?

[A]
Partially. The text is inserted, but the warning is still generated.
I found a discussion that indicated the text needed to be preceded with 'E', as such:
```
```
insert into EscapeTest (text) values (E'This is the first part \n And this is the second');
```
```
This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.
As such:
```
```
insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
```
```

s: huggingface

c: devops

d: intermediate


q:
I've read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.

I understand that it's not always good to do so. But how might one do this?

[A]
In Python monkeypatching generally works by overwriting a class or function's signature with your own. Below is an example from the
Zope Wiki
:
```
```
from SomeOtherProduct.SomeModule import SomeClass
def speak(self):
   return "ook ook eee eee eee!"
SomeClass.speak = speak
```
```
This code will overwrite/create a method called
```
speak
```
in the class. In Jeff Atwood's
recent post on monkey patching
, he showed an example in C# 3.0 which is the current language I use for work.


q:
I need to grab the base64-encoded representation of the ViewState. Obviously, this would not be available until fairly late in the request lifecycle, which is OK.

For example, if the output of the page includes:

<input type="hidden" name="__VIEWSTATE"
  id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" />

I need a way on the server-side to get the value "/wEPDwUJODU0Njc5MD...=="

To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being sent to the client, not the ViewState I'm getting back from them.

[A]
Rex, I suspect a good place to start looking is solutions that
compress the ViewState
-- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be.
Scott Hanselman on ViewState Compression
(2005)
ViewState Compression with System.IO.Compression
(2007)


q:
After upgrading a rails 1.2 website to 2.1, the ExceptionNotifier plugin no longer works, complaining about this error:

ActionView::TemplateFinder::InvalidViewPath:  Unprocessed view path
  found:
  "/path/to/appname/vendor/plugins/exception_notification/lib/../views".
  Set your view paths with #append_view_path, #prepend_view_path, or #view_paths=.

What causes it and how do I fix it?

[A]
This was caused by a change in rails 2.1 which prevents rails from loading views from any arbitrary path for security reasons.
There is now an updated version of the plugin on github, so the solution is to use that.
The old solution here for posterity
To work around it, edit
```
init.rb
```
under your
```
vendor/plugins/exception_notification
```
directory, and add the following code to the end
```
```
ActionController::Base.class_eval do
  append_view_path File.dirname(__FILE__) + '/lib/../views'
end
```
```
This adds the ExceptionNotifier plugins' views folder to the list, so it is allowed to load them.


q:
What is the best way to display Flash content in a C# WinForms application? I would like to create a user control (similar to the current PictureBox) that will be able to display images and flash content.

It would be great to be able to load the flash content from a stream of sorts rather than a file on disk.

[A]
While I haven't used a flash object inside a windows form application myself, I do know that it's possible.
In Visual studio on your toolbox, choose to add a new component.
Then in the new window that appears choose the
"COM Components"
tab to get a list in which you can find the
"Shockwave Flash Object"
Once added to the toolbox, simply use the control as you would use any other "standard" control from visual studio.
three simple commands are available to interact with the control:
AxShockwaveFlash1.Stop()
AxShockwaveFlash1.Movie = FilePath &
"\FileName.swf"
AxShockwaveFlash1.Play()
which, I think, are all self explanatory.
It would be great to be able to load
  the flash content from a stream of
  sorts rather than a file on disk.
I just saw you are also looking for a means to load the content from a stream,
and because I'm not really sure that is possible with the shockwave flash object I will give you another option (two actually).
the first is the one I would advise you to use only when necessary, as it uses the full blown
"webbrowser component"
(also available as an extra toolbox item), which is like trying to shoot a fly with a bazooka.
of course it will work, as the control will act as
a real browser window
(actually the internet explorer browser), but its not really meant to be used in the way you need it.
the second option is to use something I just discovered while looking for more information about playing flash content inside a windows form.
F-IN-BOX
is a commercial solution that will also play content from a given website URL. (The link provided will direct you to the .NET code you have to use).


q: I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using File.Delete().

[A]
You can use this program,
Handle
, to find which process has the lock on your file. It's a command-line tool, so I guess you use the output from that. I'm not sure about finding it programmatically.
If deleting the file can wait, you could specify it for deletion when your computer next starts up:
Start
```
REGEDT32 (W2K)
```
or
```
REGEDIT (WXP)
```
and navigate to:
```
```
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager
```
```
W2K and WXP
W2K:
Edit
Add Value...
Data Type:
```
REG_MULTI_SZ
```
Value Name:
```
PendingFileRenameOperations
```
OK
WXP:
Edit
New
Multi-String Value
enter
```
PendingFileRenameOperations
```
In the Data area, enter
```
"\??\" + filename
```
to be deleted. LFNs may
be entered without being embedded in quotes. To delete
```
C:\Long Directory Name\Long File Name.exe
```
, enter the following data:
```
```
\??\C:\Long Directory Name\Long File Name.exe
```
```
Then press
OK
.
The "destination file name" is a null (zero) string. It is entered
as follows:
W2K:
Edit
Binary
select Data Format: Hex
click at the end of the hex string
enter 0000 (four zeros)
OK
WXP:
Right-click the value
choose "Modify Binary Data"
click at the end of the hex string
enter 0000 (four zeros)
OK
Close
```
REGEDT32/REGEDIT
```
and reboot to delete the file.
(Shamelessly stolen from
some random forum
, for posterity's sake.)


q:
For instance, my query is like the following using SQL Server 2005:

SELECT * FROM Table WHERE FREETEXT(SearchField, 'c#')

I have a full text index defined to use the column SearchField which returns results when using:

SELECT * FROM Table WHERE SearchField LIKE '%c#%'

I believe # is a special letter, so how do I allow FREETEXT to work correctly for the query above?

[A]
Quoting a much-replicated help page about Indexing Service query language:
To use specially treated characters such as &, |, ^, #, @, $, (, ), in a query, enclose your query in quotation marks (“).
As far as I know, full text search in
```
MSSQL
```
is also done by the Indexing Service, so this might help.


q:
Most mathematicians agree that:

eπi + 1 = 0

However, most floating point implementations disagree. How well can we settle this dispute?

I'm keen to hear about different languages and implementations, and various methods to make the result as close to zero as possible. Be creative!


q: What is the correct way to get the process size on Solaris, HP-UX and AIX? Should we use top or ps -o vsz or something else?

[A]
Yes, you are right to lock at the VSZ.
```
ps u
```
will give you the VSZ and RSS, which are the virtual memory size and resident set size.  The RSS is how much physical memory has been allocated to the process, and the VSZ is the virtual memory size of the process.  If you have several copies of a program running, a lot of the memory in the VSZ will be shared between those processes.


q:
Given that indexing is so important as your data set increases in size, can someone explain how indexing works at a database-agnostic level?

For information on queries to index a field, check out How do I index a database column.

[A]
Why is it needed?
When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.
Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires
```
(N+1)/2
```
block accesses (on average), where
```
N
```
is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at
```
N
```
block accesses.
Whereas with a sorted field, a Binary Search may be used, which has
```
log2 N
```
block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.
What is indexing?
Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.
The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.
How does it work?
Firstly, let’s outline a sample database table schema;
```
Field name       Data type      Size on disk
id (Primary key) Unsigned INT   4 bytes
firstName        Char(50)       50 bytes
lastName         Char(50)       50 bytes
emailAddress     Char(100)      100 bytes
```
Note
: char was used in place of varchar to allow for an accurate size on disk value.
This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the
id
(a sorted key field) and one using the
firstName
(a non-key unsorted field).
Example 1
-
sorted vs unsorted fields
Given our sample database of
```
r = 5,000,000
```
records of a fixed size giving a record length of
```
R = 204
```
bytes and they are stored in a table using the MyISAM engine which is using the default block size
```
B = 1,024
```
bytes. The blocking factor of the table would be
```
bfr = (B/R) = 1024/204 = 5
```
records per disk block. The total number of blocks required to hold the table is
```
N = (r/bfr) = 5000000/5 = 1,000,000
```
blocks.
A linear search on the id field would require an average of
```
N/2 = 500,000
```
block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of
```
log2 1000000 = 19.93 = 20
```
block accesses. Instantly we can see this is a drastic improvement.
Now the
firstName
field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact
```
N = 1,000,000
```
block accesses. It is this situation that indexing aims to correct.
Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the
firstName
field is outlined below;
```
Field name       Data type      Size on disk
firstName        Char(50)       50 bytes
(record pointer) Special        4 bytes
```
Note
: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.
Example 2
-
indexing
Given our sample database of
```
r = 5,000,000
```
records with an index record length of
```
R = 54
```
bytes and using the default block size
```
B = 1,024
```
bytes. The blocking factor of the index would be
```
bfr = (B/R) = 1024/54 = 18
```
records per disk block. The total number of blocks required to hold the index is
```
N = (r/bfr) = 5000000/18 = 277,778
```
blocks.
Now a search using the
firstName
field can utilize the index to increase performance. This allows for a binary search of the index with an average of
```
log2 277778 = 18.08 = 19
```
block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to
```
19 + 1 = 20
```
block accesses, a far cry from the 1,000,000 block accesses required to find a
firstName
match in the non-indexed table.
When should it be used?
Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.
Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space.


q:
Hopefully, I can get answers for each database server.

For an outline of how indexing works check out: How does database indexing work?

[A]
The following is SQL92 standard so should be supported by the majority of RDMBS that use SQL:
```
```
CREATE INDEX [index name] ON [table name] ( [column name] )
```
```


q:
One of the sites I maintain relies heavily on the use of ViewState (it isn't my code). However, on certain pages where the ViewState is extra-bloated, Safari throws a "Validation of viewstate MAC failed" error.

This appears to only happen in Safari. Firefox, IE and Opera all load successfully in the same scenario.

[A]
I've been doing a little research into this and whilst I'm not entirely sure its the cause I believe it is because Safari is not returning the full result set (hence cropping it).
I have been in dicussion with another developer and found the following post on Channel 9 as well which recommends making use of the SQL State service to store the viewstate avoiding the postback issue and also page size.
http://channel9.msdn.com/forums/TechOff/250549-ASPNET-ViewState-flawed-architecture/?CommentID=270477#263702
Does this seem like the best solution?


q:
I have a file in the following format:

Data Data
Data
[Start]
Data I want
[End]
Data

I'd like to grab the Data I want from between the [Start] and [End] tags using a Regex. Can anyone show me how this might be done?

[A]
```
```
\[start\](.*?)\[end\]
```
```
Zhich'll put the text in the middle within a capture.


q:
My company is using CVS as our de-facto standard for source control. However, I've heard a lot of people say that SVN is better.

I know SVN is newer, but other than that, I'm unfamiliar with its benefits.

What I'm looking for is a good, succinct comparison of the two systems, noting any advantages or disadvantages of each in a Java/Eclipse development environment.

[A]
One of the many comparisons:
http://wiki.scummvm.org/index.php/CVS_vs_SVN
Now this is very specific to that project, but a lot of stuff apllies in general.
Pro Subversion:
Support for versioned renames/moves (impossible with CVS): Fingolfin, Ender
Supports directories natively: It's possible to remove them, and they are versioned: Fingolfin, Ender
File properties are versioned; no more "executable bit" hell: Fingolfin
Overall revision number makes build versioning and regression testing much easier: Ender, Fingolfin
Atomic commits: Fingolfin
Intuitive (directory-based) branching and tagging: Fingolfin
Easier hook scripts (pre/post commit, etc): SumthinWicked (I use it for Doxygen after commits)
Prevents accidental committing of conflicted files: Salty-horse, Fingolfin
Support for custom 'diff' command: Fingolfin
Offline diffs, and they're instant: sev


q:
I am looking for a tool that can detect malicious requests (such as obvious SQL injection gets or posts) and will immediately ban the IP address of the requester/add to a blacklist. I am aware that in an ideal world our code should be able to handle such requests and treat them accordingly, but there is a lot of value in such a tool even when the site is safe from these kinds of attacks, as it can lead to saving bandwidth, preventing bloat of analytics, etc.

Ideally, I'm looking for a cross-platform (LAMP/.NET) solution that sits at a higher level than the technology stack; perhaps at the web-server or hardware level. I'm not sure if this exists, though.

Either way, I'd like to hear the community's feedback so that I can see what my options might be with regard to implementation and approach.

[A]
The problem with a generic tool is that it is very difficult to come up with a set of rules that will only match against a genuine attack.
SQL keywords are all English words, and don't forget that the string
```
```
DROP TABLE users;
```
```
is perfectly valid in a form field that, for example, contains an answer to a programming question.
The only sensible option is to sanitise the input before ever passing it to your database but pass it on nonetheless.  Otherwise lots of perfectly normal, non-malicious users are going to get banned from your site.


q: I have a Queue<T> object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items.  Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class?

[A]
Why wouldn't you just use an array with a size of 2?  A Queue is supposed to be able to dynamically grow and shrink.
Or create a wrapper class around an instance of
```
Queue<T>
```
instance and each time one enqueues a
```
<T>
```
object, check the size of the queue.  If larger than 2, dequeue the first item.


q:
I am using MSBuild to build my stuff. I want to use CruiseControl.net as by Build Server.

Now, CCNET refers nAnt a lot, but it looks as if ccnet can do most of the stuff nant could do through the project configuration and msbuild. Also, nAnt seems a bit unsupported, with a Beta release that is almost a year old now.

In short: I am actually quite happy with MSBuild (especially since it's the "official" compiler front end) and a bit uncomfortable with nAnt, but I do not want to judge prematurely.

What would be reasons to use nAnt over MSBuild? Especially with ccnet, which seems to overlap a bit with nant in terms of features (and adding the automated build related stuff)

[A]
In my opinion it is more a question of personal preference.  nAnt is a great framework and MSBuild is almost as capable.  With the ability to easily develop custom tasks (in both frameworks) you can accomplish almost anything that you need to do.
I cannot answer the "still supported" portion of your questions, but I would say if you are already comfortable with nAnt then it's probably viable.  If you (or someone in your group) is familiar with MSBuild then that is a fine way to go as well.


q:
Is there any way to check whether a file is locked without using a try/catch block?

Right now, the only way I know of is to just open the file and catch any System.IO.IOException.

[A]
No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan).
Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice.
If your code would look like this:
```
```
if not locked then
    open and update file
```
```
Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions.


q:
Original Question

I am looking for a function that attempts to quantify how "distant" (or distinct) two colors are. This question is really in two parts:

What color space best represents human vision?

What distance metric in that space best represents human vision (euclidean?)

[A]
The easiest
distance
would of course be to just consider the colors as 3d vectors originating from the same origin, and taking the distance between their end points.
If you need to consider such factors that green is more prominent in judging intensity, you can weigh the values.
ImageMagic
provides the following scales:
red: 0.3
green: 0.6
blue: 0.1
Of course, values like this would only be meaningful in relation to other values for other colors, not as something that would be meaningful to humans, so all you could use the values for would be similiarity ordering.


q:
I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows.

I don't want it to hang on a "Are you sure?", "Are you really sure?", "Even zip files?", "Surely not read-only files too!" loop as soon as I step away.

I don't want it to work for hours and then stop unexpectedly: "Someone once opened this file and so I won't copy it!" and then cancel the whole copy or just quit with no indication of what was done and what work remains.

What file management programs do you have experience with?  Which do you recommend?

This question is related to my other question: How can I use an old PATA hard disk drive on my newer SATA-only computer?

[A]
Use
Robocopy (Robust File Copy)
.
NOTE:
In Windows Vista and Server 2008 when you type:
```
```
xcopy /?
```
```
you get:
NOTE: Xcopy is now deprecated, please use Robocopy.
So start getting used to robocopy :)


q:
I saw many questions asking 'how' to unit test in a specific language, but no question asking 'what', 'why', and 'when'.

What is it?

What does it do for me?

Why should I use it?

When should I use it (also when not)?

What are some common pitfalls and misconceptions

[A]
Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are:
Running the tests becomes automate-able and repeatable
You can test at a much more granular level than point-and-click testing via a GUI
Note that if your test code writes to a file, opens a database connection or does something over the network, it's more appropriately categorized as an integration test. Integration tests are a good thing, but should not be confused with unit tests. Unit test code should be short, sweet and quick to execute.
Another way to look at unit testing is that you write the tests first. This is known as Test-Driven Development (TDD for short). TDD brings additional advantages:
You don't write speculative "I might need this in the future" code -- just enough to make the tests pass
The code you've written is always covered by tests
By writing the test first, you're forced into thinking about how you want to call the code, which usually improves the design of the code in the long run.
If you're not doing unit testing now, I recommend you get started on it. Get a good book, practically any xUnit-book will do because the concepts are very much transferable between them.
Sometimes writing unit tests can be painful. When it gets that way, try to find someone to help you, and resist the temptation to "just write the damn code". Unit testing is a lot like washing the dishes. It's not always pleasant, but it keeps your metaphorical kitchen clean, and you really want it to be clean. :)
Edit: One misconception comes to mind, although I'm not sure if it's so common. I've heard a project manager say that unit tests made the team write all the code twice. If it looks and feels that way, well, you're doing it wrong. Not only does writing the tests usually speed up development, but it also gives you a convenient "now I'm done" indicator that you wouldn't have otherwise.


q: This is an open-ended question.  What approaches should I consider?

[A]
There are some parallel extensions to .NET that are currently in testing and available at Microsoft's
Parallel Computing Developer Center
. They have a few interesting items that you would expect like Parallel foreach and a parallel version of LINQ called PLINQ. Some of the best information about the extensions is on
Channel 9
.


q:
I'm setting up a dedicated SQL Server 2005 box on Windows Server 2008 this week, and would like to pare it down to be as barebones as possible while still being fully functional.

To that end, the "Server Core" option sounds appealing, but I'm not clear about whether or not I can run SQL Server on that SKU.  Several services are addressed on the Microsoft website, but I don't see any indication about SQL Server.

Does anyone know definitively?

[A]
Not sure how credible
this source is
, but:
The Windows Server 2008 Core edition can:
Run the file server role.
Run the Hyper-V virtualization server role.
Run the Directory Services role.
Run the DHCP server role.
Run the IIS Web server role.
Run the DNS server role.
Run Active Directory Lightweight Directory Services.
Run the print server role.
The Windows Server 2008 Core edition cannot:
Run a SQL Server.
Run an Exchange Server.
Run Internet Explorer.
Run Windows Explorer.
Host a remote desktop session.
Run MMC snap-in consoles locally.


q:
Is it possible to configure xampp to serve up a file outside of the htdocs directory?

For instance, say I have a file located as follows:

C:\projects\transitCalculator\trunk\TransitCalculator.php

and my xampp files are normally served out from:

C:\xampp\htdocs\

(because that's the default configuration) Is there some way to make Apache recognize and serve up my TransitCalculator.php file without moving it under htdocs? Preferably I'd like Apache to serve up/have access to the entire contents of the projects directory, and I don't want to move the projects directory under htdocs.

edit: edited to add Apache to the question title to make Q/A more "searchable"

[A]
You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.
Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.
EDIT:
alias myapp c:\myapp\
I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot.  This is probably going to be more useful to you in the long term.


q:
I'm trying to do this (which produces an unexpected T_VARIABLE error):

public function createShipment($startZip, $endZip, $weight =
$this->getDefaultWeight()){}

I don't want to put a magic number in there for weight since the object I am using has a "defaultWeight" parameter that all new shipments get if you don't specify a weight. I can't put the defaultWeight in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following?

public function createShipment($startZip, $endZip, weight = 0){
    if($weight <= 0){
        $weight = $this->getDefaultWeight();
    }
}

[A]
This isn't much better:
```
```
public function createShipment($startZip, $endZip, $weight=null){
    $weight = !$weight ? $this->getDefaultWeight() : $weight;
}

// or...

public function createShipment($startZip, $endZip, $weight=null){
    if ( !$weight )
        $weight = $this->getDefaultWeight();
}
```
```


q:
I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state.

How are people handling maintaining RESTfulness in AJAX apps?

[A]
This is similar to what Kevin said.  You can have your client state as some javascript object, and when you want to save the state, you serialize the object (using JSON and base64 encoding).  You can then set the fragment of the href to this string.
```
```
var encodedState = base64(json(state));
var newLocation = oldLocationWithoutFragment + "#" + encodedState;

document.location = newLocation; // adds new entry in browser history
document.location.replace(newLocation); // replaces current entry in browser history
```
```
The first way will treat the new state as a new location (so the back button will take them to the previous location).  The latter does not.


q:
How do you express an integer as a binary number with Python literals?

I was easily able to find the answer for hex:

>>> 0x12AF
4783
>>> 0x100
256

and octal:

>>> 01267
695
>>> 0100
64

How do you use literals to express binary in Python?

Summary of Answers

Python 2.5 and earlier: can express binary using int('01010101111',2) but not with a literal.

Python 2.5 and earlier: there is no way to express binary literals.

Python 2.6 beta: You can do like so: 0b1100111 or 0B1100111.

Python 2.6 beta: will also allow 0o27 or 0O27 (second character is the letter O) to represent an octal.

Python 3.0 beta: Same as 2.6, but will no longer allow the older 027 syntax for octals.

[A] As far as I can tell Python, up through 2.5, only supports hexadecimal & octal literals.  I did find some discussions about adding binary to future versions but nothing definite.


q:
For those of us that like to use the graphical version of Vim or Emacs, instead of the console version, which version do you recommend?

For Vim, there's Mac OS X Vim, MacVim, Vim-Cocoa.

For Emacs, CarbonEmacs, XEmacs, and Aquamacs.

Are there more? Which of these are ready for prime-time? If it's a tough call, what are the trade-offs? Are all of these still being maintained?

No discussion of Vim versus Emacs, if you don't mind, or comparisons with other editors.

[A]
MacVim
works well and certainly looks more mature than Vim-Cocoa, moreover there is a Cocoa plugin architecture in the pipeline for MacVim (and someone is already working on a TextMate style file browser tray plugin which is a huge ++ IMHO).
There was also a Carbon version of Vim, but this didn't offer a great deal over the Terminal version. i.e. only allowed one window open, not very OSX in appearance...
Aquamacs
is very usable and looks pretty good. Supports both traditional Mac OS style keyboard shortcuts (command-O, command-S) and the Control/Meta shortcuts for those raised on traditional Emacs. It is definitely more Mac-like than Carbon Emacs. It seems stable and fast, but I am not an Emacs guru so I don't stress it all that much when I use it. I can't speak to the extensiveness of the included elisp packages, either.
Someone syncs Carbon Emacs with the upstream tree quarterly I think. Aquamacs has a more irregular schedule, but it's seen some pretty major updates over the last year.
GNU Emacs
for OSX can be found at
emacsformacosx.com
. In addition to the latest stable release, there are also pre-release test builds and nightly builds, and Atom feeds are provided for tracking all three release types.


q:
My office has a central Source Safe 2005 install that we use for source control. I can't change what the office uses on the server.

I develop on a laptop and would like to have a different local source control repository that can sync with the central server (when available) regardless of the what that central provider is. The reason for the request is so I can maintain a local stable branch/build for client presentations while continuing to develop without having to jump through flaming hoops. Also, as a consultant, my clients may request that I use their source control provider and flexibility here would make life easier.

Can any of the existing distributed source control clients handle that?

[A]
You should be able to check out the current version of the code and then create a git repository around it. Updating that and committing it to your local git repository should be painless. As should cloning it.
The only catch is that you need to have them both ignore each other (I've done something similar with SVN) by messing with the appropriate ignore files. I'm presuming SourceSafe let's you ignore things. And you'll need to do certain operations twice (like telling both that you are deleting a file).


q:
I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes.  Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using IntelliSense or using the classes in a visual designer.

These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0.  I know about ICustomTypeDescriptor and ICustomPropertyProvider, but I'm pretty certain those can't be used in Silverlight.

It's not as much a functional issue as a usability issue.  What should I do?

Update

Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the new operator.  (I know, it's ridiculous)

[A]
While you cannot prevent usage of those inherited members to my knowledge, you should be able to hide them from IntelliSense using the
EditorBrowsableAttribute
:
```
```
Using System.ComponentModel;

[EditorBrowsable(EditorBrowsableState.Never)]
private string MyHiddenString = "Muahahahahahahahaha";
```
```
Edit:
Just saw this in the documentation comments, which makes it kinda useless for this purpose:
There is a prominent note that states that this attribute "does not suppress members from a class in the same assembly". That is true but not complete. Actually, the attribute does not suppress members from a class in the same solution.


q: When I want to make a copy of a database, I always create a new empty database, and then restore a backup of the existing database into it. However, I'm wondering if this is really the least error-prone, least complicated, and most efficient way to do this?

[A]
It is possible to skip the step of creating the empty database. You can create the new database as part of the restore process.
This is actually the easiest and best way I know of to clone a database. You can eliminate errors by scripting the backup and restore process rather than running it through the SQL Server Management Studio
There are two other options you could explore:
Detach the database, copy the .mdf file and re-attach.
Use SQL Server Integration Services (SSIS) to copy all the objects over
I suggest sticking with backup and restore and automating if necessary.


q:
The .XFDL file extension identifies XFDL Formatted Document files. These belong to the XML-based document and template formatting standard. This format is exactly like the XML file format however, contains a level of encryption for use in secure communications.

I know how to view XFDL files using a file viewer I found here.  I can also modify and save these files by doing File:Save/Save As.  I'd like, however, to modify these files on the fly. Any suggestions? Is this even possible?

Update #1: I have now successfully decoded and unziped a .xfdl into an XML file which I can then edit. Now, I am looking for a way to re-encode the modified XML file back into base64-gzip (using Ruby or the command line)

[A]
If the encoding is
base64
then this is the solution I've stumbled upon on the web:
"Decoding XDFL files saved with 'encoding=base64'.
Files saved with:
```
```
application/vnd.xfdl;content-encoding="base64-gzip"
```
```
are simple base64-encoded gzip files. They can be easily restored to XML by first decoding and then unzipping them. This can be done as follows on Ubuntu:
```
```
sudo apt-get install uudeview
uudeview -i yourform.xfdl
gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xfdl
```
```
The first command will install uudeview, a package that can decode base64, among others. You can skip this step once it is installed.
Assuming your form is saved as 'yourform.xfdl', the uudeview command will decode the contents as 'UNKNOWN.001', since the xfdl file doesn't contain a file name. The '-i' option makes uudeview uninteractive, remove that option for more control.
The last command gunzips the decoded file into a file named 'yourform-unpacked.xfdl'.
Another
possible solution -
here
Side Note: Block quoted < code > doesn't work for long strings of code


q: When spliting a solution in to logical layers, when is it best to use a separate project over just grouping by a folder?

[A]
I usually do a project for the GUI a project for the business logic a project for data access and a project for unit tests.
But sometimes it is prudent to have separation based upon services (if you are using a service oriented architecture) Such as Authentication, Sales, etc.
I guess the rule of thumb that I work off of is that if you can see it as a component that has a clear separation of concerns then a different project could be prudent. But I would think that folders versus projects could just be a preference or philosophy.
I personally feel that if reusable code is split into projects it is simpler to use other places than if it is just in folders.


q:
I'm writing an app to help facilitate some research, and part of this involves doing some statistical calculations. Right now, the researchers are using a program called SPSS. Part of the output that they care about looks like this:

They're really only concerned about the F and Sig. values. My problem is that I have no background in statistics, and I can't figure out what the tests are called, or how to calculate them.

I thought the F value might be the result of the F-test, but after following the steps given on Wikipedia, I got a result that was different from what SPSS gives.

[A]
This website
might help you out a bit more.  Also
this one
.
I'm working from a fairly rusty memory of a statistics course, but here goes nothing:
When you're doing analysis of variance (ANOVA), you actually calculate the F statistic as the ratio from the mean-square variances "between the groups" and the mean-square variances "within the groups".  The second link above seems pretty good for this calculation.
This makes the F statistic measure exactly how powerful your model is, because the "between the groups" variance is explanatory power, and "within the groups" variance is random error.  High F implies a highly significant model.
As in many statistical operations, you back-determine Sig. using the F statistic.  Here's where your Wikipedia information comes in slightly handy.  What you want to do is - using the degrees of freedom given to you by SPSS - find the proper P value at which an
F table
will give you the F statistic you calculated.  The P value where this happens [F(table) = F(calculated)] is the significance.
Conceptually, a lower significance value shows a very strong ability to reject the null hypothesis (which for these purposes means to determine your model has explanatory power).
Sorry to any math folks if any of this is wrong.  I'll be checking back to make edits!!!
Good luck to you.  Stats is fun, just maybe not this part.  =)


q:
If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?

I expect this list to be varied and to cover a wide range of things.

To search: Use the search box in the upper-right corner. To search the answers of the current question, use inquestion:this.  For example:

inquestion:this "Code Complete"

[A]
Code Complete
(2nd edition) by Steve McConnell
The Pragmatic Programmer
Structure and Interpretation of Computer Programs
The C Programming Language
by Kernighan and Ritchie
Introduction to Algorithms
by Cormen, Leiserson, Rivest & Stein
Design Patterns
by the Gang of Four
Refactoring: Improving the Design of Existing Code
The Mythical Man Month
The Art of Computer Programming
by Donald Knuth
Compilers: Principles, Techniques and Tools
by Alfred V. Aho, Ravi Sethi and Jeffrey D. Ullman
Gödel, Escher, Bach
by Douglas Hofstadter
Clean Code: A Handbook of Agile Software Craftsmanship
by Robert C. Martin
Effective C++
More Effective C++
CODE
by Charles Petzold
Programming Pearls
by Jon Bentley
Working Effectively with Legacy Code
by Michael C. Feathers
Peopleware
by Demarco and Lister
Coders at Work
by Peter Seibel
Surely You're Joking, Mr. Feynman!
Effective Java
2nd edition
Patterns of Enterprise Application Architecture
by Martin Fowler
The Little Schemer
The Seasoned Schemer
Why's (Poignant) Guide to Ruby
The Inmates Are Running The Asylum: Why High Tech Products Drive Us Crazy and How to Restore the Sanity
The Art of Unix Programming
Test-Driven Development: By Example
by Kent Beck
Practices of an Agile Developer
Don't Make Me Think
Agile Software Development, Principles, Patterns, and Practices
by Robert C. Martin
Domain Driven Designs
by Eric Evans
The Design of Everyday Things
by Donald Norman
Modern C++ Design
by Andrei Alexandrescu
Best Software Writing I
by Joel Spolsky
The Practice of Programming
by Kernighan and Pike
Pragmatic Thinking and Learning: Refactor Your Wetware
by Andy Hunt
Software Estimation: Demystifying the Black Art
by Steve McConnel
The Passionate Programmer (My Job Went To India)
by Chad Fowler
Hackers: Heroes of the Computer Revolution
Algorithms + Data Structures = Programs
Writing Solid Code
JavaScript - The Good Parts
Getting Real
by 37 Signals
Foundations of Programming
by Karl Seguin
Computer Graphics: Principles and Practice in C
(2nd Edition)
Thinking in Java
by Bruce Eckel
The Elements of Computing Systems
Refactoring to Patterns
by Joshua Kerievsky
Modern Operating Systems
by Andrew S. Tanenbaum
The Annotated Turing
Things That Make Us Smart
by Donald Norman
The Timeless Way of Building
by Christopher Alexander
The Deadline: A Novel About Project Management
by Tom DeMarco
The C++ Programming Language (3rd edition)
by Stroustrup
Patterns of Enterprise Application Architecture
Computer Systems - A Programmer's Perspective
Agile Principles, Patterns, and Practices in C#
by Robert C. Martin
Growing Object-Oriented Software, Guided
by Tests
Framework Design Guidelines
by Brad Abrams
Object Thinking
by Dr. David West
Advanced Programming in the UNIX Environment
by W. Richard Stevens
Hackers and Painters: Big Ideas from the Computer Age
The Soul of a New Machine
by Tracy Kidder
CLR via C#
by Jeffrey Richter
The Timeless Way of Building
by Christopher Alexander
Design Patterns in C#
by Steve Metsker
Alice in Wonderland
by Lewis Carol
Zen and the Art of Motorcycle Maintenance
by Robert M. Pirsig
About Face - The Essentials of Interaction Design
Here Comes Everybody: The Power of Organizing Without Organizations
by Clay Shirky
The Tao of Programming
Computational Beauty of Nature
Writing Solid Code
by Steve Maguire
Philip and Alex's Guide to Web Publishing
Object-Oriented Analysis and Design with Applications
by Grady Booch
Effective Java
by Joshua Bloch
Computability
by N. J. Cutland
Masterminds of Programming
The Tao Te Ching
The Productive Programmer
The Art of Deception
by Kevin Mitnick
The Career Programmer: Guerilla Tactics for an Imperfect World
by Christopher Duncan
Paradigms of Artificial Intelligence Programming: Case studies in Common Lisp
Masters of Doom
Pragmatic Unit Testing in C# with NUnit
by Andy Hunt and Dave Thomas with Matt Hargett
How To Solve It
by George Polya
The Alchemist
by Paulo Coelho
Smalltalk-80: The Language and its Implementation
Writing Secure Code
(2nd Edition) by Michael Howard
Introduction to Functional Programming
by Philip Wadler and Richard Bird
No Bugs!
by David Thielen
Rework
by Jason Freid and DHH
JUnit in Action


q:
I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using preg_replace for extract and wrapping purposes, but it's not outputting anything.

preg_replace("/[A-Z]/", "<span class=\"initial\">$1</span>", $str)

[A]
You need to put the pattern in parentheses
```
/([A-Z])/
```
, like this:
```
```
preg_replace("/([A-Z])/", "$1", $str)
```
```


q:
I am getting back into a bit more .NET after a few-years of not using it full-time and am wondering what the good unit testing packages are these days.

I'm familiar with NUnit (a few years ago) and have played briefly around with IronRuby, with the goal of getting something like RSpec going, but I don't know much beyond that.

I realize I could google for this and call it a day, but I believe I'm likely to get a better and more informed response from asking a question here :-)

Suggestions?

[A]
I like
MbUnit
, er,
Gallio
.  Most importantly to me is having good tools support inside Visual Studio.  For that I use
Resharper
, which has an
MbUnit test runner
.  A lot of folks seem to like
TestDriven.NET
as their test runner as well.


q:
I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false.

$canMerge = ($condition1 && $condition2) ? 'true' : 'false';
...
<?php if ($canMerge) { ?>Stuff<?php } ?>

What's up?

[A]
The value of 'false' is true. You need to remove the quotes:
```
```
$canMerge = ($condition1 && $condition2) ? true : false;
```
```


q:
I've got a menu in Python. That part was easy. I'm using raw_input() to get the selection from the user.

The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:

import sys
print """Menu
1) Say Foo
2) Say Bar"""
answer = raw_input("Make a selection> ")

if "1" in answer: print "foo"
elif "2" in answer: print "bar"

It would be great to have something like

print menu
while lastKey = "":
    lastKey = check_for_recent_keystrokes()
if "1" in lastKey: #do stuff...

[A]
On Linux:
set raw mode
select and read the keystroke
restore normal settings
```
import sys
import select
import termios
import tty

def getkey():
    old_settings = termios.tcgetattr(sys.stdin)
    tty.setraw(sys.stdin.fileno())
    select.select([sys.stdin], [], [], 0)
    answer = sys.stdin.read(1)
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
    return answer

print """Menu
1) Say Foo
2) Say Bar"""

answer=getkey()

if "1" in answer: print "foo"
elif "2" in answer: print "bar"
```


q:
OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes.  Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up.

I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes.

I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there.

[A]
for C# 3.5
without notifyicon therefore you will need to terminate this application in task manager manually
```
```
using System;
using System.Drawing;
using System.Windows.Forms;

static class Program
{
    static void Main()
    {
        Timer timer = new Timer();
        // timer.Interval = 4 minutes
        timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond);
        timer.Tick += (sender, args) => { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); };
        timer.Start();
        Application.Run();
    }
}
```
```


q:
I am currently working on a project and my goal is to locate text in an image. OCR'ing the text is not my intention as of yet. I want to basically obtain the bounds of text within an image. I am using the AForge.Net imaging component for manipulation. Any assistance in some sense or another?

Update 2/5/09:
I've since went along another route in my project. However I did attempt to obtain text using MODI (Microsoft Office Document Imaging). It allows you to OCR an image and pull text from it with some ease.

[A]
This is an active area of research. There are literally oodles of academic papers on the subject. It's going to be difficult to give you assistance especially w/o more deatails. Are you looking for specific types of text? Fonts? English-only? Are you familiar with the academic literature?
"Text detection" is a standard problem in any OCR (optical character recognition) system and consequently there are lots of bits of code on the interwebs that deal with it.
I could start listing piles of links from google but I suggest you just do a search for "text detection" and start reading :). There is ample example code available as well.


q: What's the best way to import a CSV file into a strongly-typed data structure?

[A]
A good simple way to do it is to open the file, and read each line into an array, linked list, data-structure-of-your-choice. Be careful about handling the first line though.
This may be over your head, but there seems to be a direct way to access them as well using a
connection string
.
Why not try using Python instead of C# or VB? It has a nice CSV module to import that does all the heavy lifting for you.


q:
Using ASP.NET MVC there are situations (such as form submission) that may require a RedirectToAction.

One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to.

As I require the form to contain the originally POSTed data, for user convenience, as well as validation purposes, how can I pass the data through the RedirectToAction()?  If I use the viewData parameter, my POST parameters will be changed to GET parameters.

[A]
The solution is to use the TempData property to store the desired Request components.
For instance:
```
```
public ActionResult Send()
{
    TempData["form"] = Request.Form;
    return this.RedirectToAction(a => a.Form());
}
```
```
Then in your "Form" action you can go:
```
```
public ActionResult Form()
{
    /* Declare viewData etc. */

    if (TempData["form"] != null)
    {
        /* Cast TempData["form"] to
        System.Collections.Specialized.NameValueCollection
        and use it */
    }

    return View("Form", viewData);
}
```
```


q:
I was just wondering if there is an elegant way to set the maximum CPU load for a particular thread doing intensive calculations.

Right now I have located the most time consuming loop in the thread (it does only compression) and use GetTickCount() and Sleep() with hardcoded values. It makes sure that the loop continues for a certain period and then sleeps for a certain minimum time. It more or less does the job, i.e. guarantees that the thread will not use more than 50% of CPU.
However, behavior is dependent on the number of CPU cores (huge disadvantage) and simply ugly (smaller disadvantage :)).
Any ideas?

[A]
I can't think of any cross platform way of what you want (or any guaranteed way full stop) but as you are using GetTickCount perhaps you aren't interested in cross platform :)
I'd use interprocess communications and set the intensive processes nice levels to get what you require but I'm not sure that's appropriate for your situation.
EDIT:
I agree with
Bernard
which is why I think a process rather than a thread might be more appropriate but it just might not suit your purposes.


q:
In many places, (1,2,3) (a tuple) and [1,2,3] (a list) can be used interchangeably.

When should I use one or the other, and why?

[A]
The list
```
[1,2,3]
```
is dynamic and flexible but that flexibility comes at a speed cost.
The tuple
```
(1,2,3)
```
is fixed (immutable) and therefore faster.


q:
When you data bind in C#, the thread that changes the data causes the control to change too. But if this thread is not the one on which the control was created, you'll get an Illegal Cross Thread Operation exception.

Is there anyway to prevent this?

[A]
You should be able to do something like:
```
```
if (control.InvokeRequired)
{
    control.Invoke(delegateWithMyCode);
}
else
{
    delegateWithMyCode();
}
```
```
InvokeRequired is a property on Controls to see if you are on the correct thread, then Invoke will invoke the delegate on the correct thread.
UPDATE: Actually, at my last job we did something like this:
```
```
private void SomeEventHandler(Object someParam)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new SomeEventHandlerDelegate(SomeEventHandler), someParam);
    }

    // Regular handling code
}
```
```
which removes the need for the else block and kind of tightens up the code.


q:
When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, pass-by-value or pass-by-reference.

So here is my question to all of you, in your favorite language, how is it actually done? And what are the possible pitfalls?

Your favorite language can, of course, be anything you have ever played with: popular, obscure, esoteric, new, old...

[A]
Here is my own contribution for the
Java programming language
.
first some code:
```
```
public void swap(int x, int y)
{
  int tmp = x;
  x = y;
  y = tmp;
}
```
```
calling this method will result in this:
```
```
int pi = 3;
int everything = 42;

swap(pi, everything);

System.out.println("pi: " + pi);
System.out.println("everything: " + everything);

"Output:
pi: 3
everything: 42"
```
```
even using 'real' objects will show a similar result:
```
```
public class MyObj {
    private String msg;
    private int number;

    //getters and setters
    public String getMsg() {
        return this.msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getNumber() {
        return this.number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    //constructor
    public MyObj(String msg, int number) {
        setMsg(msg);
        setNumber(number);
    }
}

public static void swap(MyObj x, MyObj y)
{
    MyObj tmp = x;
    x = y;
    y = tmp;
}

public static void main(String args[]) {
    MyObj x = new MyObj("Hello world", 1);
    MyObj y = new MyObj("Goodbye Cruel World", -1);

    swap(x, y);

    System.out.println(x.getMsg() + " -- "+  x.getNumber());
    System.out.println(y.getMsg() + " -- "+  y.getNumber());
}

"Output:
Hello world -- 1
Goodbye Cruel World -- -1"
```
```
thus it is clear that Java passes its parameters
by value
, as the value for
pi
and
everything
and the
MyObj objects
aren't swapped.
be aware that "by value" is the
only way
in java to pass parameters to a method. (for example a language like c++ allows the developer to pass a parameter by reference using '
&
' after the parameter's type)
now the
tricky part
, or at least the part that will confuse most of the new java developers: (borrowed from
javaworld
)
Original author: Tony Sintes
```
```
public void tricky(Point arg1, Point arg2)
{
    arg1.x = 100;
    arg1.y = 100;
    Point temp = arg1;
    arg1 = arg2;
    arg2 = temp;
}
public static void main(String [] args)
{
    Point pnt1 = new Point(0,0);
    Point pnt2 = new Point(0,0);
    System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
    System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
    System.out.println(" ");
    tricky(pnt1,pnt2);
    System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
    System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}

"Output
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0"
```
```
tricky
successfully changes the value of pnt1!
This would imply that Objects are passed by reference, this is not the case!
A correct statement would be:
the
Object references
are passed by value.
more from Tony Sintes:
The method successfully alters the
  value of pnt1, even though it is
  passed by value; however, a swap of
  pnt1 and pnt2 fails! This is the major
  source of confusion. In the main()
  method, pnt1 and pnt2 are nothing more
  than object references. When you pass
  pnt1 and pnt2 to the tricky() method,
  Java passes the references by value
  just like any other parameter. This
  means the references passed to the
  method are actually copies of the
  original references. Figure 1 below
  shows two references pointing to the
  same object after Java passes an
  object to a method.
(source:
javaworld.com
)
Conclusion
or a long story short:
Java passes it parameters
by value
"by value"
is the
only way
in java to pass a parameter to a method
using
methods from the object
given as parameter
will alter
the object as the references point to the original objects. (if that method itself alters some values)
useful links:
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
http://www.ibm.com/developerworks/java/library/j-passbyval/
http://www.ibm.com/developerworks/library/j-praxis/pr1.html
http://javadude.com/articles/passbyvalue.htm


q: What do the result codes in SVN mean? I need a quick reference.

[A]
For additional details see the SVNBook:
"Status of working copy files and directories"
.
The common statuses:
U
: Working file was updated
G
: Changes on the repo were automatically merged into the working copy
M
: Working copy is modified
C
: This file conflicts with the version in the repo
?
: This file is not under version control
!
: This file is under version control but is missing or incomplete
A
: This file will be added to version control (after commit)
A+
: This file will be moved (after commit)
D
: This file will be deleted (after commit)
S
: This signifies that the file or directory has been switched from the path of the rest of the working copy (using svn switch) to a
  branch
I
: Ignored
X
: External definition
~
: Type changed
R
: Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place.
L
: Item is locked
E
: Item existed, as it would have been created, by an svn update.


q: How do I create a branch in SVN?

[A]
Create a new branch using the
```
svn copy
```
command as follows:
```
```
$ svn copy svn+ssh://host.example.com/repos/project/trunk \
           svn+ssh://host.example.com/repos/project/branches/NAME_OF_BRANCH \
      -m "Creating a branch of project"
```
```


q:
As a novice in practicing test-driven development, I often end up in a quandary as to how to unit test persistence to a database.

I know that technically this would be an integration test (not a unit test), but I want to find out the best strategies for the following:

Testing queries.

Testing inserts. How do I know that the insert that has gone wrong if it fails? I can test it by inserting and then querying, but how can I know that the query wasn't wrong?

Testing updates and deletes -- same as testing inserts

What are the best practices for doing these?

Regarding testing SQL: I am aware that this could be done, but if I use an O/R Mapper like NHibernate, it attaches some naming warts in the aliases used for the output queries, and as that is somewhat unpredictable I'm not sure I could test for that.

Should I just, abandon everything and simply trust NHibernate? I'm not sure that's prudent.

[A]
You do the unit testing by mocking out the database connection. This way, you can build scenarios where specific queries in the flow of a method call succeed or fail. I usually build my mock expectations so that the actual query text is ignored, because I really want to test the fault tolerance of the method and how it handles itself -- the specifics of the SQL are irrelevant to that end.
Obviously this means your test won't actually verify that the method
works
, because the SQL may be wrong. This is where integration tests kick in. For that, I expect someone else will have a more thorough answer, as I'm just beginning to get to grips with those myself.


q:
When looking beyond the RAD (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called Model-View-Controller, Model-View-Presenter and Model-View-ViewModel. My question has three parts to it:

What issues do these patterns address?

How are they similar?

How are they different?

[A]
Both of these frameworks aim to seperate concerns - for instance, interaction with a data source (model), application logic (or turning this data into useful information) (Controller/Presenter) and display code (View).  In some cases the model can also be used to turn a data source into a higher level abstraction as well.  A good example of this is the
MVC Storefront project
.
There is a discussion
here
regarding the differences between MVC vs MVP.
The distinction made is that in an MVC application traditionally has the view and the controller interact with the model, but not with each other.
MVP designs have the Presenter access the model and interact with the view.
Having said that, ASP.NET MVC is by these definitions an MVP framework because the Controller accesses the Model to populate the View which is meant to have no logic (just  displays the variables provided by the Controller).
To perhaps get an idea of the ASP.NET MVC distinction from MVP, check out
this MIX presentation
by Scott Hanselman.


q:
I want to get the MD5 Hash of a string value in SQL Server 2005. I do this with the following command:

SELECT HashBytes('MD5', 'HelloWorld')

However, this returns a VarBinary instead of a VarChar value. If I attempt to convert 0x68E109F0F40CA72A15E05CC22786F8E6 into a VarChar I get há ðô§*à\Â'†øæ instead of 68E109F0F40CA72A15E05CC22786F8E6.

Is there any SQL-based solution?

Yes

[A]
I have found the solution else where:
```
```
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)
```
```


q:
Checkboxes in HTML forms don't have implicit labels with them. Adding an explicit label (some text) next to it doesn't toggle the checkbox.

How do I make a checkbox toggle from clicking on the text label as well?

[A]
If you correctly markup your HTML code, there is no need for javascript. The following code will allow the user to click on the label text to tick the checkbox.
```
```
<label for="surname">Surname</label>
<input type="checkbox" name="surname" id="surname" />
```
```
The
for
attribute on the label element links to the
id
attribute on the input element and the browser does the rest.
This has been testing to work in:
IE6
IE7
Firefox


q:
I have come across a lot of optimization tips which say that you should mark your classes as sealed to get extra performance benefits.

I ran some tests to check the performance differential and found none. Am I doing something wrong? Am I missing the case where sealed classes will give better results?

Has anyone run tests and seen a difference?

Help me learn :)

[A]
The JITter will sometimes use non-virtual calls to methods in sealed classes since there is no way they can be extended further.
There are complex rules regarding calling type, virtual/nonvirtual, and I don't know them all so I can't really outline them for you, but if you google for sealed classes and virtual methods you might find some articles on the topic.
Note that any kind of performance benefit you would obtain from this level of optimization should be regarded as last-resort, always optimize on the algorithmic level before you optimize on the code-level.
Here's one link mentioning this:
Rambling on the sealed keyword


q:
Can a LINQ enabled app run on a machine that only has the .NET 2.0 runtime installed?

In theory, LINQ is nothing more than syntactic sugar, and the resulting IL code should look the same as it would have in .NET 2.0.

How can I write LINQ without using the .NET 3.5 libraries? Will it run on .NET 2.0?

[A]
No, because while you thought LINQ is really just syntactic sugar, it actually heavily used expression trees -- a feature absent in .NET 2.0.
That being said .NET 3.5 only builds up on top of .NET 2.0, and that's the reason why the IL doesn't look "different" or "special".
I do not see a reason why you shouldn't just install the .NET 3.5 Framework. Everything .NET 2.0 will work fine on it, promise :)


q:
Is there a way to create a JButton with your own button graphic and not just with an image inside the button?

If not, is there another way to create a custom JButton in java?

[A]
I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit
```
javax.swing.AbstractButton
```
and create your own. Should be pretty simple to wire something together with their existing framework.


q:
I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of FlexUnit but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist?

Also, are there any other resources on how to do Flex development "the right way" besides the Cairngorm microarchitecture example?

[A]
The
dpUint
testing framework has a test runner built with AIR which can be integrated with a build script.
There is also my
FlexUnit
automation kit which does more or less the same for FlexUnit. It has an Ant macro that makes it possible to run the tests as a part of an Ant script, for example:
```
```
<target name="run-tests" depends="compile-tests">
  <flexunit swf="${build.home}/tests.swf" failonerror="true"/>
</target>
```
```


q: How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?

[A]
I'm definitely not a Ruby expert, but I'll give it a shot:
```
```
$ irb
system "echo Hi"
Hi
=> true
```
```
You should also be able to do things like:
```
```
cmd = 'ls'
system(cmd)
```
```


q:
How do I rewrite a URL in ASP.NET?

I would like users to be able to go to

http://www.website.com/users/smith

instead of

http://www.website.com/?user=smith

[A]
Try the Managed Fusion Url Rewriter and Reverse Proxy:
http://urlrewriter.codeplex.com
The rule for rewriting this would be:
```
```
# clean up old rules and forward to new URL
RewriteRule ^/?user=(.*)  /users/$1 [NC,R=301]

# rewrite the rule internally
RewriteRule ^/users/(.*)  /?user=$1 [NC,L]
```
```


q:
I want to be able to do:

For Each thing In things
End For

CLASSIC ASP - NOT .NET!

[A]
Whatever your [things] are need to be written outside of VBScript.
In VB6,
you can write a Custom Collection class
, then you'll need to compile to an ActiveX DLL and register it on your webserver to access it.


q:
I see in the Stack Overflow footer that the SVN Revision number is displayed. Is this automated and if so, how does one implement it in ASP.NET?

(Solutions in other languages are acceptable)

[A]
Make sure that the file has s
```
vn:keywords "Rev Id"
```
and then put
```
$Rev$
```
somewhere in there.
See
this question and the answers to it
.


q:
In the code below

For i = LBound(arr) To UBound(arr)

What is the point in asking using LBound? Surely that is always 0.

[A]
Probably it comes from VB6. Because with
Option Base
statement in VB6, you can alter the lower bound of arrays like this:
```
```
Option Base 1
```
```
Also in VB6, you can alter the lower bound of a specific array like this:
```
```
Dim myArray(4 To 42) As String
```
```


q:
I've been able to find details on several self-balancing BSTs through several sources, but I haven't found any good descriptions detailing which one is best to use in different situations (or if it really doesn't matter).

I want a BST that is optimal for storing in excess of ten million nodes. The order of insertion of the nodes is basically random, and I will never need to delete nodes, so insertion time is the only thing that would need to be optimized.

I intend to use it to store previously visited game states in a puzzle game, so that I can quickly check if a previous configuration has already been encountered.

[A]
The two self-balancing
```
BST
```
s I'm most familiar with are red-black and
```
AVL
```
, so I can't say for certain if any other solutions are better, but as I recall, red-black has faster insertion and slower retrieval compared to
```
AVL
```
.
So if insertion is a higher priority than retrieval, red-black may be a better solution.


q:
What is actually the difference between these two casts?

SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;

Normally, shouldn't they both be explicit casts to the specified type?

[A]
The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception.
[Edit]
My original answer is certainly the most pronounced difference, but as Eric Lippert
points out
, it's not the only one. Other differences include:
You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value
You can't use 'as' to
convert
things, like numbers to a different representation (float to int, for example).
And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed."


q:
Jeff mentioned the concept of 'Progressive Enhancement' when talking about using JQuery to write stackoverflow.

After a quick Google, I found a couple of high-level discussions about it.

Can anyone recommend a good place to start as a programmer.

Specifically, I have been writing web apps in PHP and would like to use YUI to improve the pages I am writing, but a lot of them seem very JavaScript based, with most of the donkey work being done using JavaScript. To me, that seems a bit overkill, since viewing the site without Javascript will probably break most of it.

Anyone have some good places to start using this idea, I don't really care about the language.

Ideally, I would like to see how you start creating the static HTML first, and then adding the YUI (or whatever Ajax framework) to it so that you get the benefits of a richer client?

[A]
As you've said
To me, that seems a bit overkill, since viewing the site without Javascript will probably break most of it.
This isn't progressive enhancement. Progressive enhancement is when the site works perfectly without JavaScript or CSS, and
then
adding (layering) these extra technologies/code to increase the usability and functionality of the website.
The best example I can give is the tag input box on this website. With JavaScript turned off, it would still work allowing you to enter tags separated with a space. With JavaScript turned on, you get a drop down with suggestions of previous entries.
This is progressive enhancement.


q:
I have 2 SQLite databases, one downloaded from a server (server.db), and one used as storage on the client (client.db). I need to perform various sync queries on the client database, using data from the server database.

For example, I want to delete all rows in the client.db tRole table, and repopulate with all rows in the server.db tRole table.

Another example, I want to delete all rows in the client.db tFile table where the fileID is not in the server.db tFile table.

In SQL Server you can just prefix the table with the name of the database. Is there anyway to do this in SQLite using Adobe Air?

[A]
It's possible to open multiple databases at once in SQLite, but it's doubtful if can be done when working from Flex/AIR. In the command line client you run
```
ATTACH DATABASE path/to/other.db AS otherDb
```
and then you can refer to tables in that database as
```
otherDb.tableName
```
just as in MySQL or SQL Server.
Tables in an attached database can be referred to using the syntax database-name.table-name.
ATTACH DATABASE documentation at sqlite.org


q:
How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu.

I can't use the TreeViews' SelectedNode property because the node is only been right-clicked and not selected.

[A]
You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs.
```
```
void treeView1MouseUp(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Right)
    {
        // Select the clicked node
        treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);

        if(treeView1.SelectedNode != null)
        {
            myContextMenuStrip.Show(treeView1, e.Location);
        }
    }
}
```
```


q: How do you disable autocomplete in the major browsers for a specific input (or form field)?

[A]
Firefox 30 ignores
```
autocomplete="off"
```
for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following
commentary
from May 5, 2014:
The password manager
always
prompts if it wants to save a password. Passwords are not saved without permission from the user.
We are the third browser to implement this change, after IE and Chrome.
According to the
Mozilla Developer Network
documentation, the Boolean form element attribute
```
autocomplete
```
prevents form data from being cached in older browsers.
```
```
<input type="text" name="foo" autocomplete="off" />
```
```


q: What are good libraries for C with datastructures like vectors, deques, stacks, hashmaps, treemaps, sets, etc.? Plain C, please, and platform-independent.

[A]
As always, Google is your friend:
http://nixbit.com/cat/programming/libraries/c-generic-library/
specifically:
http://nixbit.com/cat/programming/libraries/generic-data-structures-library/


q: A quick glance at the present-day internet would seem to indicate that Adobe Flash is the obvious choice for embedding video in a web page.  Is this accurate, or are they other effective choices?  Does the choice of ASP.NET as a platform influence this decision?

[A]
Flash is certainly the most ubiquitous and portable solution.
98% of browsers
have Flash installed.  Other alternatives are
Quicktime
,
Windows Media Player
, or even
Silverlight
(Microsoft's Flash competitor, which can be used to embed several video formats).
I would recommend using Flash (and it's FLV video file format) for embedding your video unless you have very specific requirements as far as video quality or DRM.


q: Should be available to non-U.S. companies, easy to setup, reliable, cheap, customizable, etc. What are your experiences?

[A]
I'd say paypal or
GoogleCheckout
.
Google Checkout is either 2% + .20USD or free depending on how much you spend on adwords. If you spend a dollar on adWords, your next $10 on Google checkout is free.
Paypal
is 1.9% to 2.9% + $0.30 USD (2.9% for up to $30,000/month, 1.9% for more than $100,000/month)
Without factoring in the 20/30 cents, Paypal is just barely cheaper if you sell more than $100,000 per month, and spend nothing on adwords.


q:
Any good recommendations for a platform agnostic (i.e. Javascript) grid control/plugin that will accept pasted Excel data and can emit Excel-compliant clipboard data during a Copy?

I believe Excel data is formatted as CSV during "normal" clipboard operations.

dhtmlxGrid looks promising, but the online demo's don't actually copy contents to my clipboard!

[A]
Not an answer, but a warning: my company bought the 2007 Infragistics ASP.NET controls just for the Grid, and we regret that choice.
The quality of API is horrible (in our opinion at least), making it very hard to program against the grid (for example, inconsistent naming conventions, but this is just an inconvenience, we have complaints about the object model as well).
So I can't say that I know of a better option, I just know I will give a try to something else before paying for Infragistics products again (and the email support we got was horrible as well).


q:
Using SQL Server, how do I split a string so I can access item x?

Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?

[A]
You may find the solution in
SQL User Defined Function to Parse a Delimited String
helpful (from
The Code Project
).
You can use this simple logic:
```
```
Declare @products varchar(200) = '1|20|3|343|44|6|8765'
Declare @individual varchar(20) = null

WHILE LEN(@products) > 0
BEGIN
    IF PATINDEX('%|%', @products) > 0
    BEGIN
        SET @individual = SUBSTRING(@products,
                                    0,
                                    PATINDEX('%|%', @products))
        SELECT @individual

        SET @products = SUBSTRING(@products,
                                  LEN(@individual + '|') + 1,
                                  LEN(@products))
    END
    ELSE
    BEGIN
        SET @individual = @products
        SET @products = NULL
        SELECT @individual
    END
END
```
```


q:
When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data.  Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it).

I'll post the method that I use, but I'd like to see if there is a better way.

[A]
The OBJECT_ID function returns the internal object id for the given object name and type.  'tempdb..#t1' refers to the table #t1 in the tempdb database. 'U' is for user-defined table.
```
```
IF OBJECT_ID('tempdb..#t1', 'U') IS NOT NULL
  DROP TABLE #t1

CREATE TABLE #t1
(
  id INT IDENTITY(1,1),
  msg VARCHAR(255)
)
```
```


q:
I know I need to have (although I don't know why) a GROUP BY clause on the end of a SQL query that uses any aggregate functions like count, sum, avg, etc:

SELECT count(userID), userName
FROM users
GROUP BY userName

When else would GROUP BY be useful, and what are the performance ramifications?

[A]
Counting the number of times tags are used might be a google example:
```
```
SELECT TagName, Count(*)
AS TimesUsed
FROM Tags
GROUP BY TagName ORDER TimesUsed
```
```
If you simply want a distinct value of tags, I would prefer to use the
```
DISTINCT
```
statement.
```
```
SELECT DISTINCT TagName
FROM Tags
ORDER BY TagName ASC
```
```


q: I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks.

[A]
```
CREATE TABLE #tmpSizeChar (
     table_name sysname ,
     row_count int,
     reserved_size varchar(50),
     data_size varchar(50),
     index_size varchar(50),
     unused_size varchar(50))

CREATE TABLE #tmpSizeInt (
     table_name sysname ,
     row_count int,
     reserved_size_KB int,
     data_size_KB int,
     index_size_KB int,
     unused_size_KB int)

SET NOCOUNT ON
INSERT      #tmpSizeChar
EXEC      sp_msforeachtable 'sp_spaceused ''?'''

INSERT INTO #tmpSizeInt (
        table_name,
        row_count,
        reserved_size_KB,
        data_size_KB,
        index_size_KB,
        unused_size_KB
        )
SELECT  [table_name],
        row_count,
        CAST(SUBSTRING(reserved_size, 0, PATINDEX('% %', reserved_size)) AS int)reserved_size,
        CAST(SUBSTRING(data_size, 0, PATINDEX('% %', data_size)) AS int)data_size,
        CAST(SUBSTRING(index_size, 0, PATINDEX('% %', index_size)) AS int)index_size,
        CAST(SUBSTRING(unused_size, 0, PATINDEX('% %', unused_size)) AS int)unused_size
FROM #tmpSizeChar

/*
DROP TABLE #tmpSizeChar
DROP TABLE #tmpSizeInt
*/

SELECT * FROM #tmpSizeInt
ORDER BY reserved_size_KB DESC
```


q:
Can anyone explain this behavior?
Running:

#!/bin/sh
echo "hello world" | read var1 var2
echo $var1
echo $var2

results in nothing being ouput, while:

#!/bin/sh
echo "hello world" > test.file
read var1 var2 < test.file
echo $var1
echo $var2

produces the expected output:

hello
world

Shouldn't the pipe do in one step what the redirection to test.file did in the second example?  I tried the same code with both the dash and bash shells and got the same behavior from both of them.

[A]
It's because the pipe version is creating a subshell, which reads the variable into its local space which then is destroyed when the subshell exits.
Execute this command
```
```
$ echo $$;cat | read a
10637
```
```
and use pstree -p to look at the running processes, you will see an extra shell hanging off of your main shell.
```
```
|                       |-bash(10637)-+-bash(10786)
    |                       |             `-cat(10785)
```
```


q:
I'm wondering if it's a good idea to make verifications in getters and setters, or elsewhere in the code.

This might surprise you be when it comes to optimizations and speeding up the code, I think you should not make verifications in getters and setters, but in the code where you're updating your files or database. Am I wrong?

[A]
Validation should be captured separately from getters or setters in a validation method.  That way if the validation needs to be reused across multiple components, it is available.
When the setter is called, such a validation service should be utilized to sanitize input into the object.  That way you know all information stored in an object is valid at all times.
You don't need any kind of validation for the getter, because information on the object is already trusted to be valid.
Don't save your validation until a database update!! It is better to
fail fast
.


q:
Can anyone recommend any good add-ons or plugins for Microsoft Visual Studio?

Freebies are preferred, but if it is worth the cost then that's fine.

[A]
http://trolltech.com/products/qt/">Qt Cross-Platform Application Framework
Qt is a cross-platform application framework for desktop and embedded development. It includes an intuitive API and a rich C++ class library, integrated tools for GUI development and internationalization, and support for Java™ and C++ development
They have a plug-in for Visual Studio that costs a bit of money, but it is worth every penny.


q: When working on ASP.NET 1.1 projects I always used the Global.asax to catch all errors. I'm looking for a similar way to catch all exceptions in a Windows Forms user control, which ends up being a hosted IE control. What is the proper way to go about doing something like this?

[A]
You need to handle the
```
System.Windows.Forms.Application.ThreadException
```
event for Windows Forms. This article really helped me:
http://bytes.com/forum/thread236199.html
.


q:
Here's what I use:

SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME)

I'm thinking there may be a better and more elegant way.

Requirements:

It has to be as fast as possible (the less casting, the better).

The final result has to be a datetime type, not a string.

[A]
Your
```
CAST
```
-
```
FLOOR
```
-
```
CAST
```
already seems to be the optimum way, at least on MS SQL Server 2005.
Some other solutions I've seen have a string-conversion, like
```
Select Convert(varchar(11), getdate(),101)
```
in them, which is slower by a factor of 10.


q:
Let's say that we have an ARGB color:

Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.

When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is Color.FromARGB(255, 162, 133, 255);

The solution should work like this:

Color blend = Color.White;
Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255);

What is ToRGB's implementation?

[A]
It's called
alpha blending
.
In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255.
```
```
alpha=argb.alpha()
r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()
g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()
b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b()
```
```
note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly
Edited to add:
If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :).
In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).


q:
I started trying to play with Mono, mostly for fun at the moment.  I first tried to use the Visual Studio plugin that will convert a csproj into a makefile, but there seemed to be no version available for Visual Studio 2005. I also read about the MonoDevelop IDE, which sounded nice. Unfortunately, there's no pre-fab Windows package for it. I tried to follow some instructions to build it by combining dependencies from other semi-related installs. It didn't work, but that's probably because I'm a Windows-oriented guy and can barely spell "makefile".

So, my question is this: What's the lowest-energy way to get up and running to try some Mono-based development on Windows?

[A]
@Chris I have found that Visual Studio is the best IDE for developing against .NET -- I think the best way to target Mono is really just to develop and build in Visual Studio under Windows then just run those binaries directly on Linux (or whatever other Mono platform you are using).  There are free versions of Visual Studio if licensing is a concern.  If you are developing under Linux, the best software is probably Eclipse with a Mono plugin (see
The Mono Handbook - Eclipse
for installation instructions) but keep in mind it doesn't have near the amount of features or language integration Visual Studio has.
@modesty Mono is a 3rd party open source implementation of the .NET framework which allows you to run .NET applications on platforms other than Windows.


q:
I've always been intrigued by Map Routing, but I've never found any good introductory (or even advanced!) level tutorials on it. Does anybody have any pointers, hints, etc?

Update: I'm primarily looking for pointers as to how a map system is implemented (data structures, algorithms, etc).

[A]
Take a look at the
open street map project
to see how this sort of thing is being tackled in a truely free software project using only user supplied and licensed data and have a
wiki containing stuff you might find interesting
.
A few years back the guys involved where pretty easy going and answered lots of questions I had so I see no reason why they still aren't a nice bunch.


q:
I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc.

Unfortunately, I couldn't get the right set of cookies, etc, to make this work.  Any ideas?

Also, when the beta is finished, will my status page be accessible without logging in?

[A]
Nice idea :)
I presume you've used wget's
```
```
--load-cookies (filename)
```
```
might help a little but it might be easier to use something like Mechanize (in Perl or python) to mimic a browser more fully to get a good spider.


q:
How do I page results in SQL Server 2005?

I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method?

What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.

Any help would be much appreciated.

[A]
You can use
```
the Row_Number()
```
function.
Its used as follows:
```
```
SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName
FROM Users
```
```
From which it will yield a result set with a
```
RowID
```
field which you can use to page between.
```
```
SELECT *
FROM
    ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName
      FROM Users
    ) As RowResults
WHERE RowID Between 5 AND 10
```
```
etc


q:
#include <stdio.h>
int main() {
    unsigned long long int num = 285212672; //FYI: fits in 29 bits
    int normalInt = 5;
    printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt);
    return 0;
}

Output:

My number is 8 bytes wide and its value is 285212672l. A normal number is 0.

I assume this unexpected result is from printing the unsigned long long int. How do you printf() an unsigned long long int?

[A]
Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).
```
```
printf("%llu", 285212672);
```
```


q: I'm working on a project where I'm coding in C in a UNIX environment. I've been using the lint tool to check my source code. Lint has been around a long time (since 1979), can anyone suggest a more recent code analysis tool I could use ? Preferably a tool that is free.

[A]
For C code, you definitely should definitely use
Flexelint
.  I used it for nearly 15 years and swear by it.  One of the really great features it has is that warnings can be selectively turned off and on via comments in the code ("/* lint -e123*/").  This turned out to be a powerful documentation tool when you wanted to something out of the ordinary.  "I am turning off warning X, therefore, there is some good reason I'm doing X."
For anybody into interesting C/C++ questions, look at some of their examples on their site and see if you can figure out the bugs without looking at the hints.


q:
Does anyone have some good hints for writing test code for database-backend development where there is a heavy dependency on state?

Specifically, I want to write tests for code that retrieve records from the database, but the answers will depend on the data in the database (which may change over time).

Do people usually make a separate development system with a 'frozen' database so that any given function should always return the exact same result set?

I am quite sure this is not a new issue, so I would be very interested to learn from other people's experience.

Are there good articles out there that discuss this issue of web-based development in general?

I usually write PHP code, but I would expect all of these issues are largely language and framework agnostic.

[A]
You should look into DBUnit, or try to find a PHP equivalent (there must be one out there).  You can use it to prepare the database with a specific set of data which represents your test data, and thus each test will no longer depend on the database and some existing state.  This way, each test is self contained and will not break during further database usage.
Update: A quick google search showed a
DB unit extension
for PHPUnit.


q:
Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening.

What methods can the calling window use to make sure the new window launched properly?

[A]
If you use JavaScript to open the popup, you can use something like this:
```
```
var newWin = window.open(url);

if(!newWin || newWin.closed || typeof newWin.closed=='undefined')
{
    //POPUP BLOCKED
}
```
```


q:
I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus).

What is the best way to go about this using the win32 API?  I have tried SetForeground() but it always steals focus and does not consistenly work.

What is the best way to go about this? Any thoughts?

[A]
SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail.
The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window
Try capturing the focus with
SetCapture
prior to making the call. Also look into different ways of bringing the window to the front: SetForeGroundWindow, SetActiveWindow, even simulating a mouse click can do this.


q:
What are the most common problems that can be solved with both these data structures?

It would be good for me to have also recommendations on books that:

Implement the structures

Implement and explain the reasoning of the algorithms that use them

[A]
There's a course for such things at my university:
CSE 326
. I didn't think the book was too useful, but the projects are fun and teach you a fair bit about implementing some of the simpler structures.
As for examples, one of the most common problems (by number of people using it) that's solved with trees is that of cell phone text entry. You can use trees, not necessarily binary, to represent the space of possible words that can come out of any given list of numbers that a user punches in very quickly.


q:
One of the topics that seems to come up regularly on mailing lists and online discussions is the merits (or lack thereof) of doing a Computer Science Degree. An argument that seems to come up time and again for the negative party is that they have been coding for some number of years and they have never used recursion.

So the question is:

What is recursion?

When would I use recursion?

Why don't people use recursion?

[A]
A function that calls itself
When a function can be (easily) decomposed into a simple operation plus the same function on some smaller portion of the problem. I should say, rather, that this makes it a good candidate for recursion.
They do!
The canonical example is the factorial which looks like:
```
```
int fact(int a)
{
  if(a==1)
    return 1;

  return a*fact(a-1);
}
```
```
In general, recursion isn't necessarily fast (function call overhead tends to be high because recursive functions tend to be small, see above) and can suffer from some problems (stack overflow anyone?). Some say they tend to be hard to get 'right' in non-trivial cases but I don't really buy into that. In some situations, recursion makes the most sense and is the most elegant and clear way to write a particular function. It should be noted that some languages favor recursive solutions and optimize them much more (LISP comes to mind).


q:
If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys?  I have heard that using each may in some way have unintended side effects.  So, is that true, and is one of the two following methods best, or is there a better way?

# Method 1
while (my ($key, $value) = each(%hash)) {
    # Something
}

# Method 2
foreach my $key (keys(%hash)) {
    # Something
}

[A]
I may get bitten by this one but I think that it's personal preference.  I can't find any reference in the docs to each() being different than keys() or values() (other than the obvious "they return different things" answer.  In fact the docs state the use the same iterator and they all return actual list values instead of copies of them, and that modifying the hash while iterating over it using any call is bad.
All that said, I almost always use keys() because to me it is usually more self documenting to access the key's value via the hash itself.  I occasionally use values() when the value is a reference to a large structure and the key to the hash was already stored in the structure, at which point the key is redundant and I don't need it.  I think I've used each() 2 times in 10 years of Perl programming and it was probably the wrong choice both times =)


q:
Problem:

I have two spreadsheets that each serve different purposes but contain one particular piece of data that needs to be the same in both spreadsheets.  This piece of data (one of the columns) gets updated in spreadsheet A but needs to also be updated in spreadsheet B.

Goal:

A solution that would somehow link these two spreadsheets together (keep in mind that they exist on two separate LAN shares on the network) so that when A is updated, B is automatically updated for the corresponding record.

*Note that I understand fully that a database would probably be a better plan for tasks such as these but unfortunately I have no say in that matter.

**Note also that this needs to work for Office 2003 and Office 2007

[A]
So you mean that AD743 on spreadsheet B must be equal to AD743 on spreadsheet A?  Try this:
Open both spreadsheets on the same
machine.
Go to AD743 on spreadsheet B.
Type =.
Go to spreadsheed A and click on
AD743.
Press enter.
You'll notice that the formula is something like '
[path-to-file+file-name].worksheet-name!AD743
'.
The value on spreadsheet B will be updated when you open it.  In fact, it will ask you if you want to update.  Of course, your connection must be up and running for it to update.  Also, you can't change the name or the path of spreadsheet A.