q:
My gut feel is that document based web services are preferred in practice - is this other peoples experience? Are they easier to support? (I noted that SharePoint uses Any for the "document type" in its WSDL interface, I guess that makes it Document based).

Also - are people offering both WSDL and Rest type services now for the same functionality? WSDL is popular for code generation, but for front ends like PHP and Rails they seem to prefer rest.

[A]
Document versus RPC is only a question if you are using SOAP Web Services which require a service description (
WSDL
). RESTful web services do not not use WSDL because the service can't be described by it, and the feeling is that REST is simpler and easier to understand. Some people have proposed
WADL
as a way to describe REST services.
Languages like Python, Ruby and PHP make it easier to work with REST. the WSDL is used to generate C# code (a web service proxy) that can be easily called from a static language. This happens when you add a
Service Reference
or
Web Reference
in Visual Studio.
Whether you provide SOAP or REST services depends on your user population. Whether the services are to be used over the internet or just inside your organization affects your choice. SOAP may have some features (WS-* standards) that work well for B2B or internal use, but suck for an internet service.
Document/literal versus RPC for SOAP services are described on this
IBM DevelopWorks article
. Document/literal is generally considered the best to use in terms of interoperability (Java to .NET etc). As to whether it is easier to support, that depends on your circumstances. My personal view is that people tend to make this stuff more complicated than it needs to be, and REST's simpler approach is superior.


q:
I want some links to include a fragment identifier. Like some of the URLs on this site:

Debugging: IE6 + SSL + AJAX + post form = 404 error#5626

Is there a way to do this with any of the built-in methods in MVC? Or would I have to roll my own HTML helpers?

[A]
The short answer is: No. In ASP.NET MVC Preview 3 there's no first-class way for including an anchor in an action link. Unlike Rails' url_for :anchor, UrlHelper.GenerateUrl (and ActionLink, RedirectToAction and so on which use it) don't have a magic property name that lets you encode an anchor.
As you point out, you could roll your own that does. This is probably the cleanest solution.
Hackily, you could just include an anchor in a route and specify the value in your parameters hash:
```
```
routes.MapRoute("WithTarget", "{controller}/{action}/{id}#{target}");
...
<%= Html.ActionLink("Home", "Index", new { target = "foo" })%>
```
```
This will generate a URL like /Home/Index/#foo. Unfortunately this doesn't play well with URL parameters, which appear at the end of the URL. So this hack is only workable in really simple circumstances where all of your parameters appear as URL path components.

s: huggingface

c: devops

d: intermediate


q:
The StackOverflow transcripts are enormous, and sometimes I want to link to a little bit within it.

How do I create an HTML anchor in a FogBugz wiki page?

[A]
According to
this support message
, the feature is not yet currently implemented:
The FogBugz wiki does not currently support anchors within a document, unfortunately.  It's definitely on the list of features we're considering for the next release, though.


q:
I'm not sure if it's my system, although I haven't done anything unusual with it, but I've started noticing incorrectly rendered characters popping up in web pages, text-files, like this:

http://www.kbssource.com/strange-characters.gif

I have a hunch it's a related to the fairly recent trend to use unicode for everything, which is a good thing I think, combined with fonts that don't support all possible characters.

So, does anyone know what's causing these blips (am I right?), and how do I stop this showing up in my own content?

[A]
It appears that for this particular author, the text was edited in some editor that assumed it wasn't UTF8, and then re-wrote it out in UTF8. I'm basing this off the fact that if I tell my browser to interpret the page as different common encodings, none make it display correctly. This tells me that some conversion was done at some point improperly.
The only problem with UTF8 is that there isn't a standardized way to recognize that a file is UTF8, and until all editors are standardizing on UTF8, there will still be conversion errors. For other unicode variants, a Byte Order Mark (BOM) is fairly standard to help identify a file, but BOMs in UTF8 files are pretty rare.
To keep it from showing up in your content, make sure you're always using unicode-aware editors, and make sure that you always open your files with the proper encodings. It's a pain, unfortunately, and errors will occasionally crop up. The key is just catching them early so that you can undo it or make a few edits.


q:
I got this error today when trying to open a Visual Studio 2008 project in Visual Studio 2005:

The imported project "C:\Microsoft.CSharp.targets" was not found.

[A]
Open your csproj file in notepad (or notepad++)
Find the line:
```
```
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
```
```
and change it to
```
```
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
```
```


q:
Why are pointers such a leading factor of confusion for many new, and even old, college level students in C or C++?  Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level?

What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill like scenarios.

[A]
Why are pointers such a leading factor of confusion for many new, and even old, college level students in the C/C++ language?
The concept of a placeholder for a value - variables - maps onto something we're taught in school - algebra.  There isn't an existing parallel you can draw without understanding how memory is physically laid out within a computer, and no one thinks about this kind of thing until they're dealing with low level things - at the C/C++/byte communications level.
Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level?
Addresses boxes.  I remember when I was learning to program BASIC into microcomputers, there were these pretty books with games in them, and sometimes you had to poke values into particular addresses.  They had a picture of a bunch of boxes, incrementally labelled with 0, 1, 2... and it was explained that only one small thing (a byte) could fit in these boxes, and there were a lot of them - some computers had as many as 65535!  They were next to each other, and they all had an address.
What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill like scenarios.
For a drill?  Make a struct:
```
```
struct {
char a;
char b;
char c;
char d;
} mystruct;
mystruct.a = 'r';
mystruct.b = 's';
mystruct.c = 't';
mystruct.d = 'u';

char* my_pointer;
my_pointer = &mystruct.b;
cout << 'Start: my_pointer = ' << *my_pointer << endl;
my_pointer++;
cout << 'After: my_pointer = ' << *my_pointer << endl;
my_pointer = &mystruct.a;
cout << 'Then: my_pointer = ' << *my_pointer << endl;
my_pointer = my_pointer + 3;
cout << 'End: my_pointer = ' << *my_pointer << endl;
```
```
Same example as above, except in C:
```
```
// Same example as above, except in C:
struct {
    char a;
    char b;
    char c;
    char d;
} mystruct;

mystruct.a = 'r';
mystruct.b = 's';
mystruct.c = 't';
mystruct.d = 'u';

char* my_pointer;
my_pointer = &mystruct.b;

printf("Start: my_pointer = %c\n", *my_pointer);
my_pointer++;
printf("After: my_pointer = %c\n", *my_pointer);
my_pointer = &mystruct.a;
printf("Then: my_pointer = %c\n", *my_pointer);
my_pointer = my_pointer + 3;
printf("End: my_pointer = %c\n", *my_pointer);
```
```
Output:
```
```
Start: my_pointer = s
After: my_pointer = t
Then: my_pointer = r
End: my_pointer = u
```
```
Perhaps that explains some of the basics through example?


q:
Using Firebug v1.20b7 with Firefox v3.0.1 I use firebug a lot for web devlopment.

I have very often the problem that Firebug won't show its web console for seeing the POSTs and GETs. I can view all the other tabs, including the NET tab that gives me a lot of the same information that the CONSOLE tab does.

Curious if anyone else has had this problem, and maybe a solution, or maybe this is a bug of Firebug.

[A]
Well, 1.20b7 is technically a
beta
version of Firebug. :)
I've had problems with certain features off and on, but a restart of Firefox seems to fix it more often than not.


q:
I just moved over to the Visual Basic team here at work.

What is the equivalent keyword to break in Visual Basic, that is, to exit a loop early but not the method?

[A]
In both Visual Basic 6.0 and
VB.NET
you would use:
```
Exit For
```
to break from For loop
```
Wend
```
to break from While loop
```
Exit Do
```
to break from Do loop
depending on the loop type. See
Exit Statements
for more details.


q:
How do I escape the underscore character?

I am writing something like the following where clause and want to be able to find actual entries with _d at the end.

Where Username Like '%_d'

[A]
T-SQL Reference for LIKE
:
You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters.
For your case:
```
```
... LIKE '%[_]d'
```
```


q:
How do I turn the following 2 queries into 1 query

$sql    = "SELECT level FROM skills WHERE id = $id LIMIT 1;";
$result = $db->sql_query($sql);
$level  = (int) $db->sql_fetchfield('level');
$db->sql_freeresult($result);

++$level;

$sql    = "UPDATE skills SET level = $level WHERE id = $id;";
$result = $db->sql_query($sql);
$db->sql_freeresult($result);

I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query.

Edit: $id has already been forced to be an integer, thus no escaping is needed this time.

[A]
I get downmodded for this?
```
```
$sql = "UPDATE skills SET level = level+1 WHERE id = $id";
$result = $db->sql_query($sql);
$db->sql_freeresult($result);
```
```
In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL.
In the general case, you should not use NULL to represent zero.  Incrementing NULL
should
give an answer of NULL. If you're the kind of misguided developer who thinks NULL=0, step away from keyboard and find another pastime, you're just making life hard for the rest of us. Of course, this is the computer industry and who are we to say you're wrong? If you're not wrong, use
```
```
$sql = "UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id";
```
```
...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include
```
```
level INT DEFAULT '0' NOT NULL
```
```
in case the programmers forget to set it when they create a record.  If not everyone starts on level 0, then skip the DEFAULT and force the programmer to supply a value on creation. If some people are beyond levels, for whom having a level is a meaningless thing, then adding one to their level equally has no meaning.  In that case, drop the NOT NULL from the DDL.


