Question:
I have a multi-line string that I want to do an operation on each line, like so:

inputString = """Line 1
Line 2
Line 3"""

I want to iterate on each line:

for line in inputString:
    doStuff()

Answer:
```
```
inputString.splitlines()
```
```
Will give you a list with each item, the
```
splitlines()
```
method is designed to split each line into a list element.


Question:
y: &pause
cd ptls5.0 &pause
sdp describe Integration.dpk &pause
z: &pause
cd ptls5.0 &pause
dir &pause

I have those commands in the 1.cmd file. First three are executed fine. The result of it is that after "sdp describe Integration.dpk &pause" is executed I'm given "press any key to continue..." after I hit any key. The command prompt quits. Instead of changing drive to z:>. What is  wrong with it?

Answer:
Is "sdp" another batch file itself? If so, you will need to use
```
call
```
:
```
```
call sdp describe Integration.dpk &pause
```
```


Question:
I like to read about new and clever algorithms. And I like to think out of the box, so all kinds of algorithms from all fields of computation are welcome.

From time to time I read research papers to keep up with the current research and expand my horizon. I also like to learn new tricks. Unfortunately I tend to concentrate only on my field of interest, so I miss a lot of usefull stuff.

Let's just not post mainstream things. Instead write about something special that made you think: "Wow - now that's a clever solution!".

Answer:
I'll start with something everyone can use: introspective sort.
http://en.wikipedia.org/wiki/Introsort
A new sort algorithms that combines the best of quick, insertion and heap sort. To be exact it's not a new algorithm by itself but a
very
clever combination.
You get the speed of quick-sort up to the point where the quick-sort runs into the degenerated O(n²) case. That gets detected for almost no cost. The remaining partition get sorted using heap- or merge-sort. This not only avoids the degenerated case but creates an clear defined upper bound for stack-usage as well.
Insertion sort takes - as usual - care about all small partitions that are left over from the quick-sort pass.
For me that was a new discovery because I stopped to use quick-sort for my applications.
I do a lot of work on embedded devices and I do have to care about stack usage. Using quick-sort was always a bit risky because the faint chance that it runs amok on the stack. Even if you know that with the current data everything will be fine you never know if someone later cut'n'pastes your code into a different project and uses it for data it was never ment for.
Thanks to introspective sort I now have full control over the stack usage and get a performance boost as well.


Question: Last time I asked about the reverse process, and got some very efficient answers. I'm aiming for least lines of code here. I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding form with it.

Answer:
If your form elements have their ID set to the fieldname:
```
```
$.each(myAssocArry, function(i,val) { $('#'+i).val(val); });
```
```


Question:
I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops.

How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list?

try
{
    if (cbSubFolders.Checked == false)
    {
        string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
        foreach (string fileName in files)
            ProcessFile(fileName);
    }
    else
    {
        string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
        foreach (string fileName in files)
            ProcessFile(fileName);
    }
    lblNumberOfFilesDisplay.Enabled = true;
}
catch (UnauthorizedAccessException) { }
finally {}

Answer:
You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):
```
```
using System;
using System.IO;
static class Program
{
    static void Main()
    {
        string path = ""; // TODO
        ApplyAllFiles(path, ProcessFile);
    }
    static void ProcessFile(string path) {/* ... */}
    static void ApplyAllFiles(string folder, Action<string> fileAction)
    {
        foreach (string file in Directory.GetFiles(folder))
        {
            fileAction(file);
        }
        foreach (string subDir in Directory.GetDirectories(folder))
        {
            try
            {
                ApplyAllFiles(subDir, fileAction);
            }
            catch
            {
                // swallow, log, whatever
            }
        }
    }
}
```
```


Question:
I wrote a short bash script to complete a task that involves creating a temporary directory and storing various files in it and performing various operations on it.

In my first pass I just created the temp dir at /tmp/$$.$script", but then I tested the script on a computer where I didn't have write access to /tmp/, and I'd like to take that case into account. So my question is where's a good secondary location for this temp dir? Should I just use the current directory? The home directory? ~/tmp/? The output location of the script?

All created files do get cleaned up on script exit.

Answer:
You could try
```
/var/tmp
```
, although it's likely that
```
/tmp
```
is a symlink to that (or vice-versa).


Question:
function returnsAnArray ()
{
  return array ('test');
}

echo returnsAnArray ()[0];

generates a syntax error in PHP. What's the most efficient way to directly obtain an element from a returned array without assigning the result to a temp variable?

Answer:
This will work if there is only one member in the array:
```
```
<?php
 echo current(returnsAnArray());
 ?>
```
```


Question: What is the difference between g++ and gcc?  Which one of them should be used for general c++ development?

Answer:
```
gcc
```
and
```
g++
```
are compiler-drivers of the GNU Compiler
Collection
(which was once upon a time just the GNU
C Compiler
).
Even though they automatically determine which backends (
```
cc1
```
```
cc1plus
```
...) to call depending on the file-type, unless overridden with
```
-x language
```
, they have some differences.
The probably most important difference in their defaults is which libraries they link against automatically.
According to GCC's online documentation
link options
and
how g++ is invoked
,
```
g++
```
is equivalent to
```
gcc -xc++ -lstdc++ -shared-libgcc
```
(the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the
```
-v
```
option (it displays the backend toolchain commands being run).


Question:
When I try this with a generic class where this.value is T:

if (this.value.GetType() == typeof(int))
{
    ((int)this.value)++;
}
else
{
    throw new InvalidOperationException
            ("T must be an int to perform this operation");
}

I get a compile-time error: "Cannot convert type 'T' to 'int'"

What should I do to perform an integral operation on this.value when it's an int?

Note that this is just an example. The code does type conversions with generics, and "int" is just an example of one type for T.

Answer:
Unfortunately, it is very hard to convince the compiler about specific T implementations. One (nasty) approach is to cast to object in the middle (note this will box and unbox value-types):
```
```
int i = (int)(object)this.value;
i++;
this.value = (T)(object)i;
```
```
Ugly but it works. In .NET 3.5 I have some better wrappers for generic arithmetic,
here
. The Operator class is part of
MiscUtil
; at the simplest level, I suspect AddAlternative would work very well:
```
```
this.value = Operator.AddAlternative(this.value, 1);
```
```
This should infer the implicit <T,int> automatically, or you can add them yourself:
```
```
this.value = Operator.AddAlternative<T,int>(this.value, 1);
```
```
Benefit
: This is preferable to the original code as it doesn't actually care about the original T - it will work for any type (even your own) that supports "T +(T,int)".
I think there is also a ChangeType hiding around somewhere in there...
[edit] Collin K and others make a valid remark about the architectural implications - but being pragmatic there are times when the T really does matter that much... but I'd agree with avoiding this type of specialization unless
really
necessary. That said (as per  my comment on Collin's post), the ability to perform things like basic arithmetic (increment, Int32 division, etc) on (for example) a Matrix<T> [for T in decimal/float/int/double/etc] is often highly valuable.


Question:
I have a photo website and i want to support tags as my original category bucketing is starting to fail (some pictures are family and vacations, or school and friends).  Is there an agreed tagging db schema?

I still want to support having photos as part of an album.

Right now i have a few tables:

Photos

PhotoID

PhotoAlbumID

Caption

Date

Photo Album

AlbumID

AlbumName

AlbumDate

Answer:
There are various schemas which are effective, each with their own performance implications for the common queries you'll need as the number of tagged items grows:
http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/
http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/
Personally, I like having a tag table and a link table which associates tags with items, as it's denormalized (no duplication of tag names) and I can store additional information in the link table (such as when the item was tagged) when necessary.
You can also add some denormalised data if you're feeling frisky and want simple selects at the cost of the additional data maintenance required by storing usage counts in the tag table, or storing tag names which were used in the item table itself to avoid hitting the link table and tag table for each item, which is useful for displaying multiple items with all their tags and for simple tag versioning... if you're into that sort of thing ;)


Question:
Is there any way (maybe directly editing resource files) to configure a Tab Control (add/remove tabs and their captions and contents) at design time with Visual Studio 2008 without SP1 (I heard that SP1 has such feature)?
P.S.: I use c++ with wtl

Answer:
There are various schemas which are effective, each with their own performance implications for the common queries you'll need as the number of tagged items grows:
http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/
http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/
Personally, I like having a tag table and a link table which associates tags with items, as it's denormalized (no duplication of tag names) and I can store additional information in the link table (such as when the item was tagged) when necessary.
You can also add some denormalised data if you're feeling frisky and want simple selects at the cost of the additional data maintenance required by storing usage counts in the tag table, or storing tag names which were used in the item table itself to avoid hitting the link table and tag table for each item, which is useful for displaying multiple items with all their tags and for simple tag versioning... if you're into that sort of thing ;)


Question:
I need to create a news ticker that is updated via an RSS feed. Any ideas on how to implement this?

I would prefer Javascript  but any language is acceptable.

Answer:
There are are several good examples of this on
this DynamicDrive page
, although one of the requirements is that you can run PHP on your site. PHP here is used to fetch the actual feeds and allow your ticker to access them locally via an AJAX call.
There are several other projects out there built on JQuery, and the basic approach taken by each is:
use a PHP (or ASP.net) script to fetch the feed to your server.
access this local file via repeated AJAX calls, making use of
setTimeout
update the display (ticker) with latest data fetched
The file is fetched to your local server for the AJAX calls due to the
Same Origin Policy
:
It prevents a document or script loaded from one "origin" from getting or setting properties of a document from a different "origin".
Further examples include:
JTicker from Jason's Toolbox
JQuery feed plugin
- need to read the comments on this one, as code originally posted doesn't seem to work out of the box


Question:
I'm trying to determine if the user is using 24 hour or 12 hour time, and there doesn't seem to be a good way to figure this out other than creating an NSDateFormatter and searching the format string for the period field ('a' character)

