q: What are some good solutions for handling automatic web based software updates for windows forms projects? I am aware of microsoft one-click, but am not interested in it at this time.

[A]
it really depends on how complex of an update process is needed.
I have had a few clients with simple needs where we created our own process setup that handled it, in about 3 hours of development we have a fully working solution that met all of their needs.


q:
How can I find out, which keyboard layout the user of my ruby application is using?
My aim is to have a game, where you can move the player on a map. To go one step down and one step left you press "Y" on a german keyboard. On an American keyboard, you would press "Z". We optimized the game for windows and mac, so I would like a solution for both platforms (and we don't use any command/shift/control-keys).

[A]
For Windows, you probably have to use the
Windows API GetKeyboardLayout()
, unless Ruby provides a wrapper for that.
There are a lot of
useful I18n resources for Windows on the MSDN web site
.
It might be easier to simply allow them to configure it themselves as a preference if you don't have a good portable way of detecting it.

s: huggingface

c: devops

d: intermediate


q:
How does one combine several resources for an application (images, sounds, scripts, xmls, etc.) into a single/multiple binary file so that they're protected from user's hands? What are the typical steps (organizing, loading, encryption, etc...)?

This is particularly common in game development, yet a lot of the game frameworks and engines out there don't provide an easy way to do this, nor describe a general approach. I've been meaning to learn how to do it, but I don't know where to begin. Could anyone point me in the right direction?

[A]
Short answer: yes.
In Mac OS 6,7,8 there was a substantial API devoted to this exact task. Lookup the "Resource Manager" if you are interested. Edit: So does the
ROOT
physics analysis package.
Not that I know of a good tool right now. What platform(s) do you want it to work on?
Edited to add: All of the two-or-three tools of this sort that I am away of share a similar struture:
The file starts with a header and index
There are a series of blocks some of which may have there own headers and indicies, some of which are leaves
Each leaf is a simple serialization of the data to be stored.
The whole file (or sometimes individual blocks) may be compressed.
Not terribly hard to implement your own, but I'd look for a good existing one that meets your needs first.


q:
I have a long form that the user has to fill out.

So I broke the form into logical units and created another user control for some elements (they will be reused elsewhere).

So say the form has these fields:

UserControl3.ascx

Username
password
email    -- usercontrol2.ascx
address    -- usercontrol2.ascx
city    -- usercontrol2.ascx
state    -- usercontrol2.ascx

So now in the codebehidn of usercontrol3.ascx, how will I access the usercontrol2.ascx's fields so I can write to the db?


q:
Let's have a list of some good interview questions for SharePoint developers. Please provide one question per entry, and if possible, the answers.

Also, please feel free to suggest corrections if the provided answers are wrong.

I will go first:

Q: How does SharePoint store pages?

A: How-to-locate-sharepoint-document-library-source-page-on-the-server?

[A]
Q: What is the difference between
```
System.Web.UI.WebControls.WebParts.WebPart
```
and
```
Microsoft.SharePoint.WebPartPages.WebPart
```
?
A:
```
Microsoft.SharePoint.WebPartPages.WebPart
```
is provided in MOSS 2007 to provide backwards compatability with MOSS 2003 webparts.  In MOSS 2007, it is recommended to use
```
System.Web.UI.WebControls.WebParts.WebPart
```
instead.


q:
Why does the C++ STL not provide any "tree" containers, and what's the best thing to use instead?

I want to store a hierarchy of objects as a tree, rather than use a tree as a performance enhancement...

[A]
In a way, std::map is a tree (it is required to have the same performance characteristics as a balanced binary tree) but it doesn't expose other tree functionality.  The likely reasoning behind not including a real tree data structure was probably just a matter of not including everything in the stl.  The stl can be looked as a framework to use in implementing your own algorithms and data structures.
In general, if there's a basic library functionality that you want, that's not in the stl, the fix is to look at
BOOST
.
Otherwise, there's a
bunch
of
libraries
out
there
, depending on the needs of your tree.


q:
I have an ASP page which will fetch records from a SQL server DB table. The table "order_master" has a field called order_date. I want to frame a select query to fetch order date > a date entered by user(ex : 07/01/2008)

I tried with convert and cast, but both are not working. The sample data in order_date column is 4/10/2008 8:27:41 PM. Actually, I dont know what type it is (varchar/datetime).

Is there any way to do that?

[A]
You could create a stored procedure like this
```
```
CREATE PROCEDURE GetOrders
    @OrderDate DATETIME
AS
SELECT
    *
FROM order_master
WHERE Order_Date > @OrderDate

GO
```
```
Then you can just convert the users input to a date before calling the stored procedure via your ASP code.
Edit
I just noticed the remark about the column type, you can run this command
```
```
sp_help order_master
```
```
to get column information to find the data type of order_date.


q:
Related Article

On a similar topic to the above article, but of a more specific note. How exactly do you handle items that are in the viewstate (so they are included on submit), but can also be changed via AJAX. For instance, say we had a dropdown list that was populated through an AJAX web service call (not an update panel). How can I get the page to validate once the dropdownlist's items have been changed?

[A]
why not validating onChange even in the dropdownlist?
just add the script manager and add that property to the onchange in the Page_Load event
```
' Creating the javascript function to validate
Dim js As String
js = "function validateDDL1(ddl) { alert(ddl.value); }"

' Adding onChange javascript method
DropDownList1.Attributes.Add("onchange", "validateDDL1(this);")

' Registering the javascript
ScriptManager.RegisterClientScriptBlock(Me, GetType(String), "validateDDL1(ddl)", js, True)
```


q:
I'm using the following syntax to loop through a list collection:

For Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors

    i = IndexOf(PropertyActor)
Next

How do I get the index of the current object within the loop? I'm using IndexOf(PropertyActor) but this seems inefficient as it searches the collection when I already have the object available!

[A]
just initialize an integer variable before entering the loop and iterate it...
```
```
Dim i as Integer
For Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors
    i++
Next
```
```


q:
I have SQL data that looks like this:

events
id name         capacity
1  Cooking        10
2  Swimming       20
3  Archery        15

registrants
id  name
1   Jimmy
2   Billy
3   Sally

registrant_event
registrant_id  event_id
     1             3
     2             3
     3             2

I would like to select all of the fields in 'events' as well as an additional field that is the number of people who are currently registered for that event.  In this case Archery would have 2 registrants, Swimming would have 1, and Cooking would have 0.

I imagine this could be accomplished in a single query but I'm not sure of the correct syntax. How would a query be written to get that data?

[A]
```
```
SELECT e.*, ISNULL(ec.TotalRegistrants, 0) FROM events e LEFT OUTER JOIN
(
   SELECT event_id, Count(registrant_id) AS TotalRegistrants
   FROM registrant_event
   GROUP BY event_id
) ec ON e.id  = ec.event_id
```
```


q:
I have code like this:

template <typename T, typename U> struct MyStruct {
    T aType;
    U anotherType;
};

class IWantToBeFriendsWithMyStruct
{
    friend struct MyStruct; //what is the correct syntax here ?
};

What is the correct syntax to give friendship to the template ?

[A]
```
```
class IWantToBeFriendsWithMyStruct
{
    template <typename T, typename U>
    friend struct MyStruct;
};
```
```
Works in VS2008, and allows MyStruct to access the class.


q: I've been looking for a simple regex for URLs, does anybody have one handy that works well?  I didn't find one with the zend framework validation classes and have seen several implementations.

[A]
I used this on a few projects, I don't believe I've run into issues, but I'm sure it's not exhaustive:
```
```
$text = preg_replace(
  '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i',
  "'$3$4'",
  $text
);
```
```
Most of the random junk at the end is to deal with situations like
```
http://domain.example.
```
in a sentence (to avoid matching the trailing period). I'm sure it could be cleaned up but since it worked. I've more or less just copied it over from project to project.


q:
In MySQL 5.0 why does the following error occur when trying to create a view with a subquery in the FROM clause?

ERROR 1349 (HY000): View's SELECT contains a subquery in the FROM clause

If this is a limitation of the MySQL engine, then why haven't they implemented this feature yet?

Also, what are some good workarounds for this limitation?

Are there any workarounds that work for any subquery in the FROM clause or are there some queries that can not be expressed without using a subquery in the FROM clause?

An example query (was buried in a comment):

SELECT temp.UserName
FROM (SELECT u1.name as UserName, COUNT(m1.UserFromId) as SentCount
      FROM Message m1, User u1
      WHERE u1.uid = m1.UserFromId
      Group BY u1.name HAVING SentCount > 3 ) as temp

[A]
It appears to be a known issue.
http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html
http://bugs.mysql.com/bug.php?id=16757
Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example
```
```
SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)
```
```
can be re-written as
```
```
SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID
```
```
or
```
```
SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)
```
```
can be
```
```
SELECT FOO.* FROM FOO
LEFT OUTER JOIN FOO2
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL
```
```


q:
I need to let end users specify a time range, to be stored and used internally as a starting date/time and ending date/time.  The range could be minutes or it could be days.

Has anyone discovered an interactive control that can handle this elegantly?

Most GUI toolkits have a calendar control, so I could specify "start" with a calendar for the day and a text field for the time...and the same for "end".

I could also replace the "end" controls with a single text field or slider that simply describes how many seconds/minutes/hours after start "end" is.

What I don't like about these ideas is how much clicking, typing, and more clicking is required to describe such a simple concept.  Also I have to slap the user's hand if a time is typed in that isn't recognizable as a time.

Is there a cleaner implementation that I'm overlooking?

[A]
There is no single answer, it depends on the context. For many places good text controls are enough. Of course such things can still help by supporting pasting and some increase/decrease actions. Maybe it can even do some validation for the value.
Then there are places that need something more. Calendar can be really helpful for entering dates and some kind of slider could be used for time. (Lotus Notes calendar has a slider.)
My advise is:
Think what you need. Don't put complicated widgets to a less used dialog.
If you need these nice helpful widgets, check if there are ready made in the library you are using and take some time to see how others have done these.
Always have the text controls with support for pasting.


q:
I'm working with logging in PHP with Pear, and I get into a standard problem: can I use file-based logging when the DB is not available? I don't mind if it's slow due to concurrency issues, but it cannot fail to work due to multiple, simultaneous hits.

I'm asking this question in general (for other web technologies) and specifically for Pear for PHP.

Thanks!

