q: I'm writing a quick Rails app and was wondering how I can validate the success an exec'd command.  The two commands I'm running are and SVN update, and a cp from one directory to another.

[A]
For SVN update, check the version number before and after the update.
```
```
svn_start_version = IO.popen("svn info").readlines[4]
`svn update`
svn_end_version = IO.popen("svn info").readlines[4]
if svn_end_version > svn_start_version
  "success"
end
```
```
For the cp, you could do a filesize check on the original file being equal to the copied file.
```
```
source_file_size = IO.popen("du file1").readlines
`cp file1 file2`
dest_file_size = IO.popen("du file2").readlines
if dest_file_size == source_file_size
  "success"
end
```
```


q: I am VERY new to ASP.NET.  I come from a VB6 / ASP (classic) / SQL Server 2000 background.  I am reading a lot about Visual Studio 2008 (have installed it and am poking around).  I have read about "reflection" and would like someone to explain, as best as you can to an older developer of the technologies I've written above, what exactly Reflection is and why I would use it...  I am having trouble getting my head around that.  Thanks!

[A]
Reflection is how you can explore the internals of different Types, without normally having access (ie. private, protected, etc members).
It's also used to dynamically load DLL's and get access to types and methods defined in them without statically compiling them into your project.
In a nutshell: Reflection is your toolkit for peeking under the hood of a piece of code.
As to why you would use it, it's generally only used in complex situations, or code analysis. The other common use is for loading precompiled plugins into your project.

s: huggingface

c: devops

d: intermediate


q: I basically have an xml column, and I need to find and replace one tag value in each record.

[A]
To find a content in an XML column, look into the exist() method, as described in MSDN
here
.
```
```
SELECT * FROM Table
WHERE XMLColumn.exist('/Root/MyElement') = 1
```
```
...to replace, use the modify() method, as described
here
.
```
```
SET XMLColumn.modify('
  replace value of (/Root/MyElement/text())[1]
  with "new value"
')
```
```
..all assuming SqlServer 2005 or 2008.  This is based on XPath, which you'll need to know.


q:
I've got an app that my client wants to open a kiosk window to ie on startup that goes to their corporate internet.  Vb isn't my thing but they wanted it integrated into their current program and I figured it would be easy so I've got

Shell ("explorer.exe http://www.corporateintranet.com")

and command line thing that needs to be passed is -k

Can't figure out where in the hell to drop this to make it work.  Thanks in advance! :)

[A]
If you would like to use -k, you will probably want to call
```
iexplore.exe
```
instead of
```
explorer.exe
```
.


q:
I'm curious what tools people have found useful for building flowcharts. Obviously MS Visio and OmniGraffle come to mind but they both feel so bloated and also tend to emphasize the document formatting/printing side and less on helping to organize the actual logic. Is there anything else out there that fellow developers would recommend?

I'm hoping to find something fairly simple that would let me throw together flowcharts on the fly when I'm working through complex logic. I don't care about formatting or fonts or the like, just something that would help me keep my logic organized as I work through it. Even something that would arrange the chart itself and simply allow me to specify where to branch and what to check, etc.

Any OS would be fine, though I personally lean towards OS X apps as this has recently been my primary work environment.

[A]
Though you list it as bloated I nonetheless use
OmniGraffle
.
For quick flowcharting a series of boxes with lines to magnets in the boxes is sufficient, but the rest of the formatting options are good to have later. I find that any flowchart I take the time to draw generally ends up in a document somewhere. Even when I'm just trying to understand some difficult code, I end up with a one page document which attempts to explain that code for the next poor schmuck who has to dig in.


q:
I have a value like this:

"Foo Bar" "Another Value" something else

What regex will return the values enclosed in the quotation marks (e.g. Foo Bar and Another Value)?

[A]
In general, the following regular expression fragment is what you are looking for:
```
```
"(.*?)"
```
```
This uses the non-greedy *? operator to capture everything up to but not including the next double quote. Then, you use a language-specific mechanism to extract the matched text.
In Python, you could do:
```
```
>>> import re
>>> string = '"Foo Bar" "Another Value"'
>>> print re.findall(r'"(.*?)"', string)
['Foo Bar', 'Another Value']
```
```


q: I've got 256 colors working great in my terminal (test scripts here), but it stops working when I use ncurses (via Ruby-ncurses). Printing the escape sequences given on that page works fine, but when I initialize ncurses 'puts' stops working and I can't output the colors with any of the various ncurses color changing/string output functions I've found. What gives?

[A]
I am not sure if this would be all the story, but make sure your terminal capabilities do indeed provide for the 256 colors description.
What is the TERM environment variable value? Try setting it to xterm-256color and rerun it.
ncurses should then get the proper color escape sequences.
You can also test the terminal capabilities and terminal color output with the program we use at SXEmacs development:
http://www.triatlantico.org/tmp/tty-colors.c
Compile with gcc -o tty-colors tty-colors.c -lncurses
EDIT:
Note that just because the scripts that are found on the net output the 256 colors, that is not "all set".
Curses programs rely on terminfo and termcap and the TERM environment variable to find out how to interact with the terminal.
So in order for a curses app to be able to use the 256 colors one should set the TERM variable to an existing terminal name which supports 256 colors.
The C program above will show you
what
ncurses thinks about your terminal, not just output the xterm sequences like most scripts do [even the one from X.org]


q: I've been unsuccessfully searching for a way to install make utility on my CentOS 5.2. I've looked through some RPM repositories and online, with no avail. Installing gcc, gcc-c++ didn't help! Package build-essential is not made for CentOS/RHEL. I have RPMFORGE repo enabled in YUM.

[A]
I just double checked and CentOS 5.2 already includes make!
I found it also in one of the online mirrors, if it is easier for you:
http://centos.cogentcloud.com/5.2/os/i386/CentOS/make-3.81-3.el5.i386.rpm
if you installed the 64 bit version:
http://centos.cogentcloud.com/5.2/os/x86_64/CentOS/make-3.81-3.el5.x86_64.rpm


q:
I have a service app that creates AppDomain's during the course of its use for long running tasks. I've been tracking these by storing them in a Hashtable with a unique ID.

After a task is completed the service app then unloads the AppDomain allocated to that task and then it's removed it from the appdomain Hashtable.

Purely from a sanity checking point of view, is there a way I can query the CLR to see what app domains are still loaded by the creating app domain (i.e. so I can compare the tracking Hashtable against what the CLR actually sees)?

[A]
```
children
```
is a simple has_many association
This means, when you call
```
.children
```
, it will load them from the database (if not already present). It will then cache them.
I was going to say that your second 'test' will actually be looking at the cached values not the real database, but that shouldn't happen as you are just using
```
Task.count
```
rather than
```
d1.children.count
```
. Hrm
Have you looked at the logs? They will show you the SQL which is being executed. You may see a mysql error in there which will tell you what's going on


q:
I'm trying to set the width and height of an element with javascript to cover the entire browser viewport, and I'm successful using
document.body.clientHeight
 but in IE6 it seems that I always get horizontal and vertical scrollbars because the element must be slightly too big.

Now, I really don't want to use browser specific logic and substract a pixel or 2 from each dimension just for IE6. Also, I am not using CSS (width: 100% etc.) for this because I need the pixel amounts.

Does anyone know a better way to fill the viewport with an element in IE6+ (obviously all good browsers, too)?

Edit: Thanks Owen for the suggestion, I'm sure jQuery will work. I should have specified that I need a toolkit-agnostic solution.

[A]
This
may
help the cause ...
From
http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
:
```
```

```
```


q: Im using delphi's ttreeview as an 'options' menu. how would i go upon selecting the next node at runtime like a previous and next button? i tried the getprev and getnext methods but no luck.

[A]
Here you have the 'Next' behavior. For 'Previous' I leave as exercise for you: :-)
```
```
procedure TForm8.btn1Click(Sender: TObject);
var
  crt: TTreeNode;