Here's what I'm doing now:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSRange range = [[formatter dateFormat] rangeOfString:@"a"];
BOOL is24HourFormat = range.location == NSNotFound && range.length == 0;
[formatter release];

Which works, but feels kinda fragile. There has to be a better way, right?

Answer:
This information is provided in NSUserDefaults. Maybe under the NSShortTimeDateFormatString key? (Still requires parsing of course).
(Use
```
```
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
```
```
to dump all the pre-defined user defaults).
Not quite sure why you want to do this - I bet you have a good reason - but maybe it's best just to use the defaults in NSDateFormatter instead?


Question:
This is the one thing I could never get to work.

My problem is to detect the end of one day and the start of the next and then splitting the diff into each day.

Imagine you want to calculate a pay rate but it has to span across midnight.

It also applies to calculating time to run on timed system, or time diff it should've run.

Answer:
I prefer to record all times in Unix Epoch, that way it's as simple as
```
```
hoursWorked = ((stopTime - startTime)/60)/60
```
```
Here is a full solution it's in PHP but should be easy enough to build to any language:
```
```
<?php
$startTime = "12/31/2008 22:02"; //No AM/PM we'll use 24hour system
$endTime = "01/01/2009 06:27"; //Again no AM/PM and we spaned the midnight time gap.
/*
Use this to test for a normal shift not ocurring durring midnight.
$startTime = "01/01/2008 06:02"; //No AM/PM we'll use 24hour system
$endTime = "01/01/2008 14:27"; //Again no AM/PM and we spaned the midnight time gap.
*/
$startTime = split(' ', $startTime);
$endTime = split(' ', $endTime);
$startTime[1] = split(':', $startTime[1]);
$endTime[1] = split(':', $endTime[1]);
/*
$startTime[0] contains the date
$startTime[1][0] contains the hours
$startTime[1][1] contains the minutes
same is true for endTime
*/
if($startTime[0] != $endTime[0])
 {
    if(date2epoch($endTime[0]) > date2epoch($startTime[0]))
     {
        $minutesWorked1 = (59 - $startTime[1][1]); //Calculate how many minutes have occured from begining of shift to midnight
        $minutesWorked2 = $endTime[1][1]; //Number of minute from midnight to end of shift
        $hoursWorked1 = (23 - $startTime[1][0]);//Number of hours from start of shift to midnight
        $hoursWorked2 = $endTime[1][0];//Number of minutes from midnight to end of shift
        echo 'Before midnight you worked ' . $hoursWorked1 . ':' . $minutesWorked1 . "\nAfter midnight you worked " . $hoursWorked2 . ':' . $minutesWorked2 . '.';
     }
    else
     {
        //SOMETHING MAJOR BAD HAS HAPPENED WHILE LOGGING THE CLOCKINS AND CLOCKOUTS
     }
 }
else
 {
    echo 'Today you worked ' . ($endTime[1][0] - $startTime[1][0]) . ':' . ($endTime[1][1] - $startTime[1][1]);
 }
function date2epoch($date, $format='m/d/Y')
 {
    $date = split('/', $date);
    return mktime('0', '0', '0', $date[0], $date[1], $date[2]);
 }
?>
```
```


Question:
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:

Firstly: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?

Secondly:  When writing a program from scratch in python, what are some good ways to greatly improve performance?

For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization.  What would you do to speed it up in this case short of rewriting it in something like C?

Answer:
First thing that comes to mind:
psyco
. It runs only on x86, for the time being.
Then,
constant binding
. That is, make all global references (and
global.attr
,
global.attr.attr
…) be local names inside of functions and methods. This isn't always successful, but in general it works. It can be done by hand, but obviously is tedious.
You said apart from in-code optimization, so I won't delve into this, but keep your mind open for typical mistakes (
```
for i in range(10000000)
```
comes to mind) that people do.


Question:
Is there a way to make a popup window maximised as soon as it is opened? If not that, at least make it screen-sized? This:

window.open(src, 'newWin', 'fullscreen="yes"')

apparently only worked for old version of IE.

Answer:
Use
```
screen.availWidth
```
and
```
screen.availHeight
```
to calculate a suitable size for the height and width parameters in
```
window.open()
```
Although this is likely to be close, it will not be maximised, nor accurate for everyone, especially if all the toolbars are shown.


Question:
Are there any good MVC frameworks for native Windows Mobile code?

Barring that could someone link to an open source Windows Mobile or CE project that uses the MVC pattern?

Answer:
Perhaps you could try Qt. It provides some classes for mvc programming. Here is link for MVC in Qt.
http://doc.trolltech.com/4.4/model-view-programming.html


Question:
We're all familiar with the pre- and post-increment operators, e.g.

c++;    // c = c + 1
++c;    // ditto

and the "combined operators" which extend this principle:

c += 5;    // c = c + 5
s .= ", world";    // s = s . ", world"; e.g. PHP

I've often had a need for a 'post-combined operator', which would allow:

s =. "Hello ";    // s = "Hello " . s

Obviously, this is only really useful with non-commutable operators and the meaning is altered from pre-/post-increment, even though the syntax is borrowed.

Are you aware of any language that offers such an operator, and why isn't it more common?

Answer:
A basic objection to the example as-given is that it'd create ambiguity:
```
```
a=-5;    //'a = -5' or 'a =- 5'?
b=*p;    //'b = *p' or 'b =* p'?
c=.5;    //'c = .5' or 'c =. 5'?
```
```
Edit:
But no, I'm not aware of any languages that use them. Presumably this is because they were omitted from C from whence most other languages derive their basic operators.
And yeah, I'd love to see them in the languages I use.


Question:
My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working.

However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again.

Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there?

Answer:
If you've checked out a single folder, copied your files into it, run
```
svn add
```
and
```
svn commit
```
;  you shouldn't need to delete the files and re-checkout.
Use the files in place: once they've been committed as you describe, they're ready to be worked on.


Question: I have experimented with Lisp (actually Scheme) and found it to be a very beautiful language that I am interested in learning more about.  However, it appears that Lisp is never used in serious projects, and I haven't seen it listed as a desired skill on any job posting.  I am interested in hearing from anyone who has used Lisp or seen it used in the "real world", or who knows whether it is considered a purely academic language.

Answer:
If I started up my very own major software project now, I would make my language decision based on the criteria above. Sure, I love Lisp, CLOS is awesome, real lexical scoping rocks, Lisp macros are way cool (when used as directed), and personally I really like Lisp syntax. […] But it would take a lot, or require special circumstances, to persuade me to choose Lisp for a major software project, if I were in charge of making the choice. -
Dan Weinreb


Question:
I have the following style in an external CSS file called first.css

table { width: 100%; }

This makes the tables fill their container. If there are only two small columns they appear too far from each other.

To force the columns to appear nearer I have added this style

table { width: 50%; }

to a new file called second.css and linked it into the html file.

Is there any way to override the width property in first.css without the need to specify a width in second.css?

I would like the html behave as if there has never been a width property, but I do not want to modify first.css

Answer:
You can use:
```
```
table { width: auto; }
```
```
in second.css, to strictly make "the html behave as if there was never been a width property". But I'm not 100% sure this is exactly what you want - if not, please clarify!


Question:
I've got a div that contains some content that's being added and removed dynamically, so its height is changing often. I also have a div that is absolutely positioned directly underneath with javascript, so unless I can detect when the height of the div changes, I can't reposition the div below it.

So, how can I detect when the height of that div changes? I assume there's some jQuery event I need to use, but I'm not sure which one to hook into.

