Question: What is SafeHandle? how does it differ from IntPtr? When should I use one? What are its advantages?

Answer:
I think
MSDN
is pretty clear in definition:
The SafeHandle class provides critical
  finalization of handle resources,
  preventing handles from being
  reclaimed prematurely by garbage
  collection and from being recycled by
  Windows to reference unintended
  unmanaged objects. Before the .NET
  Framework version 2.0, all operating
  system handles could only be
  encapsulated in the IntPtr managed
  wrapper object.
The SafeHandle class contains a
  finalizer that ensures that the handle
  is closed and is guaranteed to run,
  even during unexpected AppDomain
  unloads when a host may not trust the
  consistency of the state of the
  AppDomain.
For more information about the
  benefits of using a SafeHandle, see
  Safe Handles and Critical
  Finalization.
This class is abstract because you
  cannot create a generic handle. To
  implement SafeHandle, you must create
  a derived class. To create SafeHandle
  derived classes, you must know how to
  create and free an operating system
  handle. This process is different for
  different handle types because some
  use CloseHandle, while others use more
  specific methods such as
  UnmapViewOfFile or FindClose. For this
  reason, you must create a derived
  class of SafeHandle for each operating
  system handle type; such as
  MySafeRegistryHandle,
  MySafeFileHandle, and
  MySpecialSafeFileHandle. Some of these
  derived classes are prewritten and
  provided for you in the
  Microsoft.Win32.SafeHandles namespace.


Question:
ADO.NET has the notorious DataRow class which you cannot instantiate using new.  This is a problem now that I find a need to mock it using Rhino Mocks.

Does anyone have any ideas how I could get around this problem?

Answer:
Any time I can't mock something (I prefer MoQ over Rhino, but that's beside the point) I have to code around it.
The way I see it you only have two choices.  Pay for a superior framework such as TypeMock that can mock ANY class, or code a wrapper around classes that weren't written to be mocked.
Its a sad state of affairs in the framework.  TDD wasn't a big concern back in the 1.1 days.


Question:
I am getting this error but only very occasionally.  99.9% of the time it works fine:

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

Does anyone have any idea on what the cause could be?  I only use that datatable for viewing and not updating so is it possible to easily turn off all constraints somehow?

Answer:
This typically happens when the schema on your dataset is enforcing something that your database is not.
Visual Studio will automatically read schema and try and set up some primary keys on your dataset, but if you are using a view that can possibly return multiple rows it will fail. It is easy enough to remove these constraints from the DataSet itself by deleting the constraint in the designer.
Check to ensure that your dataset is not enforcing a primary key in a situation where you could possibly have two rows with the same key, like in a View that joins two tables together and therefore duplicates the rows in the parent table. VS by default will try and create the primary key of the parent table as a unique constraint on the dataset, but the view itself enforces no such constraint.


Question:
I need to create an access (mdb) database without using the ADOX interop assembly.

How can this be done?

Answer:
Before I throw away this code, it might as well live on stackoverflow
Something along these lines seems to do the trick:
```
```
if (!File.Exists(DB_FILENAME))
{
    var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DB_FILENAME;

    // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly.
    var catType = Type.GetTypeFromProgID("ADOX.Catalog");
    object o = Activator.CreateInstance(catType);
    catType.InvokeMember("Create", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr});

    OleDbConnection cnn = new OleDbConnection(cnnStr);
    cnn.Open();
    var cmd = cnn.CreateCommand();
    cmd.CommandText = "CREATE TABLE VideoPosition (filename TEXT , pos LONG)";
    cmd.ExecuteNonQuery();

}
```
```
This code illustrates that you can access the database using OleDbConnection once its created with the ADOX.Catalog COM component.


Question: Can't seem to rename an existing Verity collection in ColdFusion without deleting, recreating, and rebuilding the collection.  Problem is, I have some very large collections I'd rather not have to delete and rebuild from scratch.  Any one have a handy trick for this conundrum?

Answer:
I don't believe that there is an easy way to rename a Verity collection.  You can always use
```
```
<cfcollection action="map" ...>
```
```
to assign an alias to an existing collection, provided you do not need to re-use the original name.


Question:
I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build.

Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each time and doesn't show the URL that I pass in. I would like it to NOT launch a new version each time but just open a new page in the current open one if it is already running.

For windows I use:

ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL);

For Linux I currently use:

pid_t pid;
char *args[2];

char *prog=0;
char firefox[]={"/usr/bin/firefox"};

if(strstri(filename,".html"))
    prog=firefox;

if(prog)
{
    args[0]=(char *)filename;
    args[1]=0;
    pid=fork();
    if(!pid)
        execvp(prog,args);

}

Answer:
If you're writing this for modern distros, you can use
```
xdg-open
```
:
```
```
$ xdg-open http://google.com/
```
```
If you're on an older version you'll have to use a desktop-specific command like
```
gnome-open
```
or
```
exo-open
```
.


Question: I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.

Answer:
If you have an NT-family Windows (one with
```
cmd.exe
```
as the shell), try
the FOR /F command
.


Question:
The following code executes a simple insert command.  If it is called 2,000 times consecutively (to insert 2,000 rows) an OleDbException with message = "System Resources Exceeded" is thrown.  Is there something else I should be doing to free up resources?

using (OleDbConnection conn = new OleDbConnection(connectionString))
using (OleDbCommand cmd = new OleDbCommand(commandText, conn))
{
    conn.Open();
    cmd.ExecuteNonQuery();
}

Answer:
The system resources exceeded error is not coming from the managed code, its coming from you killing your database (JET?)
You are opening way too many connections, way too fast...
Some tips:
Avoid round trips by not opening a new connection for every single command, and perform the inserts using a single connection.
Ensure that database connection pooling is working. (Not sure if that works with OLEDB connections.)
Consider using a more optimized way to insert the data.
Have you tried this?
```
```
using (OleDBConnection conn = new OleDBConnection(connstr))
{
    while (IHaveData)
    {
        using (OldDBCommand cmd = new OldDBCommand())
        {
            cmd.Connection = conn;
            cmd.ExecuteScalar();
        }
    }
}
```
```


Question: I know about the HIG (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch).

Answer:
Golden Rule: If you
```
alloc
```
then you
```
release
```
!
UPDATE: Unless you are using ARC


Question:
I have an MDI application. When I show a message box using MessageBox.Show(), the entire application disappears behind all of my open windows when I dismiss the message box.

The code is not doing anything special. In fact, here is the line that invokes the message box from within an MDI Child form:

MessageBox.Show(String.Format("{0} saved successfully.", Me.BusinessUnitTypeName), "Save Successful", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)

Me.BusinessUnitTypeName() is a read only property getter that returns a string, depending upon the value of a member variable. There are no side effects in this property.

Any ideas?

Answer:
Remove the
```
MessageBoxOptions.DefaultDesktopOnly
```
parameter and it will work correctly.
```
DefaultDesktopOnly
```
specifies that "
The message box is displayed on the active desktop
" which causes the focus loss.


Question:
Given this:

Public Sub timReminder_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
    If DateTime.Now() > g_RemindTime Then
        Reminders.ShowDialog()
        timReminder.Enabled = False
    End If
End Sub

I want to be able to say this (as I would in Delphi):

timReminder.Tick = timReminder_Tick

But I get errors when I try it.

Does anyone know how I can assign a custom event to a timer's on-tick event at runtime in VB.NET?

Answer:
Use the 'AddHandler' and 'AddressOf' keywords to add a handler to the Tick event.
```
AddHandler timeReminder.Tick, AddressOf timeReminder_Tick
```


Question:
I can't quite figure out this syntax problem with a case expression in a do block.

What is the correct syntax?

If you could correct my example and explain it that would be the best.

module Main where

main = do
     putStrLn "This is a test"
     s <- foo
     putStrLn s

foo = do
    args <- getArgs
    return case args of
                [] -> "No Args"
                [s]-> "Some Args"

A little update. My source file was a mix of spaces and tabs and it was causing all kinds of problems.
Just a tip for any one else starting in Haskell. If you are having problems check for tabs and spaces in your source code.

Answer:
return is an (overloaded) function, and it's not expecting its first argument to be a keyword.  You can either parenthesize:
```
```
module Main where
import System(getArgs)

main = do
     putStrLn "This is a test"
     s <- foo
     putStrLn s

foo = do
    args <- getArgs
    return (case args of
                [] -> "No Args"
                [s]-> "Some Args")
```
```
or use the handy application operator ($):
```
```
foo = do
    args <- getArgs
    return $ case args of
                [] -> "No Args"
                [s]-> "Some Args"
```
```
Stylewise, I'd break it out into another function:
```
```
foo = do
    args <- getArgs
    return (has_args args)

has_args [] = "No Args"
has_args _  = "Some Args"
```
```
but you still need to parenthesize or use ($), because return takes one argument, and function application is the highest precedence.


Question:
You can limit "Check-In Policy" rules via the "Custom Paths" policy. But the "Check-in Notes" tab doesn't seem to fit in to the same system. Why isn't "Check-In notes" just another "Check-In policy"??

I'm using Team Foundation Server 2008 SP1