begin
  with tv1 do //this is our tree
  begin
    if Selected=nil then
      crt:=Items[0] //the first one
    else
      crt:=Selected.GetNext; //for previous you'll have 'GetPrev'

    if crt<>nil then //can be 'nil' if we reached to the end
      Selected:=crt;
  end;
end;
```
```
HTH


q: Actually I will want to use that JeOS for our webserver. Is it a good choice?


q: If I modify or add an environment variable I have to restart the command prompt.  Is there a command I could execute that would do this without restarting CMD?

[A]
By design there isn't a
built in
mechanism for Windows to propagate an environment variable add/change/remove to an already running cmd.exe, either from another cmd.exe or from "My Computer -> Properties ->Advanced Settings -> Environment Variables".
If you modify or add a new environment variable outside of the scope of an existing open command prompt you either need to restart the command prompt, or, manually add using SET in the existing command prompt.
The
latest accepted answer
shows a partial work-around by manually refreshing
all
the environment variables in a script. The script handles the use case of changing environment variables globally in "My Computer...Environment Variables", but if an environment variable is changed in one cmd.exe the script will not propagate it to another running cmd.exe.


q:
I am involved in development of a tiered application that uses LINQ2SQL separated from the   web server with a NET.TCP Binding on WCF.

My questions are:

What sort of measures should I take
to achieve the best performance?

Since the entity objects returned by
the LINQ need to be converted to a
IEnumerable list to be serialized
everytime, is there anyway to remove
this dependency?

[A]
1) Concentrate on a properly normalized database design.  I would say that when you are forced to make design tradeoffs in your code vs. database design, if performance is your goal, make tradeoffs in your object design instead of your database design.  Understand that you aren't going to be able to do a proper supertype/subtype database design which will work with Linq to SQL (I'm told you need to use the EF instead).
2) Depends what you mean here.  If you're asking how you would serialize anonymous classes across the wire, the easy answer is: "you can't, so don't try".  If you want to put lists of objects across the wire, just use the ToArray() extension method on your IEnumerable collections to ship arrays of your business objects over the wire.


q:
I've got a data object with a component in it that is an System.Collections.Generic.IList, and I'd like to reflect changes to that list into a Gtk# NodeView, so that when an item is added to the list, the NodeView will get a new item added to it.

How would I listen for changes to an IList?  I have considered wrapping the IList with a class that implements IList, delegates the requisite methods, and broadcasts an event when changing it's contents, but that seems like a lot of work for something that has probably already been solved by someone else.


q:
im currently overiding the WM_NCPAINT, WM_NCCALCSIZE and WM_NCACTIVATE to paint my own color/themed title bar for an application im working on. Now this is working great however the min, max and close buttons still are xp default theme.

I looked into what controls them and the mouse messages do. However they also contol resizing and other functions that I dont want to lose.

Is there an easy way to just change the theme of these buttons?

Windows XP

MFC Forms

Visual studio 2005

[A]
I think your best bet here is to disable the buttons and redraw them with something akin to to
the code I posted in this answer
. It's in C# with WinForms, but the vast majority of it is overloaded WndProc() anyway, which you should be able to use almost copy/paste into MFC.
Implementing click handlers to do what you want them to do is trivial.
Note: The asker of that question said the code didn't work in Vista. I don't have a Vista box, but it works for me in XP.