Answer:
You can use the DOMSubtreeModified event
```
```
$(something).bind('DOMSubtreeModified' ...
```
```
But this will fire even if the dimensions don't change, and reassigning the position whenever it fires can take a performance hit. In my experience using this method, checking whether the dimensions have changed is less expensive and so you might consider combining the two.
Or if you are directly altering the div (rather than the div being altered by user input in unpredictable ways, like if it is contentEditable), you can simply fire a custom event whenever you do so.
Downside: IE and Opera don't implement this event.


Question:
If you have the following:

$var = 3; // we'll say it's set to 3 for this example
if ($var == 4) {
    // do something
} else if ($var == 5) {
    // do something
} else if ($var == 2) {
    // do something
} else if ($var == 3) {
    // do something
} else {
    // do something
}

If say 80% of the time $var is 3, do you worry about the fact that it's going through 4 if cases before finding the true case?

I'm thinking on a small site it's not a big deal, but what about when that if statement is going to run 1000s of times a second?

I'm working in PHP, but I'm thinking the language doesn't matter.

Answer:
A classic case of this occurring (with literally 5 options as in your post) was in ffmpeg, in the decode_cabac_residual function.  This was rather important, as profiling (very important--don't optimize before profiling!) showed it counted for upwards of 10-15% of the time spent in H.264 video decoding.  The if statement controlled a set of statements which was calculated differently for the various types of residuals to be decoded--and, unfortunately, too much speed was lost due to code size if the function was duplicated 5 times for each of the 5 types of residual.  So instead, an if chain had to be used.
Profiling was done on many common test streams to order them in terms of likelihood; the top was the most common, the bottom the least.  This gave a small speed gain.
Now, in PHP, I suspect that there's a lot less of the low-level style speed gain that you'd get in C, as in the above example.


Question:
I have a Boost unit test case which causes the object under test to throw an exception (that's the test, to cause an exception). How do I specify in the test to expect that particular exception.

I can specify that the test should have a certain number of failures by using BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES but that seems rather unspecific. I want to be able to say at a specific point in the test that an exception should be thrown and that it should not be counted as a failure.

Answer:
Doesn't this work?
```
```
BOOST_CHECK_THROW (expression, an_exception_type);
```
```
That should cause the test to pass if the expression throws the given exception type or fail otherwise.  If you need a different severity than 'CHECK', you could also use
```
BOOST_WARN_THROW()
```
or
```
BOOST_REQUIRE_THROW()
```
instead.  See
the documentation


Question:
Does anyone have experience with LLVM, llvm-gcc, or Clang?

The whole idea behind llvm seems very intriguing to me and I'm interested in seeing how it performs.  I just don't want to dump a whole lot of time into trying the tools out if the tools are not ready for production.

If you have experience with the tools, what do you think of them?  What major limitations have you encountered?  What are the greatest benefits?

Many thanks!

Answer:
I've had an initial play around with LLVM and working through
this tutorial
left me very very excited about it's potential; the idea that I can use it to build a JIT into an app with relative ease has me stoked.
I haven't gone deep enough to be able to offer any kind of useful opinion on it's limitations, stability, performance and suchlike. I understand that it's good on all counts but that's purely hearsay.


Question: Basically I'm running some performance tests and don't want the external network to be the drag factor. I'm looking into ways of disabling network LAN. What is an effective way of doing it programmatically? I'm interested in c#. If anyone has a code snippet that can drive the point home that would be cool.

Answer:
Found this thread while searching for the same thing, so, here is the answer :)
The best method I tested in C# uses WMI.
http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx
Win32_NetworkAdapter on msdn
C# Snippet : (System.Management must be referenced in the solution, and in using declarations)
```
```
SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
    if (((string)item["NetConnectionId"]) == "Local Network Connection")
    {
       item.InvokeMethod("Disable", null);
    }
}
```
```


Question:
This will hopefully be an easy one.  I have an F# project (latest F# CTP) with two files (Program.fs, Stack.fs).  In Stack.fs I have a simple namespace and type definition

Stack.fs

namespace Col

type Stack=
 ...

Now I try to include the namespace in Program.fs by declaring

open Col

This doesn't work and gives me the error "The namespace or module Col is not defined."  Yet it's defined within the same project.  I've got to be missing something obvious

Answer:
What order are the files in the
```
.fsproj
```
file?  Stack.fs needs to come before Program.fs for Program.fs to be able to 'see' it.
See also the start of
http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!444.entry
and the end of
http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!347.entry


Question:
I have a container div that holds two internal divs; both should take 100% width and 100% height within the container.

I set both internal divs to 100% height. That works fine in Firefox, however in IE the divs do not stretch to 100% height but only the height of the text inside them.

The following is a simplified version of my style sheet.

#container
{
   height: auto;
   width: 100%;
}

#container #mainContentsWrapper
{
   float: left;

   height: 100%;
   width: 70%;
   margin: 0;
   padding: 0;
}

#container #sidebarWrapper
{
   float: right;

   height: 100%;
   width: 29.7%;
   margin: 0;
   padding: 0;
}

Is there something I am doing wrong? Or any Firefox/IE quirks I am missing out?

Answer:
You might have to put one or both of:
```
```
html { height:100%; }
```
```
or
```
```
body { height:100%; }
```
```
EDIT: Whoops, didn't notice they were floated. You just need to float the container.


Question:
I've been working with databases for the last few years and I'd like to think that I've gotten fairly competent with using them. However I was reading recently about Joel's  Law of Leaky Abstractions and I realised that even though I can write a query to get pretty much anything I want out of a database, I have no idea how the database actually interprets the query. Does anyone know of any good articles or books that explain how databases work internally?

Some specific things I'm interested in are:

What does a database actually do to find out what matches a select statement?

How does a database interpret a join differently to a query with several "where key1 = key2" statements?

How does the database store all its memory?

How are indexes stored?

Answer:
What does a database actually do to find out what matches a select statement?
DBs are using indexes(see below)
How does a database interpret a join differently to a query with several "where key1 = key2" statements?
Join Operations can be translated to binary tree operations by merging trees.
How does the database store all its memory?
memorymapped files
for faster access of their data
How are indexes stored?
Internally DBs are working with
B-Trees
for indexing.
This should be explained in greater details on wikipedia..
http://en.wikipedia.org/wiki/B-tree
http://en.wikipedia.org/wiki/Database


Question:
After understanding (quote), I'm curious as to how one might cause the statement to execute.  My first thought was

(defvar x '(+ 2 21))
`(,@x)

but that just evaluates to (+ 2 21), or the contents of x.  How would one run code that was placed in a list?

Answer:
```
(eval '(+ 2 21))
```


Question: I want to display the TIME field from my mysql table on my website, but rather than showing 21:00:00 etc I want to show 8:00 PM. I need a function/code to do this or even any pointers in the right direction. Will mark the first reply with some code as the correct reply.

Answer:
Check this out:
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
I'd imagine you'd want date_format().
Example: DATE_FORMAT($date, "%r")


Question: What are the access.log.* files?

Answer: Apache, I believe, does log rotation.  So these would be the older log files with the access.log file being the current one.


Question:
All too often I want a WPF slider that behaves like the System.Windows.Forms.TrackBar of old. That is, I want a slider that goes from X to Y but only allows the user to move it in discrete integer positions.

How does one do this in WPF since the Value property on the Slider is double?

Answer:
The simple answer is that you take advantage of the
IsSnapToTickEnabled
and
TickFrequency
properties. That is, turn snapping to ticks on and set the tick frequency to 1.
Or, in other words ... take advantage of ticks ... but you don't necessarily have to show the ticks that you are snapping to.
Check out the following piece of xaml:
```
```
<Slider
    Orientation="Vertical"
    Height="200"
    Minimum="0"
    Maximum="10"
    Value="0"
    IsSnapToTickEnabled="True"
    TickFrequency="1"
/>
```
```


Question:
What are some of the new features that can be used in .NET 2.0 that are specific to C# 3.0/3.5 after upgrading to Visual Studio 2008? Also, what are some of the features that aren't available?

Available

Lambdas

Extension methods (by declaring an empty System.Runtime.CompilerServices.ExtensionAttribute)

Automatic properties

Object initializers

Collection Initializers

LINQ to Objects (by implementing IEnumerable extension methods, see LinqBridge)

Not Available

Expression trees

WPF/Silverlight Libraries

Answer: Lambdas & Extension methods are handled purely by the compiler and can be used with the .Net 2.0 framework.


Question:
I'm currently working on the Tips.js from mootools library and my code breaks on the line that has those el.$tmp, and console says it's undefined

Can anybody help me?

Answer:
I'd suggest taking your question and posting it, along with a link to the page to either/or/and:
http://mooforum.net
http://groups.google.com/group/mootools-users/topics
That's the community that swarms with it.
Now as for answering it here - I'd need a lot more information (code example?)


Question:
1.
How can I reinterpret cast a float to an int (or a double to a long)?

float f = 2.0f;
int i = (int)f; // causes conversion

I only want to copy the bit-pattern from f to i. How can this be done?

2.
The implicit and explicit operators in C# uses one intermediate object because the operator function is static

public static implicit operator MyClass(double s)
{
    return new MyClass(s);
}
..
..
MyClass m = 2.2; // this code uses 'm' and one intermediate object.

This is fine for reference types, but for value-types which are big (say 20-30 bytes), this will cause unnecessary data copy. Is my understanding correct? And If yes, then why doesn't C# have a non-static conversion operator or user-defined assignment operator so that the conversion/assignment takes place on 'this'? If it does, whats the way to do it?

Answer:
The
BitConverter
class can retrieve the bytes for any primitive type, which you can then use to create an int. Another option is
Buffer.BlockCopy
if you have large amounts of converting to do.
```
```
float ff = 2.0f;
int ii = BitConverter.ToInt32(BitConverter.GetBytes(ff), 0);

float[] ff = new float[...];
int[] ii = new int[ff.Length];
Buffer.BlockCopy(ff, 0, ii, 0, ff.Length * 4); // byte-wise copy of ff into ii
```
```
No there is no other option given in C#, however, I think that while you're correct in the sense that there will be a copy made, any sufficiently simple implementation will have JIT optimizations done, possibly removing the need for a copy.


Question:
I want to make sure people can't type the name of a PHP script in the URL and run it. What's the best way of doing this?

I could set a variable in the file that will be including this file, and then check that variable in the file being included, but is there an easier way?

Answer:
You could check the URI and see if that file is being called with `
```
```
$_SERVER['SCRIPT_FILENAME']
```
```
or you could move the file outside the public folder, this is a better solution.


Question:
Given:

interface I
{
}

class B: I
{
}

class C: I
{
}

class A
{

    public void Method(B arg)
    {
    }

    public void Method(C arg)
    {
    }

    public void Method(I arg)
    {
       // THIS is the method I want to simplify.
       if (I is B)
       {
          this.Method(arg as B);
       }
       else if (I is C)
       {
          this.Method(arg as C);
       }
    }
}

I know that there are better ways to design this type of interactions, but because of
details which would take too long to explain this is not possible.
Since this pattern will be duplicated MANY times, I would like to replace the
conditional logic with a generic implementation which I could use just one line.
I can't see a simple way to implement this generic method/class, but my instincts tell me it should be possible.

Any help would be appreciated.

Answer:
It doesn't exist in a convenient form withing C# -
see here
for an idea based on F#'s pattern matching, that does exactly what you want. You can do some things with reflection to select the overload at runtime, but that will be very slow, and has severe issues if anything satisfies both overloads. If you had a return value you could use the conditional operator;
```
```
return (I is B) ? Method((B)I) : ((I is C) ? Method((C)I) : 0);
```
```
Again - not pretty.


Question:
I find way too many projects to get involved in, way to many languages to play with (and way too many cool features within those languages), and way too many books to read...

How do you guys stay focused and actually get anything done, rather than leaving a trail of partially complete "experiments?"

Answer:
I think a good programmer may well have lots of unfinished "experiments" hanging around, this is a good thing.
Usually with a good manager, you will be held accountable if your work is simply not getting done. If you're a student, though, it's tougher. I realized that it is impossible to learn everything you want to.
I limit myself to only learning 1 or 2 new languages per year, and only 1 book per month. That seems to be a nice balance between programming chaos and getting my job done well.
Kudos for having a great learning attitude :)


Question:
I know what ViewData is and use it all the time, but in ASP.NET Preview 5 they introduced something new called TempData.

I normally strongly type my ViewData, instead of using the dictionary of objects approach.

So, when should I use TempData instead of ViewData?

Are there any best practices for this?

Answer:
In one sentence:
```
TempData
```
are like ViewData with one difference: They only contain data between two successive requests, after that they are destroyed. You can use
```
TempData
```
to pass error messages or something similar.
Although outdated,
this article
has good description of the
```
TempData
```
lifecycle.
As Ben Scheirman said
here
:
TempData is a session-backed temporary storage dictionary that is available for one single request.  It’s great to pass messages between controllers.


Question: Can someone explain the pros and cons of it  and any math involved with it?

Answer:
It's more accurate than vertexes (or hit-boxes etc). I'm assuming you're talking about 2d here (3d would be box-model vs vertex). Per-pixel would allow you to have detailed sprites which small things (missiles, say) would collide with more realistically.
It's more math and slower than the conventional method, which would be to draw a box (or some other easily math shape like a circle) and say 'this is the actor, anything in here is he'. It is however, more accurate.


Question:
Imagine you don't have the problem of feature creep, you have a motivated and stable team, clear defined problems to solve, AND you know the domain/language/tools related to your project.

How do you stick to a schedule and accomplish that 1.0 milestone?

What is your approach to an iterative shipping?

I'd like recommendations specially for a small team, where there are few or almost none communication problems.

Answer:
Focus on features not implementation tasks.
Work in iterations (like weekly or biweekly).
Release working features to your staging environment in order of priority.
Unit test your code as you go, so you're not slowed down by a buglist that increases geometrically as you approach the release date.
Be prepared to cut scope from the less important features. Stuff always takes longer than you think it will.
Make sure you sketch out the UI in advance (if there is a UI), and show it to potential users.
Test, test, and test some more. This seems counter-intuitive, but it saves more time than takes.


Question: Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App_Data folder (an .mdf "database"). Seems easy, and it is once you know how.

Answer:
So here's the answer from MSDN:
Choos[e] "Add New Data Source" from the
  Data menu.[And follow the connection wizard]
Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:
Click on Tools >> Connect to Database...
Select "Microsoft SQL Server Database File", take the default Data provider, and click OK
On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.
Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the "
```
AttachDbFilename
```
" attribute and value. Example:
The raw text from the Advanced panel:
```
```
Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True
```
```
The actual entry in the web.config:
```
```
<add name="SomeDataBase" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Development\blahBlah\App_Data\SomeDataFile.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />
```
```


Question:
I just moved to a new hosting company and now whenever a string gets escaped using:

mysql_real_escape_string($str);

the slashes remain in the database. This is the first time I've ever seen this happen so none of my scripts use

stripslashes()

anymore.

This is on a CentOS 4.5 64bit running php 5.2.6 as fastcgi on a lighttpd 1.4 server. I've ensured that all magic_quotes options are off and the mysql client api is 5.0.51a.

I have the same issue on all 6 of my webservers.

Any help would be appreciated.

Thanks.

Edit:

Magic Quotes isn't on. Please don't recommend turning it off. THIS IS NOT THE ISSUE.

Answer:
```
mysql_real_escape_string($str);
```
is supposed to do exactly that. it is meant to add backslashes to special characters especially when you want to pass the query to mysql. Take note that it also takes into account the character set of mysql.
For safer coding practices it would be good to edit your code and use
```
stripslashes()
```
to read out the data and remove the slashes.


Question: I know it is possible, and a lot faster than using GDI+.  However I haven't found any good example of using DirectX to resize an image and save it to disk.  I have implemented this over and over in GDI+, thats not difficult.  However GDI+ does not use any hardware acceleration, and I was hoping to get better performance by tapping into the graphics card.

Answer:
You can load the image as a texture, texture-map it onto a quad and draw that quad in any size on the screen. That will do the scaling. Afterwards you can grab the pixel-data from the screen, store it in a file or process it further.
It's easy. The basic texturing DirectX examples that come with the SDK can be adjusted to do just this.
However, it
is
slow. Not the rendering itself, but the transfer of pixel data from the screen to a memory buffer.
Imho it would be much simpler and faster to just write a little code that resizes an image using bilinear scaling from one buffer to another.


Question:
The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels.  I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit.  This is normally great, but the specific situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database.  In this case I want to exit and prevent any further tests from being run.  Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me.

The only option I have thought of so far is using ctypes or something similar to call   exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.

Answer:
You can call
```
os._exit()
```
to directly exit, without throwing an exception:
```
```
import os
os._exit(1)
```
```
This bypasses all of the python shutdown logic, such as the
```
atexit
```
module, and will not run through the exception handling logic that you're trying to avoid in this situation.  The argument is the exit code that will be returned by the process.


Question:
I have a list string tag.

I am trying to initialize a dictionary with the key as the tag string and values as the array index.

for i, ithTag in enumerate(tag):
    tagDict.update(ithTag=i)

The above returns me {'ithTag': 608}  608 is the 608th index

My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.

I'm confused, it is kind of hard to google these kind of specific questions.  I hope I worded the title of this question correctly,

Thanks!

Answer:
You actually want to do this:
```
```
for i, tag in enumerate(tag):
    tagDict[tag] = i
```
```
The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.


Question: How do you select a datagridview row on a right-click?

Answer:
```
```
// Clear all the previously selected rows
    foreach (DataGridViewRow row in yourDataGridView.Rows)
    {
      row.Selected = false;
    }

    // Get the selected Row
    DataGridView.HitTestInfo info = yourDataGridView.HitTest( e.X, e.Y );

    // Set as selected
    yourDataGridView.Rows[info.RowIndex].Selected = true;
```
```


Question:
What is a good mobile programming platform to go with for a c++ developer?

Is learning android a good option?

Answer:
Java ME
will give you the widest choice of deployment options and market share, because most mobile phones support it.  Going from C++ to Java is quite easy, since Java has fewer gotchas than C++.  As a positive side effect you will also get to learn Java on a platform whose footprint is a lot smaller and manageable than
Java SE
.


Question: I'm not the best programmer so I found it was much easier to write a program as several separate executables, which occasionally call each other.  But now I need an easy way to actually run them without writing detailed instructions like Run file one, wait until its completed and no longer in process manager before running file two, file three can be executed 15 seconds after file two has been created. Then Add a key to your registry. Etc.  I figure there must be a good software out there where I can just drop all my exes in, tell it when to run them, and output one file for my clients to run.  Any ideas?

Answer:
I've always had a good experience with
NSIS
It's open source
It has a big community (and hence lots of plugins)
For simple things, its script-based approach is nice and easy
It's lightweight and fast
On the downside, if you want to do something more sophisticated, you need to use something that looks a bit like assembly language - very odd, and not particularly pleasant.  Thanks for the comments about that - I'd forgotten all about it!


Question:
I don't have a Rails environment set up and this is actually quite hard to find a quick answer for, so I'll ask the experts.

When Rails creates a table based on your "model" that you have set up, does Rails create a table that mirrors this model exactly, or does it add in more fields to the table to help it work its magic?  If so, what other fields does it add and why?  Perhaps you could cut and paste the table structure, or simply point me to a doc or tutorial section that addresses this.

Answer:
In ActiveRecord, models are created from database tables, not the other way around.
You may also want to look into Migrations, which is a way of describing and creating the database from Ruby code. However, the migration is not related to the model; the model is still created at runtime based on the shape of the database.
There are screencasts related to ActiveRecord and Migrations on the Rails site:
http://www.rubyonrails.org/screencasts


Question:
I have this query in sql server 2000:

select pwdencrypt('AAAA')

which outputs an encrypted string of 'AAAA':

0x0100CF465B7B12625EF019E157120D58DD46569AC7BF4118455D12625EF019E157120D58DD46569AC7BF4118455D

How can I convert (decrypt) the output from its origin (which is 'AAAA')?

Answer:
I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible.
If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.
This is how you could verify a usered entered table
```
```
SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)
```
```
Replace userEnteredValue with (big surprise) the value that the user entered :)