[A]
You can pass an existing database object into the
singleton method of Log
- if you don't have a database you can revert to alternative logging methods (or good old user_error())
```
```
require_once 'DB.php';
$db = &DB::connect('pgsql://jon@localhost+unix/logs');

$conf['db'] = $db;
$logger = &Log::singleton('sql', 'log_table', 'ident', $conf);
```
```


q:
Are modal windows/dialogs considered a good practice for websites?  One of the things that concerns me about using a modal window is that it is so much like a pop-up window and it could cause user frustration or cause users to simply close it because it's intrusive. Do you know of any studies that talk about user preferences and use rates?

Are there any accessibility issues beyond having the a modal window link load the content in a new page when JavaScript is turned off? Do you like sites or web apps that use modal windows? Why or why not? What are good and bad practices for implementing modal windows? I know modals are probably most often used when displaying pictures or galleries, but what are some other practical use cases? Do you use them on your site and what lead you to your decision?

[A]
From a practice standpoint - excluding accessibility - modal windows provide an alternative that are less startling as, say, dialog boxes and feel less intrusive than pop-up windows. They usually have a more cohesive feel to the site than either of the two aforementioned method. Aside from pictures or media, I've used modal dialogs to serve the same purpose as dialog boxes - to get the user to give some form of required input, or to acknowledge something before letting them interact with the site again.
From a purely accessible standpoint, they aren't so great. They typically require JavaScript, and, because of the way that modals are managed with respect to the DOM, screen readers will not interpret them well. To combat this, it's always a good idea to degrade gracefully - one suggestion is to take the content of the modal dialog and place it on a page. Whenever the modal dialog
should
appear, have the current page redirect to the 'modal page', get the user's input, and return to the page it was on.
Finally, as far as my personal opinions are concerned, I don't mind modal windows. I think that, when used correctly, they provide a decent experience - if something
has
to get my attention, then I'd rather it do so without redirecting me from the page, showing an ugly operating system themed dialog, or a pop-up (which my browser will likely block, anyway). I guess, to sum it up, if I had to choose
how
I'd like to be interrupted, then I'd choose a modal dialog.


q: How you can read a file (text or binary) from a batch file? There is a way to read it in a binary mode or text mode?

[A]
Under NT-style cmd.exe, you can loop through the lines of a text file with
```
```
FOR /F %%i IN (file.txt) DO @echo %%i
```
```
Type "help for" on the command prompt for more information. (don't know if that works in whatever "DOS" you are using)


q:
I've never used SOAP before and I'm sort of new to Python.  I'm doing this to get myself acquainted with both technologies.  I've installed SOAPlib and I've tried to read their Client documentation, but I don't understand it too well.  Is there anything else I can look into which is more suited for being a SOAP Client library for Python?

Edit: Just in case it helps, I'm using Python 2.6.

[A]
Could this help:
http://users.skynet.be/pascalbotte/rcx-ws-doc/python.htm#SOAPPY
I found it by searching for
```
wsdl
```
and
```
python
```
, with the rational being, that you would need a wsdl description of a SOAP server to do any useful client wrappers....


q:
Is there any way to manually create fold points in code in Eclipse? I know how to enable folding and how to set the auto preferences, but i like being able to set my own fold points so I can ignore certain parts of my code. Think regions in VS.

 I know there is in VS and NetBeans, but I cannot find a way to set manual fold  points in Eclipse.

[A]
I don't think Eclipse has built in manual folding, but I did use a previous version of the following plugin for it.
Per the comment: The plugin has been recompiled for Eclipse 3.5 and is available at
the Apache Isis site
. A
direct download link
is also available. It also appears to work for Eclipse 3.6.


q:
How would I get the length of an ArrayList using a JSF EL expression?

#{MyBean.somelist.length}

does not work.

[A]
Yes, since some genius in the Java API creation committee decided that, even though certain classes have
```
size()
```
members or
```
length
```
attributes, they won't implement
```
getSize()
```
or
```
getLength()
```
which JSF and most other standards require, you can't do what you want.
There's a couple ways to do this.
One: add a function to your Bean that returns the length:
```
In class MyBean:
public int getSomelistLength() { return this.somelist.length; }

In your JSF page:
#{MyBean.somelistLength}
```
Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function
```
In JSF page:
#{ fn:length(MyBean.somelist) }
```


q:
Microsoft like implementing their own versions of popular open-source frameworks and assemblies, for example:

Microsoft's MVC Framework vs MonoRail

Microsoft's Unity IoC container vs Castle Windsor / Spring.net / Ninject etc

Microsoft's VS Unit Test framework vs nUnit (and various others)

Questions:

What else has Microsoft 'borrowed'?

Which are better in each situation and why?

What are people's attitudes towards the official Microsoft stuff vs the ALT.NET versions?

What do you think is next to be taken under the Redmond wing?

EDIT
Ok, instead of which is 'better', which do you prefer to use as a developer?

[A]
In the case of Unit Testing I've heard the answer from a Microsoft official. In fact, if I recall correctly, Microsoft's feature is even based on the NUnit code base.
The reason for copying this particular OpenSource product (and others, I've been told) is that customers want this. At first, this might seem like a cheap pretext but I can actually imagine some corporate customers who prefer it this way. Additionally, the Microsoft employee claimed that it's easier for Microsoft to provide customer support if they implemented the program themselves because they can take an extended responsability for the source. If that's true, OpenSource adoption has a long way to go. :-(


q: I need a way to determine whether the computer running my program is joined to any domain. It doesn't matter what specific domain it is part of, just whether it is connected to anything. I'm coding in vc++ against the Win32 API.

[A]
what about from the name of the computer?
edit:
this was a crapy 'answer' from way back. What I meant was cheching for the form
```
domain\name
```
in the computer name. That of course implies that you do know the name of the domain, it does not solves the issue of just knowing if the computer is in any domain.


q: I want subversion to commit a file even if it's unchanged.  Is there a way to do this?

[A]
I don't think that's possible, but first of all why do you need to do that? If a file is unchanged it shouldn't be commited.
If you really want that file grouped with other files in a commit you could change something minor inside (add a space for example).


q:
i have a class with a static public property called "Info".
via reflection i want to get this properties value, so i call:

PropertyInfo pi myType.GetProperty("Info");
string info = (string) pi.GetValue(null, null);

this works fine as long as the property is of type string. but actually my property is of type IPluginInfo and a PluginInfo type (implementing IPluginInfo) is instatiated and returned in the Info properties get accessor, like this:

public static IPluginInfo PluginInfo
{
    get
    {
        IPluginInfo Info = new PluginInfo();
        Info.Name = "PluginName";
        Info.Version = "PluginVersion";
        return Info;
    }
}

like this when i call:

IPluginInfo info = pi.GetValue(null, null) as IPluginInfo;

info is always null, whiel PropertyInfo pi is still valid. am i missing something obvious here?

[A]
Could you create a short but complete program that demonstrates the problem?
Given that you're talking about plugins, my
guess
is that you've got the problem of having IPluginInfo defined in two different assemblies. See if
this article
helps at all.
The easiest way to verify it is to call
```
pi.GetValue
```
and store the result in an
```
object
```
variable first, then do the cast or "as" in another line. That way you can break the debugger and look at the return value before it's lost.


q:
I've successfully used the Windows SendMessage method to help me do various things in my text editor, but each time I am just copying and pasting code suggested by others, and I don't really know what it means.  There is always a cryptic message number that is a parameter.  How do I know what these code numbers mean so that I can actually understand what is happening and (hopefully) be a little more self-sufficient in the future?  Thanks.

Recent example:

using System.Runtime.InteropServices;

[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg,UIntPtr wParam, IntPtr lParam);

SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));

[A]
This is the windows message code.
They are defined in the header files, and generally available translated as an include of some sort with different languages.
example:
WM_MOUSEMOVE = &H200
MK_CONTROL = &H8
MK_LBUTTON = &H1
MK_MBUTTON = &H10
MK_RBUTTON = &H2
MK_SHIFT = &H4
MK_XBUTTON1 = &H20
MK_XBUTTON2 = &H40
see
http://msdn.microsoft.com/en-us/library/ms644927(VS.85).aspx#windows_messages
.


q:
i know this is an age old question, but this is my scenario

This is in C# 2.0

Have a windows application which has a datagridview control. This needs to be populates by making a webservice call.

I want to achive the same functionality on the data if i were to use a direct connection and if i were using datasets, namely like paging and applying filters to returned data. i know returning datasets is a bad idea and am looking to find a good solution.

[A]
I might look at
ADO.NET Data Services
, aka Astoria, in VS2008 SP1.
This allows you to expose data over a web-service (WCF exposing ATOM, IIRC) - but you don't need to know all these details: the tooling worries about that for you: you just get regular IQueryable<T> sources on a data-context (not quite the same as the LINQ-to-SQL data-context, but same concept).
The good thing here is that a LINQ query (such as filtering (Where), paging (Skip/Take) etc) can get composed
all
the way from the client,
through
the web-service, and down to the LINQ-enabled data store (LINQ-to-SQL or Entity Framework, etc). So only the right data comes over the wire: if you ask for the first 10 rows (of 20000) ordered by Name, then that is what you get: 10 rows out of the database; 10 rows over the wire, no messing.


q: How do you programmatically eject(safely remove) an USB mass storage device in Windows (XP)?

[A]
You could spawn a process and use a
command line tool
. This would also work from other languages such as java where calling the Win32 api is harder.


q:
I am declaring an array of void pointers. Each of which points to a value of arbitary   type.

   void  **values;     // Array of void pointers to each value of arbitary type

Initializing values as follows:

    values = (void**)calloc(3,sizeof(void*));
    //can initialize values as: values = new void* [3];
    int ival = 1;
    float fval = 2.0;
    char* str = "word";
    values[0] = (void*)new int(ival);
    values[1] = (void*)new float(fval);
    values[2] = (void*)str;

    //Trying to Clear the memory allocated
    free(*values);
    //Error: *** glibc detected *** simpleSQL: free(): invalid pointer: 0x080611b4
    //Core dumped
    delete[] values*;
    //warning: deleting 'void*' is undefined
    //Similar Error.

Now how do I free/delete the memory allocated for values ( the array of void pointers)?