q:
When using one's own iPhone for development it's easy enough to access any crash logs via XCode->Organizer->Crash Logs.

How does one access crash logs on another person's phone if they don't have it set up for development in XCode, as would likely be the case if you were distributing your app to them via ad hoc distribution for beta testing?

[A]
Two ways:
iTunes syncs all crash reports during a regular sync. They can be found in Library/Logs/CrashReporter/MobileDevice on a Mac and probably somewhere in %APPDATA% on Windows.
You can use the
iPhone Configuration Utility for Mac OS X
on any Mac to access the phone's console and crash logs. Note:
the iPhone Web Configuration Utility, which is available for Windows and Mac (note the "web" in the name)
does not
allow this kind of access and only provides a portion of the Configuration Utility's features
.
Er, no you can't. Xcode provides this facility in the Organizer (from the Window menu), but not iPCU.


q:
When maintaining a COM interface should an empty BSTR be treated the same way as NULL?
In other words should these two function calls produce the same result?

 // Empty BSTR
 CComBSTR empty(L""); // Or SysAllocString(L"")
 someObj->Foo(empty);

 // NULL BSTR
 someObj->Foo(NULL);

[A]
Yes - a NULL BSTR is the same as an empty one. I remember we had all sorts of bugs that were uncovered when we switched from VS6 to 2003 - the CComBSTR class had a change to the default constructor that allocated it using NULL rather than an empty string. This happens when you for example treat a BSTR as a regular C style string and pass it to some function like
```
strlen
```
, or try to initialise a
```
std::string
```
with it.
Eric Lippert discusses BSTR's in great detail in
Eric's Complete Guide To BSTR Semantics
:
Let me list the differences first and
then discuss each point in
excruciating detail.
A BSTR must have identical
semantics for NULL and for "".  A PWSZ
frequently has different semantics for
those.
A BSTR must be allocated and freed
with the SysAlloc* family of
functions.  A PWSZ can be an
automatic-storage buffer from the
stack or allocated with malloc, new,
LocalAlloc or any other memory
allocator.
A BSTR is of fixed length.  A PWSZ
may be of any length, limited only by
the amount of valid memory in its
buffer.
A BSTR always points to the first
valid character in the buffer.  A PWSZ
may be a pointer to the middle or end
of a string buffer.
When allocating an n-byte BSTR you
have room for n/2 wide characters.
When you allocate n bytes for a PWSZ
you can store n / 2 - 1 characters --
you have to leave room for the null.
A BSTR may contain any Unicode data
including the zero character.  A PWSZ
never contains the zero character
except as an end-of-string marker.
Both a BSTR and a PWSZ always have a
zero character after their last valid
character, but in a BSTR a valid
character may be a zero character.
A BSTR may actually contain an odd
number of bytes -- it may be used for
moving binary data around.  A PWSZ is
almost always an even number of bytes
and used only for storing Unicode
strings.


q:
I've been trying to create a Windows Media Player plugin in Visual Studio 2008, and am having great difficulty finding the correct template. MSDN provides advice here, but it does not appear to be relevant to VS2008.

Can anyone suggest how to start a WMP plugin in Visual Studio?

EDIT: Ive accepted this answer because it worked for me, but I'm afraid it isn't the most elegant of solutions. If anyone has a better idea, please add it!