Question: I know there are HTML entities for 1/2, 1/4, and 3/4, but are there others? Like 1/3 or 1/8? Is there a good way to encode arbitrary fractions?

Answer:
Isn't just 15/16ths alright? Or even 15/16
ths
(
```
15/16<sup>ths</sup>
```
)?


Question: What is the easiest way to set up an SMS alerting system so that I will receive notification if my server doesn't respond or a GET query doesn't return correct content?

Answer:
You can get a service like
http://www.serviceuptime.com/
and the send an email to your-number@a-domain-your-provider-gives They usually have the exact domains for the providers on their respective websites but you could just try @t-mobile.com if your provider is t-mobile for example.
If you want to write your own tool should be pretty straightforward - send GET request if you dont get the expected response send email. You should run it from 2 different locations from 2 different ISPs tho because if there are routing problems and the request doesnt go through you'll get smsed


Question: V8's documentation explains how to create a Javascript object that wraps a C++ object. The Javascript object holds on to a pointer to a C++ object instance. My question is, let's say you create the C++ object on the heap, how can you get a notification when the Javascript object is collected by the gc, so you can free the heap allocated C++ object?

Answer:
In general, if a garbage-collected language can hold references to resources outside of the language engine (files, sockets, or in your case C++ objects), you should provide a 'close' method to release that resource ASAP, no point waiting until the GC thinks it's worthwhile to destroy your object.
it gets worse if your C++ object is memory-hungry and the garbage-collected object is just a reference: you might allocate thousands of objects, and the GC only sees a few KB's of tiny objects, not enough to trigger collection; while the C++ side is struggling with tens of megabytes of stale objects.