[A]
You'd have to keep track of how many void* were originally calloc'd, and iterate over them, free-ing each one, then free the original values variable.
darn formatting... (the preview is working fine).
```
```
int ct = 3;
values = (void*)calloc(ct,sizeof(void));
//can initialize values as: values = new void* [3];
int ival = 1;
float fval = 2.0;
char* str = "word";
values[0] = (void*)new int(ival);
values[1] = (void*)new float(fval);
values[2] = (void*)str;

for ( int i = 0; i < ct; i++ ) [
    delete( values[i] );
}
free( values );
```
```


q:
I need to implement some kind of metric space search in Postgres(*) (PL or PL/Python). So, I'm looking for good sources (or papers) with a very clear and crisp explanation of the machinery behind these ideas, in such way that I can implement it myself.

I would prefer clarity over efficiency.

(*) The need for that is described better here.

[A]
Especially for geographical data, look at
PostGIS
first to see if you need to implement anything. If you do, start with the papers listed in the
Wikipedia entry on GiST
.
Looking at your link, it seems your metric space is strings with some sort of edit distance as the metric. A nice but oldish overview of some solutions is given by
Navarro, Baeza-Yates, Sutinen, and Tarhio, IEEE Data Engineering Bulletin, 2001
; the related papers on Citeseer could also be useful.
Locality Sensitive Hashing
is a newer technique that might be useful, but a lot of the papers are heavy on math.


q:
I'm trying to traverse through all the subdirectories of the current directory in Perl, and get data from those files. I'm using grep to get a list of all files and folders in the given directory, but I don't know which of the values returned is a folder name and which is a file with no file extention.

How can I tell the difference?

[A]
```
```
print "$file is a directory\n" if ( -d $file );
```
```


q:
How would I go about writing my own scrollbar using standard Java 2D.

I really don't want to use swing, and I've already made up my own component parts for everything else such as buttons etc.

I'm not really looking for code, rather the math involved in the event changes and the drawing.

[A]
Why on earth would you want to write your own java GUI toolkit? You already have the choice of Swing and SWT, can you really do better than these two teams?
If you've already written the rest of the toolkit, I don't understand why the scrollbar would stump you. Without knowing anything about your event system, or how your custom components are structured, it's impossible to give much advise. I don't see this being particularly maths intensive - just maintain the height of the scrollable component, and the view it's in, and the scrollbar size should match the proportion of the component that is visible. The position of the scrollbar should match which part of the component is visible (this will have to be scaled). Specifically, what do you want to know?


q:
i want to call a series of .sql scripts to create the initial database structure

script1.sql

script2.sql
etc.

is there any way of doing this without sqlcmd or stored procedures or any other kind of code that is not sql ?
just inside a .sql file.

[A]
Sure.  Just create a little app that pulls in all the .sql files you want and executes them.  Do it in VB.NET as follows:
```
```
Sub ExecuteSqlScript(FilePath As String)

    Dim Script As String
    Dim FileNumber As Integer
    Dim Delimiter As String
    Dim aSubscript() As String
    Dim Subscript As String
    Dim i As Long

    Delimiter = ";"
    FileNumber = FreeFile
    Script = String(FileLen(FilePath), vbNullChar)

    ' Grab the scripts inside the file
    Open FilePath For Binary As #FileNumber
    Get #FileNumber, , Script
    Close #FileNumber

    ' Put the scripts into an array
    aSubscript = Split(Script, Delimiter)

    ' Run each script in the array
    For i = 0 To UBound(aSubscript) - 1
        aSubscript(i) = Trim(aSubscript(i))
        Subscript = aSubscript(i)
        CurrentProject.Connection.Execute Subscript

    Next i

End Sub
```
```
Example from:
http://snipplr.com/view/3879/run-sql-script-from-external-file/


q:
Can someone tell me what the statuses mean in SQL Server's sp_who command?  Why might a spid be suspended?  What does it mean to be "runnable"?

Thanks!

[A]
Pretty easy to find answer online.
Link
dormant.
SQL Server is resetting the session.
running.
The session is running one or more batches. When Multiple Active Result Sets (MARS) is enabled, a session can run multiple batches. For more information, see Using Multiple Active Result Sets (MARS).
background.
The session is running a background task, such as deadlock detection.
rollback.
The session has a transaction rollback in process.
pending.
The session is waiting for a worker thread to become available.
runnable.
The session's task is in the runnable queue of a scheduler while waiting to get a time quantum.
spinloop.
The session's task is waiting for a spinlock to become free.
suspended.
The session is waiting for an event, such as I/O, to complete.


q:
Are there any classes in the .NET framework I can use to throw an event if time has caught up with a specified DateTime object?

If there isn't, what are the best practices when checking this? Create a new thread constantly checking? A timer (heaven forbid ;) )?

[A]
When a thread is sleeping it consumes no CPU usage. A very simple way would be to have a thread which sleeps until the DateTime. For example
```
```
DateTime future = DateTime.Now.Add(TimeSpan.FromSeconds(30));
        new Thread(() =>
        {
            Thread.Sleep(future - DateTime.Now);
            //RaiseEvent();
        }).Start();
```
```
This basically says, get a date in the future (thirty seconds from now). Then create a thread which will sleep for the difference of the times. Then raise your event.
Edit: Adding some more info about timers. There is nothing wrong with timers, but I think it might be more work. You could have a timer with an interval of the difference between the times. This will cause the tick event to fire when the time has caught up to the date time object.
An alternative, which I would not recommend, and I seem to think you have though of this, is to have a timer go off every five seconds and check to see if the times match. I would avoid that approach and stick with having the thread sleep until there is work to be done.


q: What are the best online code beautifier and formatter out there? I'm not asking for highlighters. Any language will do.

[A]
What language??  There are different tools for almost every imaginable programming language, since they all have different syntactic rules and conventions.
Good ol'
```
indent
```
is a nice, customizable, command-line utility to format C and C++ programs.


q:
I am trying to use a class from a C# assembly in vb.net. The class has ambiguous members because vb.net is case insensitive. The class is something like this:

public class Foo {

  public enum FORMAT {ONE, TWO, THREE};

  public FORMAT Format {
    get {...}
    set {...}
   }
}

I try to access the enum: Foo.FORMAT.ONE

This is not possible because there is also a property named 'format'.

I can not change the C# assembly. How can I get around this and reference the enum from vb.net?

[A]
I don't think you can get around this. Get in touch with the author of the C# component you are trying to use and convince them to fix their code.
Incidentally, this is the primary reason behind the
```
CLSCompliant(true)
```
attribute, which if you are writing APIs or other code that has a high probability of being used by other languages you should always set. It would have flagged this issue for the original author to be aware of and fix correctly.