Answer:
That's an interesting question - the short answer is you cannot.
I have ran into the issue myself a lot where people get check-in notes and check-in policies confused because, while very different in implementation on the server, they often serve similar purposes.
Check-in notes are bits of structured meta-data that you want to collect on every check-in to a Team Project.  They can be thinks like who was the code reviewer or a reference to a ticket in an external CRM system or something.  You can make them required, or just have them defined for people to optionally fill out.
Check-in policies are bits of code that run on the client at the point of check-in that get a say if the check-in should be allowed or not.  These are useful for checking things like you have associated a check-in with a work item, given it a comment or the code you are check-in in passes certain key static code analysis rules (such as basic checking for SQL injection attacks etc).  If a check-in policy fails in the evaluation of the check-in then the user gets alerted and they get the ability to fix the problem or check-in anyway with a check-in policy override than can easily be reported on or alerted for by the TFS administrator.
Both check-in notes and check-in policies are defined and scoped at the Team Project level.  However, Microsoft got feedback that some people would like check-in policies would like to be applied to specific paths in version control rather than just the Team Project and so the Custom Path Policy was invented.
The Custom Path Policy is a bit of a hack that allows you to wrap check-in policies inside the custom path policy.  The custom path gets evaluated on every check-in and if it contains files inside the defined path then the wrapped check-in policies are evaluated for those files.  The Custom Path Policy ships in the
TFS Power Tools
and is not part of the "Out The Box" TFS experience.
So, to answer your question a different way - I suspect the answer is "because that's the way it was designed and not enough people have asked for it to be changed".
If you wanted to leave feedback at
http://connect.microsoft.com/VisualStudio
I know they take customer feedback very seriously.


Question:
At work we have 4 people working together on a few different projects. For each project we each have a local copy we work on and then there is a development, staging, and live deployment, along with any branches we have (we use subversion). Our database is MySQL.

So my question is, what is a good way to manage which revisions to the database have been made to each deployment (and for the developers their local copies). Right now each change goes into a text file that is timestamped in the name and put into a folder under the project. This isn't working very well to be honest.. I need a solution that will help keep track of what has been applied where.

Answer:
http://odetocode.com/Blogs/scott/archive/2008/01/30/11702.aspx
The above blog brought us to our current database version control system.  Simply put, no DB changes are made without an update script and all update scripts are in our source control repository.
We only manage schema changes but you may also be able/willing to consider keeping dumps of your data available in version control as well; creating such files is a pretty trivial exercise using mysqldump.
Our solution differs from the solution presented in the blog in one key manner: it's not automated.  We have to hand apply database updates, etc.  Though this can be slightly time consuming, it postponed some of the effort a fully automated system would have required.  One thing we did automate however, was the db version tracking in the software: this was pretty simple and it ensures that our software is aware of the database it's running against and will ONLY run if it knows the schema it's working with.
The hardest part of our solution was how to merge updates from our branches into our trunk.  We spent some time to develop a workflow to address the possibility of two developers trying to merge branches with DB updates at the same time and how to handle it.  We eventually settled on locking a file in version control (the file in question for us is actually a table mapping software version to db version which assists in our manual management strategy), much like you would a thread's critical section, and the developer who gets the lock goes about their update of the trunk.  When completed, the other developer would be able to lock and it is their responsibility to make any changes necessary to their scripts to ensure that expected version collisions and other bad juju are avoided.


Question: I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus?

Answer:
Doing this seems like a hack, but it seems to work:
```
```
this.TopMost = true;  // as a result the form gets thrown to the front
this.TopMost = false; // but we don't actually want our form to always be on top
```
```
Edit: Note, this merely raises an already created form without stealing focus.


Question: I am just starting with SL and WPF. I am using the DataGrid control and I need to remove the mouseover effect (I actually will need to do more customizations than that). How do I do this. I think I need to do it with a control template but not sure how. I'm researching and reading right now. Any help would be appreciated.

Answer:
Yeah You have to change the Style and ControlTemplate , But are you using experssion blend to edit XAML? Blend is the easiest tool to do this.
Try changing the ControlTemplate for a Standard Button or ListBox and once you are comfortable then go to DatGrid. Why I am suggesting this is DataGrid is a complex combination of different UIElements so the control template will be hard to understand for a beginner.
Specific to MouseOver effect removal - There will be a
VSM
tag in the control template which has some storyboards , just remove the one with
```
<vsm:VisualState x:Name="MouseOver">
```
and you are good to go.


Question:
I'm using CSS Filters to modify images on the fly within the browser. These work perfectly in Internet Explorer, but aren't supported in Firefox.

Does anyone know what the CSS Filter equivalent for these is for Firefox? An answer that would work cross browser (Safari, WebKit, Firefox, etc.) would be preferred.

<style type="text/css">
    .CSSClassName {filter:Invert;}
    .CSSClassName {filter:Xray;}
    .CSSClassName {filter:Gray;}
    .CSSClassName {filter:FlipV;}
</style>

Update: I know Filter is an IE specific feature. Is there any kind of equivalent for any of these that is supported by Firefox?

Answer:
There are no equivalents in other browsers. The closest you could get is using a graphics library like Canvas and manipulating the images in it, but you'd have to write the manipulations yourself and they'd require JavaScript.
```
filter
```
is an IE-only feature -- it is not available in any other browser.


Question: For an ecommerce website how do you measure if a change to your site actually improved usability?  What kind of measurements should you gather and how would you set up a framework for making this testing part of development?

Answer:
Multivariate testing
and reporting is a great way to actually measure these kind of things.
It allows you to test what combination of page elements has the greatest conversion rate, providing continual improvement on your site design and usability.
Google Web Optimiser
has support for this.