q:
This gets the value of whatever is selected in my dropdown menu.

document.getElementById('newSkill').value

I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at W3Schools but that didn't have the answer, does anybody here know?

For those not sure, here's the HTML for a drop down box.

<select name="newSkill" id="newSkill">
    <option value="1">A skill</option>
    <option value="2">Another skill</option>
    <option value="3">Yet another skill</option>
</select>

[A]
Does this get the correct answer?
```
```
document.getElementById("newSkill").innerHTML
```
```


q: For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions?  (or if any other IDE has something similar...)

[A]
I use
Textmate
(Mac only) which has Code folding and I find it really useful for folding functions, I know what my "getGet" function does, I don't need it taking up 10 lines of oh so valuable screen space.
I never use it to hide a for loop, if statement or similar unless showing the code to someone else where I will hide code they have seen to avoid showing the same code twice.


q:
Does anyone know why when using BindingUtils on the selectedItem property of a ComboBox you get the following warning? Any ideas how to resolve the issue?

The binding still works properly, but it would be nice to get rid of the warning.

warning: multiple describeType entries for 'selectedItem' on type 'mx.controls::ComboBox':
<accessor name="selectedItem" access="readwrite" type="Object" declaredBy="mx.controls::ComboBase">
  <metadata name="Bindable">
    <arg key="" value="valueCommit"/>
  </metadata>

[A]
Here is the code. It is basically a copy of BindingUtils.bindProperty that is setup for a ComboBox so that both the combo box and the model are updated when either of the two change.
```
```
public static function bindProperty2(site:Object, prop:String, host:Object, chain:Object, commitOnly:Boolean = false):ChangeWatcher
{
    var cbx:ComboBox = null;
    if ( site is ComboBox ) { cbx = ComboBox(site); }
    if ( host is ComboBox ) { cbx = ComboBox(host); }
    var labelField:String = "listID";

    var w:ChangeWatcher = ChangeWatcher.watch(host, chain, null, commitOnly);

    if (w != null)
    {
        var func:Function;

        if ( site is ComboBox )
        {
            func = function(event:*):void
            {
                var dp:ICollectionView = ICollectionView(site.dataProvider);
                var selItem:Object = null;

                for ( var i:int=0; i<dp.length; i++ )
                {
                    var obj:Object = dp[i];
                    if ( obj.hasOwnProperty(labelField) )
                    {
                        var val:String = String(obj[labelField]);
                        if ( val == w.getValue() )
                        {
                            selItem = obj;
                            break;
                        }
                    }
                }

                site.selectedItem = selItem;
            };

            w.setHandler(func);
            func(null);
        }
        else
        {
            func = function(event:*):void
            {
                var value:Object = w.getValue();
                if ( value == null )
                {
                    site[prop] = null;
                }
                else
                {
                    site[prop] = String(w.getValue()[labelField]);
                }
            };
            w.setHandler(func);
            func(null);
        }
    }

    return w;
}
```
```


q:
If I have .Net Form with a component/object such as a textbox that I need to access from a parent or other form I obviously need to "upgrade" the modifier to this component to an Internal or Public level variable.

Now, if I were providing a public variable of an int or string type etc. in my form class I wouldn't think twice about using Getters and (maybe) Setters around this, even if they didn't do anything other than provide direct access to the variable.

However, the VS designer doesn't seem to implement such Getters/Setters for those public objects that are components on a form (and therefore does not comply with good programming practice).

So, the question is; In order to do the "right thing" should I wrap such VS designer components or objects in a Getter and/or Setter?

[A]
I always do that, and if you ARE following an MVP design creating getter/setters for your view components would be a design requirement.
I do not understand what you mean by "does not comply with good programming practice". Microsoft violates
a lot
of good programming practices to make it easier to create stuff on Visual Studio (for the sake of rapid app development) and I do not see the lack of getters/setters for controls as evidence of violating any such best practices.


q:
How do I make Log4net only log Info level logs? Is that even possible? Can you only set a threshold?

This is what I have, and it logs Info and above as I would expect. Is there anything i can do to make it only log info?

<logger name="BrokerCollection.Model.XmlDocumentCreationTask">
  <appender-ref ref="SubmissionAppender"/>
  <level value="Info" />
</logger>

[A]
Within the definition of the appender, I believe you can do something like this:
```
```
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="INFO"/>
    </filter>
    ...
</appender>
```
```


q:
I'm using subclipse in Flex Builder 3, and recently received this error when trying to commit:

svn: Checksum mismatch for '/Users/redacted/Documents/Flex Builder 3/path/to/my/file.mxml'; expected: 'f8cb275de72776657406154dd3c10348', actual: 'null'

I worked around it by:

Committing all the other changed files, omitting the troublesome one.

Copying the contents of the trouble file to a TextMate window

Deleting my project in FlexBuilder/Eclipse

Checking my project out fresh from SVN

Copying the text of the trouble file back in from the TextMate Window

Committing the changes.

It worked, but I can't help but think there's a better way. What's actaully happening to cause the svn:checksum error, and what's the best fix.

Maybe more important -- is this a symptom of a greater problem?

[A]
The file in the .svn directory that keeps track of what you have checked out, when, what revision, and from where, has gotten corrupted somehow, for that particular file.
This is no more dangerous or critical than the normal odd file problem, and can be because of various problems, like a subversion program dying mid-change, power-disruption, etc.
Unless it happens more I wouldn't make much out of it.
It can be fixed by doing what you did, make a copy of your work-files, check out a fresh copy, and add the modified files back in.
Note that this might cause problems if you have a busy project where you would normally have to merge in changes.
For instance, you and a collegue both check out a fresh copy, and start working on the same file. At some point, your collegue checks in his modifications. When you attempt to do the same, you get the checksum problem you have. If you now make copies of your changed files, do a fresh checkout, then subversion will lose track of how your changes should be merged back in.
If you didn't get the problem in this case, when you got around to checkin in your modifications, you would need to update your working copy first, and possibly handle a conflict with your file.
However, if you do a fresh checkout, complete with your collegues changes, it now looks like you removed his changes and substituted with your own. No conflicts, and no indications from subversion that something is amiss.


q: What kinds of hook scripts are people using for Subversion? Just general ideas but code would be great too!

[A]
The most common one I think is to allow people to change revision comments after comitting.
You need to enable the 'pre-revprop-change' hook script to allow that. The example provided, if enabled allows editing only the comment property and only be the original comitter. Great for correcting typos.


q:
I'm looking for a .NET regular expression extract all the URLs from a webpage but haven't found one to be comprehensive enough to cover all the different ways you can specify a link.

And a side question:

Is there one regex to rule them all? Or am I better off using a series of less complicated regular expressions and just using mutliple passes against the raw HTML? (Speed vs. Maintainability)

[A]
Look at the URI specification. That could help you a lot. And as far as performance goes, you can pretty much extract all the HTTP links in a modest web page. When I say modest I definitely do not mean one page all encompassing HTML manuals like that of ELisp manual. Also performance is a touchy topic. My advice would be to measure your performance and then decide if you are going to extract all the links using one single regex or with multiple simpler regex expressions.
http://gbiv.com/protocols/uri/rfc/rfc3986.html


q:
Given a string like this:

a,"string, with",various,"values, and some",quoted

What is a good algorithm to split this based on commas while ignoring the commas inside the quoted sections?

The output should be an array:

[ "a", "string, with", "various", "values, and some", "quoted" ]

[A]
Of course using a CSV parser is better but just for the fun of it you could:
```
```
Loop on the string letter by letter.
    If current_letter == quote :
        toggle inside_quote variable.
    Else if (current_letter ==comma and not inside_quote) :
        push current_word into array and clear current_word.
    Else
        append the current_letter to current_word
When the loop is done push the current_word into array
```
```


q:
Is anyone successfully using the latest 64-bit Ganymede release of Eclipse on Windows XP or Vista 64-bit?

Currently I run the normal Eclipse 3.4 distribution on a 32bit JDK and launch & compile my apps with a 64bit JDK. Our previous experience has been that the 64bit Eclipse distro is unstable for us, so I'm curious if anyone is using it successfully.

We are using JDK 1.6.0_05.

[A]
I've been successfully using it on Vista x64 for some light Java work.  Nothing too involved and no extra plugins, but basic Java coding has been working without any issues.  I'm using the 3.4M7 build but it looks like the
3.4 stable build
supports Vista x64 now.


q:
Why is Array.Length an int, and not a uint. This bothers me (just a bit) because a length value can never be negative.

This also forced me to use an int for a length-property on my own class, because when you
specify an int-value, this needs to be cast explicitly...

So the ultimate question is: is there any use for an unsigned int (uint)? Even Microsoft seems not to use them.

[A]
Typically, integer values are signed, unless you explicitly need an unsigned value. It's just the way they are used. I may not agree with that choice, but that's just the way it is.
For the time being, with todays typical memory constraints, if your array or similar data structure needs an UInt32 length, you should consider other data structures.
With an array of bytes, Int32 will give you 2GB of values


q:
Why are unsigned integers not CLS compliant?

I am starting to think the type specification is just for performance and not for correctness.