[A]
Generics doesn't natively support arithmetic. However, it can be done with .NET 3.5,
like so
. The Operator class is part of
MiscUtil
. This then becomes:
```
```
public T Evaluate<T>(T x, T y) {
      switch (Operation)
      {
        case BinaryOp.Add:
            return Operator.Add(x, y);
        case BinaryOp.Subtract:
            return Operator.Subtract(x, y);
     ... etc
```
```
Since you are writing an expression parser, it might be a good idea to use Expression directly, but you're welcome to use the above.


q:
Many times I will use the same font scheme for static text in a wxPython application. Currently I am making a SetFont() call for each static text object but that seems like a lot of unnecessary work. However, the wxPython demo and wxPython In Action book don't discuss this.

Is there a way to easily apply the same SetFont() method to all these text objects without making separate calls each time?

[A]
Maybe try subclassing the text object and in your class
```
__init__
```
method just call SetFont()?
Or, do something like:
```
```
def f(C):
  x = C()
  x.SetFont(font) # where font is defined somewhere else
  return x
```
```
and then just decorate every text object you create with with it:
```
```
text = f(wx.StaticText)
```
```
(of course, if
```
StaticText
```
constructor requires some parameters, it will require changing the first lines in
```
f
```
function definition).


q: How do i delete all the tables in the schema on Apache Derby DB using JDBC?

[A]
I think most db providers don't allow DROP TABLE * (or similar).
I think the best way would be to SHOW TABLES and then go through each deleting in a loop via a resultset.
HTH.


q:
Using NHibernate from C# and only HQL (not SQL) in a way that is compatible with MS SQL Server 2005/2008 (and preferably Oracle).

Is there a way to write the order by clause so that nulls will sort at the end of the query results while the non-null results will be sorted in ascending order?

Based on the answer to the question referenced by nickf the answer is:

select x from MyClass x order by case when x.MyProperty is null then 1 else 0 end, x.MyProperty

[A]
In the Wikipedia example, those instances can be passed into a function that doesn't have to care which class those instances belong to. The function just calls
```
execute
```
on the object passed, and know that the Right Thing will happen.
A typical example of the Strategy Pattern is how files work in Unix. Given a file descriptor, you can read from it, write to it, poll it, seek on it, send
```
ioctl
```
s to it, etc., without having to know whether you're dealing with a file, directory, pipe, socket, device, etc. (Of course some operations, like seek, don't work on pipes and sockets. But reads and writes will work just fine in these cases.)
That means you can write generic code to handle all these different types of "files", without having to write separate code to deal with files versus directories, etc. The Unix kernel takes care of delegating the calls to the right code.
Now, this is Strategy Pattern as used in kernel code, but you didn't specify that it had to be user code, just a real world example. :-)


q:
I've updated my TortoiseSVN client and now I'm getting the error when trying to update or commit to different repositories:

The requested name is valid, but no data of the requested type was
  found

Any ideas on how I can solve this? Internet Explorer shows up appropriate URL just fine.

TortoiseSVN 1.5.3, Build 13783.

[A]
This error being reported is a winsock one, rather than being particular to TSVN. From
Windows Sockets Error Codes
:
The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for, e.g. an MX record is returned but no A record - indicating the host itself exists, but is not directly reachable.
It is strange that you can access the host via IE however. Is it possible that in TSVN you've specified a port number that isn't available on the remote host, and IE is accessing the host on port 80?


q:
Are there LaTeX packages for (more or less) easily drawing Gantt diagrams?

Thanks.

[A]
I have not used myself, but it looks like PSTricks offers some Gantt chart drawing capabilities.
Main PSTricks site:
http://tug.org/PSTricks/main.cgi
Example of Gantt chart using PSTricks:
http://tug.org/PSTricks/main.cgi?file=Examples/Charts/gantt


q:
I have a plug-in to an Eclipse RCP application that has a view.  After an event occurs in the RCP application, the plug-in is instantiated, its methods are called to populate the plug-in's model, but I cannot find how to make the view appear without going to the "Show View..." menu.

I would think that there would be something in the workbench singleton that could handle this, but I have not found out how anywhere.

[A]
You are probably looking for this:
```
```
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("viewId");
```
```


q:
I want to update a list of storage devices as the user inserts USB keys, adds external disks and mounts disk images. IOKit's IOServiceAddInterestNotification looks like the way to go, but the obvious use of registering general interest in kIOMediaClass only gives you notifications for unmounting of volumes and then only sometimes.

What's the right way to do this?

[A]
Would watching
```
/Volumes
```
for changes do what you need?


q:
I am studying how two-phase commit works across a distributed transaction. It is my understanding that in the last part of the phase the transaction coordinator asks each node whether it is ready to commit. If everyone agreed, then it tells them to go ahead and commit.

What prevents the following failure?

All nodes respond that they are
ready to commit

The transaction
coordinator tells them to "go ahead
and commit" but one of the nodes
crashes before receiving this
message

All other nodes commit successfully, but now the distributed transaction is corrupt

It is my understanding that when the crashed node comes back, its transaction will have been rolled back (since it never got the commit message)

I am assuming each node is running a normal database that doesn't know anything about distributed transactions. What did I miss?

[A]
No.  Point 4 is incorrect.  Each node records in stable storage that it was able to commit or rollback the transaction, so that it will be able to do as commanded even across crashes.  When the crashed node comes back up, it must realize that it has a transaction in pre-commit state, reinstate any relevant locks or other controls, and then attempt to contact the coordinator site to collect the status of the transaction.
The problems only occur if the crashed node never comes back up (then everything else thinks the transaction was OK, or will be when the crashed node comes back).


q:
Is there an app or way to browse a directory that requires different login credentials without using a mapped drive?

The issue is given one login credential Windows Explorer only allows you to map it to one drive and disallows using the same login credential to map to a different drive.


q:
I am using the jquery-ui-dialog plugin

I am looking for way to refresh the page when in some circumstances when the dialog is closed.

Is there a way to capture a close event from the dialog?

I know I can run code when the close button is clicked but that doesn't cover the user closing with escape or the x in the top right corner.

[A]
If I'm understanding the type of window you're talking about, wouldn't
$(window).unload()
(for the dialog window) give you the hook you need?
(And if I misunderstood, and you're talking about a dialog box made via CSS rather than a pop-up browser window, then
all
the ways of closing that window are elements you could register click handers for.)
Edit:
Ah, I see now you're talking about jquery-ui dialogs, which are made via CSS.  You can hook the
X
which closes the window by registering a click handler for the element with the class
ui-dialog-titlebar-close
.
More useful, perhaps, is you tell you how to figure that out quickly.  While displaying the dialog, just pop open FireBug and
Inspect
the elements that can close the window.  You'll instantly see how they are defined and that gives you what you need to register the click handlers.
So to directly answer your question, I believe the answer is really "no" -- there's isn't a close event you can hook, but "yes" -- you can hook all the ways to close the dialog box fairly easily and get what you want.


q:
I've been hearing a lot about about how the new version of VMWare Fusion can run virtual operating systems in "headless mode".

A Google search makes it clear that other virtualisation products also have similar features, however, I have not been able to find a good description of what this actually means? What is happening when you do this?

[A]
For anyone that is interested, you can activate headless mode in VMWare Fusion by running the following command in Terminal.app
```
```
defaults write com.vmware.fusion fluxCapacitor -bool YES
```
```


q:
I'm storing all localizable strings in a ResourceDictionary (in App.xaml) and assign those via the StaticResource markup extension to TextBlock.Text, Button.Content etc.

In Beta 2 and RC0, sometimes parsing the XAML in InitializeComponent() will fail with an AG_E_PARSER_BAD_PROPERTY_VALUE on the line and position where I set the attribute value to the StaticResource.

It only happens sometimes: When restarting the app, it parses and displays without any problems. The same interface code works for days or weeks, then it happens again.

Any ideas?

[A]
Parser, at least in beta 2, didnt like whitespace...
For instance:
```
```
Text="{StaticResource bleh}"
```
```
worked
however this:
```
```
Text = "{StaticResource bleh}"
```
```
bombed


q: When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like Assembly.GetCallingAssembly() but for methods.

[A]
Try this:
```
```
using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace();
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
```
```
one-liner:
```
```
(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name
```
```
It is from
Get Calling Method using Reflection [C#]
.


q:
Is there a way to exclude all svn externals when doing a recursive update?

Is there a way to exclude only 1 of all of the svn externals when doing a recursive update?

Basically I'd like to cut down the svn update time, and a couple of the SVN externals that I have will just about never get updated.

[A]
Yes, there is an option for this (to ignore all):
```
```
> svn update --ignore-externals
```
```
I don't know of any option to specifically ignore one or some externals while updating the rest.


q:
I've written a small test application using the .Net FileSystemWatcher to keep an eye on a directory. When I copy a large-ish (a few Mb) file into that directory I get the following events listed (see screenshot - and ignore the Delete event to begin with).

alt text http://robinwilson.homelinux.com/FSW.png

I get a created event (as expected), but then two changed events (about 0.7 seconds apart). Why is this? This would cause major problems in the application I am planning to develop - as I'd try and do things with the file twice (presumably once before it has finished being written to!). Is there anything I can do to stop this happening? From what I've read on StackOverflow and elsewhere, you should just get one changed event once the file has been changed and then closed. Why am I getting two?

[A]
Usually the copying program is doing it in blocks, not entire file at once. I don't think you can do anything to avoid this, you will have to adopt your algorithms to deal with this.
You can perform an attempt to open file with exclusive read rights, which should be granted to your program only when other program finished copying and closed file. Otherwise you will get IOException and you can wait for next change. But this doesn't mean you shouldn't deal with multiply change events. Opening text file in Notepad and saving it once in a while will generate change events, but file will not be locked all the time.
Another approach would be to collect touched files for a period of time, and when FileSystemWatcher stops generating events, process all files at once.


q:
I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later.

So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile.

[A]
A
user profile
(as returned by
```
django.contrib.auth.models.User.get_profile
```
) doesn't extend the User table - the model you specify as the profile model with the
```
AUTH_PROFILE_MODULE
```
setting is just a model which has a
```
ForeignKey
```
to
```
User
```
.
```
get_profile
```
and the setting are really just a convenience API for accessing an instance of a specific model which has a
```
ForeignKey
```
to a specific
```
User
```
instance.
As such, one option is to create a profile model in which the
```
ForeignKey
```
to
```
User
```
can be
```
null
```
and associate your
```
Photo
```
model with this profile model instead of the
```
User
```
model. This would allow you to create a profile for a non-existent user and attach a registered User to the profile at a later date.


q: How can I elegantly print the date in RFC822 format in Perl?

[A]
```
```
use POSIX qw(strftime);
print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n";
```
```


q: Is it possible to get notified (without polling, but via an event) when a drive letter becomes accessible. For example if you have an external hard drive that always appears as drive F - is it possible to have an event raised when that is connected and F becomes accessible?


q: I've managed to mostly ignore all this multi-byte character stuff, but now I need to do some UI work and I know my ignorance in this area is going to catch up with me! Can anyone explain in a few paragraphs or less just what I need to know so that I can localize my applications? What types should I be using (I use both .Net and C/C++, and I need this answer for both Unix and Windows).

[A]
Check out Joel Spolsky's
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
EDIT 20140523
: Also, watch
Characters, Symbols and the Unicode Miracle
by Tom Scott on YouTube - it's just under ten minutes, and a wonderful explanation of the brilliant 'hack' that is UTF-8


q:
I get the Total length of columns in constraint is too long. erro from the following

sql] Failed to execute:   CREATE TABLE GTW_WORKFLOW_MON ( WORKFLOW_NAME VARCHAR(255) NOT
NULL, WORKFLOW_LOADED NUMERIC(20) NOT NULL, ACTIVITY_NAME VARCHAR(255) NOT NULL, FLAGS
INTEGER NOT NULL, MONITOR_NAME VARCHAR(255) NOT NULL, CLASSNAME VARCHAR(255) NOT NULL, S

TR0 VARCHAR(255), STR1 VARCHAR(255), STR2 VARCHAR(255), NUM0 VARCHAR(255), NUM1
VARCHAR(255), NUM2 VARCHAR(255), DATE0 VARCHAR(255), DATE1 VARCHAR(255), DATE2
VARCHAR(255), PRIMARY KEY (WORKFLOW_NAME,WORKFLOW_LOADED,ACTIVITY_NAME,MONITOR_NAME) )

  [sql] java.sql.SQLException: Total length of columns in constraint is too long.

[A]
Your primary key constraint is 785 bytes (255+20+255+255).  If you increase your database page size to 4K it should work, barely.  You should also reconsider if you need your columns to be as wide as you are defining them.
I found a discussion group where an engineer, Radhika Gadde,
describes
that the maximum index size is related to page size.  He says:
which error you are getting while creation of Tables.
Maximum Index key length can be calculated as follows:
[(PAGESIZE -93)/5] -1
like for 2k it is
[( 2048-93)/5] -1 =[1955/5] -1 =391-1=390
if PAGESIZE is 4K
it is [(4096-93)/5] -1 =4003/5-1=800-1 =799


q:
For development, I use a local LAMP stack, for production I'm using MediaTemple's Django Container (which I'm loving BTW).  MT's container uses lighthttpd.  Honestly I've never had any other experience with it. I've always used Apache. I've been doing some reading:

Onlamp

TextDrive

Linux.com

Here's are questions:

What strengths does one have over the other?

Would it benefit me to use lighthttpd on my dev setup?

What's up with using both?  The Linux.com article talks about using lighttpd with Apache.

[A]
The benefit of both: Apache is more powerful and extensible (useless if you don't need that power, but anyway...) and lighttpd is faster at static content. The idea is of splitting your site into static content (css, js, images, etc) and dynamic code that flows through Apache.
I'm not saying you can't do a lot with lighttpd on its own. You can and people do.
If you're using lighttpd exclusively on your production server, I would seriously consider mirroring that on your development and staging servers so you know exactly what to expect before you deploy.


q:
I am working on a web-application in which dynamically-created images are used to display information. This data is currently sent to the images using a GET query-string but with more complex images and data I am worried about running into problems with the url character limit.

I could simply pass the record ID to the image and have this query the database but this would obviously increase demand on the server. Is there some way I could add an image retrieved using POST into a HTML document?

[A]
In the end, I think quering the database will probably be faster. To get a small string (say up to 2000 characters) from the database is very quick and probably faster than having the user post it all the time, especially if there is more than 1 on a page.
The best option would be create the image once and cache it if it doesn't change. When the image is requested again, check to see if it's cached and just use readfile() to send it to the browser. I like to store the cached image outside the doc root so it's not accessible by others, but this may not be a factor in what you're doing (both caching and privacy).
The SESSION might be an option, but this is the best option when you need to regenerate the image on multiple pages with slight changes, so you don't have query the db each time.


q: Where can I find a list of all types of bsd style socket errors?

[A]
You can also find a list of error codes (and a general description of their meaning) on the Open Group's pages for each function (like
connect
, for example).


q: We're starting a large web project, mostly green field. I like the Tapestry framework for java/web solutions. I have concerns about starting a Tapestry 5 project since T5 is still in beta. However, if I understand the documentation correctly, T4 development will not be supported by T5 and up. My question: Should I begin a large project for a large company with T5? If not, with the imminent release of T5, should I ignore T4 altogether?

[A]
T5 is in the last beta, the next release is RC, and then the full release. according to howard, things should be done by the end of october. so, if you're starting the project, i believe the framework will catch you with its release.
another thing, the betas are pretty quality products, howard does the great job with his framework. at my now previous company, there is a project started in september based on tapestry 5, a colleague managed to get a working example pretty quickly and it seems okay. we worked with tapestry 4 on a previous project, and when the question raised about which version to choose, the fact that T4 will be abandoned in favor of T5, and much changes in the framework concept itself, the counclusion was it's much better for a developer new in tapestry to learn new version immidiately (also, if i were to stay, i was interested in switching to T5 also as soon as possible, because i see a quality improvement in the T5 concepts compared to T4 which i worked with).
of course, you have your deadlines and project limitations which you have to take into account. if it's rather flexibile, or long-lasting project, maybe get a quick start of T5 for a week, and then decide based on your experience with it.


q:
I've got a few hundred computers running an app.  On one computer, I've seen two instances of a single bit being incorrectly set on some strings that I pull out of SQLite.  If this was my dev computer I would assume I have a bug somewhere, but there is certainly some number of installations at which point I'll start seeing rare hardware based errors.

This is certainly dependent on how much IO I do, but are there any rules of thumbs for when there is a decent chance of seeing this kind of thing?  For example, for TCP packets, this paper determined that silent, undetected corruption will occur in "roughly 1 in 16 million to 10 billion packets".

Unfortunately, running a mem/disk checker on the machine in question is not likely to happen.

[A]
When I notice strange things happening, my strategy is:
check if there is a bug
in the code
check if there is a bug in the used library/tool (SQLite, here)
check if there is a bug
in the compiler
then, and only then, check for hardware faults
In my 10 years-long career, 99,99% of bugs were software related.
Hope this helps.


q:
I'd like to zoom and unzoom in ways the base class doesn't support.

For instance, upon receiving a double tap.

[A]
I'm answering my own question, after playing with things and getting it working.
Apple has a very-simple example of this in their documentation on how to handle double taps.
The basic approach to doing programmatic zooms is to do it yourself, and then tell the UIScrollView that you did it.
Adjust the internal view's frame and bounds.
Mark the internal view as needing display.
Tell the UIScrollView about the new content size.
Calculate the portion of your
internal view that should be
displayed after the zoom, and have
the UIScrollView pan to that
location.
Also key: once you tell the UIScrollView about your new contents size it seems to reset its concept of the current zoom level.  You are now at the new 1.0 zoom factor.  So you'll almost certainly want to reset the minimum and maximum zoom factors.


q:
I've written up a weekly-review GTD checklist for myself in TiddlyWiki, using CheckboxPlugin. After I'm finished with it each week, I'd like to click one link to uncheck (reset) all of the items on it, so it's ready for the next use.

I'm storing the check information as tags on a separate tiddler page. I should be able to just erase all the tags on that page and refresh the checklist page, but I haven't been able to work out how to do that yet.

I generally work in C, C++, and Lisp, I'm just learning about Javascript. Can anyone offer some useful pointers?

(And before anyone suggests it, I've looked at the ChecklistScript on the same site. It doesn't use the CheckboxPlugin stuff, and isn't compatible with it.)

[A]
Try this (adapted from ChecklistScript's "resetall" code):
```
```
<html><form style="display:inline">
    <input type="button" value="clear all" onclick="
        var tid='SomeTiddler';
        var list='tag1 [[tag 2]] tag3 tag4';
        var tags=list.readBracketedList();
        store.suspendNotifications();
        for (var t=0; t<tags.length; t++)
            store.setTiddlerTag(tid,false,tags[t]);
        store.resumeNotifications();
        story.refreshTiddler(tid,null,true);
"></form></html>
```
```


q: What is the difference between #include and #import in C++?

[A]
Import in VC++:
```
#import
```
is for type libraries or .tlbs (COM stuff).
The content of the type library is converted into C++ classes, mostly describing the COM interfaces for you automatically, and then it is included into your file.
The
```
#import
```
directive was introduced by Microsoft as an extension to the C++ language.  You can read about it at
this MSDN article
.
The
```
#import
```
directive is also used with .NET / CLI stuff.
Import in gcc:
The import in gcc is different from the import in VC++. It is a simple way to include a header at most once only.  (In VC++ and GCC you can do this via
```
#pragma
```
once as well)
The
```
#import
```
directive was officially undeprecated by the gcc team in version 3.4 and works fine 99% of the time in all previous versions of gcc which support
Include:
```
#include
```
is for mostly header files, but to prepend the content to your current file.
```
#include
```
is part of the C++ standard.  You can read about it at
this MSDN article
.


q:
I've got a WCF Web Service method whose prototype is:

[OperationContract]
Response<List<Customer>> GetCustomers();

When I add the service reference to a client, Visual Studio (2005) creates a type called "ResponseOfArrayOfCustomerrleXg3IC" that is a wrapper for "Response<List<Customer>>".  Is there any way I can control the wrapper name?  ResponseOfArrayOfCustomerrleXg3IC doesn't sound very appealing...

[A]
Yes. The OperationContractAttribute takes a parameter called Name. You could specify it like this:
```
```
[OperationContract(Name = "NameGoesHere")]
Response<List<Customer>> GetCustomers();
```
```


q:
I have a stored procedure with the following header:

FUNCTION SaveShipment (p_user_id IN INTEGER, p_transaction_id IN INTEGER, p_vehicle_code IN VARCHAR2 DEFAULT NULL, p_seals IN VARCHAR2 DEFAULT NULL) RETURN INTEGER;

And I am having trouble running it from TOAD's Editor.  I cannot run it as part of a select from dual statement because it preforms DML, but if I try the following syntax which I saw recommended on some forum:

var c integer;
exec :c := orm_helper.orm_helper.SAVESHIPMENT (9999, 31896, NULL, '');
print c;

I get:

ORA-01008: not all variables bound
Details:
BEGIN :c := orm_helper.orm_helper.saveshipment (9999, 31896, null, ''); END;
Error at line 2
ORA-01008: not all variables bound

What's the proper syntax to run this sp manually?

[A]
Are you calling the stored procedure from another SP?
I think the syntax is (if I recall correctly):
```
```
declare
     c integer;
begin

c:=storedProc(...parameters...);
```
```
Hope this helps.


q: Is it possible to detect a valid regular expression with another regular expression?  If so please give example code below.

[A]
Unlikely.
Evaluate it in a
```
try..catch
```
or whatever your language provides.


q:
I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon.  Some questions to get us going in the right direction:

Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?

Have you already started or plan on starting soon?  Or do you plan on waiting until the final version comes out to get into full swing?

[A]
Speaking as a library author:
I'm waiting for the final version to be released. My belief, like that of most of the Python community, is that 2.x will continue to be the dominant version for a period of weeks or months. That's plenty of time to release a nice, polished 3.x release.
I'll be maintaining separate 2.x and 3.x branches. 2.x will be backwards compatible to 2.4, so I can't use a lot of the fancy syntax or new features in 2.6 / 3.0. In contrast, the 3.x branch will use every one of those features that results in a nicer experience for the user. The test suite will be modified so that 2to3 will work upon it, and I'll maintain the same tests for both branches.


q:
I'm working with a webservice that offers almost duplicated code across two namesspaces.  Lets say for example PigFeet and HorseFeet, both namespaces contain a Feet class and other code that works with the Feet class requires it to be part of that same namespace.

Right now In my code I'm forced to do something like this:

if( _animalType == AnimalType.Pig )
{
     //namespace is pigfeet
     PigFeet.Feet feet = new Feet();
     feet.WashFeet();
}

if( _animalType == AnimalType.Horse )
{
     //namespace is horsefeet
     HorseFeet.Feet feet = new Feet();
     feet.WashFeet();
 }

This is leaving me with lots of duplicated code.  Is there a way to choose a namespace more dynamically?

[A]
In your namespace imports you can assign an
alias
to a specific namespace or member.
```
```
using PigFeet = PigFeet.Feet;
using HorseFeet = HorseFeet.Feet;

//now your sample code should look something like

if( _animalType == AnimalType.Pig )
{
     //namespace is pigfeet
     PigFeet feet = new PigFeet();
     feet.WashFeet();
}

if( _animalType == AnimalType.Horse )
{
     //namespace is horsefeet
     HorseFeet feet = new HorseFeet();
     feet.WashFeet();
 }
```
```


q:
I am writing a C# program which captures signals from a external device, and sends keystrokes to another application. I am using SendKeys and it works fine.

SendKeys does "press" a key by holding and releasing it immediately. I would like to make it push key and release it at will.

My question is : "is there a way to send a "push" signal to a key, then a "release" signal after a certain amount of time ?"

I am not sure SendKeys is able to do this. Any clue ?

[A]
I don't think it's possible from .NET directly
You could try using keybd_event native call by p/invoking the function as described here:
http://pinvoke.net/default.aspx/user32.keybd_event
The MSDN for keybd_event is here:
http://msdn.microsoft.com/en-us/library/ms646304(VS.85).aspx
Hope that helps!


q:
I've created a web page that lets you input some information and then draws an image in a canvas element based on that info.  I have it pretty much working the way I want except for the printing.

Is there a way to print out the canvas element or is creating a new window to draw in, the only way to do it?

Update:

The answer was so simple.  I was thinking of a lot more complicated solution.

I wish I could pick more than 1 answer.  I wasn't able to get the canvas to print when I used * to disable display.  The simplest solution was to just turn off the form that I was using for input, using form {display:none;} in the CSS inside an @media print{}. Thanks for the quick response.

    @media print {
           form {
         display:none;
       }
    }

[A]
I'm not 100% sure of the support, but you can use CSS and put an attribute in the
```
<link>
```
tag for
```
media="print"
```
. In this CSS file, just hide the elements you don't want to show while printing:
```
display:none;
```


q: I understand that they are both supposed to be small, but what are the key differences between the two?

[A]
Exokernel
is an
operating system from MIT
(and a class of it's variants) which handles relatively little hardware abstraction.  In exokernel, the low-level responsibilities of controlling hardware (particularly
memory allocation
) are often left in the hands of the developer.  Many developers would probably prefer to have the OS take more responsibility of such low-level tasks, because most developers are just writing applications.
An exokernel just
allocates physical hardware resources to programs
.  This allows the program to use library operating systems, which are linked in to provide some of the abstraction that the exokernel isn't providing.  The developer can then choose between abstraction models, or roll their own.  Given the application, this may have great performance benefits.  If you don't know what you're doing, you can also write programs that will explode when they crash.
Most kernels will do more to
abstract physical hardware
resources into some kind of
theoretical model
.  A developer interfaces with this model, which handles the finer points of dealing with hardware internally.
The term
nanokernel
is used to describe a specific
type of kernel
.  The prefix "pico-", or "nano-", "micro-" is usually denoting the "size" of the kernel..
Bigger kernels
are more built with more features, and
handle more hardware abstraction
.  Nanokernels are relatively small kernels which
provide hardware abstraction
, but
lack system services
.  Modern microkernels also lack system services, so the terms have become analogous.
The
names of kernels
usually stem from a specific batch of research which yielded a new kind of kernel, for example the kernel developed at at Carnegie Mellon called "Mach", which was one of the first examples of a modern "microkernel".
Sidenote:
The real benefit of exokernel is choice.  Most of the time, a lot of abstraction means fewer catastrophic bugs.  In some applications, you might want to use a different abstraction model, or you might want to handle everything yourself.  If we wanted to scrap the OS abstraction for a particular project, we'd have to cut out the operating system and commit a piece of hardware to the job.  In the case of exokernel, this isn't necessary.  We can program directly "to the metal", but also choose to link in an abstraction model whenever we like.  It's a very powerful concept.
Sidenote
: Dealing with memory on such a low level is unnecessary for most application developers.  There are usually several layers of operating system built on top of a kernel, and your application will run on the highest level of the OS.  When writing in javascript, you're higher up still, interfacing with a model implemented in an application which runs on an operating system, etc. etc.  Addressing memory, while it shouldn't be ignored, might mean something entirely different to a developer who is writing on such a high level of abstraction.


q:
I have a method that takes an IQueryable. Is there a LINQ query that will give me back the size of each column in the IQueryable?

To be more clear: this is Linq-to-objects.  I want to get the length of the ToString() of each "column".

[A]
It depends.  If you mean is there a completely generic way to make this determination the answer is no.  All IQueryable will give access to is the Type of each expression.  There is no way to arbitrarily map a Type to a column size.
If on the other hand you have the ability to map a Type to members and member type to a column size then yes there is a way to get the size.
```
```
public IEnumerable GetColumnSize(IQueryable source)
{
  var types = MapTypeToMembers(source).Select(x => x.Type);
  return types.Select(x => MapTypeToSize(x));
}
```
```


q:
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()

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


q:
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?

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


q:
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!".

[A]
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.


q: 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.

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


q:
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 {}

[A]
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
            }
        }
    }
}
```
```


q:
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.

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


q:
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?

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


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

[A]
```
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).


q:
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.

[A]
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.


q:
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

[A]
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 ;)


q:
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


q:
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.

[A]
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


q:
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?

[A]
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?


q:
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.

[A]
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]);
 }
?>
```
```


q:
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?

[A]
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.


q:
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.

[A]
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.


q:
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?

[A]
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


q:
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?

[A]
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.


q:
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?

[A]
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.


q: 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.

[A]
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


q:
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

[A]
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!


q:
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.

[A]
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.


q:
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.

[A]
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.


q:
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.

[A]
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


q:
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!

[A]
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.


q: 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.

[A]
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);
    }
}
```
```


q:
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

[A]
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


q:
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?

[A]
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.


q:
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?

[A]
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


q:
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?


q: 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.

[A]
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")


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

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


q:
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?

[A]
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"
/>
```
```


q:
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

[A] Lambdas & Extension methods are handled purely by the compiler and can be used with the .Net 2.0 framework.


q:
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?

[A]
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?)


q:
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?

[A]
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.


q:
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?

[A]
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.


q:
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.

[A]
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.


q:
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?"

[A]
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 :)


q:
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?

[A]
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.


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

[A]
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.


q:
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.

[A]
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.


q: 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.

[A]
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" />
```
```


q:
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.

[A]
```
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.


q: 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.

[A]
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.


q:
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.

[A]
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.


q:
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!

[A]
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.


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

[A]
```
```
// 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;
```
```


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

Is learning android a good option?

[A]
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
.


q: 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?

[A]
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!


q:
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.

[A]
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


q:
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')?

[A]
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 :)


q: 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?

[A]
Isn't just 15/16ths alright? Or even 15/16
ths
(
```
15/16<sup>ths</sup>
```
)?