Question: I'm trying to use the Microsoft.Sdc.Tasks.ServiceProcess.Exists to check whether or not a service exists.  There is no example of using it in the documentation though.  Anyone have one?

Answer:
I've not actually used this in production myself, and I'm not sure which version you have (I have a copy of Release 2.1.3155.0) and according to the accompanying .chm help file the Task has the following properties:
DoesExist    Returns TRUE if the service specified exists
IsDisabled   Returns TRUE if the service is disabled
ServiceName  The short name that identifies the service to the system.
The ServiceName needs to be set to "The short name that identifies the service to the system, e.g. 'W3SVC'".
You might want to give it a try with a well known service (e.g. mssqlserver) and check the result of the other two properties (DoesExist/IsDisabled).
Update: Here's a sample (works):
Import the tasks, then call (e.g.)
< Microsoft.Sdc.Tasks.ServiceProcess.Exists
       ServiceName="Server">
      < Output TaskParameter="DoesExist" PropertyName="Exists" />
< /Microsoft.Sdc.Tasks.ServiceProcess.Exists >
< Message Text="Service exists? $(Exists)" />


Question:
PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array "is a list" (contains only numeric keys starting from 0)?

Basically, I want to be able to differentiate between this:

$sequentialArray = [
    'apple', 'orange', 'tomato', 'carrot'
];

and this:

$assocArray = [
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'veg1' => 'tomato',
    'veg2' => 'carrot'
];

Answer:
Unless PHP has a builtin for that, you won't be able to do it in less than O(n) - enumerating over all the keys and checking for integer type. In fact, you also want to make sure there are no holes, so your algorithm might look like:
```
```
for i in 0 to len(your_array):
    if not defined(your-array[i]):
        # this is not an array array, it's an associative array :)
```
```
But why bother? Just assume the array is of the type you expect. If it isn't, it will just blow up in your face - that's dynamic programming for you! Test your code and all will be well...


Question:
So I've been thinking of going for Microsoft certification and I have to make a choice (for now) between Windows Forms and WPF for developing Windows applications. I have had good exposure to Windows Forms but never tried WPF before. Furthermore, most of the job postings where I live seem to be WinForms-oriented. That might change in the next few years, so I was wondering if I should get started on learning WPF or stick to the tried and true Forms.

Any insight?

Answer:
WPF leverages XAML for the design/visual experience this is the same technology that Silverlight uses and in the future will be leveraged heavily by other aspects of .NET 4.0, specifically, WCF (web services) and WF (workflow).
I would highly recommend learning it if you have the cycles, however for certification purposes it might be easier to just go ahead and do the WinForms exam as WPF is quite different and in my experience had a bit of a learning curve (because of how different it is from WinForms).


Question:
I am in the position of having to make a technology choice early in a project which is targetted at mobile phones.  I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.

Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.

Answer:
Have you checked out the
Mobile Python Book
?
This practical hands-on book effectively teaches how to program your own powerful and fun applications easily on Nokia smartphones based on Symbian OS and the S60 platform.
(source:
mobilenin.com
)


Question:
I'd like to write some (java) code that takes a PDF document, and creates named destinations from all of the bookmarks. I think the iText API is the easiest way of doing this, but I have never used the API before.

How would you go about writing this sort of code with the iText API?  Can iText do the parsing needed to manipulate existing PDFs by itself?  The kind of manipulations I am thinking of are:

Open,

Find bookmarks,

Create destinations,

Save,

Close.

Or is there a different API that would be better?

Answer:
I'll just warn you up front that you may be disappointed with this.  iText isn't really intended to be used as a parser.  It's really more for creating
entirely new
PDF documents, but you can take a whack at it.
To start, using iText, you won't be able to modify the existing PDF document.  What you
can
do, though, is to make a copy with the additional features that you want.  (If somebody else knows better,
please
let me know, this drives me crazy.)
What you will want to do is create a PdfReader object from an input stream on your source file.  Then create a PdfCopy object (which is just an extended PdfWriter that makes getting data from an existing source more convenient) for your destination.
As far as I can tell, the bookmarks cannot be obtained from iText at all.  Another library may be needed.  I think
jpedal
may have the ability to extract them (it can get them as an XML document, which you may then have to parse to get what you want.)  However you get them, you can then add them to a java.util.List, and set that list as outline on the PDFCopy.  The bookmarks themselves are just HashMaps with a particular set of keys.  I'm not sure what all of the values are, but they include "Title", "Action" (which seems to be where you'd specify that this is a named destination, though I don't know what that value would be), and "URI" (which is used if this is an external link -- I suspect that this would specify the name of the named destination that you're linking to).  Again, the specifics are hard to find.
Then iterate over the pages of the reader, importing each page to the PdfCopy.
this page
may help you.
Sorry I'm not more helpful to you.  Good luck.
P.S.  If anybody else knows of a better tool that's either (L)GPL or BSD licensed, I'd love to hear about it.


Question: Am looking for C# open source NMEA parser.

Answer:
Well, I'm not familiar with it myself, but some quick searches show one on
CodeProject
, which links to 2 other such,
here
and
here
. Any of those help?


Question:
I've got a "little" problem with Zend Framework Zend_Pdf class. Multibyte characters are stripped from generated pdf files. E.g. when I write aąbcčdeę it becomes abcd with lithuanian letters stripped.

I'm not sure if it's particularly Zend_Pdf problem or php in general.

Source text is encoded in utf-8, as well as the php source file which does the job.

Thank you in advance for your help ;)

P.S. I run Zend Framework v. 1.6 and I use FONT_TIMES_BOLD font. FONT_TIMES_ROMAN does work

Answer:
I believe Zend_Pdf got UTF-8 support in 1.5 - What version of Zend Framework are you running?
Also - what font are you trying to render with? Have you tried alternate fonts?


Question:
I have some old rrdtool databases, for which the exact creation recipe has long been since lost. I need to create a new database with the same characteristics as the current ones. I've dumped a couple of old databases and pored over the contents but I'm not sure how to interpret the metadata. I think it appears in the following stanzas

<cf> AVERAGE </cf>
<pdp_per_row> 360 </pdp_per_row> <!-- 1800 seconds -->
<xff> 5.0000000000e-01 </xff>

There are four such stanzas, which correspond to the way I recall the round-robin cascading was set up. Has anyone already done this, or can give me pointers as to how to clone a new empty rrd database from an existing one? Or show me where I missed this in the documentation.

Answer:
rrdtools'
rrdinfo
is your friend!
It will tell you how the rrd file's data source(s) and archive(s) were created.  Example
```
```
$ rrdtool info random.rrd
filename = "random.rrd"
rrd_version = "0001"
step = 300
last_update = 955892996
ds[a].type = "GAUGE"
ds[a].minimal_heartbeat = 600
ds[a].min = NaN
ds[a].max = NaN
ds[a].last_ds = "UNKN"
ds[a].value = 2.1824421548e+04
ds[a].unknown_sec = 0
ds[b].type = "GAUGE"
ds[b].minimal_heartbeat = 600
ds[b].min = NaN
ds[b].max = NaN
ds[b].last_ds = "UNKN"
ds[b].value = 3.9620838224e+03
ds[b].unknown_sec = 0
rra[0].cf = "AVERAGE"
rra[0].pdp_per_row = 1
rra[0].cdp_prep[0].value = nan
rra[0].cdp_prep[0].unknown_datapoints = 0
rra[0].cdp_prep[1].value = nan
rra[0].cdp_prep[1].unknown_datapoints = 0
```
```


Question:
When the policy for a disk in Windows XP and Vista is set to enable write caching on the hard disk, is there a way to flush a file that has just been written, and ensure that it has been committed to disk?

I want to do this programmatically in C++.

Closing the file does perform a flush at the application level, but not at the operating system level.  If the power is removed from the PC after closing the file, but before the operating system has flushed the disk write cache, the file is lost, even though it was closed.

Answer:
You haven't specified the development environment, so:
.Net
IO streams have a
```
.Flush
```
method that does what you want.
Win32 API
There is the
```
FlushFileBuffers
```
call, which takes a file handle as argument.
EDIT (based on a comment from the OA): FlushFileBuffers does not need administrative privileges; it does only if the handle passed to it is the handle for a volume, not for a single file.


Question:
I've tried to override WndProc, but no message show up on paste event.

Then I tried to create custom filter and using method PreFilterMessage I was able to catch message with value 257 (KEYUP event), but that's not enough...

Answer:
Use:
```
```
protected override void OnKeyDown(KeyEventArgs e)
 {
      if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
      {
            MessageBox.Show("Hello world");
      }
      base.OnKeyDown(e);
  }
```
```
Make sure your form KeyPreview = true.


Question:
I am interested in seeing if I can improve the way we use NUnit in a Visual Studio solution containing 30+ projects.

First, would you have one assembly of tests for every assembly in the solution, or would you try to keep the number of test assemblies down? I started off creating many test assemblies, but I think this is costing us a lot in terms of build time.

Second, what strategy do you use for managing those tests that are long-running, or require special environment configuration? I would like to write an MSBuild script that automates the running of our unit tests, but it needs to skip over the tests that would take too long or would not work on the build machine.

Answer:
To answer your first question:
You can use
categories
to keep everything organised in a single assembly if that's how you want to go. As to whether it would cut down on build time, I would hazard a guess at perhaps, I don't think it'd be a huge amount overall though.
To answer your second:
You can use
categories
and the
```
[Explicit]
```
and
```
[Ignore]
```
attribute to tell NUnit which tests to run, and which tests you have to tell it to run before it will. You might also want to look at
```
[Platform]
```
or some of the other attributes, depending on what exactly your requirements on 'environment' are.
For instance, you could add an Explicit tag to all your long running tests. Then you would have to run these tests explicitly, NUnit won't run them automatically. Or add all these tests to a category, then when you run NUnit, tell it to explicitly not run that category.