Question: Is there a framework equivalent to Guice (http://code.google.com/p/google-guice) for Python?

Answer:
I haven't used it, but the
Spring Python
framework is based on Spring and implements
Inversion of Control
.
There also appears to be a Guice in Python project:
snake-guice


Question:
What is the difference between the following 2 ways to allocate and init an object?

AController *tempAController = [[AController alloc] init];
self.aController = tempAController;
[tempAController release];

and

self.aController= [[AController alloc] init];

Most of the apple example use the first method. Why would you allocate, init and object and then release immediately?

Answer:
Every object has a reference count.  When it goes to 0, the object is deallocated.
Assuming the property was declared as
```
@property (retain)
```
:
Your first example, line by line:
The object is created by
```
alloc
```
, it has a reference count of 1.
The object is handed over to
```
self
```
's
```
setAController:
```
method, which sends it a
```
retain
```
message (because the method doesn't know where the object is coming from), incrementing its reference count to 2.
The calling code no longer needs the object itself, so it calls
```
release
```
, decrementing the reference count to 1.
Your second example basically does steps 1 and 2 but not 3, so at the end the object's reference count is 2.
The rule is that if you create an object, you are responsible for releasing it when you're done with it.  In your example, the code is done with tempAController after it sets the property.  It is the setter method's responsibility to call
```
retain
```
if it needs that object to stick around.
It's important to remember that
```
self.property = foo;
```
in Objective-C is really just shorthand for
```
[self setProperty:foo];
```
and that the
```
setProperty:
```
method is going to be retaining or copying objects as needed.
If the property was declared
```
@property (copy)
```
, then the object would have been copied instead of retained.  In the first example, the original object would be released right away; in the second example, the original object's reference count would be 1 even though it should be 0.  So you would still want to write your code the same way.
If the property was declared
```
@property (assign)
```
, then
```
self
```
isn't claiming ownership of the object, and somebody else needs to retain it.  In this case, the first example would be incorrect.  These sorts of properties are rare, usually only used for object delegates.


Question:
Is there a good reason why there is no Pair<L,R> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.

It seems that 1.6 is providing something similar (AbstractMap.SimpleEntry<K,V>), but this looks quite convoluted.

Answer:
It depends on what you want to use it for.  The typical reason to do so is to iterate over maps, for which you simply do this (Java 5+):
```
```
Map<String, Object> map = ... ; // just an example
for (Map.Entry<String, Object> entry : map.entrySet()) {
  System.out.printf("%s -> %s\n", entry.getKey(), entry.getValue());
}
```
```


Question:
Yet again, my teacher was unable to answer my question. I knew who may be able to...

So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put

setbuf( stdout , NULL );

at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly.

My question is this: will this statement affect a cout statement, or simply a printf() statement that I call?

Thanks in advance!

Answer:
By default, iostreams and stdio are synchronised.
Reference.
This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise
```
std::endl
```
or
```
std::flush
```
(from
```
<ostream>
```
), which may help you. e.g.,
```
```
std::cout << "Hello, world!" << std::endl;
```
```
or
```
```
std::cout << "Hello, world!\n" << std::flush;
```
```
Both of these do the same thing. (
```
std::endl
```
= print endline, then flush.)


Question: The title is self explanatory. Is there a way of directly doing such kind of importing?

Answer:
Although my MySQL background is limited, I don't think you have much luck doing that. However, you should be able to migrate over all of your data by restoring the db to a MSSQL server, then creating a SSIS or DTS package to send your tables and data to the MySQL server.
hope this helps


Question:
We are putting up a company blog at companyname.com/blog but for now the blog is a Wordpress installation that lives on a different server (blog.companyname.com).

The intention is to have the blog and web site both on the same server in a month or two, but that leaves a problem in the interim.

At the moment I am using mod_rewrite to do the following:

http://companyname.com/blog/article-name redirects to http://blog.companyname.com/article-name

Can I somehow keep the address bar displaying companyname.com/blog even though the content is coming from the latter blog.companyname.com?

I can see how to do this if it is on the same server and vhost, but not across a different server?

Thanks

Answer:
Rather than using mod_rewrite, you could use
mod_proxy
to set up a reverse proxy on companyname.com, so that requests to
http://companyname.com/blog/article-name
are proxied (rather than redirected) to
http://blog.companyname.com/article-name
.
Here are
more instructions and examples
.


Question:
I need to pad numbers with leading zeros (total 8 digits) for display. I'm using oracle.

select to_char(1011,'00000000') OPE_NO from dual;
select length(to_char(1011,'00000000')) OPE_NO from dual;

Instead of '00001011' I get ' 00001011'.
Why do I get an extra leading blank space? What is the correct number formatting string to accomplish this?

P.S. I realise I can just use trim(), but I want to understand number formatting better.

@Eddie: I already read the documentation. And yet I still don't understand how to get rid of the leading whitespace.

@David: So does that mean there's no way but to use trim()?

Answer:
From that same
documentation
mentioned by
EddieAwad
:
Negative return values automatically
  contain a leading negative sign and
  positive values automatically contain
  a leading space unless the format
  model contains the MI, S, or PR format
  element.
EDIT
: The right way is to use the FM modifier, as answered by Steve Bosman. Read the section about
Format Model Modifiers
for more info.


Question:
I'm just trying to time a piece of code. The pseudocode looks like:

start = get_ticks()
do_long_code()
print "It took " + (get_ticks() - start) + " seconds."

How does this look in Python?

More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?

Answer:
What you need is
```
time()
```
function from
```
time
```
module:
```
```
import time
start = time.time()
do_long_code()
print "it took", time.time() - start, "seconds."
```
```
You can use
timeit
module for more options though.


Question: I was inserting data into a MS Access database using JDBC-ODBC driver.  The blank mdb file was 2KB.  After populating this database, the size grew to 155MB.  Then I was deleting the data.  But I found the size of mdb remains the same as 155MB.  I don't get any errors.  But is it normal this way?  I would expect the file size reduces.  If it is designed in this way, what is the idea behind it?  Thanks

Answer:
MS Access doesn't free up space used by records even after they are deleted. You can free the space manually when you need to or automatically each time you close the application.
To do it manually, use the Compact and Repair utility:
Backup your database, as there is a
bug in Access 2007
that may delete your database during the compacting procedure.
If you are compacting a multiuser (shared) database that is located on a server or shared folder, make sure that no one else has it open.
On the Tools menu, point to Database Utilities, and then click Compact and Repair Database.
To do it automatically when you close the application:
Open the database that you want MS Access to compact automatically.
On the Tools menu, click Options, and then choose the General tab.
Select the Compact On Close check box.
After deleting the data and compacting the database don't be surprised if is still larger than 100 KB. There is a certain amount of overhead that cannot be removed after you add data the first time.
Also, beware that AutoNumber field values behave differently than advertised after the compacting procedure: According to the MS Access 2000 documentation, if you delete records from the end of a table that has an AutoNumber field, compacting the database resets the AutoNumber value. So the AutoNumber value of the next record you add will be one greater than the AutoNumber value of the last undeleted record in the table.
I have
not
found this to be the case: If you have 100 Autonumbered records and delete the last 50, the next AutoNumber record (according to the documentation) should be numbered "51". But in my experience it is numbered "101", instead.


Question:
I have one thread that writes results into a Queue.

In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:

def queue_get_all(q):
    items = []
    while 1:
        try:
            items.append(q.get_nowait())
        except Empty, e:
            break
    return items

Is this a good way to do it ?

Edit:

I'm asking because sometimes the
  waiting thread gets stuck for a few
  seconds without taking out new
  results.

The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling wx.WakeUpIdle, as is recommended.

Answer:
I see you are using get_nowait() which according to the documentation, "return[s] an item if one is immediately available, else raise the Empty exception"
Now, you happen to break out of the loop when an Empty exception is thrown. Thus, if there is no result immediately available in the queue, your function returns an empty items list.
Is there a reason why you are not using the get() method instead? It may be the case that the get_nowait() fails because the queue is servicing a put() request at that same moment.


Question:
I'm storing an object (TTF_Font) in a shared_ptr that is provided to me from a third-party API. I cannot use new or delete on the object, so the shared_ptr is also provided a "freeing" functor.

// Functor
struct CloseFont
{
    void operator()(TTF_Font* font) const
    {
        if(font != NULL) {
            TTF_CloseFont(font);
        }
    }
};

boost::shared_ptr<TTF_Font> screenFont;

screenFont = boost::shared_ptr<TTF_Font>( TTF_OpenFont("slkscr.ttf", 8), CloseFont() );

If, later, I need to explicitly free this object is it correct to do this:

screenFont.reset();

And then let screenFont (the actual shared_ptr object) be destroyed naturally?

Answer:
shared_ptr<>::reset() will drop the refcount by one.  If that results in the count dropping to zero, the resource pointed to by the shared_ptr<> will be freed.
So I think the answer for you is, yes that will work.  Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen.
To be clear, the normal usage of shared_ptr<> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally.  reset() is only required if you need to release that particular instance of the shared resource before the shared_ptr<> would be naturally destructed.


Question:
GWT gets locale from either the  locale property or the locale query string.  If neither is specified, it uses the "default" (ie en_US) locale.

Why doesn't it get it from the browser settings?

It seems the only solution to this is to replace your static html launch page with something like a JSP that reads the browser locales and sets the  locale or redirects using the query string. There has to be a better solution than this or simply hard-coding a locale, surely?

Answer:
If you put a list of available languages into your *.gwt.xml file it will by default switch to the first language listed.
```
```
<!-- Slovenian in Slovenia -->
<extend-property name="locale" values="sl"/>

<!-- English language, independent of country -->
<extend-property name="locale" values="en"/>
```
```


Question:
I recently read somewhere that writing a regexp to match an email address, taking into account all the variations and possibilities of the standard is extremely hard and is significantly more complicated than what one would initially assume.

Why is that?

Are there any known and proven regexps that actually do this fully?

What are some good alternatives to using regexps for matching email addresses?

Answer:
For the
formal
e-mail spec, yes, it is technically impossible via Regex due to the recursion of things like comments (especially if you don't remove comments to whitespace first), and the various different formats (an e-mail address isn't always someone@somewhere.tld). You can get close (with some massive and incomprehensible Regex patterns), but a far better way of checking an e-mail is to do the very familiar handshake:
they tell you their e-mail
you e-mail them a confimation link with a Guid
when they click on the link you know that:
the e-mail is correct
it exists
they own it
Far better than blindly accepting an e-mail address.


Question: See title: what does it mean for a C++ function to be inline?

Answer:
The function body is literally inserted inside the caller function. Thus, if you have multiple calls to this function, you get multiple copies of the code. The benefit is you get faster execution.
Usually very short function are inlined, when the copy of the function body would be not much bigger than the usual prologue/epilogue code generated for the normal function call.
You can read more at MSDN article about inline -
http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx


Question: Is it possible to enumerate all the current errors being displayed through an "Error Provider" without having to access the controls?

Answer: There is a summary validator that will give you all of the errors, but it's pretty ugly, and I'm not sure if you can use it without displaying it on the page.  Technically, if you are doing things the "right way", all of you error handling should be handled in your midddle teir and then bubbled to the screen that way, so you already have access to all the errors in a collection or dictionary.


Question:
How do I write an Excel workbook to a MemoryStream without first saving it to the file system?

All options within the Microsoft.Office.Interop.Excel.WorkBook save options take a filename.

Answer:
I have done extensive work with the PIA and with storing Excel files in a document repository and streaming it out to the browser, and I have not been able to find a solution to using the PIA without first writing the contents to the file system first.
I think that you are going to have to swallow the bullet and deal with the file system as an intermediary.  The good news is that you can just give the file a unique name like a guid or use some other tempfilename method (not sure if one exists in .net) and just delete the contents when you are done.


Question:
How can I use JUnit idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test
public void testFooThrowsIndexOutOfBoundsException() {
  boolean thrown = false;

  try {
    foo.doStuff();
  } catch (IndexOutOfBoundsException e) {
    thrown = true;
  }

  assertTrue(thrown);
}

I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.

Answer:
How about this: catch a very general exception, make sure it makes it out of the catch block, then assert that the class of the exception is what you expect it to be.  This assert will fail if a) the exception is of the wrong type (eg. if you got a Null Pointer instead) and b) the exception wasn't ever thrown.
```
```
public void testFooThrowsIndexOutOfBoundsException() {
  Throwable e = null;

  try {
    foo.doStuff();
  } catch (Throwable ex) {
    e = ex;
  }

  assertTrue(e instanceof IndexOutOfBoundsException);
}
```
```


Question:
I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this:

lines = open('filename.py').readlines()

How to find the line number, where the docstring ends?

Answer:
If you're using the standard docstring format, you can do something like this:
```
```
count = 0
for line in lines:
    if line.startswith ('"""'):
        count += 1
        if count < 3:
            # Before or during end of the docstring
            continue
    # Line is after docstring
```
```
Might need some adaptation for files with no docstrings, but if your files are formatted consistently it should be easy enough.


Question: CLR profiler does not seem to work with the Silverlight CLR. Does another memory profiler exist?

Answer:
Doesn't seem to be one available yet. However, as
recommended in this forum thread
, you can convert your Silverlight app to a WPF application and profile that:
There is no tool as of now but as a workaround you can easily create a desktop (WPF) version of your Silverlight client from the same code base and few tweaks (refer Scot's blog for an example on this -
http://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-8-creating-a-digg-desktop-application-using-wpf.aspx
) .  Once you are done with this you can run any performance profiler that works with WPF.
Not an optimal solution, but it sounds like the best option for now...
Update:
Just saw a
blog post
about XPerf which is a cpu sampler for Silverlight. Not exactly a memory profiler but a good tool for testing the performance of Silverlight apps...


Question:
Alright, I have been doing the following (variable names have been changed):

FileInputStream fis = null;
try
{
    fis = new FileInputStream(file);

    ... process ...

}
catch (IOException e)
{
    ... handle error ...
}
finally
{
    if (fis != null)
        fis.close();
}

Recently, I started using FindBugs, which suggests that I am not properly closing streams.  I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException.  What are people supposed to do here?  The Java libraries throw too many checked exceptions.

Answer:
Something like the following should do it, up to you whether you throw or swallow the IOException on attempting to close the stream.
```
```
FileInputStream fis = null;
try
{
    fis = new FileInputStream(file);

    ... process ...

}
catch (IOException e)
{
    ... blah blah blah ...
}
finally
{
    try
    {
        if (fis != null)
            fis.close();
    }
    catch (IOException e)
    {
    }
}
```
```