[A]
Not all languages have the concept of unsigned ints. For example VB 6 had no concept of unsigned ints which I suspect drove the decision of the designers of VB7/7.1 not to implement as well (it's implemented now in VB8).
To quote:
http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx
The CLS was designed to be large enough to include the language
constructs that are commonly needed by developers, yet small enough
that most languages are able to support it. In addition, any language
construct that makes it impossible to rapidly verify the type safety
of code was excluded from the CLS so that all CLS-compliant languages
can produce verifiable code if they choose to do so.
Update: I did wonder about this some years back, and whilst I can't see why a UInt wouldn't be type safety verifiable, I guess the CLS guys had to have a cut off point somewhere as to what would be the baseline minimum number of value types supported. Also when you think about the longer term where more and more languages are being ported to the CLR why force them to implement unsigned ints to gain CLS compliance if there is absolutely no concept, ever?


q:
I have the following html.erb code that I'm looking to move to Haml:

<span class="<%= item.dashboardstatus.cssclass %>" ><%= item.dashboardstatus.status %></span>

What it does is associate the CSS class of the currently assigned status to the span.

How is this done in Haml? I'm sure I'm missing something really simple.

[A]
Not sure. Maybe:
```
```
%span{:class => item.dashboardstatus.cssclass }= item.dashboardstatus.status
```
```


q:
So I have a Sybase stored proc that takes 1 parameter that's a comma separated list of strings and runs a query with in in an IN() clause:

CREATE PROCEDURE getSomething @keyList varchar(4096)
AS
SELECT * FROM mytbl WHERE name IN (@keyList)

How do I call my stored proc with more than 1 value in the list?
So far I've tried

exec getSomething 'John'         -- works but only 1 value
exec getSomething 'John','Tom'   -- doesn't work - expects two variables
exec getSomething "'John','Tom'" -- doesn't work - doesn't find anything
exec getSomething '"John","Tom"' -- doesn't work - doesn't find anything
exec getSomething '\'John\',\'Tom\'' -- doesn't work - syntax error

EDIT: I actually found this page that has a great reference of the various ways to pas an array to a sproc

[A]
Do you need to use a comma separated list? The last couple of years, I've been taking this type of idea and passing in an XML file. The openxml "function" takes a string and makes it like xml and then if you create a temp table with the data, it is queryable.
```
```
DECLARE @idoc int
DECLARE @doc varchar(1000)
SET @doc ='
<ROOT>
<Customer CustomerID="VINET" ContactName="Paul Henriot">
   <Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00">
      <OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>
      <OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>
   </Order>
</Customer>
<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
   <Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">
      <OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>
   </Order>
</Customer>
</ROOT>'
--Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
-- Execute a SELECT statement that uses the OPENXML rowset provider.
SELECT    *
FROM       OPENXML (@idoc, '/ROOT/Customer',1)
            WITH (CustomerID  varchar(10),
                  ContactName varchar(20))
```
```


q:
There are two popular closure styles in javascript. The first I call anonymous constructor:

new function() {
  var code...
}

and the inline executed function:

(function() {
  var code...
})();

are there differences in behaviour between those two? Is one "better" over the other?

[A]
@Lance: the first one is also executing. Compare it with a named constructor:
```
```
function Blah() {
    alert('blah');
}
new Bla();
```
```
this is actually also executing code. The same goes for the anonymous constructor...
But that was not the question ;-)


q:
In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?

Example:

foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}

[A]
```
break
```
would stop the
```
foreach
```
loop completely,
```
continue
```
would skip to the next
```
DataRow
```
.


q:
I'm suddenly back to WinForms, after years of web development, and am having trouble  with something that should be simple.  I have an ArrayList of business objects bound to a  Windows Forms DataGrid.  I'd like the user to be able to edit the cells, and when finished,  press a Save button.  At that point I'd like to iterate the all the rows and columns in the  DataGrid to find any changes, and save them to the database.  But I can't find a way to  access the DataGrid rows.

I'll also want to validate individual cells real time, as they are edited, but I'm pretty  sure that can be done.  (Maybe not with an ArrayList as the DataSource?)  But as for iterating the DataGrid, I'm quite surprised it doesn't seem possible.

Must I really stuff my business objects data into datatables in order to use the datagrid?


q:
One of those classic programming interview questions...

You are given two marbles, and told that they will break when dropped from some certain height (and presumably suffer no damage if dropped from below that height). You’re then taken to a 100 story building (presumably higher than the certain height), and asked to find the highest floor your can drop a marble from without breaking it as efficiently as possible.

Extra info

You must find the correct floor (not a possible range)

The marbles are both guaranteed to break at the same floor

Assume it takes zero time for you to change floors - only the number of marble drops counts

Assume the correct floor is randomly distributed in the building

[A]
They each break when dropped from the same height, or are they different?
If they're the same, I go to the 50th floor and drop the first marble.  If it doesn't break, I go to the 75th floor and do the same, as long as it keeps not breaking I keep going up by 50% of what's left.  When it does break, I go back to one higher than where I was previously (so if it broke at the 75th floor I go back to the 51st floor) and drop the second marble and move up a floor at a time until it breaks, at which point I know the highest floor I can drop from with no marble breakage.
Probably not the best answer, I'm curious to see how others answer.


q:
It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.

List<string> sl = new List<string>();
List<object> ol;
ol = sl;

results in Cannot implicitly convert type System.Collections.Generic.List<string> to System.Collections.Generic.List<object>

And then...

List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;

results in Cannot convert type System.Collections.Generic.List<string> to System.Collections.Generic.List<object>

Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.

[A]
The reason is that a generic class like
```
List<>
```
is, for most purposes, treated externally as a normal class. e.g. when you say
```
List<string>()
```
the compiler says
```
ListString()
```
(which contains strings). [Technical folk: this is an extremely plain-English-ified version of what's going on]
Consequently, obviously the compiler can't be smart enough to convert a ListString to a ListObject by casting the items of its internal collection.
That's why there's extension methods for IEnumerable like Convert() that allow you to easily supply conversion for the items stored inside a collection, which could be as simple as casting from one to another.


q:
I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's malloc and free concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet.

How do release, retain and autorelease work and what are the conventions about their use?

(Or failing that, what did you read which helped you get it?)

[A]
Objective-C uses
Reference Counting
, which means each Object has a reference count. When an object is created, it has a reference count of "1". Simply speaking, when an object is referred to (ie, stored somewhere), it gets "retained" which means its reference count is increased by one. When an object is no longer needed, it is "released" which means its reference count is decreased by one.
When an object's reference count is 0, the object is freed. This is basic reference counting.
For some languages, references are automatically increased and decreased, but objective-c is not one of those languages. Thus the programmer is responsible for retaining and releasing.
A typical way to write a method is:
```
```
id myVar = [someObject someMessage];
.... do something ....;
[myVar release];
return someValue;
```
```
The problem of needing to remember to release any acquired resources inside of code is both tedious and error-prone. Objective-C introduces another concept aimed at making this much easier: Autorelease Pools. Autorelease pools are special objects that are installed on each thread. They are a fairly simple class, if you look up NSAutoreleasePool.
When an object gets an "autorelease" message sent to it, the object will look for any autorelease pools sitting on the stack for this current thread. It will add the object to the list as an object to send a "release" message to at some point in the future, which is generally when the pool itself is released.
Taking the code above, you can rewrite it to be shorter and easier to read by saying:
```
```
id myVar = [[someObject someMessage] autorelease];
... do something ...;
return someValue;
```
```
Because the object is autoreleased, we no longer need to explicitly call "release" on it. This is because we know some autorelease pool will do it for us later.
Hopefully this helps. The Wikipedia article is pretty good about reference counting. More information about
autorelease pools can be found here
. Also note that if you are building for Mac OS X 10.5 and later, you can tell Xcode to build with garbage collection enabled, allowing you to completely ignore retain/release/autorelease.


q:
I'm a new Windows programmer and I'm not sure where I should store user configurable application settings.  I understand the need to provide a user friendly means for the user to change application settings, like an Edit | Settings form or similar.  But where should I store the values after the user hits the Apply button on that form?

What are the pros and cons of storing settings in the Windows registry vs. storing them in a local INI file or config file or similar?

[A]
Pros of config file:
Easy to do. Don't need to know any Windows API calls. You just need to know the file I/O interface of your programming language.
Portable. If you port your application to another OS, you don't need to change your settings format.
User-editable. The user can edit the config file outside of the program executing.
Pros of registry:
Secure. The user can't accidentally delete the config file or corrupt the data unless he/she knows about regedit. And then the user is just asking for trouble.
I'm no expert Windows programmer, but I'm sure that using the registry makes it easier to do other Windows-specific things (user-specific settings, network administration stuff like group policy, or whatever else).
If you just need a simple way to store config information, I would recommend a config file, using INI or XML as the format. I suggest using the registry only if there is something specific you want to get out of using the registry.


q: What are some of the best or most popular rule engines?  I haven't settled on a programming language, so tell me the rule engine and what programming languages it supports.

[A]
I have a bit of experience with both Haley Expert Rules and Haley Office Rules. Both nice systems, but I'd need to know a bit more abut what you want to use them for to answer definitively (See
http://www.haley.com
)
They both support C# and Java (and I think also a web service api).
The difference between the two is mostly around how much natural language modelling you want to get into. Office rules lets business users write rules in an Office document, and is mostly focused around legislative requirements modelling. Expert rules can be a bit more flexible in definition how it handles natural language, but requires more work defining language structures up front.
Hope some of that helps.


q:
I have inherited some legacy PHP code what was written back when it was standard practice to use register_globals (As of PHP 4.2.0, this directive defaults to off, released 22. Apr 2002).