Question:
I read that you could call JavaScript code from a Java Applet by calling

JApplet.getAppletContext().showDocument( "javascript:alert('Hello World');" );

However, when I do this i get the following error:

java.net.MalformedURLException: unknown protocol: javascript

How do I work around this?

Answer:
```
```
try {
        this.getAppletContext().showDocument(new URL("javascript:alert('hello world');"));
    }catch(Exception e) {
        e.printStackTrace();
    }
```
```
Works !!
Maybe the browser does not have javascript enabled.. just a guess


Question:
In MSVC, DebugBreak() or __debugbreak cause a debugger to break. On x86 it is equivalent to writing "_asm int 3", on x64 it is something different. When compiling with gcc (or any other standard compiler) I want to do a break into debugger, too. Is there a platform independent function or intrinsic? I saw the XCode question about that, but it doesn't seem portable enough.

Sidenote: I mainly want to implement ASSERT with that, and I understand I can use assert() for that, but I also want to write DEBUG_BREAK or something into the code.

Answer:
What about defining a conditional macro based on #ifdef that expands to different constructs based on the current architecture or platform.
Something like:
```
```
#ifdef _MSC_VER
#define DEBUG_BREAK __debugbreak()
#else
...
#endif
```
```
This would be expanded by the preprocessor the correct debugger break instruction based on the platform where the code is compiled. This way you always use
```
DEBUG_BREAK
```
in your code.


Question:
I only want a list of files that have been added (not ones that have been modified) since a certain date. Is there an easy way to do this?

Answer: Here's what ended up working for me, thanks guys!

svn log -v -r{2008-10-1}:HEAD svn://path.to.repo/ | grep "^   A" | grep ".java" | sort -u

Answer:
```
```
svn log -v -r{2008-10-1}:HEAD | grep "^   A"
```
```


Question:
Good day.

I have a program thats launches an external application. That external app has a right click sub menu on it which I need to disable. Is it possible (without modifying the external app) to disable the right click? Maybe permission or group policies and etc.

Thanks.

Answer:
I wasn't sure I wanted to post as I don't have a huge amount of scope on the matter, but it's definatley possible.
If you have a handle to the application (if not you can get one) you can use that to disable right click within the application.
http://www.codeguru.com/forum/showthread.php?t=190440
http://support.microsoft.com/kb/318804
seems like the most helpful links, it just goes on about how you should hook and then disregard
```
WM_RBUTTONDOWN
```
and
```
WM_RBUTTONUP
```
.
I'll try and write up a better thing later with an example.
More links/edits
This link could be useful as it explains that you're going to need to use unmanaged c/c++ to hook using setWindowsHookEx.
http://social.msdn.microsoft.com/Forums/en-US/clr/thread/8dd657b5-647b-443b-822d-ebe03ca4033c/
Hope this helps
[EDIT]
I think this can actually be done in a C# application completely. I will post a solution tonight
[/EDIT]


Question:
I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.

When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:

b = wx.Button(self, 10, "Default Button", (20, 20))
        self.Bind(wx.EVT_BUTTON, self.OnClick, b)
def OnClick(self, event):
        self.log.write("Click! (%d)\n" % event.GetId())

But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value?

It would greatly reduce copy & pasting the same code but with different callers.

Answer:
You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific.
```
```
b = wx.Button(self, 10, "Default Button", (20, 20))
        self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b)
def OnClick(self, event, somearg):
        self.log.write("Click! (%d)\n" % event.GetId())
```
```
If you're out to reduce the amount of code to type, you might also try a little automatism like:
```
```
class foo(whateverwxobject):
    def better_bind(self, type, instance, handler, *args, **kwargs):
        self.Bind(type, lambda event: handler(event, *args, **kwargs), instance)

    def __init__(self):
        self.better_bind(wx.EVT_BUTTON, b, self.OnClick, 'somevalue')
```
```


Question: What is the easiest way to copy the all the values from a column in a table to another column in the same table?

Answer:
This script will update ALL values in the field1 with the values from the field2 in the corresponding row
```
```
UPDATE table SET field1 = field2
```
```


Question:
Question says it all, really.
My application is a time tracker.  It's currently written as a spreadsheet, but there's just too much data and I would like to impose a bit more structure on it.

SQLite seems like a neat way to go.

I would be open to other suggestions, too.

Answer:
There are some providers available:
http://sqlite.phxsoftware.com/
http://sourceforge.net/projects/sqlite-dotnet2
And you can get up and running in just three minutes according to this chap:
http://www.mikeduncan.com/sqlite-on-dotnet-in-3-mins/
Updated Jan 5 2009:
We actually have this rolled out to our shared (partial trust) hosting environment and it works really well according to early customer feedback.


Question: I'd like to get comments from people who have used or evaluated Coverity for statically analysing Java-code. I know it's popular in C/C++ world, but is it worth spending the money for Java analysis or am I better off with PMD, Findbugs and other Open Source tools?

Answer:
I'll chip in with a somewhat relevant answer. I've used Klocwork for the both Java and C code. Klocwork is a close competitor of Coverity... cost-wise they are about the same ( look carefully, Klocwork looks cheaper until you actually buy what you need ), and feature-wise they fight back and forth.
For C/C++, it's great. For Java.... well, it helped find a lot of resource leaks ( #$@^#ing Java developers seem to forget that resources like file handles aren't garbage collected ), but it doesn't seem to find many "critical" bugs. It's probably because the language itself does help protect against some of the more basic but hard to find errors ( array overflows, pointer corruption, etc ).
Get Coverity in to run a demo, they are more than happy to. See what sort of things they find.


Question:
If I safe an Array and reload it, is there a possibility to get the size if its unknown?
Thanks

Answer:
What do you mean by "unknown"? You can get the length of any java array with the length field.
```
```
int[] myArray = deserializeSomeArray();
int size = myArray.length;
```
```


Question:
A TextBox is set to AutoPostback as changing the value should cause a number of (display-only) fields to be recalculated and displayed.

That works fine.

However, when the field is tabbed out of, the focus briefly moves on to the next field, then disappears when the page is redrawn so there is no focus anywhere.

I want the focus to be on the new field, not the textbox I've just changed.
Is there a way to work out which field had the focus and force it to have it again when the page is redrawn?

Answer:
This is "by design". If you are using ASP.NET 2.0+ you can try calling the Focus method of your TextBox once the postback occurs (preferably in the TextChanged event of the TextBox).
I am not sure if there is any built-in way to track focus but I found
this
article in CodeProject which should do the trick.


Question:
How can ALTER be used to drop a column in a MySQL table if that column exists?

I know I can use ALTER TABLE my_table DROP COLUMN my_column, but that will throw an error if my_column does not exist. Is there alternative syntax for dropping the column conditionally?

I'm using MySQL version 4.0.18.

Answer:
For MySQL, there is none:
MySQL Feature Request
.
Allowing this is arguably a really bad idea, anyway:
```
IF EXISTS
```
indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.
But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.
MariaDB also supports the following starting with 10.0.2:
```
```
DROP [COLUMN] [IF EXISTS] col_name
```
```
i. e.
```
```
ALTER TABLE my_table DROP IF EXISTS my_column;
```
```
But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.


Question:
I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me?

At the moment I am doing:

SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
    qDebug("lynxThreeFile::readSlideInfoHeader");
}

but what I want is something generic:

SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
    qDebug(this.className() + "::" + this.functionName());
}

Answer:
"
```
__FUNCTION__
```
" is supported by both MSVC and GCC and should give you the information you need.


Question:
Given an SQLConnection object how can you get a schema for a single table?

I seemed to be able to get the schema from a DataSet which I'd gotten from running a query, but all the schema info I could get from the connection seemed to be related to what tables were available and not the actual details on the tables.

Answer:
I think accessing the schema from the query (via GetSchemaTable) is the only way to do it.
You can run a query which returns no rows (select * from table where 1=2) if the schema is all you're interested in.
You should use the KeyInfo CommandBehaviour to execute the source query, as otherwise not all the information returned is guaranteed to be accurate
```
```
Command.ExecuteReader(CommandBehavior.KeyInfo)
```
```


Question:
Has anyone seen a good twin slider control for .Net (Win forms or WPF).

I'm looking for something that will allow me to select a range from within a set so the first slider would be the start of the range and the second would be the end.

I remember seeing a Swing double slider but it was 6 years ago and I can't for the life of me remember who made it. It was open source though.

Answer:
Devexpress have a good one:
The RangeTrackBarControl control extends the functionality provided by the TrackBarControl enabling end-users to select a range of values. Two sliders can be used to set the minimum and maximum values:
alt text http://www.devexpress.com/Help/XtraEditors/img/RangeTrackBarControl.png
you can get them free from:
http://www.devexpress.com/Products/Free/WebRegistration/
hope this helps!


Question:
I'm trying to have my Struts2 app redirect to a generated URL. In this case, I want the URL to use the current date, or a date I looked up in a database. So /section/document becomes /section/document/2008-10-06

What's the best way to do this?

Answer:
I ended up subclassing Struts'
```
ServletRedirectResult
```
and overriding it's
```
doExecute()
```
method to do my logic before calling
```
super.doExecute()
```
. it looks like this:
```
```
public class AppendRedirectionResult extends ServletRedirectResult {
   private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

  @Override
  protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    String date = df.format(new Date());
    String loc = "/section/document/"+date;
    super.doExecute(loc, invocation);
  }
}
```
```
I'm not sure if this is the best way to do it, but it works.


Question: I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect SERVER['argc'], but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.