Question:
I am debugging some code in the Selenium-rc proxy server. It seems the culprit is the HttpURLConnection object, whose interface for getting at the HTTP headers does not cope with duplicate header names, such as:

Set-Cookie: foo=foo; Path=/
Set-Cookie: bar=bar; Path=/

The way of getting at the headers through the HttpURLConnection (using getHeaderField(int n) and getHeaderFieldKey(int n)) seems to be causing my second cookie to be lost. My question is

Is it true that HttpURLConnection itself can't cope with it, and

If so, is there a workaround to it?

Answer:
Without actually having tried it (can't remember to have handled that topic myself), there's also getHeaderFields, inherited from
UrlConnection
. Does this do what you need?


Question:
I need to import largish (24MB) text files into a MySQL table. Each line looks like this:

1 1 0.008  0  0  0  0  0

There are one or more spaces after each field, and the last field is tailed by about 36 spaces before the newline.

How do I import such a file into MySQL? From the documentation it seems that LOAD DATA expects all fields to be terminated by exactly the same string. I have tried

LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ' ';

but MySQL will interpret a sequence of more than one space as delimiting an empty field.

Any ideas?

Answer:
If you're on unix/linux then you can put it through sed.
open a terminal and type:
```
```
sed 's/ \+/ /g' thefile > thefile.new
```
```
this replaces all sequences of multiple spaces with one space.


Question:
How do you setup an asp.net sql membership role/membership provider on a production machine? I'm trying to setup BlogEngine.NET and all the documentation says to use the ASP.NET Website Administration tool from Visual Studio but that isn't available on a production machine. Am I the first BlogEngine user to use it on a non-development box?

The SQL server is completely blocked off from everything but the production box, I do have SQL Management Studio on there though.

EDIT: I mean, how do you add new users/roles, not how do you create the tables. I've already ran aspnet_regsql to create the schema.

EDIT2: MyWSAT doesn't work because it requires an initial user in the database as well. I need an application that will allow me to create new users in the membership database without any authentication, just a connection string.

Answer:
You'll have to have .NET 2.0 installed on the machine, all the VS tool is is a GUI wrapper for a command line tool which is part of the framework.
Check C:\Windows\Microsoft.NET\Framework\v2.0.50727 for the app aspnet_regsql.exe
/? for command line switches, /W for a wizard mode


Question:
I started using Sandcastle some time ago to generate a Documentation Website for one of our projects. It's working quite well but we've always only written documentation for classes, methods, properties (...) in our project and had completely separate documentation for the overall project and project parts/modules/namespaces. It would be nice if I could merge that documentation together and add respective documentation to the generated helper files but I can't figure out how to do it.

Just adding comments to the namespace declaration doesn't seem to work (C#):

/// <summary>
/// My short namespace description
/// </summary>
namespace MyNamespace { ... }

Does anyone know how to do this? I know it's possible somehow and it would be really nice to have... :)

Answer:
If you use
Sandcastle Help File Builder
there is a dialog to enter the Namespace summaries. (Apparently also support for defining a specific class, but I wouldn't prefer it..)
From the feature list:
Definition of project summary and
  namespace summary comments that will
  appear in the help file. You can also
  easily indicate which namespaces to
  include or exclude from the help file.
  Support is also included for
  specifying namespace comments via a
  NamespaceDoc class within each
  namespace.


Question:
I've seen a few examples on how to do build deployment, however I have something unique that I'd like to do:

Deploy the build to a folder that has the build number (eg. Project\Builds\8423)

Alter the version number in the .NET AssmblyInfo.cs to match the build number

Has anyone done this before with .NET projects using NAnt + CruiseControl.net?

Answer:
i haven't done it with nant, but we have written a custom application in C# that reads the  assembly and increments the release number.
we call it from an exec block in the ccnet config.
creating a folder and copying files would be trivial to add to that application
our thinking was we use C# all day, so it would be quicker to fix/alter the build program written in C#, then if we had to learn the intracies of nant scripts on top of that
obviously if you use nant all the time, there would be no reason not to build a custom nant plugin to do the job


Question:
I'm just wondering if there can be a case where the hostname can be successfully resolved but the returned hostEntry.AddressList is empty.

Currently I'm doing something like this:

IPHostEntry hostEntry = Dns.GetHostEntry("some.hostname.tld");
if (hostEntry.AddressList.Count() < 1)
{
  // can that ever happen?
  throw new ArgumentException("hostName has no assigned IP-Address");
}
TcpClient client = new TcpClient(hostEntry.AddressList[0], 1234);

My assumption is that Dns.GetHostEntry either throws an exception if the hostname is not found or otherwise the AddressList is nonempty, but I'm not sure about that.

Answer:
You have three possible situations here:
The hostname exists (DNS has an A Record) and resolves to an IP Address
Condition is never hit
The hostname exists (DNS knows about the domain) however no A records exists.
This is an extremely unlikely scenario, and I think this can never happen in the first place.
The hostname doesn't exist
Exception is thrown, you never get there.
So no, I don't think that can ever happen.


Question:
We are using fmt:setBundle to load a resource bundle from a database (we extended the ResourceBundle class to do that).
When we modify a value in database, we have to reload the web server to display the new value on the web app.

Is there any simple way to use the new value without restarting the web server ?

(We do not want to always look up the value from database but we would like to invalidate the cache, for example by calling a special 'admin' URL)

EDIT : We are using JDK 1.4, so I would prefer a solution on that version. :)

Answer:
If you're using JDK 1.6 you can use the callback methods
```
getTimeToLive()
```
and
```
needsReload()
```
in
ResourceBundle.Control
to control if the bundle cache needs to be loaded with new values from the database.


Question:
I have a requirement to be able to provide a flex component in English and several asian languages.  I have looked at the flex documentation and it seems that I have to build several swf's, which feels wrong.

Does anyone know of a straightforward and practical way of bundling string resources in different languages and handling the fonts?

Answer:
We use Flex for the client part of our application and support I18N via
```
ResourceBundle
```
s.


Question:
I would like to know what of the many XSLT engines out there works well with Perl.

I will use Apache (2.0) and Perl, and I want to obtain PDFs and XHTMLs.

I'm new to this kind of projects so any comment or suggestion will be welcome.

Thanks.

Doing a simple search on Google I found a lot and I suppose that there are to many more.

http://www.mod-xslt2.com/

http://xml.apache.org/xalan-j/

http://saxon.sourceforge.net/

http://www.dopscripts.com/xslt_parser.html

Any comment on your experiences will be welcome.

Answer:
Can't really say which is the best solution because I didn't have a chance to try them all.
But I can recommend you to try Perl module
LibXSLT
.
It's an interface to the gnome libxslt library. I used it on one of my recent project was satisfied with it.


Question:
I am very new to creating webservers - and I have had several goes at trying to understand them and write a quick webserver, but it's never quite 'clicked'.  At the moment I am under the impression that REST would be most suitable for my purposes (I will explain later).

Can anyone either show me a basic code example in Java (using Tomcat Apache) or a tutorial resource to show how a webserver:

Can be used for security - i.e. pass in some kind of value to identify the client - from their the webserver will either deny or grant access to the client dependant on some criteria - maybe a lookup list.

Once the client is successfully accepted they will be allowed to pass in some more values to the webserver that will be used to write a row in a database table.

Many thanks.

PS - I would have thought there might have been soemthing that comes with Eclipse Ganymede? If someone can confirm?

Answer:
The best way to write restful resources in Java is via the JAX-RS standard. So I'd recommend you download
Jersey which is the JAX-RS reference implementation
and check out its examples; its got lots of them. Take an example for a spin then try hacking it to do what you like.
BTW JAX-RS can be run inside any Servlet engine - you just build a WAR and deploy it (there are examples in the Jersery samples) - though Jersey also comes with a small lightweight web server you can use too which is a little easier to use - again there are examples in the distro of this.


Question:
How do I initialize an automatic download of a file in Internet Explorer?

For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads.

In Firefox this is easy, you just need to include a meta tag in the header, <meta http-equiv="Refresh" content="n;url"> where n is the number of seconds and url is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers?

Answer:
I recently solved it by placing the following script on the page.
```
```
setTimeout(function () { window.location = 'my download url'; }, 5000)
```
```
I agree that a meta-refresh would be nicer but if it doesn't work what do you do...


Question:
I have an error occuring frequently from our community server installation whenever the googlesitemap.ashx is traversed on a specific sectionID. I suspect that a username has been amended but the posts havn't recached to reflect this.

Is there a way a can check the data integruity by performing a select statement on the database, alternatively is there a way to force the database to recache?

Answer:
I recently solved it by placing the following script on the page.
```
```
setTimeout(function () { window.location = 'my download url'; }, 5000)
```
```
I agree that a meta-refresh would be nicer but if it doesn't work what do you do...


Question:
In my environment here I use Java to serialize the result set to XML.
It happens basically like this:

//foreach column of each row
xmlHandler.startElement(uri, lname, "column", attributes);
String chars = rs.getString(i);
xmlHandler.characters(chars.toCharArray(), 0, chars.length());
xmlHandler.endElement(uri, lname, "column");

The XML looks like this in Firefox:

<row num="69004">
    <column num="1">10069</column>
    <column num="2">sd&#26;</column>
    <column num="3">FCVolume                      </column>
</row>

But when I parse the XML I get the a

org.xml.sax.SAXParseException: Character reference "&#26" is an
  invalid XML character.

My question now is: Which charactes do I have to replace or how do I have to encode my characters, that they will be valid XML?

Answer:
Extensible Markup Language (XML) 1.0
says:
The ampersand character (&) and the
  left angle bracket (<) must not appear
  in their literal form, except when
  used as markup delimiters, or within a
  comment, a processing instruction, or
  a CDATA section. If they are needed
  elsewhere, they must be escaped using
  either numeric character references or
  the strings "&" and "<"
  respectively. The right angle bracket
  (>) may be represented using the
  string ">", and must, for
  compatibility, be escaped using either
  ">" or a character reference when
  it appears in the string "]]>" in
  content, when that string is not
  marking the end of a CDATA section.
You can skip the encoding if you use CDATA:
```
```
<column num="1"><![CDATA[10069]]></column>
<column num="2"><![CDATA[sd&]]></column>
```
```


Question:
In Eclipse 3.3.2, I would like to replace a character (say ',') by a new line in a file.
What should I write in the "Replace with" box in order to do so ?

EDIT : Many answers seems to be for Eclipse 3.4. Is there a solution for Eclipse 3.3.X ?

Answer:
Check box 'Regular Expressions' and use '\R' in the 'Replace with' box
It's a new feature introduced with Eclipse 3.4, See
What's New in 3.4


Question: If I hit a page which calls session_start(), how long would I have to wait before I get a new session ID when I refresh the page?

Answer:
Check out php.ini the value set for session.gc_maxlifetime is the ID lifetime in seconds.
I believe the default is 1440 seconds (24 mins)
http://www.php.net/manual/en/session.configuration.php
Edit:
As some comments point out, the above is not entirely accurate.  A wonderful explanation of why, and how to implement session lifetimes is available here:
How do I expire a PHP session after 30 minutes?


Question:
I am trying to configure Reporting Services 2005SP2 on a machine with SQL 2008 on another hosting the ReportServer DB.

When I create the ReportServerDB the DB is created as version C.0.9.45:

When, afterwards, I try to initialise Reporting Services, I get an error about an incorrect version number. Reporting Services created a ReportServer DB version C.0.9.45 but now expects a version C.0.8.54.

Changing compatibility settings of the DB doesn’t have an effect. And changing the version number sproc in the DB to return what Reporting Services wants to hear only delays the crash until initialisation has started.

Any ideas?

Answer: You must have created the reportServerDB using the SQL 2008 configuration tool. If you want to use the 2005 version of the server you need to create the configuration database using the configuration tool that came with SQL 2005. The 2005 SP2 tool will create a database with version C.0.8.54


Question:
I am using Eclipse for quite some time and I still haven't found how to configure the Problems View to display only the Errors and Warnings of interest. Is there an easy way to filter out warnings from a specific resource or from a specific path? For example, when I generate javadoc I get tons of irrelevant html warnings. Also, is there a way to change the maximum number of appearing warnings/errors?

I am aware of the filters concept, but I am looking for some real life examples. What kind of filters or practices do other people use?

Edit: I found the advice to filter on "On selected element and its children" to be the best one. I have one other issue however. If I have "a lot" of warnings or errors, only the first 100 appear. In the rare case I want to see all of them, how do I do it?

Answer:
In the top right hand corner of the problems pane is a filter button (it looks like three arrows pointing to the right), clicking that will let you configure the view.  You can filter by element, such as the class you're editing or working set, the type of problem (e.g. java problems, buildfile problems etc..) and by severity.  It's actually very configurable.
See
http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.user/concepts/cprbview.htm
for details and screenshots.


Question: What i mean exactly is that build.xml that actually included those plugins like findbugs etc. Or nicely done build.xml

Answer: You could use maven 2, because it has built-in plugin support.And all the stuff like: PMD, Findbugs, Checkstyle etc , could be integrated automatically . If you have some existing code it could be called from maven you could use maven-antrun-plugin.


Question:
This is a followup question of How to encode characters from Oracle to Xml?

In my environment here I use Java to serialize the result set to xml. I have no access to the output stream itself, only to a org.xml.sax.ContentHandler.

When I try to output characters in a CDATA Section:

It happens basically like this:

xmlHandler.startElement(uri, lname, "column", attributes);
String chars = "<![CDATA["+rs.getString(i)+"]]>";
xmlHandler.characters(chars.toCharArray(), 0, chars.length());
xmlHandler.endElement(uri, lname, "column");

I get this:

<column>&lt;![CDATA[33665]]&gt;</column>

But I want this:

<column><![CDATA[33665]]></column>

So how can I output a CDATA section with a Sax ContentHandler?

Answer:
It is getting escaped because the handler.characters function is designed to escape and the
```
<![CDATA[
```
part isn't considered part of the value.
You need to use the newly exposed methods in
```
DefaultHandler2
```
or use the
```
TransformerHandler
```
approach where you can set the output key
```
CDATA_SECTION_ELEMENTS
```
, which takes a whitespace delimited list of tag names that should output sub text sections enclosed in CDATA.
```
```
StreamResult streamResult = new StreamResult(out);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "column");
hd.setResult(streamResult);
hd.startDocument();
hd.startElement("","","column",atts);
hd.characters(asdf,0, asdf.length());
hd.endElement("","","column");
hd.endDocument();
```
```