We know now that it is bad for security to have it enabled. The problem is how do I find all the places in the code where I need to use $_GET or $_POST? My only thought was to set the error reporting to warn about uninitialized variables and then test each part of the site. Is there an easier way? Will I have to test each code path in the site or will PHP give a warning on a file basis?

[A]
I know that there's a way to set php.ini values for that script with a certain command, I thus went looking and found this too -
Goto last post on page
I also found the following post which may be of use -
Goto last post on the page
I will add to this more if nobody has found an answer but I must now catch a train.


q: How should I load files into my Java application?

[A]
The short answer
Use one of these two methods:
```
Class.getResource(String)
```
```
Class.getResourceAsStream(String)
```
For example:
```
```
InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg");
```
```
--
The long answer
Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:
```
```
File file = new File("C:\\Users\\Joe\\image.jpg");
```
```
This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.
Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).
Instead, use the
```
getResource()
```
methods in the
```
Class
```
class. This makes the application much more portable. It  can be moved to different platforms, machines, or directories and still function correctly.


q:
I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a favicon.ico file in the root of the website.

I found this nice little guide: How to Add a Favicon. However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use).

Is there a third method that works across all the most popular browsers?

[A]
This is how they're doing it right here on Stack Overflow:
```
```
<link rel="shortcut icon" href="/favicon.ico" />
```
```


q:
At work we are currently still using JUnit 3 to run our tests. We have been considering switching over to JUnit 4 for new tests being written but I have been keeping an eye on TestNG for a while now. What experiences have you all had with either JUnit 4 or TestNG, and which seems to work better for very large numbers of tests? Having flexibility in writing tests is also important to us since our functional tests cover a wide aspect and need to be written in a variety of ways to get results.

Old tests will not be re-written as they do their job just fine. What I would like to see in new tests though is flexibility in the way the test can be written, natural assertions, grouping, and easily distributed test executions.

[A]
First I would say, don't rewrite all your tests just to suit the latest fad.  Junit3 works perfectly well, and the introduction of annotations in 4 doesn't buy you very much (in my opinion).  It is much more important that you guys
write
tests, and it sounds like you do.
Use whatever seems most natural and helps you get your work done.
I can't comment on TestNG b/c I haven't used it.  But I would recommend
unitils
, a great wrapper for JUnit/TestNG/DBUnit/EasyMock, regardless of which route you take. (It supports all the flavors mentioned above)


q:
I am working on a new project. Is there any benefit with going with a WCF web service over a regular old fashion web service?

Visual Studio offers templates for both. What are the differences? Pros and cons?

[A]
The Pros of doing all by yourself is:
No learning curve
Very flexible
The Pros of WCF are:
Costs less time in the longer run
Switch protocols without programming
A disadvantage of WCF: some static property names
can be pretty lengthy
...
To summarize: WCF lets you focus on programming, but you need to learn it first ;-)


q: Since I started studying object-oriented programming, I frequently read articles/blogs saying  functions are better, or not all problems should be modeled as objects. From your personal programming adventures, when do you think a problem is better solved by OOP?

[A]
I think it fits best when you are modeling something cohesive with state and associated actions on those states.  I guess that's kind of vague, but I'm not sure there is a perfect answer here.
The thing about OOP is that it lets you encapsulate and abstract data and information away, which is a real boon in building a large system.  You can do the same with other paradigms, but it seems OOP is especially helpful in this category.
It also kind of depends on the language you are using.  If it is a language with rich OOP support, you should probably use that to your advantage.  If it doesn't, then you may need to find other mechanisms to help break up the problem into smaller, easily testable pieces.


q:
I probably spend far too much time trying to make my visual interfaces look good, and while I'm pretty adept at finding the right match between usability and style one area I am hopeless at is making nice looking icons.

How do you people overcome this (I'm sure common) problem?  I'm thinking of things like images on buttons and perhaps most important of all, the actual application icon.

Do you rely on third party designers, in or out of house?  Or do you know of some hidden website that offers lots of icons for us to use?  I've tried Google but I seem to find either expensive packages that are very specific, millions of Star Trek icons or icons that look abysmal at 16x16 which is my preferred size on in-application buttons.

Any help/advice appreciated.

[A]
We have an in-house designer that does ours, although we also use freelance designers, too.
You could try starting a design competition on
99 Designs
?
There are also some free icon sets available,
like these
.
If you google around, you'll also find quite a few commercially available icon sets that you can use (although obviously neither of the icon set options will get you an icon specific to your app!).
Hope that helps!


q:
Suppose I have a stringbuilder in C# that does this:

StringBuilder sb = new StringBuilder();
string cat = "cat";
sb.Append("the ").Append(cat).(" in the hat");
string s = sb.ToString();

would that be as efficient or any more efficient as having:

string cat = "cat";
string s = String.Format("The {0} in the hat", cat);

If so, why?

EDIT

After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at injecting one string into another.

In both cases above I want to inject one or more strings into the middle of a predefined template string.

Sorry for the confusion

[A]
I would suggest not, since String.Format was not designed for concatenation, it was design for formatting the output of various inputs such as a date.
```
```
String s = String.Format("Today is {0:dd-MMM-yyyy}.", DateTime.Today);
```
```


q:
I have a Microsoft keyboard with a series of non-standard buttons such as "Mail", "Search" , "Web/Home" etc.

It would be nice to be able to bind these keys so they execute arbitrary programs.

Does anybody know how to do this in Debian Etch?

[A]
I can't say for certain because I'm not using Debian but if you're using Gnome the easiest way is to run gnome-keybinding-properties (System > Preferences > Keyboard Shortcuts)
Instead of typing a shortcut such as
Ctrl
+
M
, hit the button on your keyboard.
If you would prefer to do this via command line or with a different desktop environment, this may help:
Unusual keys and keyboards


q:
As a long time World of Warcraft player, and a passionate developer I have decided that I would like to combine the two and set about developing some addins.  Not only to improve my gameplay experience but as a great opportunity to learn something new.

Does anyone have any advice on how to go about starting out?

Is there an IDE one can use?  How does one go about testing?  Are there any ready made libraries available?  Or would I get a better learning experience by ignoring the libraries and building from scratch? How do I oneshot Hogger?

Would love to hear your advice, experiences and views.

[A]
This article
explains how to start pretty well.
Your first bookmark is possibly the US Interface Forum, especially the Stickies for that:
http://us.battle.net/wow/en/forum/1011693/
Then, grab some simple addons to learn how XML and LUA interacts. The
WoWWiki HOWTO List
is a good point here as well.
One important thing to keep in mind: World of Warcraft is available in many languages. If you have a EU Account, you got an excellent testing bed by simply downloading the language Packs for Spanish, German and French. If you're an US Guy, check if you can get the Latin America version. That way, you can test it against another language version.
Once you made 1 or 2 really small and simple addons just to learn how to use it, have a look at the various frameworks.
WowAce
is a popular one, but there are others.
Just keep one thing in mind: Making an Addon is work. Maintaining one is even more work. With each new Patch, there may be breaking changes, and the next Addon will surely cause a big Exodus of Addons, just like Patch 2.0.1 did.


q:
I have some code for starting a thread on the .NET CF 2.0:

ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();

If I call this inside a loop the items completely out of order. How do introduce a wait after t.Start(), so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?

[A]
If I'm reading this properly, you're starting work items on bunch of threads but you're concerned that the threads are completing out of order, and, would prefer to wait until each thread completes in the order they were started ?
If this is the case then I'm not sure why you're creating a thread per work item. Maybe you could expand?
If you did need to wait for a thread to complete the you could just do:
```
```
t.Join();
```
```


q:
I want to get started doing some game development using Microsoft's XNA. Part of that is Shader development, but I have no idea how to get started. I know that nVidia's FX Composer is a great tool to develop shaders, but I did not find much useful and updated content on how to actually get started.

What tutorials would you recommend?

[A]
SAMS's
XNA Unleashed
by Chad Carter is a great starting point for XNA and assumes little knowledge of game development practices or hard maths before you start. It has two chapters on basic and advanced shaders.
As a sidenote, keep an eye out on Google for WPF Shader tutorials, it now uses the same technology to allow customer shaders in WPF applications and tutorials for that I believe are largely compatible with XNA.


q:
I have a quad core machine and would like to write some code to parse a text file that takes advantage of all four cores. The text file basically contains one record per line.

Multithreading isn't my forte so I'm wondering if anyone could give me some patterns that I might be able to use to parse the file in an optimal manner.

My first thoughts are to read all the lines into some sort of queue and then spin up threads to pull the lines off the queue and process them, but that means the queue would have to exist in memory and these are fairly large files so I'm not so keen on that idea.

My next thoughts are to have some sort of controller that will read in a line and assign it a thread to parse, but I'm not sure if the controller will end up being a bottleneck if the threads are processing the lines faster than it can read and assign them.

I know there's probably another simpler solution than both of these but at the moment I'm just not seeing it.

[A]
I'd go with your original idea. If you are concerned that the queue might get too large implement a buffer-zone for it (i.e. If is gets above 100 lines the stop reading the file and if it gets below 20 then start reading again. You'd need to do some testing to find the optimal barriers). Make it so that any of the threads can potentially be the "reader thread" as it has to lock the queue to pull an item out anyway it can also check to see if the "low buffer region" has been hit and start reading again. While it's doing this the other threads can read out the rest of the queue.
Or if you prefer, have one reader thread assign the lines to three other
processor
threads (via their own queues) and implement a
work-stealing strategy
. I've never done this so I don't know how hard it is.