q:
Need a refresher on bits/bytes, hex notation and how it relates to programming (C# preferred).

Looking for a good reading list (online preferably).

[A]
A bit is either 1 or 0.
A byte is 8 bits.
Each character in hex is 4 bits represented as 0-F
0000 is 0
0001 is 1
0010 is 2
0011 is 3
...
1110 is E
1111 is F
There's a pretty good intro to C#'s bit-munching operations
here


q:
trying to get a side project hobby going to keep me motivated from my 9-5 job on C# and was looking at Boo. some ?'s

what has your experience being with Boo?

what kind of apps/projects have you done with Boo or

what is Boo capable of?

Guess being the web world, would like to get my hands dirty with desktop applications etc.

[A]
While it only uses Boo as the implementation language (rather than being fundamentally
about
Boo), have you read Ayende's "
Building Domain Specific Languages in Boo
"? It's not fully published yet, but you can get an early access edition.
I haven't had time to look carefully at Boo yet, but the
main
advantages over C# 3 (which gained some of Boo's features) appear to be terseness (lots of type inference) and metaprogramming.


q:
Lets say I've got two interchangeable pieces of code and I want to figure out which one of them takes less processor time to execute. How would I do this?

To get a very rough estimation I could just put NSLog() calls on either side of the code I wanted to profile, but it seems like the processor being otherwise very busy could skew the results.

[A]
Unless one of these two pieces of code is already in your app,
and
you've already profiled your app's overall performance to determine that the existing code is a major bottleneck, then what you're doing is called "premature optimization."
Xcode includes an excellent
profiler
tool called "
Shark
." For some versions, it's found in /Developer/Applications; for others, it's in a "Performance Tools" subdirectory.
Shark will tell you exactly how much time, as a percentage of overall execution time, your app is spending in each part of your code. The idea of using a tool like Shark is to follow the "80/20 rule" - your app will spend 80% of its time running 20% of its code, so for the best results you should spend 80% of
your
time optimizing that same 20%.
So, to answer your question directly, assuming that you
have
run Shark, and you're looking to optimize the topmost bottleneck, simply replace it with your optimized code and run your app under Shark again. Then, compare the percentage of the overall time being spent in the replacement code to that of the original.


q:
This is happening on Vista.
I created a new dialog based MFC project to test this. I added a CEdit control to my dialog. I called SetLimitText to let my CEdit receive 100000 characters. I tried both:

this->m_cedit1.SetLimitText(100000);
UpdateData(FALSE);

and

static_cast<CEdit*>(GetDlgItem(IDC_EDIT1))->LimitText(100000);

I placed these calls on InitDialog.

after I paste 5461 characters into my CEdit, it becomes empty and unresponsive. Any ideas as to what is causing this and workarounds to be able to paste long strings of text in a CEdit or any other control?

note: 5461 is 0x1555 or 1010101010101 in binary, which i find quite odd.

if I paste 5460 characters I have no problems.

[A]
I contacted microsof support.
The goal was to have approximately
 240000 characters in one single
 editable line of text.
I am able to reproduce the issue on
 Windows Vista (x64 and x32 both) but
not
on Windows XP.
this code works fine in XP:
```
```
BOOL ClongeditXPDlg::OnInitDialog()
 {
     CDialog::OnInitDialog();

     // Set the icon for this dialog.  The framework does this automatically
     //  when the application's main window is not a dialog
     SetIcon(m_hIcon, TRUE);            // Set big icon
     SetIcon(m_hIcon, FALSE);        // Set small icon

     // TODO: Add extra initialization here
     UINT limit = m_longEdit.GetLimitText();
     m_longEdit.SetLimitText(240000);
     UINT limit2 = m_longEdit.GetLimitText();

     CString str;
     str = _T("");
     for(int i = 0; i < 250000; i++)
         str += _T("a");

     m_longEdit.SetWindowText(str);

     return TRUE;  // return TRUE  unless you set the focus to a control
 }
```
```
If I use a CRichEdit control instead,
 when I press "end" key or "right
 arrow" key after pasting a long string
 inside, i cannot see all the
 characters in the Rich Edit Control.
 trying to scroll past the last visible
 character produces a beep. The rest of
 the characters are there, I know this
 because if i double-click the Rich
 Edit  Control and copy the text using
 ctrl-c and then paste it on  a text
 editor, I can see the 240000
 characters. So the control  is holding
 the right amount of characters, but
 the last  characters are not viewable
 except in an external editor, so  my
 original problem remains.
Here are the answers by microsoft
 representatives:
Problem here is that an edit control
  with a large number of  characters in
  it does not paint its text.
I tried setting different characters,
  and discovered that I  could fit more
  'l's than 'x's than 'm's. The issue
  isn't  directly the number of
  characters, but is likely the number
  of pixels.  Multiplying the number of
  visible characters by  the pixel width
  of the characters in the selected font
  shows  that the limit is about 32k
  pixels.
another answer from microsoft:
I did extensive research on this issue
  and would like to update you about the
  case progress.
The primary difference between the
  Edit control on Vista and on XP is
  that the Edit control on Vista
  pre-composes its glyphs for better
  international support (internally, it
  ends up calling ExtTextOut with
  ETO_GLYPH_INDEX and an array of glyphs
  rather than a string of characters.
  This ends up saving the glyph indices
  into a metafile and so runs into the
  32k pixel limit. When too many
  characters are provided, ExtTextOut
  fails and draws nothing.  The Edit
  control on XP doesn't precompose the
  glyphs and so doesn't have this
  problem, but won't handle
  international characters as well.
The edit control on XP will clip at
  32k, but since that is offscreen it
  isn't obvious.  When scrolling to the
  right, it starts with the first
  visible character so the visible part
  of the control is always earlier than
  32k pixels.
The RichEdit control draws the
  beginning, but after hitting End,
  edits occur mostly offscreen.
  RichEdit 3.0 and 4.1 gives similar
  behavior.  This appears to be the 32k
  pixel limit of RichEdit control, as
  the it draws its text on an offscreen
  bitmap before displaying it to the
  screen.
Considering these points, the behavior
  is by design. You would need to create
  your own control to get the behavior
  of displaying as big string as 240000
  in a single line.
and the last one:
I did further research on this issue
  for finding any light weight
  workaround for overcoming 32k pixels
  limit, but unfortunately it seems that
  there is no workaround for this.
Couple of alternatives that we tried
  are RichEdit 3.0,  RichEdit
  4.1, using UniScribe, using different fonts etc., but none of them seems to
  suffice your requirement.
Possibly, you would need to create
  your own custom control if you wish to
  display an editable single-line string
  which exceeds 32k pixel limit in
  Windows Vista.


q:
I'm trying to see if the user has pressed a decimal separator in a text box, and either allow or suppress it depending on other parameters.

The NumberdecimalSeparator returns as 46, or '.' on my US system. Many other countries use ',' as the separator. The KeyDown event sets the KeyValue to 190 when I press the period.

Do I just continue to look for commas/periods, or is there a better way?

[A]
The call
```
```
CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
```
```
gets the decimal separator for the current user interface culture. You can use other cultures to get the separator for other languages.
EDIT
From the 166 cultures that are reported in my system (
```
CultureInfo.GetCultures(CultureTypes.SpecificCultures).Count()
```
), it seems that only two separators are used: period and comma. You can try this in your system:
```
```
var seps = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
            .Select(ci => ci.NumberFormat.NumberDecimalSeparator)
            .Distinct()
            .ToList();
```
```
Assuming that this is true, this method may be helpful (note that the
```
keyCode
```
is OR'ed with the
```
modifiers
```
flag in order to eliminate invalid combinations):
```
```
private bool IsDecimalSeparator(Keys keyCode, Keys modifiers)
    {
        Keys fullKeyCode = keyCode | modifiers;
        if (fullKeyCode.Equals(Keys.Decimal))          // value=110
            return true;

        string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
        if (uiSep.Equals("."))
            return fullKeyCode.Equals(Keys.OemPeriod); // value=190
        else if (uiSep.Equals(","))
            return fullKeyCode.Equals(Keys.Oemcomma);  // value=188
        throw new ApplicationException(string.Format("Unknown separator found {0}", uiSep));
    }
```
```
A last note: According to
Keys enumeration
, the value 46 that you mention corresponds to the DEL (Delete) key (i.e. the point when Num Lock is OFF).


q:
How can I setup a default value to a property defined as follow:

public int MyProperty { get; set; }

That is using "prop" [tab][tab] in VS2008 (code snippet).

Is it possible without falling back in the "old way"?:

private int myProperty = 0; // default value
public int MyProperty
{
    get { return myProperty; }
    set { myProperty = value; }
}

Thanks for your time.
Best regards.

[A]
Just set the "default" value within your constructor.
```
```
public class Person
{
   public Person()
   {
       this.FirstName = string.Empty;
   }

   public string FirstName { get; set; }
}
```
```
Also, they're called Automatic Properties.


q: I'm working on moving from using tables for layout purposes to using divs (yes, yes the great debate).  I've got 3 divs, a header, content and footer.  The header and footer are 50px each.  How do I get the footer div to stay at the bottom of the page, and the content div to fill the space in between?  I don't want to hard code the content divs height because the screen resolution can change.

[A]
if you are trying to maximize the height of your content div, in the CSS add
height: 100%;


q:
I have a menu that I am using and it will change the background color when I hover using a:hover but I want to know how to change the class=line so that it sticks.

So from the home if they click contacts the home pages

from (a href="#" class="clr") to (a href="#")

and Contacts would change

from (a href="#") to (a href="#" class="clr")

any help?

JD

[A]
The way to change class (I assume you're talking of the DOM), in javascript is:
```
```
document.getElementById("element").className='myClass';
```
```
Hope this helps.


q:
How can I replace multiple spaces in a string with only one space in C#?

Example:

1 2 3  4    5

would be:

1 2 3 4 5

[A]
```
```
string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
```
```


q:
The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from the_base_class.

class the_base_class:
    somedata = {}
    somedata['was_false_in_base'] = False

class subclassthing(the_base_class):
    def __init__(self):
            print self.somedata

first = subclassthing()
{'was_false_in_base': False}
first.somedata['was_false_in_base'] = True
second = subclassthing()
{'was_false_in_base': True}
>>> del first
>>> del second
>>> third = subclassthing()
{'was_false_in_base': True}

Defining self.somedata in the __init__ function is obviously the correct way to get around this (so each class has it's own somedata dict) - but when is such behavior desirable?

[A]
You are right,
```
somedata
```
is shared between all instances of the class and it's subclasses, because it is created at class
definition
time. The lines
```
```
somedata = {}
somedata['was_false_in_base'] = False
```
```
are executed when the class is defined, i.e. when the interpreter encounters the
```
class
```
statement -
not
when the instance is created (think static initializer blocks in Java). If an attribute does not exist in a class instance, the class object is checked for the attribute.
At class definition time, you can run arbritrary code, like this:
```
```
import sys
 class Test(object):
     if sys.platform == "linux2":
         def hello(self):
              print "Hello Linux"
     else:
         def hello(self):
              print "Hello ~Linux"
```
```
On a Linux system,
```
Test().hello()
```
will print
```
Hello Linux
```
, on all other systems the other string will be printed.
In constrast, objects in
```
__init__
```
are created at
instantiation
time and belong to the instance only (when they are assigned to
```
self
```
):
```
```
class Test(object):
    def __init__(self):
        self.inst_var = [1, 2, 3]
```
```
Objects defined on a class object rather than instance can be useful in many cases. For instance, you might want to cache instances of your class, so that instances with the same member values can be shared (assuming they are supposed to be immutable):
```
```
class SomeClass(object):
    __instances__ = {}

    def __new__(cls, v1, v2, v3):
        try:
            return cls.__insts__[(v1, v2, v3)]
        except KeyError:
            return cls.__insts__.setdefault(
               (v1, v2, v3),
               object.__new__(cls, v1, v2, v3))
```
```
Mostly, I use data in class bodies in conjunction with metaclasses or generic factory methods.


q:
I need a SQL query that returns ContactDate, SortName, City, ContactType, and Summary from the tables below. If any value is null, I need it to return the text “No Entry”.

ContactTable

ContactID

ContactDate

UserID

Summary

ContactType

SortName

UserTable

UserID

FirstName

LastName

AddressID

AddressTable

AddressID

City

Street

State

Zip

[A]
```
```
SELECT COALESCE(CAST(CONVERT(VARCHAR(10), ContactTable.ContactDate, 101) AS VARCHAR(10)), 'No Entry') AS ContactDate,
       COALESCE(ContactTable.SortName, 'No Entry') AS SortName,
       COALESCE(AddressTable.City, 'No Entry') AS City,
       COALESCE(ContactTable.ContactType, 'No Entry') AS ContactType
FROM ContactTable
LEFT OUTER JOIN UserTable ON ContactTable.UserID = UserTable.UserID
LEFT OUTER JOIN AddressTable ON UserTable.AddressID = AddressTable.AddressID
```
```
Here
is a chart of SQL DateTime formats for the CONVERT statement above.


q:
Occasionally my MS Access reports:

The search key was not found in any record

After this happens the solution is to close Access, compact and
repair the backend and then delete the record.

What causes this and how can I avoid it?

[A]
You do not mention the version of Access that you are using. Microsoft reports a bug in 2000:
BUG: You receive a "The search key was not found in any record" error message when you compact a database or save design changes in Access 2000
http://support.microsoft.com/kb/301474
If this is not your problem, here is a pretty comprehensive FAQ by Tony Toews, Microsoft Access MVP:
Corrupt Microsoft Access MDBs FAQ
http://www.granite.ab.ca/access/corruptmdbs.htm
If the problem is constantly occuring, you need to find the reason for the corruption of your table, and you will find a number of suggestions for tracking the cause in the site link above.


q:
I have a couple tables in which I created an object ID as either an Int or Bigint, and in both cases, they seem to autoincrement by 10 (ie, the first insert is object ID 1, the second is object ID 11, the third is object ID 21, etc).  Two questions:

Why does it do that?

Is that a problem?

[A]
Check to see the seed value of the autoincrement isn't set to 10.
You can check by:
```
```
SELECT Auto_increment FROM information_schema.tables WHERE table_name='the_table_you_want';
```
```
As noted elsewhere you can change by using the system variable @@set_auto_increment_increment
```
```
SET @@auto_increment_increment=1;
```
```
If you want to start the values at a number other than one you can go:
```
```
ALTER TABLE tbl AUTO_INCREMENT = 100;
```
```


q:
In a previous question, I learned how to keep a footer div at the bottom of the page. (see other question)

Now I'm trying to vertically center content between the header and footer divs.

so what I've got is:

#divHeader
{
    height: 50px;
}

#divContent
{
    position:absolute;
}

#divFooter
{
    height: 50px;
    position:absolute;
    bottom:0;
    width:100%;
}
<div id="divHeader">
    Header
</div>
<div id="divContent">
    Content
</div>
<div id="divFooter">
    Footer
</div>

I've tried creating a parent div to house the existing 3 divs and giving that div a vertical-align:middle; but that gets me nowhere.

[A]
You need to either set the
```
height
```
of the div to fill the whole content area or its coordinates have to be in the center. Something like
```
top:50%; left:50%
```
but of course that will make the div a bit off to the bottom-right.


q:
I have a JavaScript resource that has the possibility of being edited at any time. Once it is edited I would want it to be propagated to the user's browser relatively quickly (like maybe 15 minutes or so), however, the frequency of this resource being editing is few and far between (maybe 2 a month).

I'd rather the resource to be cached in the browser, since it will be retrieved frequently, but I'd also like the cache to get reset on the browser at a semi-regular interval.

I know I can pass a no-cache header when I request for the resource, but I was wondering when the cache would automatically reset itself on the browser if I did not pass no-cache.

I imagine this would be independent for each browser, but I'm not sure.

I tried to Google this, but most of the hits I found were about clearing the browser's cache... which isn't what I'm looking for.

[A]
Put a version on your javascript code like this that is updated when you make a change
```
```
<script src="/code.js?ver=123" type="text/javascript"></script>
```
```
They will then always get new version.


q: When I dump a Sybase database, it doesn't seem to matter whether there's data in the tables or not, the file size is the same. I've been told that this is down to the fact that my dump file is binary and not logical, so the file of the dump file is based on the allocated size of the database. I know that Oracle can use logical dump files, but can I get Sybase to do the something similar, or is there any other sneaky ways of getting the dump file size down?

[A]
Since somewhere around version 12 you have been able to perform compressed dumps in ASE.
The syntax is:
dump database database_name to file_name [ with compression=compress_level]
compress_level is 0-9. 0 is no compression and 9 is the most. The more you compress the higher the CPU usage whilst running the dump. You just need to peform a little testing to find an appropriate balance of size versus performance.
No special commands are needed to load the dump.


q:
Since I've started to use jQuery, I have been doing a lot more JavaScript development.

I have the need to parse different date formats and then to display them into another format.

Do you know of any good tool to do this?

Which one would you recommend?

[A]
2014 update:
Moment.js
is an excellent date manipulation library, which includes parsing functions. It doesn't include automatic date format detection, but you can
specify multiple parsing patterns
.
Do you know the format of the dates before hand though, or are they user input?
A deprecated library for parsing dates is Datejs
. It hasn't been updated since 2007.


q: In vi[m] there is the ! command which lets me pipe text through a shell command -- like sort or indent -- and get the filtered text back into the buffer. Is there an equivalent in emacs?

[A]
Late edit
: As much as I appreciate the upvotes, Jurta's answer is the way to go. And Greg's hack is neater than mine.
I'll leave the rest of this here because it might be worth something, but...
```
M-x shell-command-on-region
```
, which appears to be bound to
```
M-|
```
by default.
I see that this does not do exactly what Rohit asked for. Using
```
C-h f shell-command-on-region
```
reveals that the desired behavior is available in the non-interactive version of the command (by setting the argument
```
replace
```
to non-nil). We should be able to write a wrapper to do this.
Try this (load it into
```
*scratch*
```
and run
```
M-x eval-buffer
```
, if it works, copy it to your .emacs file):
```
```
(defun shell-command-on-region-replace (start end command)
  "Run shell-command-on-region interactivly replacing the region in place"
  (interactive (let (string)
         (unless (mark)
           (error "The mark is not set now, so there is no region"))
         ;; Do this before calling region-beginning
         ;; and region-end, in case subprocess output
         ;; relocates them while we are in the minibuffer.
         ;; call-interactively recognizes region-beginning and
         ;; region-end specially, leaving them in the history.
         (setq string (read-from-minibuffer "Shell command on region: "
                            nil nil nil
                            'shell-command-history))
         (list (region-beginning) (region-end)
               string)))
  (shell-command-on-region start end command t t)
  )
```
```
And note as I say in the comments that this is not a very emacsy thing to do. But I think it works.
For any readers who don't know how to select a region:
Move the "point" (current cursor position) to one end of the region, and use
```
C-space
```
to activate the "mark"
Move the point to the other end of the region
Your done, invoke the command


q:
I would like to either prevent or handle a StackOverflowException that I am getting from a call to the XslCompiledTransform.Transform method within an Xsl Editor I am writing. The problem seems to be that the user can write an Xsl script that is infinitely recursive, and it just blows up on the call to the Transform method.  (That is, the problem is not just the typical programmatic error, which is usually the cause of such an exception.)

Is there a way to detect and/or limit how many recursions are allowed?  Or any other ideas to keep this code from just blowing up on me?

[A]
From Microsoft:
Starting with the .NET Framework
  version 2.0, a StackOverflowException
  object cannot be caught by a try-catch
  block and the corresponding process is
  terminated by default. Consequently,
  users are advised to write their code
  to detect and prevent a stack
  overflow. For example, if your
  application depends on recursion, use
  a counter or a state condition to
  terminate the recursive loop.
I'm assuming the exception is happening within an internal .NET method, and not in your code.
You can do a couple things.
Write code that checks the xsl for infinite recursion and notifies the user prior to applying a transform (Ugh).
Load the XslTransform code into a separate process (Hacky, but less work).
You can use the Process class to load the assembly that will apply the transform into a separate process, and alert the user of the failure if it dies, without killing your main app.
EDIT: I just tested, here is how to do it:
MainProcess:
```
```
// This is just an example, obviously you'll want to pass args to this.
Process p1 = new Process();
p1.StartInfo.FileName = "ApplyTransform.exe";
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

p1.Start();
p1.WaitForExit();

if (p1.ExitCode == 1)
   Console.WriteLine("StackOverflow was thrown");
```
```
ApplyTransform Process:
```
```
class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        throw new StackOverflowException();
    }

    // We trap this, we can't save the process,
    // but we can prevent the "ILLEGAL OPERATION" window
    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        if (e.IsTerminating)
        {
            Environment.Exit(1);
        }
    }
}
```
```


q: Im curious what the exact meaning of "committed" memory is when the value is queried from the MemoryUsage class.  That class explains it as "committed represents the amount of memory (in bytes) that is guaranteed to be available for use by the Java virtual machine."  Does this mean that the memory is in use by the jvm process and NOT available to other processes until it is released by the java process, or does it mean that the java process will be successful if it tries to allocate up to that amount of memory?  I realize this might be implementation specific but i am only interested in hotspot.

[A]
"Does this mean that the memory is in use by the jvm process and NOT available to other processes" would be the correct one. So its less then (or equal to) the amount of memory the OS sees as taken by the JVM process.
http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html
(sorry no anchors to link to).


q:
I want to do sparse high dimensional (a few thousand features) least squares regression with a few hundred thousands of examples. I'm happy to use non fancy optimisation - stochastic gradient descent is fine.

Does anyone know of any software already implemented for doing this, so I don't have to write to my own?

Kind regards.

[A]
While I don't know for sure, this strikes me as the kind of thing that
LAPACK
(linear algebra package) would be able to provide support for.  They are typically interested in large matrix math, incluing sparse matrices and out-of-core sizes.  The basic version is FORTRAN, but there are ports of the libraries for C and other languages.
As LAPACK uses BLAS (basic linear algebra subprograms) for many of its underlying calls, you will probably also want to check out
Sparse BLAS
.


q:
I am having trouble in exporting to excel and it crashes out at the .set_Value function.

It seems to work if I change object[,] to string[,] but by doing this I lose the formatting.

Anyone Help?

[A]
Are you passing '
```
null
```
' for missing parameters rather than
```
System.Reflection.Missing.Value
```
?


q:
Scenario: I have a function that I need to tweak in some way (example; make it work slightly different in different places). For some reason I end up having to add something ugly to the code, either in the function or at existing call sites. Assume that the sum total "ugly" is the same in both cases.

The question is which choice should I pick and why?

Should I encapsulate it so I don't need to look at it or should I extract it so that it doesn't add semantic trash to the function?

What would effect your choice? What about if:

The function will "never" be called except from the current locations.

New calls to the function won't need the "ugliness".

The function is really clean and generic right now

The function is already a hack job.

you wrote the function

you didn't wright the function

etc.

[A]
Put the ugly in the function, hands down. If this is in C++ be sure to have the implementation in the .cpp file. Perhaps you may consider writing two functions to abstract the ugly from the main function body.
Procedural/OOP programming exists to take the "ugly" out of the interface (among other things). It is important to realize that the more code that is required to call the function the less useful it becomes. Also remember to document the code clearly and note that there is ugly code in there and why.
Also, if this function is big enough you may consider putting it in its own .cs file, or .cpp/.h pair (depending on which language you are using).


q: How do I put a gridview row in edit mode programmatically?

[A]
Just implement the Row_Editing event and do something like this:
```
```
protected void Row_Editing(object sender, GridViewEditArgs e)
{
  myGridView.EditItemIndex = e.EditItemIndex;
  BindData();
}
```
```
Bind data will populate the GridView with the data.


q:
How do I remove the key 'bar' from an array foo so that 'bar' won't show up in

for(key in foo){alert(key);}


q:
After some find and replace refactoring I ended up with this gem:

const class A
{
};

What does "const class" mean? It seems to compile ok.

[A]
If you had this:
```
```
const class A
{
} a;
```
```
Then it would clearly mean that 'a' is const. Otherwise, I think that it is likely invalid c++.


q:
Is there any meaningful distinction between:

class A(object):
    foo = 5   # some default value

vs.

class B(object):
    def __init__(self, foo=5):
        self.foo = foo

If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?

[A]
There is a significant
semantic
difference (beyond performance considerations):
when the attribute is defined on the instance
(which is what we usually do), there can be multiple objects referred to.
Each gets a totally separate version of that attribute
.
when the attribute is defined on the class
, there is only one underlying object referred to, so if operations on different instances of that class both attempt to set/(append/extend/insert/etc.) the attribute, then:
if the attribute is a
builtin type
(like int, float, boolean, string), operations on one object will overwrite (clobber) the value
if the attribute is a
mutable type
(like a list or a dict), we will get unwanted leakage.
For example:
```
```
>>> class A: foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[5]
>>> class A:
...  def __init__(self): self.foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[]
```
```


q:
Is there a way of using an 'OR' operator or equivalent in a PHP switch?

For example, something like this:

switch ($value) {

    case 1 || 2:
        echo 'the value is either 1 or 2';
        break;
}

[A]
```
```
switch ($value)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}
```
```
This is called "falling through" the case block. The term exists in most languages implementing a switch statement.


q:
I have experimented with a sigmoid and logarithmic fade out for volume over a period of about half a second to cushion pause and stop and prevent popping noises in my music applications.

However neither of these sound "natural". And by this I mean, they sound botched. Like an amateur engineer was in charge of the sound decks.

I know the ear is logarithmic when it comes to volumes, or at least, twice as much power does not mean twice as loud. Is there a magic formula for volume fading? Thanks.

[A]
I spent many of my younger years mixing music recordings, live concerts and being a DJ for my school's radio station and the one thing I can tell you is that where you fade is also important.
Fading in on an intro or out during the end of a song sounds pretty natural as long as there are no vocals, but some of these computerized radio stations will fade ANYWHERE in a song to make the next commercial break ... I don't think there's a way to make that sound good.
In any case, I'll also answer the question you asked ... the logarithmic attenuation used for adjusting audio levels is generally referred to as "audio taper".  Here's an excellent article that describes the physiology of human hearing in relation to the electronics we now use for our entertainment.  See:
http://tangentsoft.net/audio/atten.html
.


q:
My problem is that I can't seem to get the image from my bundle to display properly. This method is in the view controller that controls the tableview. headerView is loaded with the tableview in the .nib file and contains a few UILabels (not shown) that load just fine. Any ideas?

- (void)viewDidLoad {
    [super viewDidLoad];

    [[self view] setTableHeaderView:headerView];
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *imagePath = [bundle pathForResource:@"awesome_lolcat" ofType:@"jpeg"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    imageView = [[UIImageView alloc] initWithImage:image];
}

[A]
FIrst you need to figure out whether your image is loading properly. The quickest way to get an image is to use the UIImage convenience method +[UIImage imageNamed: rawImageName].
Also, is this a UITableViewController? (it's unclear, but implied).
Where is imageView being used? You create it near the bottom, but don't seem to do anything with it. You probably want to create the image view, assign it an image, and then add it as a subview to the headerView.
```
```
//this assumes that headerView is an already created UIView, perhaps an IBOutlet

   UIImage     *image = [UIImage imageNamed: @"awesome_lolcat.jpeg"];
   UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
   [headerView addSubview: [imageView autorelease]];
   [[self view] setTableHeaderView: headerView];
```
```


q:
I want to enforce CHECK constraint on a date range such that all dates in column BIRTH_DATE are less than tomorrow and greater than or equal to 100 years ago.  I tried this expression in a CHECK constraint:

BIRTH_DATE >= (sysdate - numtoyminterval(100, 'YEAR')) AND BIRTH_DATE < sysdate + 1

But I received the error "ORA-02436: date or system variable wrongly specified in CHECK constraint"

Is there a way to accomplish this using a CHECK constraint instead of a trigger?

[A]
A check constraint expression has to be deterministic, so this sort of sliding date range is not enforcable in a check constraint.  From the
SQL Reference
Conditions of check constraints cannot
  contain the following constructs:
```
```
* Subqueries and scalar subquery expressions
* Calls to the functions that are not deterministic (CURRENT_DATE,
```
```
CURRENT_TIMESTAMP, DBTIMEZONE, LOCALTIMESTAMP, SESSIONTIMEZONE,
  SYSDATE, SYSTIMESTAMP, UID, USER, and
  USERENV)


q:
What is the best way to approach removing items from a collection in C#, once the item is known, but not it's index.  This is one way to do it, but it seems inelegant at best.

//Remove the existing role assignment for the user.
int cnt = 0;
int assToDelete = 0;
foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
    if (spAssignment.Member.Name == shortName)
    {
        assToDelete = cnt;
    }
    cnt++;
}
workspace.RoleAssignments.Remove(assToDelete);

What I would really like to do is find the item to remove by property (in this case, name) without looping through the entire collection and using 2 additional variables.

[A]
If you want to access members of the collection by one of their properties, you might consider using a
```
Dictionary<T>
```
or
```
KeyedCollection<T>
```
instead. This way you don't have to search for the item you're looking for.
Otherwise, you could at least do this:
```
```
foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
    if (spAssignment.Member.Name == shortName)
    {
        workspace.RoleAssignments.Remove(spAssignment);
        break;
    }
}
```
```


q:
Can an ArrayList of Node contain a non-Node type?

Is there a very dirty method of doing this with type casting?

[A]
Yes, but you will get class cast exceptions if you try to access a non-node element as if it were a node. Generics are discarded at (for) runtime.
For example:
```
```
import java.util.*;
import java.awt.Rectangle;

public class test {
    public static void main(String args[]) {
        List<Rectangle> list = new ArrayList<Rectangle>();
        /* Evil hack */
        List lst = (List)list;

        /* Works */
        lst.add("Test");

        /* Works, and prints "Test" */
        for(Object o: lst) {
            System.err.println(o);
        }

        /* Dies horribly due to implicitly casting "Test" to a Rectangle */
        for(Rectangle r: list) {
            System.err.println(r);
        }
    }
}
```
```


q:
I have a shared library that I wish to link an executable against using GCC. The shared library has a nonstandard name not of the form libNAME.so, so I can not use the usual -l option. (It happens to also be a Python extension, and so has no 'lib' prefix.)

I am able to pass the path to the library file directly to the link command line, but this causes the library path to be hardcoded into the executable.

For example:

g++ -o build/bin/myapp build/bin/_mylib.so

Is there a way to link to this library without causing the path to be hardcoded into the executable?

[A]
If you can copy the shared library to the working directory when g++ is invoked then this should work:
```
```
g++ -o build/bin/myapp _mylib.so other_source_files
```
```


q:
I've got a script that dynamically calls and displays images from a directory, what would be the best way to paginate this?  I'd like to be able to control the number of images that are displayed per page through a variable within the script.  I'm thinking of using URL varriables (ie - http://domain.com/page.php?page=1) but am unsure how to go about this.

Thanks for the help.

[A]
pagination is the same concept with or without sql. you just need your basic variables, then you can create the content you want. here's some quasi-code:
```
```
$itemsPerPage = 5;

$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$totalItems = getTotalItems();
$totalPages = ceil($totalItems / $itemsPerPage);

function getTotalItems() {
// since they're images, perhaps we'll scan a directory of images to determine
// how many images we have in total
}

function getItemsFromPage($page, $itemsPerPage) {
// function to grab $itemsPerPage based on which $page we're on
}

function getPager($totalPages, $currentPage) {
// build your pager
}
```
```
hope that helps you get started!


q:
Trying to implement a progress dialog window for file uploads that looks like a cross between IE download dialog and Firefox download dialog with a python GUI library on Windows.

What asynchronous (S)FTP libraries are there for python? Ideally I should be able to do file upload resumes and track the progress of each parallel file uploads.

If I'm running each file uploads in a separate process, how to get the upload status and display it in a progress bar dialog?

[A]
"ftplib" is the standard ftp library built in to Python. In Python 2.6, it had a callback parameter added to the method used for uploading.
That callback is a function you provide to the library; it is called once for every block that is completed.
Your function can send a message to the GUI (perhaps on a different thread/process, using standard inter-thread or inter-process communications) to tell it to update its progress bar.
Reference


q:
What is the best way to allow a team of programmers to use Netbeans, Eclipse and IntelliJ on the same project, thus eliminating the "which IDE is better" question.

Which files should or should not be checked into source code control?

[A]
Well, that's a pretty self-answering question.
The files to not check into source control are files that have to do with the IDEs themselves.
Leave it to the developers to generate these files.
If you use Maven, it can generate the files such as Eclipse's
```
.project
```
and
```
.classpath
```
for you. Eclipse in general is very easy to use with a basic file structure (with the new
```
Java Project
```
option).
I think Maven has Netbeans support as well, not sure about IntelliJ though.
Maven's site is
maven.apache.org
.


q:
My organization is considering using Jabber as an agnostic device to device to application messaging protocol.

Does anyone know of the best practice existing Microsoft competitor to Jabber?  Or, an emerging competitor?  And, if so, a good URL reference to get a jump start?

Website for Jabber:
http://www.jabber.org/web/Main_Page

[A]
Jabber is several things : the older name of the  Extensible Messaging and Presence Protocol (XMPP), the jabber server and application, and the jabber network.
Windows Communication Foundation
is a web-service based API for communicating between applications?
Office Communicator is an application that uses SIP/SIMPLE messaging protocol.
What do you really need? The application or the protocol/api with which to build an application?


q:
My company has an existing established WinForm application which in running on WinXP.  The application does alot of sound processing using DirectSound.

My company would like to evaluate Mono, as an alternative on a per workstation cost to Vista/Win Server 2008.

I've heard that different estimates, ranging from 'it will work easily on Mono' to 'it could take months of recoding in certain cases to get a WinForm app to run with Mono on Linux'.

Does anyone have a good real world experience with this?
A good link reference?
I would like to get a better idea before I commit to testing.

Thanks!

[A]
The WinForms part will be easy, you may have to do very little as Mono now claims to support Winforms 100%, however all the DirectSound calls will have to be rewritten to use an API available on Linux, ALSA being the obvious choice.
I have written small apps in VS 2005 and ported them with ease to Mono. If you do a lot of P/Invokes, then you'll have to take that into account, as those may have to be completely rewritten or rethought.
Also, check out
MOMA
: "The Mono Migration Analyzer (MoMA) tool helps you identify issues you may have when porting your .Net application to Mono. It helps pinpoint platform specific calls (P/Invoke) and areas that are not yet supported by the Mono project."


q:
I've created the following regex pattern in an attempt to match a string 6 characters in length ending in either "PRI" or "SEC", unless the string = "SIGSEC". For example, I want to match ABCPRI, XYZPRI, ABCSEC and XYZSEC, but not SIGSEC.

(\w{3}PRI$|[^SIG].*SEC$)

It is very close and sort of works (if I pass in "SINSEC", it returns a partial match on "NSEC"), but I don't have a good feeling about it in its current form. Also, I may have a need to add more exclusions besides "SIG" later and realize that this probably won't scale too well. Any ideas?

BTW, I'm using System.Text.RegularExpressions.Regex.Match() in C#

Thanks,
Rich

[A]
Assuming your regex engine supports negative lookaheads, try this:
```
```
((?!SIGSEC)\w{3}(?:SEC|PRI))
```
```
Edit: A commenter pointed out that .NET does support negative lookaheads, so this should work fine (thanks, Charlie).


q:
i noticed that paypal displays a very different favicon,
one that's not just a simple 16x16 icon and is lengthy?
anyone can teach me?

[A]
I think you are refering to the green box that shows the PayPal logo followed by "PayPal, Inc. (US)".
If so, it is not a favicon, but a feature of Firefox 3 to show sites with extended validation (EV). See also
http://news.cnet.com/8301-13554_3-9974672-33.html


q: I have recently started working on a very large C++ project that, after completing 90% of the implementation, has determined that they need to demonstrate 100% branch coverage during testing.  The project is hosted on an embedded platform (Green Hills Integrity).  I'm looking for suggestions and experiences from others on StackOverflow that have used code coverage products in similar environments.  I'm interested in both positive and negative comments regarding these types of tools.

[A]
100% branch coverage?  That's quite the requirement, especially since some branches (defaults in case statements for state machines, for instance) should not be possible to run.  I expect there are
some
exceptions, and if there aren't you might need to understand what coverage testing can and cannot accomplish before you start - otherwise you'll end up pulling your hair out, or worse - giving incorrect data.
Most coverage testing for embedded systems is actually performed on PCs.  The code is ported, certain aspects of the microcontroller are emulated in software, and
Bullseye
or another similar PC code coverage utility is run.  The reason this is done is that there are too many microcontrollers and compilers/debuggers/test environments to develop code coverage tools for each one.
When code coverage tools do exist for a specific embedded platform they aren't as powerful, configurable, easy to use, and bug free as those developed for the PC platform.  The processors don't often have the trace capability (without high end emulation hardware) needed to perform good code coverage without inserting additional debug code into your firmware, which then has consequences and side effects that are difficult to control, especially with timing issues in real time systems.
Porting code over is not terribly difficult as long as you can abstract the hardware specific code (and since you're using C++ properly, that should be easy, right? ;-D ).  The biggest issue you'll run into is types, which while better specified in C++ than they were in C still pose some issues.  Make sure you're using a types.h or similar setup to specifically tell the compiler exactly what each type you use is and how it should be interpreted.
After that, you can go to town testing the core logic on the PC.  You can even test the low level hardware drivers if you are interested in developing the software emulation required for that, although timing issues can be somewhat troublesome.
Software testing tools such as
MxVDev
perform a lot of the microcontroller emulation for you and help with timing issues as well, but you'll still have a bit of work even with such help.
If you must do this on the system itself, you'll need to purchase an emulator for the processor with coverage capability - not an inexpensive proposition (many emulators cost upwards of $30k for the full set of tools and emulation hardware), but it's one of the many tools used in high reliability environments such as the automotive and aerospace industries.
-Adam
Disclaimer: I work for the company that produces MxVDev.


q:
I am just getting started with Silverlight and have recently added a Silverlight project to an established solution. In this particular scenario my solution included an existing ASP.NET web site (not application) which Visual Studio kindly offered to integrated my Silverlight application into, which I accepted.

So everything is fine and all, and the Silverlight XAP is being copied to the web site's ClientBin directory. Now I have decided to start a new ASP.NET MVC web application that will eventually replace the older (non-MVC) web site. But I cannot for the life of me figure out what Visual Studio modified to get the XAP to automatically appear in the web site's ClientBin on build, so that I can reproduce that on my MVC site.

So my question is essentially, what are the manually steps for getting Visual Studio to autocopy a Silverlight application's XAP to a newly added ASP.NET MVC web application?

[A]
The copying of the XAP to the ClientBin is a MSBuild task. If you're using a standard ASP.NET project template it can be found under the Silverlight Link section.
For everything else you might be able to figure out the name of the MSBuild task and add it to your ASP.NET MVC project. The easier solution would probably be to use a custom post-build event on the APS.NET project to copy the file.
There is no "magic" happening, oter than copying the XAP file from the BIN directory of your Silverlight project to the ClientBin of your web application. It doesn't even have to live inside the ClientBin directory - you can copy it to any directory, or the root of your site.
Update:
The recently released Beta 1 of ASP.NET MVC includes support for Silverlight projects, so you can link it to your ASP.NET MVC application the same way you do for regular ASP.NET applications.


q:
My team uses an internal team maven repo that is shared from a development server using Apache. We also run the Continuum CI server on the same machine. Maven builds in Continuum are run with the "install" goal, which copies the final artifact directly into the shared directory.

The question is, what is the difference between adding files to the shared repo using mvn install and using the deploy goal (mvn-deploy plugin)?

It seems to me that using mvn deploy creates additional configuration hassles, but I have read somewhere that installing files into a shared repo is a bad idea for some reason related to the internal workings of maven.

update: I get the functional differences between deploy and install; I am actually more interested in the low level details in terms of what files are created in the maven repo.

[A]
From the Maven docs
, sounds like it's just a difference in
which
repository you install the package into:
install - install the package into the local repository, for use as a dependency in other projects locally
deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.
Maybe there is some confusion in that "install" to the CI server installs it to it's local repository, which then you as a user are sharing?


q:
OS: Vista enterprise

When i switch between my home and office network, i always face issues with getting connected to the network. Almost always I have to use the diagnostic service in 'Network and sharing center' and the problem gets solved when i use the reset network adapter option.

This takes a lot of time (3-4 min) and so i was trying to find either a command or a powershell script/cmdlet which i can use directly to reset the network adapter and save myself these 5 mins every time i have to switch between the networks. Any pointers?

[A]
See this article from The Scripting Guys,
"How Can I Enable or Disable My Network Adapter?"
tl/dr:
```
```
Restart-NetAdapter   -Name "Your Name Here"
```
```
You can get the list using
```
```
Get-NetAdapter
```
```


q:
Can standard pointers in .Net do this? Or does one need to resort to P/invoke?

Note that I'm not talking about object references; I'm talking about actual C# pointers in unsafe code.

[A]
C#, as a managed and protected run time engine, does not allow low level hardware access and the memory locations associated with actual hardware are not available.
You'll need to use a port driver or write your own in C++ or C with the proper Windows API to access the memory mapped I/O regions of interest.  This will run in a lower ring than the C# programs are capable of.
This is why you don't see drivers written in C#, although I understand many are writing access routines with C++, but the main driver logic in C#.  It's tricky, though, as crashes and restarting can become tricky, not to mention synchronization and timing issues (which are somewhat more concrete in C++ at a lower ring, even though windows is far from a real-time system).
-Adam


q:
I'm using the MonthCalendar control and want to programmatically select a date range. When I do so the control doesn't paint properly if Application.EnableVisualStyles() has been called. This is a known issue according to MSDN.

Using the MonthCalendar with visual
  styles enabled will cause a selection
  range for the MonthCalendar control to
  not paint correctly
  (from: http://msdn.microsoft.com/en-us/library/system.windows.forms.monthcalendar.aspx)

Is there really no fix for this other than not calling EnableVisualStyles? This seems to make that particular control entirely useless for a range of applications and a rather glaring oversight from my perspective.

[A]
While looking for a solution to the same problem, I first encountered this question here, but later I discovered a blog entry by
Nicke Andersson
. which I found very helpful.
Here is what I made of Nicke's example:
```
```
public class MonthCalendarEx : System.Windows.Forms.MonthCalendar
{
    private int _offsetX;
    private int _offsetY;
    private int _dayBoxWidth;
    private int _dayBoxHeight;

    private bool _repaintSelectedDays = false;

    public MonthCalendarEx() : base()
    {
        OnSizeChanged(null, null);
        this.SizeChanged += OnSizeChanged;
        this.DateChanged += OnSelectionChanged;
        this.DateSelected += OnSelectionChanged;
    }

    protected static int WM_PAINT = 0x000F;

    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_PAINT)
        {
            Graphics graphics = Graphics.FromHwnd(this.Handle);
            PaintEventArgs pe = new PaintEventArgs(
                graphics, new Rectangle(0, 0, this.Width, this.Height));
            OnPaint(pe);
        }
    }

    private void OnSelectionChanged(object sender, EventArgs e)
    {
        _repaintSelectedDays = true;
    }

    private void OnSizeChanged(object sender, EventArgs e)
    {
        _offsetX = 0;
        _offsetY = 0;

        // determine Y offset of days area
        while (
            HitTest(Width / 2, _offsetY).HitArea != HitArea.PrevMonthDate &&
            HitTest(Width / 2, _offsetY).HitArea != HitArea.Date)
        {
            _offsetY++;
        }

        // determine X offset of days area
        while (HitTest(_offsetX, Height / 2).HitArea != HitArea.Date)
        {
            _offsetX++;
        }

        // determine width of a single day box
        _dayBoxWidth = 0;
        DateTime dt1 = HitTest(Width / 2, _offsetY).Time;

        while (HitTest(Width / 2, _offsetY + _dayBoxHeight).Time == dt1)
        {
            _dayBoxHeight++;
        }

        // determine height of a single day box
        _dayBoxWidth = 0;
        DateTime dt2 = HitTest(_offsetX, Height / 2).Time;

        while (HitTest(_offsetX + _dayBoxWidth, Height / 2).Time == dt2)
        {
            _dayBoxWidth++;
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        if (_repaintSelectedDays)
        {
            Graphics graphics = e.Graphics;
            SelectionRange calendarRange = GetDisplayRange(false);
            Rectangle currentDayFrame = new Rectangle(
                -1, -1, _dayBoxWidth, _dayBoxHeight);

            DateTime current = SelectionStart;
            while (current <= SelectionEnd)
            {
                Rectangle currentDayRectangle;

                using (Brush selectionBrush = new SolidBrush(
                    Color.FromArgb(
                        255, System.Drawing.SystemColors.ActiveCaption)))
                {
                    TimeSpan span = current.Subtract(calendarRange.Start);
                    int row = span.Days / 7;
                    int col = span.Days % 7;

                    currentDayRectangle = new Rectangle(
                        _offsetX + (col + (ShowWeekNumbers ? 1 : 0)) * _dayBoxWidth,
                        _offsetY + row * _dayBoxHeight,
                        _dayBoxWidth,
                        _dayBoxHeight);

                    graphics.FillRectangle(selectionBrush, currentDayRectangle);
                }

                TextRenderer.DrawText(
                    graphics,
                    current.Day.ToString(),
                    Font,
                    currentDayRectangle,
                    System.Drawing.SystemColors.ActiveCaptionText,
                    TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);

                if (current == this.TodayDate)
                {
                    currentDayFrame = currentDayRectangle;
                }

                current = current.AddDays(1);
            }

            if (currentDayFrame.X > 0)
            {
                graphics.DrawRectangle(new Pen(
                    new SolidBrush(Color.Red)), currentDayFrame);
            }

            _repaintSelectedDays = false;
        }
    }
}
```
```


q:
I have db table with parent child relationship as:

NodeId    NodeName    ParentId
------------------------------
1         Node1       0
2         Node2       0
3         Node3       1
4         Node4       1
5         Node5       3
6         Node6       5
7         Node7       2

Here parentId = 0 means that it is a root level node. Now I want to write an SQL Query which will return child at all level of a parent category.

e.g. for nodeId = 1, it should return 3, 4, 5, 6.

I am using MS SQL Server 2005

[A]
```
```
with [CTE] as (
    select * from [TheTable] c where c.[ParentId] = 1
    union all
    select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId]
)
select * from [CTE]
```
```


q:
Title says most of it.

I have inherited a Joomla site and the client wants part of the main template (a feature-type box) to be editable via the Joomla backend.

I guess really it is a content item that never gets displayed as its own page, but as a part of all pages.

Is that possible?

Thanks.

EDIT: By editable, I mean as a piece of content, not as editing the template HTML. I hardly expect non-tech users to get things right in a WYSIWYG text editor, much less change HTML code that could screw up the whole site.

[A] Joomla templates are always editable via the backend.  Just got to Extensions->Template Manager->Select the template you're using to edit it->and then up in the toolbar there will options for editing the html or the css as well as many design (look) options over on the right.  That is in Joomla 1.5.


q:
I'm going to be distributing a plugin that will be routinely updated with features, bug fixes, and updates to downloadable corpuses.

The usual update site mechanism can do the update ok - when the user asks it to.

The problem is that (unlike MS Office), the automatic updater preference is off by default and I don't want to change that default for my users or count on them changing it.

Can I write something that occasionally checks for updates? Or prompt the user regularly? What's bad form and what's acceptable ?

[A]
Eclipse 3.4 check automatically for plugin updates by default.
You will see a popup window in the bottom right when an update is available.
To configure automatic updates, go to Window > Preferences > Install Updates > Automatic Updates


q: Is it possible to access the crash log over the application? The last.fm client showed me today a "we found a crash log" altert with the option to send it, so I think it must be possible.

[A]
Yes, although you probably won't get much out of them if you don't have the dSYM file and source code:
After you've synced with iTunes the
  crash logs should be in one of the
  following folders:
On Mac OS X they are located in
  ~/Library/Logs/CrashReporter/MobileDevice.
Windows XP: C:\Documents and
  Settings\Application Data\Apple
  computer\Logs\CrashReporter/
Windows Vista:
  C:\Users\AppData\Roaming\Apple
  computer\Logs\CrashReporter/MobileDevice/
(This from the
help page
for my application.)


q: I've been trying to programatically feed the paper on a pos printer (Epson TM-U220D). The problem I have is that the last line of the document don't get printed, instead, it is printed as the first line of the next document printed. I tried POS for .NET sending the "ESC|flF" command, also tried to send the raw esc/pos command using the serial port, but it doesn't work. Any ideas?

[A]
If the printer is on LPT1, shell out to DOS and give to CMD.EXE or COMMAND.COM whatever the C# equivalent is of this BASIC expression:
```
```
"ECHO " & Chr(12) & ">LPT1"
```
```
Either that or append a Chr(12) to the output text.


q:
When you plot things in Matlab, the most recently plotted data series is placed on top of whatever's already there. For example:

figure; hold on
plot(sin(linspace(0,pi)),'linewidth',4,'color',[0 0 1])
plot(cos(linspace(0,pi)),'linewidth',4,'color',[1 0 0])

Here, the red line is shown on top of the blue line (where they intersect). Is there any way to set "how deep" a line is drawn, so that you can plot things beneath what's already there?

[A]
Use the
uistack
command.  For example:
```
```
h1 = plot(1:10, 'b');
hold on;
h2 = plot(1:10, 'r');
```
```
will plot two lines with the red line plotted on top of the blue line.  If you then do:
```
```
uistack(h1);
```
```
the blue line will be brought to the front.


q:
Its a little tricky to search for 'var:*' because most search engines wont find it.

I'm not clear exactly what var:* means, compared to say var:Object

I thought it would let me set arbitrary properties on an object like :

var x:*  = myObject;
x.nonExistantProperty = "123";

but this gives me an error :

Property nonExistantProperty not found on x

What does * mean exactly?

Edit: I fixed the original var:* to the correct var x:*. Lost my internet connection

[A]
It's the "untyped" type. It just means that the variable can be of any type. Basically the same effect as using this:
```
```
var x = myObject;
```
```


q: I am looking to set full trust for a single web part, is this possible?  manifest.xml maybe?

[A]
Have you tried registering the assembly in the GAC? This is the preferred approach to giving any assembly full trust on your machine:
```
```
gacutil.exe \i C:\Path\To\Dll.dll
```
```
Hope that helps. Let me know if I misunderstood your question.


q:
I have a UserControl with some predefined controls (groupbox,button,datagridview) on it, these controls are marked as protected and the components variable is also marked as protected.

I then want to inherit from this base UserControl to another UserControl, however the DataGridView is always locked in the designer.

I suspect it may have something to do with the DataGridView implementing ISupportInitilize.

public class BaseGridDetail : UserControl

Has a DataGridView control (et al) defined.

public class InheritedDetail : BaseGridDetail

The DataGridView control is locked

Does anyone have any ideas how to make this control available in the designer after inheritenace?

[A]
I left an answer but re-read your question and decided to delete it.
What is it about the DataGridView that you're trying to modify in the inherited control? It's columns? I've been able to do this by setting up a protected method in my base UserControl and passing the grid's column collection into it, like this:
```
```
// in base UserControl
public BaseGridDetail()
{
    InitializeComponent();

    InitGridColumns(dataGridView1.Columns);
}

protected virtual void InitGridColumns(DataGridViewColumnCollection columns)
{
    columns.Clear();
}
```
```
Now your derived control can simply override that method, like so:
```
```
// in InheritedDetail
protected override void InitGridColumns(DataGridViewColumnCollection columns)
{
    base.InitGridColumns(columns);
    // add my own custom columns
}
```
```


q: If I click on File -> Close, it closes the buffer like I want, but doesn't list a key mapping. What is the key mapping?

[A]
BKB has already given correct answer. Just wanted to add that
```
C-h b
```
lists the key bindings applicable in current buffer


q: What are the downsides to using static methods in a web site business layer versus instantiating a class and then calling a method on the class?  What are the performance hits either way?

[A]
The performance differences will be negligible.
The downside of using a static method is that it becomes less testable. When dependencies are expressed in static method calls, you can't replace those dependencies with mocks/stubs. If all dependencies are expressed as interfaces, where the implementation is passed into the component, then you can use a mock/stub version of the component for unit tests, and then the real implementation (possibly hooked up with an IoC container) for the real deployment.


q:
I am setting up my Java EE version of Eclipse to compile Servlets. I have the problem where Eclipse says "HttpServlet" cannot be resolved because it can't find the Java EE jar files.

I am using Windows XP. I already have Tomcat 6.0 up and running. I think the easiest solution would be to link to the servlet-api.jar file in the Tomcat installation.

I added it to the Windows CLASSPATH environment variable. Now it looks like this:
.;C:\Program Files\Java\jre1.6.0_04\lib\ext\QTJava.zip;C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar

That didn't work. Am I doing something wrong?

What is the best solution?

[A]
a few thing to check:
Did you create your project as a "Dynamic Web Project" (via New->Project...->Web->Dynamic Web Project) ?
you should have a Web App Librairies directory which does contains:
Web App Librairies
JRE System Library
Apache Tomcat vx.y
Did you select a server in "Window -> Preferences... -> Server -> Installed Runtimes" ?
Do you have a TOMCAT_HOME in Prefereces -> Java -> Build Path -> Classpath variable referring to the home directory of your tomcat installation ? Try to add it to your project classpath.


q: How do I prevent Visual Studio 2008 from automatically creating the "Mixed Platforms" and "Any CPU" solution configurations? We have "Win32" and "x64" configurations and a developer needs to choose between them. However, as soon as anyone makes any changes to the solution VS automatically creates "Mixed Platforms" and it seems to be the default configuration. This causes a lot of issues, because it turns out some new projects are not selected in this configuration or the wrong project configuration is selected, etc. I just want to stop it doing that and manage the solution configurations myself.

[A]
We see a similar issue with Visual Studio 2005 projects that we want to build both for a Win32 configuration and for a number of distinct smart device platform/configuration combinations.
At arbitrary times, every configuration gets auto-generated for every platform, whether it's valid or not, exploding the size of each of our ~50 project files and causing a lot of work to fix the issue.
It consistently happens when we open the Configuration Manager dialog, and it sometimes (but not always) happens when changing a project setting for a configuration.  In the latter case, it seems to be related to manipulating the platform and configuration drop-downs on the project setting dialog.
We filed it as a Visual Studio issue; MSFT closed it as "won't fix".