Answer:
I think
```
```
$_SERVER['REMOTE_ADDR']
```
```
will not be populated from the CLI.
Also, all the HTTP_* keys in the $_SERVER superglobal won't be populated from the CLI, or do it the right way hop just mentioned :-)


Question:
This is a question you can read everywhere on the web with various answers:

$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

$exts = split("[/\\.]", $filename);
$n    = count($exts)-1;
$ext  = $exts[$n];

etc.

However, there is always "the best way" and it should be on Stack Overflow.

Answer:
```
pathinfo()
```
```
```
$path_info = pathinfo('/foo/bar/baz.bill');

echo $path_info['extension']; // "bill"
```
```


Question:
Besides open-sourcing your project and legislation, are there ways to prevent, or at least minimize the damages of code leaking outside your company/group?

We obviously can't block Internet access (to prevent emailing the code) because programmer's need their references. We also can't block peripheral devices (USB, Firewire, etc.)

The code matters most when it has some proprietary algorithms and in-house developed knowledge (as opposed to regular routine code to draw GUIs, connect to databases, etc.), but some applications (like accounting software and CRMs) are just that: complex collections of routine code that are simple to develop in principle, but will take years to write from scratch. This is where leaked code will come in handy to competitors.

As far as I see it, preventing leakage relies almost entirely on human process. What do you think? What precautions and measures are you taking? And has code leakage affected you before?

Answer:
You can't stop it getting out. So two solutions - stop people wanting to hurt you, and have legal precautions. To stop people hating you treat them right (saying more is probably off topic for stack overflow).
I'm not a lawyer, but to give yourself legal protection, if you believe in it, patent the ideas, put a copyright notice in the code, and make sure the contracts for your programmers specify carefully intellectual property rights.
But at the end of the day, the answer is run quicker than the competition.


Question:
Please consider this example class:

[Serializable]
public class SomeClass
{
    private DateTime _SomeDateTime;

    public DateTime SomeDateTime
    {
        get { return _SomeDateTime; }
        set { _SomeDateTime = value; }
    }
}

I would like to alter the serialization of any DateTime declared in the class according to my own rules. The members of this class will change frequently and I don't want to maintain a custom serializer for every change. Also I would like this behaviour to be inherited by subclasses and not code a custom serializer for every one. The serialization is being output by a web service. Thanks for any help!

Answer:
Have you thought about simply using a Nullable date time
```
```
public DateTime? SomeDateTime {get; set;}
```
```
This way you can actually have a null value as a legitimate value in your class. Typically you want to avoid custom serialization whenever possible. Once you do custom serialization such as implementing
ISerializable
, then you are stuck with it, and all other derived classes are stuck with it.
Remember what a pain in the butt it is to have to always override the ISerializable members for custom exceptions? This is because System.Exception implements ISerializable and therefore all derived exceptions (that means everything) must implement those members if you ever expect them to cross AppDomains.


Question:
When merging topic branch "B" into "A" using git merge, I get some conflicts. I know all the conflicts can be solved using the version in "B".

I am aware of git merge -s ours. But what I want is something like git merge -s theirs.

Why doesn't it exist? How can I achieve the same result after the conflicting merge with existing git commands? (git checkout every unmerged file from B)

The "solution" of just discarding anything from branch A (the merge commit point to B version of the tree) is not what I am looking for.

Answer:
I solved my problem using
```
```
git checkout -m old
git checkout -b new B
git merge -s ours old
```
```


Question:
I have developed a Windows CE 4.2 Application in VS 2003. When i deploy the CAB file in the device having X86 has its processor, a short cut for the application is created in Start >> Program >> Application. But I want a short cut for the application on the
desktop.

I modified the INF file to add a new shortcut that points to the desktop folder inside windows folder but it didn't work. Also, If i replace the default shortcut created when I build the CAB file with the location of desktop it still creates a short cut in the Programs and not on the desktop.

Does anyone has a solution for this ?

Answer:
I would check out the link:
http://msdn.microsoft.com/en-us/library/ms938387.aspx
That should get you well on your way. Basically shortcuts in CE are just ASCII files of the format:
21#\Windows\solitare.exe
Where 21# is the number of characters in that path. Here's another link to MSDN with more info on that:
http://msdn.microsoft.com/en-us/embedded/aa731295.aspx
Hope that helps!


Question:
As a function argument I get a vector<double>& vec (an output vector, hence non-const) with unknown length and values. I want to initialise this vector to a specific length n with all zeroes.

This will work

vec.clear();
vec.resize( n, 0.0 );

And this will work as well:

vec.resize( n );
vec.assign( n, 0.0 );

Is the second more efficient (because no memory deallocation/allocation is involved)? Is there a more efficient way to do this?

Answer:
```
```
std::vector<double>(n).swap(vec);
```
```
This has the advantage of actually compacting your vector too. (In your first example,
```
clear()
```
does not guarantee to compact your vector.)


Question:
How do you trigger a javascript function using actionscript  in flash?

The goal is to trigger jQuery functionality from a flash movie

Answer:
Take a look at the
ExternalInterface
-Class.
From the AS3-Language Reference:
The ExternalInterface class is the
  External API, an application
  programming interface that enables
  straightforward communication between
  ActionScript and the Flash Player
  container– for example, an HTML page
  with JavaScript. Adobe recommends
  using ExternalInterface for all
  JavaScript-ActionScript communication.
And it's work like this:
```
```
ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript);
ExternalInterface.call("sendToJavaScript", input.text);
```
```
You can submit parameters and recieve callbacks...pretty cool, right? ;)
As I know it will also work on AS2...


Question:
Assuming I have an ArrayList

ArrayList<MyClass> myList;

And I want to call toArray, is there a performance reason to use

MyClass[] arr = myList.toArray(new MyClass[myList.size()]);

over

MyClass[] arr = myList.toArray(new MyClass[0]);

?

I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.

Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...

Answer:
Using 'toArray' with the array of the correct size will perform better as the alternative will create first the zero sized array then the array of the correct size. However, as you say the difference is likely to be negligible.
Also, note that the javac compiler does not perform any optimization. These days all optimizations are performed by the JIT/HotSpot compilers at runtime. I am not aware of any optimizations around 'toArray' in any JVMs.
The answer to your question, then, is largely a matter of style but for consistency's sake should form part of any coding standards you adhere to (whether documented or otherwise).


Question:
In C#, does anybody know why the following will compile:

int i = 1;
++i;
i++;

but this will not compile?

int i = 1;
++i++;

(Compiler error: The operand of an increment or decrement operator must be a variable, property or indexer.)

Answer:
My guess: to avoid such ugly and unnecessary constructs. Also it would use 2 operations (2x INC) instead of one (1x ADD 2).
Yes, i know ... "but i want to increase by two and i'm a l33t g33k!"
Well, don't be a geek and write something that doesn't look like an inadvertent mistake, like this:
```
```
i += 2;
```
```


Question:
Is entity framework just a fancy name for another CRUD code generator?

Or is there more to it?

Answer: They changed the switch statement (from C/Java/C++) behavior for c#.  I guess the reasoning was that people forgot about the fall through and errors were caused.  One book I read said to use goto to simulate, but this doesn't sound like a good solution to me.


Question:
I'm starting on a project that I expect will include a substantial amount of non-Java code (mostly shell and SQL scripts).

I would still like to manage this project with Maven. What are the best practices wrt non-Java source code and Maven? Where should the source go? What happens to them during the different lifecycle phases? Any pointers or links to more information would be greatly appreciated.

Answer:
You must not put the non-Java code into resources, if you don't want to include these files into your JAR files like heckj has suggested. Everything that is located in resources is automatically copied into the JAR file and I guess you don't want shell scripts and SQL scripts be included in a JAR file, right?
So the Maven way would be to create additional folders under src/main. E.g. create a
sql
folder for your SQL scripts, an
sh
folder for your shell scripts and so on. This is the location where other Maven plugins also expect sources, e.g. for C++, Groovy and so on.


Question:
Is Oracle Application Express suitable for Intranet client/server application?
If so, what should I do to enable client access to application?

Well, I am working as a PowerBuilder/Oracle developer, so I am familiar with client/server architecture. I have recently read an article about APEX so I would like to develop APEX variation of my PowerBuilder/Oracle app, which is pretty much HR app. It should not be Internet accessible app, just a couple of windows boxes in a small network. I have no problem with developing app in PL/SQL and SQL (will have to read and ask a lot, though). I would just like to know is APEX suitable for Intranet app - it should be as it is suitable for Internet app :) - and how should I enable client's browser to access an application since there would be nothing like  http:/www.appdomain.com ? I know next to nothing about win networks :)

Answer:
Application Express applications are accessed via a URL in a browser, with a URL something like:
```
```
http://www.mydomain.com/pls/mydad/f?p=MYAPP
```
```
A client/server application would have to launch a browser window and pass in the appropriate URL.


Question:
I have a Rails application for project management where there are Project and Task models. A project can have many tasks, but a task can also have many tasks, ad infinitum.

Using nested resources, we can have /projects/1/tasks, /projects/1/tasks/new, /projects/1/tasks/3/edit etc.

However, how do you represent the recursive nature of tasks RESTfully? I don't want go another level deep, so perhaps the following would do:

map.resources :tasks do |t|
    t.resources :tasks
end

That would give me the following urls:

/tasks/3/tasks/new
/tasks/3/tasks/45/edit

Or perhaps when it comes to an individual task I can just use /tasks/45/edit

Is this a reasonable design?

Cam