q: How can I create rounded corners using CSS?

[A]
Since CSS3 was introduced, the best way to add rounded corners using CSS is by using the
```
border-radius
```
property. You can
read the spec
on the property, or get some
useful implementation information on MDN
:
If you are using a browser that
doesn't
implement
```
border-radius
```
(Chrome pre-v4, Firefox pre-v4, IE8, Opera pre-v10.5, Safari pre-v5), then the links below detail a whole bunch of different approaches. Find one that suits your site and coding style, and go with it.
CSS Design: Creating Custom Corners
& Borders
CSS Rounded Corners 'Roundup'
25 Rounded Corners Techniques with CSS


q:
In other words, is this Singleton implementation thread safe:

public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}

[A]
The
Common Language Infrastructure specification
guarantees that "a type initializer shall run exactly once for any given type, unless explicitly called by user code." (Section 9.5.3.1.) So unless you have some whacky IL on the loose calling Singleton::.cctor directly (unlikely) your static constructor will run exactly once before the Singleton type is used, only one instance of Singleton will be created, and your Instance property is thread-safe.
Note that if Singleton's constructor accesses the Instance property (even indirectly) then the Instance property will be null. The best you can do is detect when this happens and throw an exception, by checking that instance is non-null in the property accessor. After your static constructor completes the Instance property will be non-null.
As
Zoomba's answer
points out you will need to make Singleton safe to access from multiple threads, or implement a locking mechanism around using the singleton instance.


q:
What tools would you recommend for setting up CI for build and deployment of multiple websites built on DotNetNuke using SVN for source control?

We are currently looking at configuring Cruise Control to work with NAnt, NUnit, NCover and Trac as a test case. What other combinations would worth investigating?

We have full control of our development environment so using some form of CI is certain here but I would also like to convince our production services team that they can reliably deploy to the system test, uat and even production environments using these tools.

[A]
I would have a look at Team City
http://www.jetbrains.com/teamcity/index.html
I know some people who are looking in to this and they say good things about it.
My companies build process is done in FinalBuilder so I'm going to be looking at their server soon.
CC is quite good in that you can have one CC server monitor another CC server so you could set up stuff like - when a build completes on your build server, your test server would wake up, boot up a virtual machine and deploy your application.  Stuff like that.


q:
I'm trying to alpha blend sprites and backgrounds with devkitPro (including libnds, libarm, etc).

Does anyone know how to do this?

[A]
It's been a
long
time since I've done any GBA programming, but as I recall, the DS supports most (if not all) of the stuff that GBA supports.
This
link has a section on how to do alpha blending for GBA (section 13.2). I don't know if there's a DS-specific way of doing it, but this should work for you.


q:
What I'd like to do is something like the following:

FooClass.prototype.method = function():String
{
    return "Something";
}

var foo:FooClass = new FooClass();
foo.method();

Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype.

The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway.

Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3.

Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question. :) Also, upmods for the good suggestions.

[A]
Yes, such a thing is possible.
In fact, your example is very close to the solution.
Try
```
```
foo["method"]();
```
```
instead of
```
```
foo.method();
```
```


q:
Can anyone recommend software or a .NET library that will check for bounced emails and the reason for the bounce? I get bounced emails into a pop3 account that I can read then.

I need it to keep my user database clean from invalid email addresses and want to automate this (mark user as invalid email).

[A]
It's pretty easy to do with a TcpClient. Open the server:
```
```
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(POP3Server, POP3Port);
NetworkStream stream = tcpClient.GetStream();
```
```
Read the welcome message:
```
```
int read = stream.Read(inBuffer, 0, inBuffer.Length);
string response = Encoding.ASCII.GetString(inBuffer, 0, read);
if (response.IndexOf("+OK") != 0) throw new ...;
```
```
Write back to the server:
```
```
byte[] outBuffer = Encoding.ASCII.GetBytes("USER " + account + "\r\n");
stream.Write(outBuffer, 0, outBuffer.Length);
```
```
That sends the USER command. You need to login and then you can start grabbing messages - see the POP3
RFC
for the full list of commands. If you're not looking to roll your own check out this
CodeProject article
.


q:
What I want to do is something like this: I have enums with combined flagged values.

public static class EnumExtension
{
    public static bool IsSet<T>( this T input, T matchTo )
        where T:enum //the constraint I want that doesn't exist in C#3
    {
        return (input & matchTo) != 0;
    }
}

So then I could do:

MyEnum tester = MyEnum.FlagA | MyEnum.FlagB

if( tester.IsSet( MyEnum.FlagA ) )
    //act on flag a

Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.

Does anyone know a workaround?

[A]
Darren, that would work if the types were specific enumerations - for general enumerations to work you have to cast them to ints (or more likely uint) to do the boolean math:
```
```
public static bool IsSet( this Enum input, Enum matchTo )
{
    return ( Convert.ToUInt32( input ) & Convert.ToUInt32( matchTo ) ) != 0;
}
```
```


q:
We have a junior programmer that simply doesn't write enough tests.

I have to nag him every two hours, "have you written tests?"

We've tried:

Showing that the design becomes simpler

Showing it prevents defects

Making it an ego thing saying only bad programmers don't

This weekend 2 team members had to come to work because his code had a NULL reference and he didn't test it

My work requires top quality stable code, and usually everyone 'gets it' and there's no need to push tests through. We know we can make him write tests, but we all know the useful tests are those written when you're into it.

Do you know of more motivations?

[A]
If the junior programmer, or anyone, doesn't see the value in testing, then it will be hard to get them to do it...period.
I would have made the junior programmer sacrifice their weekend to fix the bug.  His actions (or lack there of) are not affecting him directly.  Also, make it apparent, that he will not see advancement and/or pay increases if he doesn't improve his skills in testing.
In the end, even with all your help, encouragement, mentoring, he might not be a fit for your team, so let him go and look for someone who does get it.


q:
I'm part of a team that develops a pretty big Swing Java Applet. Most of our code are legacy and there are tons of singleton references. We've bunched all of them to a single "Application Context" singleton. What we now need is to create some way to separate the shared context (shared across all applets currently showing) and non-shared context (specific to each applet currently showing).

However, we don't have an ID at each of the locations that call to the singleton, nor do we want to propagate the ID to all locations. What's the easiest way to identify in which applet context we're running? (I've tried messing with classloaders, thread groups, thread ids... so far I could find nothing that will enable me to ID the origin of the call).

[A]
If I understand you correctly, the idea is to get a different "singleton" object for each caller object or "context".
One thing you can do is to create a thread-local global variable where you write the ID of the current context. (This can be done with AOP.) Then in the singleton getter, the context ID is fetched from the thread-local to use as a key to the correct "singleton" instance for the calling context.
Regarding AOP there should be no problem using it in applets since, depending on your point-cuts, the advices are woven at compile time and a JAR is added to the runtime dependencies. Hence, no special evidence of AOP should remain at run time.


q:
Alright, so maybe I shouldn't have shrunk this question sooo much... I have seen the post on the most efficient way to find the first 10000 primes.  I'm looking for all possible ways.  The goal is to have a one stop shop for primality tests.  Any and all tests people know for finding prime numbers are welcome.

And so:

What are all the different ways of finding primes?

[A]
The Sieve of Eratosthenes
is a decent algorithm:
Take the list of positive integers 2 to any given Ceiling.
Take the next item in the list (2 in the first iteration) and remove all multiples of it (beyond the first) from the list.
Repeat step two until you reach the given Ceiling.
Your list is now composed purely of primes.
There is a functional limit to this algorithm in that it exchanges speed for memory.  When generating very large lists of primes the memory capacity needed skyrockets.


q:
What does the expression "Turing Complete" mean?

Can you give a simple explanation, without going into too many theoretical details?

[A]
From
wikipedia
:
Turing completeness, named after Alan
  Turing, is significant in that every
  plausible design for a computing
  device so far advanced can be emulated
  by a universal Turing machine — an
  observation that has become known as
  the Church-Turing thesis. Thus, a
  machine that can act as a universal
  Turing machine can, in principle,
  perform any calculation that any other
  programmable computer is capable of.
  However, this has nothing to do with
  the effort required to write a program
  for the machine, the time it may take
  for the machine to perform the
  calculation, or any abilities the
  machine may possess that are unrelated
  to computation.
While truly Turing-complete machines
  are very likely physically impossible,
  as they require unlimited storage,
  Turing completeness is often loosely
  attributed to physical machines or
  programming languages that would be
  universal if they had unlimited
  storage. All modern computers are
  Turing-complete in this sense.
I don't know how you can be more non-technical than that except by saying "turing complete means 'able to answer computable problem given enough time and space'".


q:
Lately I had to change some code on older systems where not all of the code has unit tests.

Before making the changes I want to write tests, but each class created a lot of dependencies and other anti-patterns which made testing quite hard.

Obviously, I wanted to refactor the code to make it easier to test, write the tests and then change it.

Is this the way you'd do it? Or would you spend a lot of time writing the hard-to-write tests that would be mostly removed after the refactoring will be completed?