Question:
I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists.  Here is my GetItem method:

public static T GetItem<T>(string key, Func<T> defaultValue)
{
    if (HttpContext.Current.Session[key] == null)
    {
        HttpContext.Current.Session[key] = defaultValue.Invoke();
    }
    return (T)HttpContext.Current.Session[key];
}

Now, how do I actually use this, passing in the Func<T> as an inline method parameter?

Answer:
Why don't you pass the default value directly? What use is the functor?
By the way,
```
defaultValue.Invoke()
```
is quite verbose. It's also possible to just write
```
defaultValue()
```
.


Question: In C++ the storage class specifier static allocates memory from the data area. What does "data area" mean?

Answer:
I'm not familiar with the term “data area” but memory is often divided into “code section” and “data section”. Code resides in the former, data in the latter. I presume this is what's meant here.
Classically, there's no distinction between the two. However, many modern operating systems can prohibit the execution of code int he data segment (provided the CPU supports this distinction). This sometimes goes by the catch phrase of “NX flag”, as in “no execution” and can effectively prevent some cases of malicious code injection.
/EDIT: Notice that the C++ standard doesn't mention a “data area”.


Question:
In a question answer I find the following coding tip:-

2) simple lambdas with one parameter:

x => x.ToString() //simplify so many calls

As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples.

I've researched lambdas so I think I know what they do, however I may not fully understand so a little unpacking might also be in order.

Answer:
This basically expands to:
```
```
private string Lambda(object x) {
  return x.ToString();
}
```
```


Question: I need to consume a wcf service dynamically when all i know is its URL. I do not have the option of creating a service reference or web reference as my client side code picks up the URL from a config file. What classes and methods can i use from the System.ServiceModel namespace for doing so.

Answer:
If you know the contract then you can do something like:
```
```
using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri("http://localhost:8000/Web")))
```
```
More
here


Question:
We're in the process of developing a measurement device that will be running
CE 6.0 with CF 3.5 on x86 embedded hardware, a PC is used to control the
device and is connected with it using ethernet.

We would like to communicate using interfaces (using DCOM (we know it is not
supported by default on CE6), .NET Remoting or Web services) instead of
using some sort of (custom) protocol. Calling methods defined in an
interface is so much easier and elegant then parsing raw data.

What would be the best solution in this case?

Answer:
I've had some experience setting up comms between CE devices and a PC, and have used custom interfaces using winsock (thwacking some bytes back and forwards) and have tried SOAP. In Windows CE 5.0, the Microsoft provided SOAP server took our device down somehow every couple of hours or so. I spent many weeks trying to work out what was wrong, thinking it was something I'd done wrong. So, I prefer to stick to winsock now because at least I've got a chance of knowing what's going on and can fix it.
Also, CE devices aren't always the quickest performers depending on what hardware you've got. Web-services take up some overhead and time converting data to XML, and this may be a performance hit you are or are not able to afford.


Question: Can anyone recommend good simulation software for mobile devices?  I am most interested in Nokia smart phones.

Answer:
Are you looking for Emulator for Nokia phones? You can find those
here
..
Otherwise explain clearly what kind of simulation software you are looking for!


Question:
I'm writing a shell for a project of mine, which by design parses commands that looks like this:

COMMAND_NAME ARG1="Long Value" ARG2=123 ARG3=me@me.com

My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.

Any ideas how can this be solved? Any existing library for this?

Answer:
Without fairly intensive surgery on optparse or getopt, I don't believe you can sensibly make them parse your format. You can easily parse your own format, though, or translate it into something optparse could handle:
```
```
parser = optparse.OptionParser()
parser.add_option("--ARG1", dest="arg1", help="....")
parser.add_option(...)
...
newargs = sys.argv[:1]
for idx, arg in enumerate(sys.argv[1:])
    parts = arg.split('=', 1)
    if len(parts) < 2:
        # End of options, don't translate the rest.
        newargs.extend(sys.argv[idx+1:])
        break
    argname, argvalue = parts
    newargs.extend(["--%s" % argname, argvalue])

parser.parse_args(newargs)
```
```


Question:
I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help.

I would like to expose an iterator for a class like this:

template <class T>
class MyContainer
{
public:
    // Here is the problem:
    // typedef for MyIterator without exposing std::vector publicly?

    MyIterator Begin() { return mHiddenContainerImpl.begin(); }
    MyIterator End() { return mHiddenContainerImpl.end(); }

private:
    std::vector<T> mHiddenContainerImpl;
};

Am I trying at something that isn't a problem? Should I just typedef std::vector< T >::iterator? I am hoping on just depending on the iterator, not the implementing container...