Answer:
there's no reason they should have decendant URLS.
logically:
```
/projects/1  --> project 1
/projects/1/edit ( etc )
/tasks/1     --> task 1
/project/1/tasks --> task list for project 1
/project/1/tasks/new
/project/1/tasks/1/edit ->  /tasks/5/edit ( redundancy )
/project/1/tasks/1 -> redirect to /tasks/1
/tasks/1/project -> redirect to /projects/1
/tasks/3/tasks --> list of tasks that are children tasks of task 3
/tasks/3/tasks/5 -> redirect /tasks/5/    ( because you don't really need to have a recursive URL )
/tasks/5/parents -> list of tasks that are parents of tasks 3
/tasks/5/parents/3 -> redirect /tasks/3/
```
there's no reason IMHO to require the URLs be associative, you're not going to need to know that task 5 is a child of task 3 to edit task 5.


Question:
With the new approach of having the get/set within the attribut of the class like that :

public string FirstName {
        get; set;
    }

Why simply not simply put the attribute FirstName public without accessor?

Answer:
Because, in the future, if you change the implementation, code using the current interface won't break.
For instance, you implement a simple class with a public field and start using your class in some external modules. A month later you discover you need to implement lazy loading in that class. You would then need to transform the field to a property. From the external module point of ciew, it might look the same syntaxicaly, but it is not. A property is a set of functions, while a field is an offset in a class instance.
By using a property, you effectively reduce the risk the interface will change.


Question:
Basically I'm trying to accomplish the same thing that "mailto:bgates@microsoft.com" does in Internet Explorer Mobile.

But I want to be able to do it from a managed Windows Mobile application. I don't want to send an email pro grammatically in the background.

I want to be able to create the email in Pocket Outlook and then let the user do the rest.

Hopefully that helps you hopefully help me!

Answer:
I assume you use C#. You add a reference to System.Diagnostics and then write the following code:
```
```
ProcessStartInfo psi =
  new ProcessStartInfo("mailto:bla@bla.com?subject=MySubject", "");
Process.Start(psi);
```
```
This will start the default email client on your mobile device.
The
mailto protocol definition
might come handy too.


Question:
I have inherited a c# class 'Button' (which I can't change) which clashes with the BCL class 'Windows.Forms.Button'. Normally, Id be very happy to go:

MyPackage.MyClass.Button;

But there are a large number or references to this class which is a pain to have to re-type.

Is there any way to get the compiler (linker?) to default to using the customised version of Button over the BCL version?

Answer:
You could remove
```
using Windows.Forms;
```
from the top of the code. That would of course mean that you would have to reference all Windows.Forms items specifically.


Question:
This may be simple one, but 5 mins of Googling didn't give me the answer.
How do you save and load bitmaps using .Net librabries?

I have an Image object and I need to save it to disk in some format (preferably png) and load back in later.
A C# example would be great.

Answer:
About 10 seconds of google lead me to
this example
for the save method, you can dig around a bit more for the others.


Question:
I'm building an interface much like the built-in Weather application's flipside view, or the Alarms view of the Clock application in editing mode. The table view is always in editing mode, so the delete icon appears on the left side of each cell.

When the table view is in editing mode, my delegate doesn't receive didSelectRowAtIndexPath notifications. It receives accessoryButtonTappedForRowWithIndexPath notifications, but that's not what I want to do. I want my rows to stay selectable, even when the table view is in editing mode.

Any ideas on how I can accomplish this?

Thanks,

P.S. Hooray for the lifted NDA. =)

Answer:
Set
```
table.allowsSelectionDuringEditing
```
to
```
YES
```
.


Question:
I would like to know how much disk space a directory is going to consume before I bring it over from the Perforce server.  I don't see any way to do this other than getting the files and looking at the size of the directory in a file manager.  This, of course, defeats the purpose.

Is there a way to get file size info from Perforce without actually getting the files?

Answer:
```
p4 fstat
```


Question: What are the relative merits of the xdoc and apt formats for writing websites of Maven projects? Is one more expressive than the other? Has one got better tool support than the other?

Answer:
The XDOC format is definitely a richer mechanism for creating documents and is required if you want to produce documents with TOC/TOF, headers, footers or footnotes (and other document attributes), since the APT format doesn't support these.
That being said, I tend to use the APT format for almost all internal documents as I enjoy writing in the APT format.  When compared to writing XDOC (with all its XML loveliness), APT is a breeze.  By the same token, when I'm writing a plugin that generates content, I tend to use the XDOC format, since it's pretty easy to write software that creates the required XML.


Question: Will content requested over https still be cached by web browsers or do they consider this insecure behaviour?  If this is the case is there anyway to tell them it's ok to cache?

Answer:
By default web browsers should cache content over HTTPS the same as over HTTP, unless explicitly told otherwise via the
HTTP Headers
received.
This link
is a good introduction to setting cache setting in HTTP headers.
is there anyway to tell them it's ok to cache?
This can be achieved by setting the
```
max-age
```
value in the
```
Cache-Control
```
header to a non-zero value, e.g.
```
```
Cache-Control: max-age=3600
```
```
will tell the browser that this page can be cached for 3600 seconds (1 hour)


Question:
It seems that when I use a tool (such as winmerge) to update my codebase... my Visual Studio Team System (VSTS) integration with Team Foundation Server (TFS) doesn't seem to pick it up.

How do I know which files to check out and check back in? Is there something I am missing? Is this a feature that isn't part of VSTS & TFS?

Answer:
First, this is probably because the files have not yet been checked out.  If you do that first before running your update, TFS will see those changes.
Second, you can use TFS Power Tools (available from MS) to review local repository for changes that are not recognized.  If there are found differences, power toys resets the status of the file so Pending Changes window sees the change.  this does not require you to check-out the files, it will do that for you if there are differences.
Pretty nifty.
Power Tools for 2008 is here:
http://www.microsoft.com/en-us/download/details.aspx?id=15836
and you are looking for the "Online" command:
"Online Command - Use the online command to create pending edits on writable files that do not have pending edits."


Question:
I am using my own db for phpbb3 forum, and I wish to insert some data from the forum into my own tables. Now, I can make my own connection and it runs my query but in trying to use the $db variable(which I think is what you're meant to use??) it gives me an error.

I would like someone to show me the bare bones which i insert my query into to be able to run it.

Answer:
Well.. You haven't given us very much information, but there are two things you need to do to connect and query to a database.
For phpbb, you may want to read the documentation they have presented:
http://wiki.phpbb.com/Database_Abstraction_Layer
Here is a general overview of how you'd execute a query:
```
```
include($phpbb_root_path . 'includes/db/mysql.' . $phpEx);

$db = new dbal_mysql();
// we're using bertie and bertiezilla as our example user credentials. You need to fill in your own ;D
$db->sql_connect('localhost', 'bertie', 'bertiezilla', 'phpbb', '', false, false);

$sql = "INSERT INTO (rest of sql statement)";

$result = $db->sql_query($sql);
```
```


Question:
Within a spring webflow, i need to implement a navigation bar that will allow to "step back" or resume the flow to one of the previous view.

For example :

View 1 = login

View 2 = My informations

View 3 = My messages

View 4 = Close session

For this example, i would like to return back to view 2 from the view 4 page.

Answer:
It depends how you're going about doing this.  If you're doing this within a single flow, you'll have something like this:
```
```
<view-state id="loginView" view="login.jsp">
    <action-state bean="someBean" method="login" />
    <transition on="success" to="informationView" />
</view-state>

<view-state id="informationView" view="information.jsp">
    <render-actions>
        <action-state bean="someBean" method="retrieveInformation" />
    </render-actions>
    <transition on="forward" to="messageView" />
    <transition on="back" to="loginView" />
</view-state>

<view-state id="messageView" view="message.jsp">
    <render-actions>
        <action-state bean="someBean" method="retrieveMessage" />
    </render-actions>
    <transition on="forward" to="closeView" />
    <transition on="back" to="informationView" />
</view-state>

<view-state id="closeView" view="logout.jsp">
    <transition on="jumpBack" to="informationView" />
</view-state>
```
```
The "jumpBack" transition on "closeView" will jump you back to view state #2, which is your information view.
With sub-flows it is tricky.  You'd need to chain it: call a subflow, and if an event is signaled that states you need to end your flow with a specific state, immediately do so.
For example, say that your flow chain is login->information->message->close.
On the close flow, the end-state would be "returnToInformation".
The message flow has a transition on="returnToInformation" to="returnToInformation".
"returnToInformation" is also an end-state in the message flow.
Then, the information flow has a transition on="returnToInformation" to="displayInformationPage", which would then re-display the information page.


Question:
I am trying to match floating-point decimal numbers with a regular expression.  There may or may not be a number before the decimal, and the decimal may or may not be present, and if it is present it may or may not have digits after it.  (For this application, a leading +/- or a trailing "E123" is not allowed).  I have written this regex:

/^([\d]*)(\.([\d]*))?$/

Which correctly matches the following:

1
1.
1.23
.23

However, this also matches empty string or a string of just a decimal point, which I do not want.

Currently I am checking after running the regex that $1 or $3 has length greater than 0.  If not, it is not valid.  Is there a way I can do this directly in the regex?

Answer:
I think this will do what you want.  It either starts with a digit, in which case the decimal point and digits after it are optional, or it starts with a decimal point, in which case at least one digit is mandatory after it.
```
```
/^\d+(\.\d*)?|\.\d+$/
```
```


Question:
This PHP code...

207    if (getenv(HTTP_X_FORWARDED_FOR)) {
208        $ip   = getenv('HTTP_X_FORWARD_FOR');
209        $host = gethostbyaddr($ip);
210    } else {
211        $ip   = getenv('REMOTE_ADDR');
212        $host = gethostbyaddr($ip);
213    }

Throws this warning...

Warning: gethostbyaddr()
  [function.gethostbyaddr]: Address is
  not in a.b.c.d form in C:\inetpub...\filename.php on line 212

It seems that $ip is blank.

Answer:
Why don't you use
```
```
$_SERVER['REMOTE_ADDR']
```
```
and
```
```
$_SERVER['HTTP_X_FORWARDED_FOR']
```
```