[A]
First of all,
here's a great article with tips on unit testing
.  Secondly, I found a great way to avoid making tons of changes in old code is to just refactor it a little until you can test it.  One easy way to do this is to make private members protected, and then override the protected field.
For example, let's say you have a class that loads some stuff from the database during the constructor.  In this case, you can't just override a protected method, but you can extract the DB logic to a protected field and then override it in the test.
```
```
public class MyClass {
    public MyClass() {
        // undesirable DB logic
    }
}
```
```
becomes
```
```
public class MyClass {
    public MyClass() {
        loadFromDB();
    }

    protected void loadFromDB() {
        // undesirable DB logic
    }
}
```
```
and then your test looks something like this:
```
```
public class MyClassTest {
    public void testSomething() {
        MyClass myClass = new MyClassWrapper();
        // test it
    }

    private static class MyClassWrapper extends MyClass {
        @Override
        protected void loadFromDB() {
            // some mock logic
        }
    }
}
```
```
This is somewhat of a bad example, because you could use DBUnit in this case, but I actually did this in a similar case recently because I wanted to test some functionality totally unrelated to the data being loaded, so it was very effective.  I've also found such exposing of members to be useful in other similar cases where I need to get rid of some dependency that has been in a class for a long time.
I would recommend against this solution if you are writing a framework though, unless you really don't mind exposing the members to users of your framework.
It's a bit of a hack, but I've found it quite useful.


q:
Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :)

I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF?

On the front-end

[A]
We use
pdflib
to create PDF files from our rails apps. It has bindings for PHP, and a ton of other languages.
We use the commmercial version, but they also have a
free/open source version
which has some limitations.
Unfortunately, this only allows creation of PDF's.
If you want to open and 'edit' existing files, pdflib do provide
a product which does this this
, but costs a
LOT


q: The company I'm currently working for is using Selenium for Uniting-Testing our User Interface. What do you use to Unit-Test your Web UI and how effective do you find it?

[A]
We use Selenium Core, but are switching gradually to Selenium RC which is much nicer and easier to manage. We have written lots of custom code to make the tests run on our Continuous Integration servers, some of them in parallel suites to run faster.
One thing you'll find is that Selenium seems to restart the browser for each test (you can set it not to do this, but we got memory problems when we did that). This can be slow in Firefox, but is not too bad in IE (one time I'm thankful for Bill Gates's OS integraion).


q: After a couple of hours fighting with the Gallery2 RSS module and getting only the message, "no feeds have yet been defined", I gave up.  Based on a Google search for "no feeds have yet been defined", this is a pretty common problem.  Do you have any tips and/or tricks for getting the Gallery2 RSS module to work?  Or any tips for a relatively-PHP-ignorant developer trying to debug problems with this PHP application?

[A]
My eventual (and hopefully temporary) solution to this problem was a Python CGI script.  My script follows for anyone who might find it useful (despite the fact that this is a total hack).
```
```
#!/usr/bin/python
"""A CGI script to produce an RSS feed of top-level Gallery2 albums."""

#import cgi
#import cgitb; cgitb.enable()
from time import gmtime, strftime
import MySQLdb

ALBUM_QUERY = '''
    select g_id, g_title, g_originationTimestamp
    from g_Item
    where g_canContainChildren = 1
    order by g_originationTimestamp desc
    limit 0, 20
    '''

RSS_TEMPLATE = '''Content-Type: text/xml

<?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <title>TITLE</title>
    <link>http://example.com/gallery2/main.php</link>
    <description>DESCRIPTION</description>
    <ttl>1440</ttl>
%s
  </channel>
</rss>
'''

ITEM_TEMPLATE = '''
    <item>
      <title>%s</title>
      <link>http://example.com/gallery2/main.php?g2_itemId=%s</link>
      <description>%s</description>
      <pubDate>%s</pubDate>
    </item>
'''

def to_item(row):
    item_id = row[0]
    title = row[1]
    date = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(row[2]))
    return ITEM_TEMPLATE % (title, item_id, title, date)

conn = MySQLdb.connect(host = "HOST",
                       user = "USER",
                       passwd = "PASSWORD",
                       db = "DATABASE")
curs = conn.cursor()
curs.execute(ALBUM_QUERY)
print RSS_TEMPLATE % ''.join([ to_item(row) for row in curs.fetchall() ])
curs.close()
```
```


q:
I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class?

Here's one way I thought of but it doesn't seem right:

Edit: I'm using C++.

class Gui {
    public:
        void update_all();
        void draw_all() const;
        int add_button(Button *button); // Returns button id
        void remove_button(int button_id);
    private:
        Button *buttons[10];
        int num_buttons;
}

This code has a few problems, but I just wanted to give you an idea of what I want.

[A]
One useful strategy to keep in mind might be the
composite pattern
. At a low level, it might allow you to treat all GUI objects (and collections of objects) more easily once built. But I have no idea what's involved in GUI framework design, so one place to find general inspiration is in the source code of an existing project.
WxWidgets
is a cross-platform GUI framework with source available. Good luck with your project!


q: Is there a simple way to drop a group of interrelated tables in SQL Server? Ideally I'd like to avoid having to worry about what order they're being dropped in since I know the entire group will be gone by the end of the process.

[A]
I don't have access to SQL Server to test this, but how about:
```
```
DROP TABLE IF EXISTS table1, table2, table3 CASCADE;
```
```


q: What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005?

[A]
This can be done via SQL Enterprise Manager or like this:
```
```
ALTER DATABASE <database>
SET COMPATIBILITY_LEVEL = { 80 | 90 | 100 }
```
```
Use 90 for 2005 compatibility.
This replaces the functionality used for previous releases, the stored procedure
sp_dbcmptlevel
.


q:
Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal. If yes why does not it round the decimal digits but even mantissa part.

From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online.

Please let me know if you have any idea on this.

[A]
If I'm understanding you correctly, it sounds like you're expecting the MathContext to control how many digits should be kept after the decimal point.  That's not what it's for.  It specifies how many digits to keep,
total
.  So if you specify that you want 3 significant digits, that's all you're going to get.
For example, this:
```
```
System.out.println(new BigDecimal("1234567890.123456789",
                   new MathContext(20)));

System.out.println(new BigDecimal("1234567890.123456789",
                   new MathContext(10)));

System.out.println(new BigDecimal("1234567890.123456789",
                   new MathContext(5)));
```
```
will output:
```
```
1234567890.123456789
1234567890
1.2346E+9
```
```


q:
Recently I have been having issues with Firefox 3 on Ubuntu Hardy Heron.

I will click on a link and it will hang for a while.  I don't know if its a bug in Firefox 3 or a page running too much client side JavaScript, but I would like to try and debug it a bit.

So, my question is "is there a way to have some kind of process explorer, or task manager sort of thing for Firefox 3?"

I would like to be able to see what tabs are using what percent of my processor via the JavaScript on that page (or anything in the page that is causing CPU/memory usage).

Does anybody know of a plugin that does this, or something similar?  Has anyone else done this kind of inspection another way?

I know about FireBug, but I can't imagine how I would use it to finger which tab is using a lot of resources.

Any suggestions or insights?

[A]
It's probably the
awesome firefox3 fsync "bug"
, which is a giant pile of fail.
In summary
Firefox3 saves its bookmarks and history in an SQLite database
Every time you load a page it writes to this database several times
SQLite cares deeply that you don't lose your bookmarks, so each time it writes, instructs the kernel to flush it's database file to disk and ensure that it's fully written
Many variants of linux, when told to flush like that, flush EVERY FILE. This may take up to a minute or more if you have background tasks doing any kind of disk intensive stuff.
The kernel makes firefox wait while this flush happens, which locks up the UI.


q:
When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management) ?

When building a SOAP API you have WS-Security as a guide and much literature exists on the topic. I have found less information about securing REST endpoints.

While I understand REST intentionally does not have specifications analogous to WS-* I am hoping best practices or recommended patterns have emerged.

Any discussion or links to relevant documents would be very much appreciated.
If it matters, we would be using WCF with POX/JSON serialized messages for our REST API's/Services built using v3.5 of the .NET Framework.

[A]
There are no standards for REST other than HTTP. There are established REST services out there. I suggest you take a peek at them and get a feel for how they work.
For example, we borrowed a lot of ideas from Amazon's S3 REST service when developing our own. But we opted not to use the more advanced security model based on request signatures. The simpler approach is HTTP Basic auth over SSL. You have to decide what works best in your situation.
Also, I highly recommend the book
RESTful Web Services
from O'reilly. It explains the core concepts and does provide some best practices. You can generally take the model they provide and map it to your own application.


q: In the SSW rules to better SQL Server Database there is an example of a full database maintenance plan: SSW. In the example they run both a Reorganize Index and then a Rebuild Index and then Update Statistics. Is there any point to this? I thought Reorganize Index was a fast but less effective version of Rebuild Index? and that an index rebuild would also update the statistics automatically (on the clustered index at least).

[A]
The reorganize and rebuild are different things.
Reorganize: it's a defrag for indexes. Takes the existing index(es) and defragments the existing pages. However if the pages are not in a contiguous manner, they stays like before. Only the content of the pages are changing.
Rebuild: actually it drops the index and rebuilds it from scratch. It means that you will get a completely new index, with defragmented and contiguous pages.
Moreover with rebuild you can change partitioning or file groups, but with reorganize you can defrag not only the whole index, but also only one partition of the index.
The update statistics is automatic on clustered indexes, but not on the non-clustered ones.


q:
First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier.

I myself have always had problems with

naming,

placing

So,