Answer:
This should do what you want:
```
```
typedef typename std::vector<T>::iterator MyIterator;
```
```
From
Accelerated C++
:
Whenever you have a type, such as
```
vector<T>
```
, that depends on a template parameter, and you want to use a member of that type, such as
```
size_type
```
, that is itself a type, you must precede the entire name by
```
typename
```
to let the implementation know to treat the name as a type.


Question:
I'm planning to write a web service aka api for my application which was developed with .Net and SQLServer. .Net provides a simple way to create webservices by creating asmx files. But i need to know how best it can be designed or what are the best practices in creating a web service in .net or some pointers to good articles as this is my first experience in web services programming. Eventhough SF has many references to best practices in API (which are very good) i dont find much information oriented for .net webservices.

Update: After dariom's reply i would like to mention that i'm doing it in .net 2.0

Answer:
It's not easy to remember all the best practices out there, but here is my advice:
Avoid using data types which aren't easily serializable or aren't compatible with the WS standards (and thus you won't be able to consume the service using different languages). Most notably are RecordSets and other MS-only reference types.
Notice there's a difference between static web service (a static method which has [webmethod]) and non-static (memeber function). This might affect your performance and resource usage.
There's a difference between designing a .NET webservice that runs inside your intranet, and a webservice designed for the internet. The second should be simpler in that the XML data that goes on the wire should be much smaller.
I guess the webservice is going to deployed on an IIS server. Notice there's a difference in authentication when running inside the intranet and on the internet. You might need to use impersonation for the service to be able to do specific tasks.
I guess there's much much more, better look for some documentation discussing that.


Question:
I recently started learning Emacs. I went through the tutorial, read some introductory articles, so far so good.

Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs 22.

I read all information I could find but most of it seems fairly outdated and I'm still confused.

The questions:

What is their difference?

Which mode should I install and use?

Are there other Emacs add-ons that are essential for Python development?

Relevant links:

EmacsEditor @ wiki.python.org

PythonMode @ emacswiki.org

Answer:
If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain that it didn't work very nicely in the past, but there are updates available that fix some of the issues (for instance, on the emacswiki page you link), and you would hope some were integrated upstream by now. If I were the GNU Emacs kind, I would use python.el until I found specific reasons not to.
The python-mode.el's single biggest problem as far as I've seen is that it doesn't quite understand triple-quoted strings. It treats them as single-quoted, meaning that a single quote inside a triple-quoted string will throw off the syntax highlighting: it'll think the string has ended there. You may also need to change your auto-mode-alist to turn on python-mode for .py files; I don't remember if that's still the case but my init.el has been setting auto-mode-alist for many years now.
As for other addons, nothing I would consider 'essential'. XEmacs's func-menu is sometimes useful, it gives you a little function/class browser menu for the current file. I don't remember if GNU Emacs has anything similar. I have a rst-mode for reStructuredText editing, as that's used in some projects. Tying into whatever VC you use, if any, may be useful to you, but there is builtin support for most and easily downloaded .el files for the others.


Question: I have an script that falls over if any of the procedures it is trying to create already exists. How can I check/drop if this procedure is already created?

Answer:
I would guess something along the lines of:
```
```
IF EXISTS
(
    SELECT *
    FROM SYSPROCS
    WHERE SPECIFIC_SCHEMA = ???
      AND SPECIFIC_NAME = ???
      AND ROUTINE_SCHEMA = ???
      AND ROUTINE_NAME = ???
)
    DROP PROCEDURE ???
```
```
I don't know if you actually need the SPECIFIC_* information or not and I don't know how to handle cases where you have two procedures with the same name but different call signatures, but hopefully this gets you on the right track.


Question:
I'm attempting to check for the existence of a node using the following .NET code:

xmlDocument.SelectSingleNode(
        String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName));

This always raises:

XPathException: Expression must evaluate to a node-set.

Why am I getting this error and how can I resolve it? Thank you.

Answer:
Try:
```
```
Node node = xmlDocument.SelectSingleNode(String.Format("//ErrorTable/ProjectName = '{0}'", projectName));

if (node != null) {
    // and so on
}
```
```
Edit: silly error


Question: I have a list of tuples eg. [{1,40},{2,45},{3,54}....{7,23}] where 1...7 are days of the week (calculated by finding calendar:day_of_the_week()). So now I want to change the list to [{Mon,40},{Tue,45},{Wed,54}...{Sun,23}]. Is there an easier way to do it than lists:keyreplace?

Answer:
Simple. Use map and a handy tool from the httpd module.
```
```
lists:map(fun({A,B}) -> {httpd_util:day(A),B} end, [{1,40},{2,45},{3,54},{7,23}]).
```
```


Question:
When you're adding javaDoc comments to your code and you're outlining the structure of an XML document that you're passing back, what's the best way to represent attributes? Is there a best practice for this?

My general structure for my javaDoc comments is like this:

/**
 * ...
 *
 * @return XML document in the form:
 *
 * <pre>
 * &lt;ROOT_ELEMENT&gt;
 *    &lt;AN_ELEMENT&gt;
 *    &lt;MULTIPLE_ELEMENTS&gt;*
 * &lt;/ROOT_ELEMENT&gt;
 * </pre>
 */

Answer:
Not sure I clearly  understand your question.
My preferred solution would be to embed the schema XSD or DTC in the description of the return parameter. Your solution seems to lead to personal idioms on how to represent things like multiple elements or others. Using a standard like XSD or DTD allows you to have a well know and recognized language on how to describe the structure of a XML document.
Regarding the JavaDoc representation if you are using Eclipse you can specify under Save Actions to format your document. This way you can write normally with > and < and see it converted to the escaped HTML codes.


Question:
I made a view to abstract columns of different tables and pre-filter and pre-sort them. There is one column whose content I don't care about but I need to know whether the content is null or not. So my view should pass an alias as "true" in case the value of this specified column isn't null and "false" in case the value is null.

How can I select such a boolean with T-SQL?

Answer:
You have to use a
CASE
statement for this:
```
```
SELECT CASE WHEN columnName IS NULL THEN 'false' ELSE 'true' END FROM tableName;
```
```


Question:
As far as i know it is not possible to do the following in C# 2.0

public class Father
{
    public virtual Father SomePropertyName
    {
        get
        {
            return this;
        }
    }
}

public class Child : Father
{
    public override Child SomePropertyName
    {
        get
        {
            return this;
        }
    }
}

I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic.

public new Child SomePropertyName

Is there any solution in 2.0?
What about any features in 3.5 that address this matter?

Answer:
No. C# does not support this idea (it's called "return type covariance").
You can however do this:
```
```
public class FatherProp
{
}

public class ChildProp: FatherProp
{
}

public class Father
{
    public virtual FatherProp SomePropertyName
    {
        get
        {
            return new FatherProp();
        }
    }
}

public class Child : Father
{
    public override FatherProp SomePropertyName
    {
        get
        {
            // override to return a derived type instead
            return new ChildProp();
        }
    }
}
```
```
i.e. use the contract defined by the base class, but return a derived type. I have made a more detailed sample to make this point clearer - returning "this" again wouldn't change anything.
It is possible (but messy) to test the returned object for it's actual type (i.e. "if someObject is ChildProp"), but it is better to call a virtual method on it that does the right thing for its type.
The base class virtual method (in this case, virtual property) not only has an implementation, but also defines a contract: that a child class can supply a different implementation of SomePropertyName if it meets this contract (i.e. SomePropertyName returns an object of type "FatherProp"). Returning an object of type "ChildProp" derived from "FatherProp" meets this contract. But you can't change the contract in "Child" - this contract applies to all classes descended from "Father".
If you take a step back and look at your broader design, there are other language constructs in the C# toolkit that you may also want to think about instead - Generics, or interfaces.


Question:
I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit.

Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?

Answer:
You might try doing this in the doPost() method of your servlet
```
```
multi = new MultipartRequest(request, dirName, FILE_SIZE_LIMIT);