Where do you put your domain specific constants (and what is the best name for such a class)?

Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)?

Where to put Exceptions?

Are there any standards to which I can refer?

[A]
Class names should always be descriptive and self-explanatory. If you have multiple domains of responsibility for your classes then they should probably be refactored.
Likewise for you packages. They should be grouped by domain of responsibility. Every domain has it's own exceptions.
Generally don't sweat it until you get to a point where it is becoming overwhelming and bloated. Then sit down and don't code, just refactor the classes out, compiling regularly to make sure everything works. Then continue as you did before.


q: In C, are the shift operators (<<, >>) arithmetic or logical?

[A]
When shifting left, there is no difference between arithmetic and logical shift. When shifting right, the type of shift depends on the type of the value being shifted.
(As background for those readers unfamiliar with the difference, a "logical" right shift by 1 bit shifts all the bits to the right and fills in the leftmost bit with a 0. An "arithmetic" shift leaves the original value in the leftmost bit. The difference becomes important when dealing with negative numbers.)
When shifting an unsigned value, the >> operator in C is a logical shift. When shifting a signed value, the >> operator is an arithmetic shift.
For example, assuming a 32 bit machine:
```
```
signed int x1 = 5;
assert((x1 >> 1) == 2);
signed int x2 = -5;
assert((x2 >> 1) == -3);
unsigned int x3 = (unsigned int)-5;
assert((x3 >> 1) == 0x7FFFFFFD);
```
```


q:
Is there an official convention for naming private fields in VB.NET?  For example, if I have a property called 'Foo', I normally call the private field '_Foo'.  This seems to be frowned upon in the Offical Guidelines:

"Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields."

In C#, you could call the private field 'foo', the property 'Foo', and refer to the private field as 'this.foo' in the constructor.  As VB.NET is case insensitive you can't do this - any suggestions?

[A]
I still use the _ prefix in VB for private fields, so I'll have _foo as the private field and Foo as the property. I do this for c# as well and pretty much any code I write. Generally I wouldn't get too caught up in "what is the right way to do it" because there isn't really a "right" way (altho there are some very bad ways) but rather be concerned with doing it consistently.
At the end of the day, being consistent will make your code much more readable and maintainable than using any set of "right" conventions.


q:
I have an array in Perl:

my @my_array = ("one","two","three","two","three");

How do I remove the duplicates from the array?

[A]
You can do something like this as demonstrated in
perlfaq4
:
```
```
sub uniq {
    my %seen;
    grep !$seen{$_}++, @_;
}

my @array = qw(one two three two three);
my @filtered = uniq(@array);

print "@filtered\n";
```
```
Outputs:
```
```
one two three
```
```
If you want to use a module, try the
```
uniq
```
function from
```
List::MoreUtils
```


q:
I have a project that I'm currently working on but it currently only supports the .net framework 2.0. I love linq, but because of the framework version I can't use it. What I want isn't so much the ORM side of things, but the "queryability" (is that even a word?) of Linq.

So far the closest is llblgen but if there was something even lighter weight that could just do the querying for me that would be even better.

I've also looked at NHibernate which looks like it could go close to doing what I want, but it has a pretty steep learning curve and the mapping files don't get me overly excited.

If anyone is aware of something that will give me a similar query interface to Linq (or even better, how to get Linq to work on the .net 2.0 framework) I'd really like to hear about it.

[A]
There's a way to reference LINQ in the .NET 2.0 Framework, but I have to warn you that it
might
be against the terms of use/EULA of the framework:
LINQ on the .NET 2.0 Runtime


q:
Whenever I design a database, I always wonder if there is a best way of naming an item in my database. Quite often I ask myself the following questions:

Should table names be plural?

Should column names be singular?

Should I prefix tables or columns?

Should I use any case in naming items?

Are there any recommended guidelines out there for naming items in a database?

[A]
No. A table should be named after the entity it represents.
Person, not persons is how you would refer to whoever one of the records represents.
Again, same thing. The column FirstName really should not be called FirstNames. It all depends on what you want to represent with the column.
NO.
Yes. Case it for clarity. If you need to have columns like "FirstName", casing will make it easier to read.
Ok. Thats my $0.02


q:
Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.

If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):

$ ls -ld foo bar
drwxr-xr-x   2 greg  greg  68 Aug 11 22:36 bar
lrwxr-xr-x   1 greg  greg   3 Aug 11 22:36 foo -> bar
$ cd foo
$ pwd
/Users/greg/tmp/foo
$

What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar".

[A]
According to the standards,
```
pwd -P
```
should return the path with symlinks resolved.
C function
```
char *getcwd(char *buf, size_t size)
```
from
```
unistd.h
```
should have the same behaviour.
getcwd
pwd


q: Can it be done and if so, how?

[A]
You can use Merge Replication. Theres a tutorial here
SQL Server Compact 3.5 How-to Tutorials
(Number 5).


q: I'd like a concise introduction to the different options.

[A]
From
Wikipedia
Embedded in an SWF file
using the Flash authoring tool (supported in Flash Player 6 and later). The entire file must be transferred before playback can begin. Changing the video requires rebuilding the SWF file.[citation needed]
Progressive download via HTTP
(supported in Flash Player 7 and later). This method uses ActionScript to include an externally hosted Flash Video file client-side for playback. Progressive download has several advantages, including buffering, use of generic HTTP servers, and the ability to reuse a single SWF player for multiple Flash Video sources. Flash Player 8 includes support for random access within video files using the partial download functionality of HTTP, sometimes this is referred to as streaming. However, unlike streaming using RTMP, HTTP "streaming" does not support real-time broadcasting. Streaming via HTTP requires a custom player and the injection of specific Flash Video metadata containing the exact starting position in bytes and timecode of each keyframe. Using this specific information, a custom Flash Video player can request any part of the Flash Video file starting at a specified keyframe. For example, Google Video and Youtube support progressive downloading and can seek to any part of the video before buffering is complete. The server-side part of this "HTTP pseudo-streaming" method is fairly simple to implement, for example in PHP, as an Apache HTTPD module, or a lighttpd module. Rich Media Project provides players and Flash components compatible with "HTTP pseudo-streaming" method.
Streamed via RTMP to the Flash Player
using the Flash Media Server (formerly called Flash Communication Server), VCS, ElectroServer, Wowza Pro or the open source Red5 server. As of April 2008, there are four stream recorders available for this protocol, re-encoding screencast software excluded.
There is a useful introduction from Adobe here:
Flash video learning guide


q:
I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.

What can I do to resolve this?

[A]
If you need to manipulate it on the client side, you can't use the Visible property on the server side.  Instead, set its CSS display style to "none".  For example:
```
```
<asp:Label runat="server" id="Label1" style="display: none;" />
```
```
Then, you could make it visible on the client side with:
```
```
document.getElementById('Label1').style.display = 'inherit';
```
```
You could make it hidden again with:
```
```
document.getElementById('Label1').style.display = 'none';
```
```
Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice.  You'll need to use the ClientID with getElementById, not the server side ID, if they differ.


q: I have read through several reviews on Amazon and some books seem outdated.  I am currently using MyEclipse 6.5 which is using Eclipse 3.3.  I'm interested in hearing from people that have experience learning RCP and what reference material they used to get started.

[A]
Although I don't have personal experience, a few friends of mine did Eclipse RCP development, and they used the book "
Eclipse Rich Client Platform: Designing, Coding, and Packaging Java(TM) Applications
". They seemed to like it a lot, and I looked it at myself, and it seemed useful. If I was going to do RCP development on Eclipse, I would probably get this book.
To clarify - this book is geared toward Eclipse 3.1, and since I haven't done any RCP development of my own, I'm not sure how much things have changed.


q:
I would like to use a language that I am familiar with - Java, C#, Ruby, PHP, C/C++, although examples in any language or pseudocode are more than welcome.

What is the best way of splitting a large XML document into smaller sections that are still valid XML? For my purposes, I need to split them into roughly thirds or fourths, but for the sake of providing examples, splitting them into n components would be good.

[A]
Well of course you can always extract the top-level elements (whether this is the granularity you want is up to you). In C#, you'd use the XmlDocument class. For example, if your XML file looked something like this:
```
```
<Document>
  <Piece>
     Some text
  </Piece>
  <Piece>
     Some other text
  </Piece>
</Document>
```
```
then you'd use code like this to extract all of the Pieces:
```
```
XmlDocument doc = new XmlDocument();
doc.Load("<path to xml file>");
XmlNodeList nl = doc.GetElementsByTagName("Piece");
foreach (XmlNode n in nl)
{
    // Do something with each Piece node
}
```
```
Once you've got the nodes, you can do something with them in your code, or you can transfer the entire text of the node to its own XML document and act on that as if it were an independent piece of XML (including saving it back to disk, etc).


q:
As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on Active Record.

Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains why it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?)

Hopefully this won't turn into a holy war about design patterns -- all I want to know is ****specifically**** what's wrong with Active Record.

If it doesn't scale well, why not?

What other problems does it have?

[A]
The main thing that I've seen with regards to complaints about Active Record is that when you create a model around a table, and you select several instances of the model, you're basically doing a "select * from ...". This is fine for editing a record or displaying a record, but if you want to, say, display a list of the cities for all the contacts in your database, you could do "select City from ..." and only get the cities. Doing this with Active Record would require that you're selecting all the columns, but only using City.
Of course, varying implementations will handle this differently. Nevertheless, it's one issue.
Now, you can get around this by creating a new model for the specific thing you're trying to do, but some people would argue that it's more effort than the benefit.
Me, I dig Active Record. :-)
HTH