if(submitButton.equals(multi.getParameter("Submit")))
{
    out.println("Files:");
    Enumeration files = multi.getFileNames();
    while (files.hasMoreElements()) {
    String name = (String)files.nextElement();
    String filename = multi.getFilesystemName(name);
    String type = multi.getContentType(name);
    File f = multi.getFile(name);
    if (f.length() > FILE_SIZE_LIMIT)
    {
        //show error message or
        //return;
        return;
    }
}
```
```
This way you don't have to wait to completely process your HttpRequest and can return or show an error message back to the client side. HTH


Question: Anybody knows how to do this? I got all the information of the email (body, subject, from , to, cc, bcc) and need to generate an .eml file out of it.

Answer:
EML files are just plain text files. The headers are separated from the body by a blank line. Headers look like this:
```
```
From: "DR CLEMENT OKON" <drclement@nigerianspam.com>
To: "You" <you@yourdomain.com>
Subject: REQUEST FOR URGENT BUSINESS RELATIONSHIP
Date: Tue, 30 Sep 2008 09:42:47 -0400
```
```
For more info, the official spec is
RFC 2822
. It's actually not as hard to read as some RFCs.
Edit: When I said "plain text" I should have thought for a second. I really meant plain ASCII - and not the 8-bit "extended ASCII" either - just up to character 127. If you want more than seven bits, you need some kind of encoding and things get complicated.


Question: I would like to send HTML email with graphic elements included. I have no idea to attach garaphics to this email.

Answer:
I'm not going to bore you with a mediocre explanation here so instead let me link to this great tutorial over at Sitepoint which explained it to me in plain English! -
advanced-email-php


Question:
With the best will in the world, whatever software you (and me) write will have some kind of defect in it.

What can I do, as a developer, to make things easier for the support department (first line, through to third line, and development) to diagnose, workaround and fix problems that the user encounters.

Notes

I'm expecting answers which are predominantly technical in nature, but I expect other answers to exist.

"Don't release bugs in your software" is a good answer, but I know that already.

Answer:
Technical features:
In the error dialogue for a desktop app, include a clickable button that opens up and email, and attaches the stacktrace, and log, including system properties.
On an error screen in a webapp, report a timestamp including nano-seconds and error code, pid, etc so server logs can be searched.
Allow log levels to be dynamically changed at runtime. Having to restart your server to do this is a pain.
Log as much detail about the environment in which you're executing as possible (probably on startup).
Non-technical:
Provide a known issues section in your documentation. If this is a web page, then this correspond to a triaged bug list from your bug tracker.
Depending on your audience, expose some kind of interface to your issue tracking.
Again, depending on audience, provide some forum for the users to help each other.
Usability solves problems before they are a problem. Sensible, non-scary error messages often allow a user to find the solution to their own problem.
Process:
watch your logs. For a server side product, regular reviews of logs will be a good early warning sign for impending trouble. Make sure support knows when you think there is trouble ahead.
allow time to write tools for the support department. These may start off as debugging tools for devs, become a window onto the internal state of the app for support, and even become power tools for future releases.
allow some time for devs to spend with the support team; listening to customers on a support call, go out on site, etc. Make sure that the devs are not allowed to promise anything. Debrief the dev after doing this - there maybe feature ideas there.
where appropriate provide user training. An impedence mismatch can cause the user to perceive problems with the software, rather than the user's mental model of the software.


Question: Which Computer-aided Software Engineering tools do you use and why? In what ways do they increase your productivity or help you design your programs? Or, in case you do not use CASE tools, what are your reasons for this?

Answer:
I have used Rational Rose and a few other similar packages in the past. Mostly I have used them for the UML diagram elements and have not gone into the more detailed functionality such as code generation etc.
I mostly use them for aiding the design process and clarifying my own ideas. Often I find that, in trying to come up with a design for a componant, I end up needing to write down / draw what I want to happen so I can get a clear overview in my mind of what needs to happen and why. I have found that in a lot of cases, what I end up trying to draw is essentially the same as a predefined kind of diagram in UML, such as a Use Case Diagram etc. and by then adopting that style, it becomes easier to get my ideas on paper as I have some framework to work within.
So, I use CASE tools principally for thier UML / designing tools at a highish, semi-abstract level.


Question:
In the past and with most my current projects I tend to use a for loop like this:

var elements = document.getElementsByTagName('div');
for (var i=0; i<elements.length; i++) {
    doSomething(elements[i]);
}

I've heard that using a "reverse while" loop is quicker but I have no real way to confirm this:

var elements = document.getElementsByTagName('div'),
    length = elements.length;

while(length--) {
    doSomething(elements[length]);
}

What is considered as best practice when it comes to looping though elements in JavaScript, or any array for that matter?

Answer:
At the risk of getting yelled at, i would get a javascript helper library like
jquery
or
prototype
they encapsulate the logic in nice methods - both have an .each method/iterator to do it - and they both strive to make it cross-browser compatible
EDIT: This answer was posted in 2008. Today much better constructs exist. This particular case could be solved with a
```
.forEach
```
.


Question:
We have a project consisting of multiple subprojects. With each subproject we potentially have some hibernate mapping files but in the end only one actual hibernate session. Those subprojects could be combined in several ways, some depend on each other. My problem is that actually I want to have a SessionFactoryBean which would be able to collect those mappings/mappinglocations from the applicationContext(s) and configure itself.

Has somebody written something like this, or do I have to do it myself (I envision something a bit like the urlresolver or viewresolver functionality from SpringMVC)?

Answer:
```
LocalSessionFactoryBean
```
has a configLocations property.  You inject the list of config locations, and it will gather tham together for a single session factory configuration.


Question:
Following Izb's question about Best binary XML format for JavaME, I'm looking for an implementation for either binary XML-like formats or just plain XML. My metrics for such implementation, by most important first, are:

Supported phones. A basic JTWI phone should be able to run it.

It should be either verified or open source, so I could have it verified.

Small memory footprint.

Fast.

Easy to use on server side.

Answer:
The W3C defined a binary encoding for XML, it's called Fast InfoSet, but it's optimised for high-volume web services, rather than embedded devices, and I don't think there are any light and fast implementations suitable for you.
If you want to stick with plain XML, and you need a DOM implementation, then go with XOM (
http://xom.nu
). It's easily the DOM with the smallest footprint, and it's very fast.
But if you really need to reduce your footprint, then you need to use a non-DOM API like SAX or STAX, but that's considerably more work.


Question:
We are using a PHP scripting for tunnelling file downloads, since we don't want to expose the absolute path of downloadable file:

header("Content-Type: $ctype");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=\"$fileName\"");
readfile($file);

Unfortunately we noticed that downloads passed through this script can't be resumed by the end user.

Is there any way to support resumable downloads with such a PHP-based solution?

Answer:
Yes. Support byteranges. See
RFC 2616 section 14.35
.
It basically means that you should read the
```
Range
```
header, and start serving the file from the specified offset.
This means that you can't use readfile(), since that serves the whole file. Instead, use
fopen()
first, then
fseek()
to the correct position, and then use
fpassthru()
to serve the file.


Question:
I happened to debate with a friend during college days whether advanced mathematics is necessary for any veteran programmer. He used to argue fiercely against that. He said that programmers need only basic mathematical knowledge from high school or fresh year college math, no more no less, and that almost all of programming tasks can be achieved without even need for advanced math. He argued, however, that algorithms are fundamental & must-have asset for programmers.

My stance was that all computer science advances depended almost solely on mathematics advances, and therefore a thorough knowledge in mathematics would help programmers greatly when they're working with real-world challenging problems.

I still cannot settle on which side of the arguments is correct. Could you tell us your stance, from your own experience?

Answer:
computer science != programming
OK, seriously, I know good and bad programmers who were English and Psychology majors and some that were Computer Science majors.  Some very famous guys that I admire as developers didn't have a CS background.  Larry Wall(Perl), for example, was a linguist.
On the other hand, it helps to know something about the domain you are working on because then you can at least see if your data makes sense and help your customer/users drill down to what they really want.
And yes, there's the issue of computational complexity and efficient data structures and program correctness.  That's stuff you learn in Computer Science and that's useful to know in almost any domain, but it's neither necessary nor sufficient.


Question:
I want to find out, with an SQL query, whether an index is UNIQUE or not. I'm using SQLite 3.

I have tried two approaches:

SELECT * FROM sqlite_master WHERE name = 'sqlite_autoindex_user_1'

This returns information about the index ("type", "name", "tbl_name", "rootpage" and "sql"). Note that the sql column is empty when the index is automatically created by SQLite.

PRAGMA index_info(sqlite_autoindex_user_1);

This returns the columns in the index ("seqno", "cid" and "name").

Any other suggestions?

Edit: The above example is for an auto-generated index, but my question is about indexes in general. For example, I can create an index with "CREATE UNIQUE INDEX index1 ON visit (user, date)". It seems no SQL command will show if my new index is UNIQUE or not.

Answer:
you can programmatically build a select statement to see if any tuples point to more than one row. If you get back three columns, foo, bar and baz, create the following query
```
```
select count(*) from t
group by foo, bar, baz
having count(*) > 1
```
```
If that returns any rows, your index is not unique, since more than one row maps to the given tuple. If sqlite3 supports derived tables (I've yet to have the need, so I don't know off-hand), you can make this even more succinct:
```
```
select count(*) from (
    select count(*) from t
    group by foo, bar, baz
    having count(*) > 1
)
```
```
This will return a single row result set, denoting the number of duplicate tuple sets. If positive, your index is not unique.


Question:
I have a dictionary of 200,000 items (the keys are strings and the values are integers).

What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?

 a={ 'keyC':1, 'keyB':2, 'keyA':1 }
b = a.items()
b.sort( key=lambda a:a[0])
b.sort( key=lambda a:a[1], reverse=True )
print b
>>>[('keyB', 2), ('keyA', 1), ('keyC', 1)]

Answer:
You can't sort dictionaries.  You have to sort the list of items.
Previous versions were wrong.  When you have a numeric value, it's easy to sort in reverse order.   These will do that.  But this isn't general.  This only works because the value is numeric.
```
```
a = { 'key':1, 'another':2, 'key2':1 }

b= a.items()
b.sort( key=lambda a:(-a[1],a[0]) )
print b
```
```
Here's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option.
```
```
def valueKeyCmp( a, b ):
    return cmp( (-a[1], a[0]), (-b[1], b[0] ) )

b.sort( cmp= valueKeyCmp )
print b
```
```
The more general solution is actually two separate sorts
```
```
b.sort( key=lambda a:a[1], reverse=True )
b.sort( key=lambda a:a[0] )
print b
```
```


Question:
How can this line in Java be translated to Ruby:

    String className = "java.util.Vector";

    ...

    Object o = Class.forName(className).newInstance();

Thanks!

Answer:
```
```
Object::const_get('String').new()
```
```


Question:
I have to work on an old 1.3 JVM and I'm asked to create a secure connection to another server. Unfortunately the HttpsURLConnection only appears sinc JVM 1.4.

Is there another way to create a secure connection? Is there a library that I could you to add this fonctionnality?

Answer:
You need to install the Java Secure Socket Extension (JSSE), which used to be required because Sun wouldn't ship it with the JDK because of comedy export restrictions. I had a look on Sun's web site, but the JDK 1.3 instructions are preving elusive.  Bear in mind that JDK 1.3 is now end-of-lifed by Sun, so they may not have any information any more.
http://hc.apache.org/httpclient-3.x/sslguide.html


Question:
I'm discovering a simple solution for singular-plural keywords searches. I heard about stemming but I don't want to use all its features, only plural/singular transformation. The language is Dutch. Have looked at http://www.snowball.tartarus.org before. Does anyone know the simple solution for singular|plural relevant searches?
Thanks in advance.