q:
I want to open a file for reading, the C++ way. I need to be able to do it for:

text files, which would involve some sort of read line function.

binary files, which would provide a way to read raw data into a char* buffer.

[A]
There are three ways to do this, depending on your needs. You could use the old-school C way and call
```
fopen
```
/
```
fread
```
/
```
fclose
```
, or you could use the C++ fstream facilities (
```
ifstream
```
/
```
ofstream
```
), or if you're using MFC, use the
```
CFile
```
class, which provides functions to accomplish actual file operations.
All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:
```
```
int nsize = 10;
std::vector<char> somedata(nsize);
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata.data(), nsize);
myfile.close();
```
```
Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing).


q: Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties?

[A]
The official tutorial on the
CPAN site
is good.
There's also a good article called
Camel POOP
at CodeProject.


q:
I'm importing some data from a CSV file, and numbers that are larger than 1000 get turned into 1,100 etc.

What's a good way to remove both the quotes and the comma from this so I can put it into an int field?

Edit:

The data is actually already in a MySQL table, so I need to be able to this using SQL. Sorry for the mixup.

[A]
You could use this perl command.
```
```
Perl -lne 's/[,|"]//; print' file.txt > newfile.txt
```
```
You may need to play around with it a bit, but it should do the trick.


q:
Even though I always strive for complete validation these days, I often wonder if it's a waste of time.  If the code runs and it looks the same in all browsers (I use browsershots.org to verify) then do I need to take it any further or am I just being overly anal?

What level do you hold your code to when you create it for:

a) yourself
b) your clients

P.S. Jeff and company, why doesn't stack overflow validate? :)

EDIT: Some good insights, I think that since I've been so valid-obsessed for so long I program knowing what will cause problems and what won't so I'm in a better position than people who create a site first and then "go back and fix the validation problems"

I think I may post another question on stack overflow; "Do you validate as you go or do you finish and then go back and validate?" as that seems to be where this question is going

[A]
a) Must look the same
b) As standards-compliant as possible, but not so anal that it blocks finishing work
In a situation where you have perpetual access to the code, I don't think standards-compliance is all that important, since you can always make changes to the code if something breaks. If you don't have perpetual access (ie, you sign off on the code and it becomes someone else's responsibility), it's probably best to be as standards-compliant as possible to minimize maintenance headaches later... even if you never have to deal with the code again, your reputation persists and can be transmitted to other potential clients, and many teams like to blame the previous developer(s) for problems that come up.


q:
When restoring a SQL Server Database, I notice that there are 3 different Recovery States to choose from:

Restore with Recovery

Restore with No Recovery

Restore with Standby

I've always left it at it's default value, but what do they all mean?

(Preferably in layman's terms)

[A]
From Books On line, i think it is pretty clear after you read it
NORECOVERY
Instructs the restore operation to not roll back any uncommitted transactions. Either the NORECOVERY or STANDBY option must be specified if another transaction log has to be applied. If neither NORECOVERY, RECOVERY, or STANDBY is specified, RECOVERY is the default.
SQL Server requires that the WITH NORECOVERY option be used on all but the final RESTORE statement when restoring a database backup and multiple transaction logs, or when multiple RESTORE statements are needed (for example, a full database backup followed by a differential database backup).
Note  When specifying the NORECOVERY option, the database is not usable in this intermediate, nonrecovered state.
When used with a file or filegroup restore operation, NORECOVERY forces the database to remain in the restoring state after the restore operation. This is useful in either of these situations:
A restore script is being run and the log is always being applied.
A sequence of file restores is used and the database is not intended to be usable between two of the restore operations.
RECOVERY
Instructs the restore operation to roll back any uncommitted transactions. After the recovery process, the database is ready for use.
If subsequent RESTORE operations (RESTORE LOG, or RESTORE DATABASE from differential) are planned, NORECOVERY or STANDBY should be specified instead.
If neither NORECOVERY, RECOVERY, or STANDBY is specified, RECOVERY is the default. When restoring backup sets from an earlier version of SQL Server, a database upgrade may be required. This upgrade is performed automatically when WITH RECOVERY is specified. For more information, see Transaction Log Backups .
STANDBY
= undo_file_name
Specifies the undo file name so the recovery effects can be undone. The size required for the undo file depends on the volume of undo actions resulting from uncommitted transactions. If neither NORECOVERY, RECOVERY, or STANDBY is specified, RECOVERY is the default.
STANDBY allows a database to be brought up for read-only access between transaction log restores and can be used with either warm standby server situations or special recovery situations in which it is useful to inspect the database between log restores.
If the specified undo file name does not exist, SQL Server creates it. If the file does exist, SQL Server overwrites it.
The same undo file can be used for consecutive restores of the same database. For more information, see Using Standby Servers.
Important  If free disk space is exhausted on the drive containing the specified undo file name, the restore operation stops.
STANDBY is not allowed when a database upgrade is necessary.


q:
I'd like to allow a user to set up an SSH tunnel to a particular machine on a particular port (say, 5000), but I want to restrict this user as much as possible. (Authentication will be with public/private keypair).

I know I need to edit the relevant ~/.ssh/authorized_keys file, but I'm not sure exactly what content to put in there (other than the public key).

[A]
See
this post on authenticating public keys
.
The two main things you need to remember are:
Make sure you
```
chmod 700 ~/.ssh
```
Append the public key block to authorized-keys


q:
When I have two mysql servers that have different jobs (holding different databases) but want to be able to use one of them to slip in when the other one fails, what would you suggest how I keep the data on both of them equal "close to realtime"?

Obviously it's not possible to make a full database dump every x minutes.

I've read about the Binary Log, is that the way that I need to go? Will that not slow down the fallback server a lot? Is there a way to not include some tables in the binary log - where it doesn't matter that the data has changed?

[A]
Binary log is definitely the way to go. However, you should be aware that with
MySQL
you can't just flip back and forth between servers like that.
One server will be the
master
and the other will be the slave. You write/read to the master, but can only read from the slave server. If you ever write to the slave, they'll be out of sync and there's no easy way to get them to sync up again (basically, you have to swap them so the master is the new slave, but this is a tedious manual process).
If you need true hot-swappable backup databases you might have to go to a system other than
MySQL
. If all you want is a read-only live backup that you can use instantly in the worst-case scenario (master is permanently destroyed), Binary Log will suit you just fine.


q:
Is there a general procedure for programming extensibility capability into your code?

I am wondering what the general procedure is for adding extension-type capability to a system you are writing so that functionality can be extended through some kind of plugin API rather than having to modify the core code of a system.

Do such things tend to be dependent on the language the system was written in, or is there a general method for allowing for this?

[A]
Find out what minimum requrements you want to put on a plugin writer. Then make one or more Interfaces that the writer must implement for your code to know when and where to execute the code.
Make an API the writer can use to access some of the functionality in your code.
You could also make a base class the writer must inherit. This will make wiring up the API easier. Then use some kind of reflection to scan a directory, and load the classes you find that matches your requirements.
Some people also make a scripting language for their system, or implements an interpreter for a subset of an existing language. This is also a possible route to go.
Bottom line is: When you get the code to load, only your imagination should be able to stop you.
Good luck.


q: How can I find the high water mark (the historical maximum number of concurrent users) in an oracle database (9i).

[A]
This should do the trick:
```
```
SELECT sessions_highwater FROM v$license;
```
```


q:
How can I figure out the size of a file, in bytes?

#include <stdio.h>

unsigned int fsize(char* file){
  //what goes here?
}

[A]
If you're fine with using the std c library:
```
```
#include <sys/stat.h>
off_t fsize(char *file) {
    struct stat filestat;
    if (stat(file, &filestat) == 0) {
        return filestat.st_size;
    }
    return 0;
}
```
```


q:
What is the best way to create redundant subversion repositories?

I have a subversion repository (linked through apache2 and WebDAV) and would like to create a mirror repository on a different server in the event of outages, but I am not certain of the best way to proceed.

I am thinking that post-commit scripts could be used to propagate changes, but I am not sure if this is the best way to go, anyone have any input

[A]
Do you really need per-commit back-ups? There are almost certainly better ways of safe-guarding against failures than going down that route. For example, given that most failures are disk failures, move to a RAID array and/or NAS/SAN storage will provide you with better general protection and, if configured correctly, better performance. At that point, off-site back-ups becomes a matter of using the tools available. See the
Repository maintenance section
of the svn manual for details.
If you truly do need per-commit back-ups then, yeah, post-commit scripts are the way to go.


q: I need to prevent Session Fixation, a particular type of session hijacking, in a Java web application running in JBoss. However, it appears that the standard idiom doesn't work in JBoss. Can this be worked around?

[A]
This defect
(found
here
) points the way to the solution. The Tomcat instance that runs in JBoss is configured with emptySessionPath="true", rather than "false", which is the default. This can be modified in
```
.../deploy/jboss-web.deployer/server.xml
```
; both the HTTP and AJP connectors have this option.
The feature itself is used to eliminate the context path (eg. "foo" in
http://example.com/foo
) from being included in the JSESSIONID cookie. Setting it to false will break applications that rely on cross-application authentication, which includes stuff built using some portal frameworks. It didn't negatively affect the application in question, however.