Answer:
Use a dictionary, a list of stopwords (those you don't want to singularize) plus the rules for the language. If you don't know Dutch then I cannot help you, but show you how it'd be done in Spanish, for instance:
Plurals end with s, if it doesn't then it's done
If it ends with s,
check if it's a verb or conjugation ending with s if it is one, then it's done (verbs could be added to the stopwords list)
if it's not a verb, remove s
if the word exists in the dictionary, done
if it doesn't remove the previous letter, and check it in the dictionary.
if it's still not there it's an exception you'll need to check manually to code in the exceptions (I cannot right now think of any, but they always exist :)
Of course this will not translate directly to Dutch.
In general stemmers are already done and provide most of what you need, why don't you want them?


Question:
I've got a XmlNodeList which I need to have it in a format that I can then re-use within a XSLT stylesheet by calling it from a C# extension method.

Can anyone help? I have read that it might have something to do with using a XPathNavigator but I'm still a bit stuck.

Answer:
I had to solve this issue myself a couple of years ago. The only way I managed it was to create an XML fragment containing the nodes in the node list and then passing in the children of the fragment.
```
```
XsltArgumentList arguments = new XsltArgumentList();
XmlNodeList nodelist;
XmlDocument nodesFrament = new XmlDocument();
XmlNode root = nodesFragment.CreateElement("root");
foreach (XmlNode node in nodeList)
{
    root.AppendChild(node);
}
nodesFragment.AppendChild(root);

arguments.AddParam("argumentname", string.Empty, nodesFragment.CreateNavigator().SelectChildren(XPathNodeType.All));
```
```
Then you need to make sure you have the corresponding argument in your XSLT, of course.
Note that you probably don't need the additional XmlDocument. You could just call CreateNavigator() on the root XmlNode instance and use your existing XmlDocument for creating the element (I wrote this code some time ago and I've learned more since then - but I know the code above works, I haven't tried any alternatives).


Question: I understand access modifiers at the class level and below, but why would an entire assembly be private? I assume by default, assemblies are public?

Answer:
Well, in the context of assemblies, private means the assembly cannot be referenced by another application outside the directory it's contained in. Therefore, private to the application it's being used for.
As for your question about the default being public....someone correct me if I'm wrong, but there is no public. It would be shared. A shared assembly can obviously be referenced by multiple applications and must reside in the GAC. All the rules of the GAC would then apply.


Question:
Background

I have a massive db for a SharePoint site collection.  It is 130GB and growing at 10gb per month.  100GB of the 130GB is in one site collection. 30GB is the version table.  There is only one site collection - this is by design.

Question

Am I able to partition a database (SharePoint) using SQL 2005s data partitioning features (creating multiple data files)?
Is it possible to partition a database that is already created?
Has anyone partitioned a SharePoint DB? Will I encounter any issues?

Answer:
You would have to create a partition set and rebuild the table on that partition set.  SQL2005 can only partition on a single column, so you would have to have a column in the DB that
Behaves fairly predictably so you don't get a large skew in the amount of data in each partition
IIRC the column has to be a numeric or datetime value
In practice it's easiest if it's monotonically increasing - you can create a series of partitions (automatically or manually) and the system will fill them up as it gets to the range definitions.
A date (perhaps the date the document was entered) would be ideal.  However, you may or may not have a useful column on the large table.  M.S. tech support would be the best source of advice for this.
The partitioning
should
be transparent to the application (again, you need a column with appropriate behaviour to use as a partition key).
Unless you are lucky enough to have a partition key column that is also used as a search predicate in the most common queries you may not get much query performance benefit from the partitioning.  An example of a column that works well is a date column on a data warehouse.  However, your Sharepoint application may not make extensive use of this sort fo query.


Question:
I'm using VisualSVN Server to host an SVN repo, and for some automation work, I'd like to be able to get specific versions via the http[s] layer.

I can get the HEAD version simply via an http[s] request to the server (httpd?) - but is there any ability to specify the revision, perhaps as a query-string? I can't seem to find it...

I don't want to do a checkout unless I can help it, as there are a lot of files in the specific folder, and I don't want them all - just one or two.

Answer:
Subversion does not publicly document the Uris it uses internally to access that information. (And where it is documented, it is explicitly stated that this can change in future versions)
To access this information on the web you could use a web viewer (E.g.
websvn,
viewvc
).
If you want to access it from your own program you could also use a client binding like SharpSvn.
```
```
using (SvnClient client = new SvnClient())
using (FileStream fs = File.Create("c:\\temp\\file.txt"))
{
    // Perform svn cat http://svn.collab.net/svn/repos/trunk/COMMITTERS -r 23456
    //                    > file.txt

    SvnCatArgs a = new SvnCatArgs();
    a.Revision = 23456;
    client.Cat(new Uri("http://svn.collab.net/svn/repos/trunk/COMMITTERS"), a, fs);
}
```
```
[Update 2008-12-31: One of the next few versions of Subversion will start documenting public urls you can use for retrieving old versions.]


Question:
Getting sporadic errors from users of a CMS; Ajax requests sometimes result in a "501 Method not implemented" response from the server. Not all the time; usually works.

Application has been stable for months. Users seem to be getting it with Firefox 3. I've seen a couple references via Google to such problems being related to having "charset=UTF-8" in the Content-type header, but these may be spurious

Has anyone seen this error or have any ideas about what the cause could be?

Thanks

Ian

Answer: You may want to check the logs of the server to see what's causing the issue. For example, it might be that these requests are garbled, say, because of a flaw in the HTTP 1.1 persistent connection implementation.


Question:
I'm trying to change the background color of a single subplot in a MATLAB figure.

It's clearly feasible since the UI allows it, but I cannot find the function to automate it.

I've looked into whitebg, but it changes the color scheme of the whole figure, not just the current subplot.

(I'm using MATLAB Version 6.1 by the way)

Answer:
I've not used Matlab in several years, but I think it might well be the whitebg method called after the subplot declaration, similar to the way in which you would set a title.
```
```
subplot(3, 2, 4), hist(rand(50)), whitebg('y');
```
```


Question: How do I use the ofstream to write text to the end of a file without erasing its content inside?

Answer:
You can pass the flag
```
ios::app
```
when opening the file:
```
```
ofstream ofs("filename", ios::app);
```
```


Question: Which Ajax framework/toolkit can you recommend for building the GUI of web applications that are using struts?

Answer:
Struts already come with
Dojo
framework. You can set your application theme to ajax and you will be able to use it.
Give a look at struts.ui.theme property at struts.properties file!
A good article for you to read is
this one at  JavaWorld


Question:
I want to use VBScript to catch errors and log them (ie on error "log something") then resume the next line of the script.

For example,

On Error Resume Next
'Do Step 1
'Do Step 2
'Do Step 3

When an error occurs on step 1, I want it to log that error (or perform other custom functions with it) then resume at step 2. Is this possible? and how can I implement it?

EDIT: Can I do something like this?

On Error Resume myErrCatch
'Do step 1
'Do step 2
'Do step 3

myErrCatch:
'log error
Resume Next

Answer:
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.
```
```
On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0
```
```
The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.


Question:
For a university project I programmed a Internet Explorer Browser Helper Object to process  web document information while browsing. It were running successful on Windows XP with IE6 and IE7.

Now I have the issue that under Windows Vista the same BHO needs administrator rights to run. Browser and BHO running if you start the IE as administrator but if you start as normal user it crashes.

The BHO is of course registered on the system and activated in the browser.

What can I do that a user with non-admin rights can run the registered and activated BHO? Or is maybe something else the reason and I totally miss it?

Thank you very much for your help!

Answer:
Not sure if your problem is related to custom actions in your installer but the following two links should help you.
Building a BHO with the UAC in mind -
http://simonguest.com/blogs/smguest/archive/2006/11/19/Building-Browser-Helper-Objects-using-Managed-Code.aspx
(a little over half way down)
Using the NoImpersonate script -
http://blogs.msdn.com/astebner/archive/2007/05/28/2958062.aspx


Question:
I have a program which needs to behave slightly differently on Tiger than on Leopard. Does anybody know of a system call which will allow me to accurately determine which version of Mac OS X I am running. I have found a number of macro definitions to determine the OS of the build machine, but nothing really good to determine the OS of the running machine.

Thanks,
Joe

Answer:
In terminal:
```
```
system_profiler SPSoftwareDataType
```
```
Gives:
```
```
Software:

    System Software Overview:

      System Version: Mac OS X 10.5.5 (9F33)
      Kernel Version: Darwin 9.5.0
      Boot Volume: Main
      Boot Mode: Normal
      Computer Name: phoenix
      User Name: Douglas F Shearer (dougal)
      Time since boot: 2 days 16:55
```
```
Or:
```
```
sw_vers
```
```
Gives:
```
```
ProductName:    Mac OS X
ProductVersion: 10.5.5
BuildVersion:   9F33
```
```


Question:
I'm trying to format a column in a <table/> using a <col/> element. I can set background-color, width, etc., but can't set the font-weight. Why doesn't it work?

<table>
    <col style="font-weight:bold; background-color:#CCC;">
    <col>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td>4</td>
    </tr>
</table>

Answer:
A
```
col
```
tag must be inside of a
```
colgroup
```
tag, This may be something to do with the problem.


Question:
I am looking for a way in LINQ to match the follow SQL Query.

Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number

Really looking for some help on this one.  The above query gets the max uid of each Serial Number because of the Group By Syntax.

Answer:
```
```
using (DataContext dc = new DataContext())
        {
            var q = from t in dc.TableTests
                    group t by t.SerialNumber
                        into g
                        select new
                        {
                            SerialNumber = g.Key,
                            uid = (from t2 in g select t2.uid).Max()
                        };
        }
```
```