Question:
Anyone using WPF for real LOB applications?

We have all seen the clever demos of WPF showing videos mapped onto 3D elements. These look great but what about the real world of line-of-business applications that make up the majority of developers efforts. Is WPF just for nice eye candy?

Answer:
I feel the eye candy demos are targeted mostly towards designers. Having said that, there is a huge potential in improving usability of LOB apps using WPF.
Check this article about the potential of Silverlight
.
Line-of-business applications have a notorious reputation for being all business and no pleasure. The fact is that "user experience" has never really been a top concern when developing line-of-business (LOB) applications. While many LOB-style applications are putting an increasing emphasis on usability, they often fall short on appeal. User experience is actually a combination of both usability and appeal.


Question:
I am attempting to copy a custom struct from kernel space to user space. inside user space errno returns 'bad address'.  What is the usual cause of a bad address error?

if(copy_to_user(info, &kernel_info, sizeof(struct prinfo)))

Answer:
Bad Address error means that the address location that you have given is invalid. With the case you have above I would guess it is because you are passing a copy of
```
info
```
instead of a pointer to
```
info
```
's memory location.
Looking at the docs,
```
copy_to_user
```
is defined as
```
```
copy_to_user(void __user * to, const void * from, unsigned long n);
```
```
So unless your
```
info
```
variable is a pointer I would update your code to be:
```
```
if(copy_to_user(&info, &kernel_info, sizeof(struct prinfo)) ) {
    //some stuff here i guess
}
```
```


Question: I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles.  I saw it done here: http://www.dayah.com/periodic/.  Click on an element and the iframe is displayed and links to the article only (no wrapper).  So how'd they do that?  Seems like JavaScript handles showing the iframe and constructing the href but after browsing the pages javascript (http://www.dayah.com/periodic/Script/interactivity.js) I still can't figure out how the url is built.  Thanks.

Answer:
You could always download the site and scrap it. I think everything inside
```
<div id="bodyContent">
```
is the content of the article - sans navigation, header, footer, etc..
Don't forget to credit. ;)


Question:
Let's say I have the following simple enum:

enum Response
{
    Yes = 1,
    No = 2,
    Maybe = 3
}

How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?

Answer:
I probably wouldn't
bind
the data as it's an enum, and it won't change after compile time (unless I'm having one of those
stoopid
moments).
Better just to iterate through the enum:
```
```
Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Response))

For i As Integer = 0 To itemNames.Length - 1
    Dim item As New ListItem(itemNames(i), itemValues(i))
    dropdownlist.Items.Add(item)
Next
```
```
Or the same in C#
```
```
Array itemValues = System.Enum.GetValues(typeof(Response));
Array itemNames = System.Enum.GetNames(typeof(Response));

for (int i = 0; i <= itemNames.Length - 1 ; i++) {
    ListItem item = new ListItem(itemNames[i], itemValues[i]);
    dropdownlist.Items.Add(item);
}
```
```


Question:
Let's say I have the following simple table variable:

declare @databases table
(
    DatabaseID    int,
    Name        varchar(15),
    Server      varchar(15)
)
-- insert a bunch rows into @databases

Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?

Answer:
You can use a while loop:
```
```
While (Select Count(*) From #TempTable) > 0
Begin
    Insert Into @Databases...

    Delete From #TempTable Where x = x
End
```
```


Question: Best recommendations for accessing and manipulation of sqlite databases from JavaScript.

Answer:
Well, if you are working on client side JavaScript, I think you will be out of luck... browsers tend to sandbox the JavaScript environment so you don't have access to the machine in any kind of general capacity like accessing a database.
If you are talking about an SQLite DB on the server end accessed from the client end, you could set up an AJAX solution that invokes some server side code to access it.
If you are talking about Rhino or some other server side JavaScript, you should look into the host language's API access into SQLite (such as the JDBC for Rhino).
Perhaps clarify your question a bit more...?


Question:
Given the following XML:

<current>
  <login_name>jd</login_name>
</current>
<people>
  <person>
    <first>John</first>
    <last>Doe</last>
    <login_name>jd</login_name>
  </preson>
  <person>
    <first>Pierre</first>
    <last>Spring</last>
    <login_name>ps</login_name>
  </preson>
</people>

How can I get "John Doe" from within the current/login matcher?

I tried the following:

<xsl:template match="current/login_name">
  <xsl:value-of select="../people/first[login_name = .]"/>
  <xsl:text> </xsl:text>
  <xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>

Answer:
I think what he actually wanted was the replacement in the match for the "current" node, not a match in the person node:
```
```
<xsl:variable name="login" select="//current/login_name/text()"/>

<xsl:template match="current/login_name">
<xsl:value-of select='concat(../../people/person[login_name=$login]/first," ", ../../people/person[login_name=$login]/last)'/>

</xsl:template>
```
```


Question:
I was wondering if anybody knew of a method to configure apache to fall back to returning a static HTML page, should it (Apache) be able to determine that PHP has died?  This would provide the developer with a elegant solution to displaying an error page and not (worst case scenario) the source code of the PHP page that should have been executed.

Thanks.

Answer:
I would assume that this typically results in a 500 error, and you can configure apaches 500 handler to show a static page:
ErrorDocument 500 /500error.html
You can also read about error handlers on
apaches documentation site


Question:
I'm trying to construct a find command to process a bunch of files in a directory using two different executables.  Unfortunately, -exec on find doesn't allow to use pipe or even \| because the shell interprets that character first.

Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command):

find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print

Answer:
As this outputs a list would you not :
```
```
find /path/to/jpgs -type f -exec jhead -v {} \; | grep 123
```
```
or
```
```
find /path/to/jpgs -type f -print -exec jhead -v {} \; | grep 123
```
```
Put your grep on the results of the find -exec.


Question:
I need to build something that starts serving a H.264 encoded video to a flash player halfway through the file (to support skipping to a point in the video that has not been buffered yet).

Currently, the videos are in the FLV container format, but transcoding is an option. I managed to re-write the file header and metadata information for a given byte offset. This works for older videos, but not for H.264 encoded files. I suspect this is because the video tags inside the file also have to be altered, which is not feasible (it would take too much processing power).

What is the "proper" way to do it?

Answer:
@yoavf - I think the OP is interested in server-side aspects of streaming on-demand h.264 inside of FLV files.  Reuse of existing players would be nice for him, I think.  Or maybe that is my own needs coming out?  <:S
From yoavf's second link, there is another link to Tinic Uro's
What just happened to video on the web?
.  A relevant quote:
Will it be possible to place H.264 streams into the traditional FLV file structure? It will, but we strongly encourage everyone to embrace the new standard file format. There are functional limits with the FLV structure when streaming H.264 which we could not overcome without a redesign of the file format. This is one reason we are moving away from the traditional FLV file structure. Specifically dealing with sequence headers and enders is tricky with FLV streams.
So, it seems one can either tinker with ffmpeg encoding (if that is how you are getting your FLVs, like I am) or one can get into the new format.  Hmmmm....


Question:
I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.

1) Is it actually worth taking such things into account?

2) Assuming it is worth taking it into account, how do I do this?

I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.

Answer:
If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes.
Nonetheless you can use the time command to measure everything and can compare it with the timing within a script.
Like this:
```
```
$ time script.php
HI!

real    0m3.218s
user    0m0.080s
sys     0m0.064s
```
```
It will give you clock time, user time (php interpreter) and sys time (OS time)
If you are thinking web, then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if, say, you are using WSGI v/s mod_php. Then you'd have to hook probes into the webserving parts of the chain as well


Question:
I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!

Suppose I have the following XML (using e4x):

var xml:XML = <root><example>foo</example></root>

I can change the contents of the example node using the following code:

xml.example = "bar";

However, if I have this:

var xml:XML = <root>foo</root>

How do i change the contents of the root node?

xml = "bar";

Obviously doesn't work as I'm attempting to assign a string to an XML object.

Answer:
If you're trying to change the root element of a document, you don't really need to-- just throw out the existing document and replace it. Alternatively, just wrap your  element in a more proper root element (you shouldn't be editing the root node anyway) and you'd be set.
Of course, that doesn't answer your question. There's an ugly JS hack that can do what you want, but bear in mind that it's likely far slower than doing the above. Anyway, here it is:
```
```
var xml = <root>foo</root>; // </fix_syntax_highlighter>
var parser = new DOMParser();
var serializer = new XMLSerializer();

// Parse xml as DOM document
// Must inject "<root></root>" wrapper because
// E4X's toString() method doesn't give it to us
// Not sure if this is expected behaviour.. doesn't seem so to me.
var xmlDoc = parser.parseFromString("<root>" +
  xml.toString() + "</root>", "text/xml");

// Make the change
xmlDoc.documentElement.firstChild.nodeValue = "CHANGED";

// Serialize back to string and then to E4X XML()
xml = new XML(serializer.serializeToString(xmlDoc));
```
```
You can ignore the fix_syntax_highlighter comment.


Question: I've just heard the term covered index in some database discussion - what does it mean?

Answer:
A
covering index
is an index that contains all of, and possibly more, the columns you need for your query.
For instance, this:
```
```
SELECT *
FROM tablename
WHERE criteria
```
```
will typically use indexes to speed up the resolution of which rows to retrieve using
criteria
, but then it will go to the full table to retrieve the rows.
However, if the index contained the columns
column1, column2
and
column3
, then this sql:
```
```
SELECT column1, column2
FROM tablename
WHERE criteria
```
```
and, provided that particular index could be used to speed up the resolution of which rows to retrieve, the index already contains the values of the columns you're interested in, so it won't have to go to the table to retrieve the rows, but can produce the results directly from the index.
This can also be used if you see that a typical query uses 1-2 columns to resolve which rows, and then typically adds another 1-2 columns, it could be beneficial to append those extra columns (if they're the same all over) to the index, so that the query processor can get everything from the index itself.
Here's an
article: Index Covering Boosts SQL Server Query Performance
on the subject.


Question: I've been wondering what exactly are the principles of how the two properties work. I know the second one is universal and basically doesn't deal with time zones, but can someone explain in detail how they work and which one should be used in what scenario?

Answer:
DateTime.UtcNow
tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer.
DateTime.Now
gives the date and time as it would appear to someone in your current locale.
I'd recommend using
```
DateTime.Now
```
whenever you're displaying a date to a human being - that way they're comfortable with the value they see - it's something that they can easily compare to what they see on their watch or clock. Use
```
DateTime.UtcNow
```
when you want to store dates or use them for later calculations that way (in a client-server model) your calculations don't become confused by clients in different time zones from your server or from each other.


Question:
Several times now I've been faced with plans from a team that wants to build their own bug tracking system - Not as a product, but as an internal tool.

The arguments I've heard in favous are usually along the lines of :

Wanting to 'eat our own dog food' in terms of some internally built web framework

Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way

Believing that it isn't difficult to build a bug tracking system

What arguments might you use to support buying an existing bug tracking system? In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked?

Answer:
The most basic argument for me would be the time loss. I doubt it could be completed in less than a month or two. Why spend the time when there are soooo many good bug tracking systems available? Give me an example of a feature that you have to tweak and is not readily available.
I think a good bug tracking system has to reflect your development process. A very custom development process is inherently bad for a company/team. Most agile practices favor
Scrum
or these kinds of things, and most bug tracking systems are in line with such suggestions and methods. Don't get too bureaucratic about this.


Question:
To commemorate the public launch of Stack Overflow, what's the shortest code to cause a stack overflow? Any language welcome.

ETA: Just to be clear on this question, seeing as I'm an occasional Scheme user: tail-call "recursion" is really iteration, and any solution which can be converted to an iterative solution relatively trivially by a decent compiler won't be counted. :-P

ETA2: I've now selected a “best answer”; see this post for rationale. Thanks to everyone who contributed! :-)

Answer:
My current best (in x86 assembly) is:
```
```
push eax
jmp short $-1
```
```
which results in 3 bytes of object code (
```
50 EB FD
```
). For 16-bit code, this is also possible:
```
```
call $
```
```
which also results in 3 bytes (
```
E8 FD FF
```
).


Question:
An instance of class A instantiates a couple of other objects, say for example from class B:

$foo = new B();

I would like to access A's public class variables from methods within B.

Unless I'm missing something, the only way to do this is to pass the current object to the  instances of B:

$foo = new B($this);

Is this best practice or is there another way to do this?

Answer:
I would first check if you are not using the wrong pattern: From your application logic, should B really know about A? If B needs to know about A, a parent-child relationship seems not quite adequate. For example, A could be the child, or part of A's logic could go into a third object that is "below" B in the hierarchy (i. e. doesn't know about B).
That said, I would suggest you have a method in B to register A as a data source, or create a method in A to register B as an
Observer
and a matching method in B that A uses to notify B of value changes.


Question: Is there an easy way to avoid dealing with text encoding problems?

Answer:
The obvious names for these classes are ReaderInputStream and WriterOutputStream. Unfortunately these are not included in the Java library. However, google is your friend.
I'm not sure that it is going to get around all text encoding problems, which are nightmarish.
There is an RFE,
but it's Closed, will not fix.


Question:
I am trying to refactor some code I have for software that collects current status of agents in a call queue. Currently, for each of the 6 or so events that I listen to, I check in a Mnesia table if an agent exists and change some values in the row depending on the event or add it as new if the agent doesn't exist. Currently I have this Mnesia transaction in each event and of course that is a bunch of repeated code for checking the existence of agents and so on.

I'm trying to change it so that there is one function like change_agent/2 that I call from the events that handles this for me.

My problems are of course records.... I find no way of dynamically creating them or merging 2 of them together or anything. Preferably there would be a function I could call like:

change_agent("001", #agent(id = "001", name = "Steve")).
change_agent("001", #agent(id = "001", paused = 0, talking_to = "None")).

Answer:
It is difficult to write generic access functions for records.
One workaround for this is the
'exprecs'
library, which
will generate code for low-level record access functions.
The thing you need to do is to add the following lines to
a module:
```
```
-compile({parse_transform, exprecs}).
-export_records([...]).  % name the records that you want to 'export'
```
```
The naming convention for the access functions may look strange, but was inspired by a proposal from Richard O'Keefe. It is, at least, consistent, and unlikely to clash with existing functions. (:


Question:
I recently asked about keyword expansion in Git and I'm willing to accept the design not to really support this idea in Git.

For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:

svn propset svn:keywords "Id" expl3.dtx

to keep this string up-to-date:

$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $

But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:

"We ignore all SVN properties except svn:executable"

But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?

Answer:
You could set the ident attribute on your files, but that would produce strings like
```
```
$Id: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef$
```
```
where
```
deadbeef...
```
is the sha1 of the blob corresponding to that file. If you really need that keyword expansion, and you need it in the git repo (as opposed to an exported archive), I think you're going to have to go with the
```
ident
```
gitattribute with a custom script that does the expansion for you. The problem with just using a hook is then the file in the working tree wouldn't match the index, and git would think it's been modified.


Question:
I have a winform app that calls a web service to check for updates.  This works in dev and it also works everywhere else I've tried it, just not on the installed copy on my machine (which happens to be the same in dev).

The error is:

Cannot execute a program. The command being executed was "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe" /noconfig /fullpaths @"C:\Documents and Settings\Giovanni.DOUBLE-AFSSZ043\Local Settings\Temp\squ8oock.cmdline".

The firewall is disabled and I've looked for "C:\Documents and Settings\Giovanni.DOUBLE-AFSSZ043\Local Settings\Temp\squ8oock.cmdline" and it is not there.  Note that every time I try to use the web service the ".cmdline" file is different, for example the second time I ran it it was "dae8rgen.cmdline."  No matter what name it has, I can never find the file.

Any suggestions?

Answer:
The ".cmdline" file is an autogenerated file produced by the .NET framework. The application is attempting to real-time compile an XML Serializer used to parse the data from the web service.
Have you verified that you can execute "csc.exe" from a command-line window? Even just typing "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe /?" should get you a list of compiler options (or should give you an error if you don't have permissions to execute it).
What user account are you running this under, and does it have permissions to execute .exe files in the windows directory? Similarly, I know you said this happens with the installed copy on your machine, but is it possible it's executing off a network share and receiving limited Code Access Security permissions which would prevent it from running local executables?
For reference, here is a KB article showing a similar error that can occur in ASP.NET when the user account doesn't have enough permissions.
http://support.microsoft.com/kb/315904


Question: How is it possible to read/write to the Windows registry using Java?

Answer:
Yes, using the java.util.Preferences API, since the Windows implementation of it uses the Registry as a backend.
In the end it depends on what you're wanting to do: storing preferences for your app is what the Preferences does just great. If you're wanting to actually change registry keys not having to do with your app, you'll need some JNI app, as described by Mark (shameless steal here):
From a quick google:
Check the WinPack for JNIWrapper. It has full Windows Registry access support including Reading and Writing.
The WinPack Demo has Registry Viewer implemented as an example.
Check at
http://www.teamdev.com/jniwrapper/winpack/#registry_access
And...
There is also try JNIRegistry @
http://www.trustice.com/java/jnireg/
There is also the option of invoking an external app, which is responsible for reading / writing the registry.


Question: In PHP, how can I replicate the expand/contract feature for Tinyurls as on search.twitter.com?

Answer:
If you want to find out where a tinyurl is going, use fsockopen to get a connection to tinyurl.com on port 80, and send it an HTTP request like this
```
```
GET /dmsfm HTTP/1.0
Host: tinyurl.com
```
```
The response you get back will look like
```
```
HTTP/1.0 301 Moved Permanently
Connection: close
X-Powered-By: PHP/5.2.6
Location: http://en.wikipedia.org/wiki/TinyURL
Content-type: text/html
Content-Length: 0
Date: Mon, 15 Sep 2008 12:29:04 GMT
Server: TinyURL/1.6
```
```
example code...
```
```
<?php
$tinyurl="dmsfm";

$fp = fsockopen("tinyurl.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET /$tinyurl HTTP/1.0\r\n";
    $out .= "Host: tinyurl.com\r\n";
    $out .= "Connection: Close\r\n\r\n";

    $response="";

    fwrite($fp, $out);
    while (!feof($fp)) {
        $response.=fgets($fp, 128);
    }
    fclose($fp);

    //now parse the Location: header out of the response

}
?>
```
```


Question:
I have a solution with multiple project. I am trying to optimize AssemblyInfo.cs files by linking one solution wide assembly info file. What are the best practices for doing this? Which attributes should be in solution wide file and which are project/assembly specific?

Edit: If you are interested there is a follow up question What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

Answer:
Using a single AseemblyInfo.cs file for multiple projects is not recommended.
The AssemblyInfo file includes information that might be relevant only for that specific assembly. The two most obvious pieces of information are the
```
AssemblyTitle
```
and
```
AssemblyVersion
```
.
A better solution might be to use
```
targets
```
file, which are handled by the MSBuild, in order to "inject" assembly attributes to more than one project.


Question:
Say I have an ASMX web service, MyService.  The service has a method, MyMethod.  I could execute MyMethod on the server side as follows:

MyService service = new MyService();
service.MyMethod();

I need to do similar, with service and method not known until runtime.

I'm assuming that reflection is the way to go about that.  Unfortunately, I'm having a hard time making it work.  When I execute this code:

Type.GetType("MyService", true);

It throws this error:

Could not load type 'MyService' from assembly 'App_Web__ktsp_r0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

Any guidance would be appreciated.

Answer:
I'm not sure if this would be the best way to go about it.  The most obvious way to me, would be to make an HTTP Request, and call the webservice using an actual HTTP GET or POST. Using your method, I'm not entirely sure how you'd set up the data you are sending to the web service. I've added some sample code in VB.Net
```
```
Dim HTTPRequest As HttpWebRequest
Dim HTTPResponse As HttpWebResponse
Dim ResponseReader As StreamReader
Dim URL AS String
Dim ResponseText As String

URL = "http://www.example.com/MyWebSerivce/MyMethod?arg1=A&arg2=B"

HTTPRequest = HttpWebRequest.Create(URL)
HTTPRequest.Method = "GET"

HTTPResponse = HTTPRequest.GetResponse()

ResponseReader = New StreamReader(HTTPResponse.GetResponseStream())
ResponseText = ResponseReader.ReadToEnd()
```
```


Question: It's big problem to convert mod_rewrite rules to lighttpd format

Answer:
It is generally a case of just going through one by one and converting them.  I don't know of any automated means,
The docs -
http://redmine.lighttpd.net/projects/1/wiki/Docs:ModRewrite
- has the regexes available, and some examples.
if there are any particularly problematical items, I'd edit the question to show them, and ask for the answers here.


Question:
What are the advantages/disadvantages between MS VS C++ 6.0 and MSVS C++ 2008?

The main reason for asking such a question is that there are still many decent programmers that prefer using the older version instead of the newest version.

Is there any reason the might prefer the older over the new?

Answer:
Well, for one thing it may be because the executables built with MSVS 6 require only msvcrt.dll (C runtime) which is shipped with Windows now.
The MSVS 2008 executables need msvcrt9 shipped with them (or already installed).
Plus, you have a lot of OSS libraries already compiled for Windows 32 bit with the 6.0 C runtime, while for the 2008 C runtime you have to take the source and compile them yourself.
(most of those libraries are actually compiled with MinGW, which too uses the 6.0 C runtime - maybe that's another reason).


Question:
We are developing a middleware SDK, both in C++ and Java to be used as a library/DLL by, for example, game developers, animation software developers, Avatar developers to enhance their products.

What I would like to know is this: Are there standard "Best Practices" for the development of these types of API?

I am thinking in terms of usability, readability, efficiency etc.

Answer:
There are lots of ways to design apis, depending on what you are solving. I think a full answer to this question would be worthy off a whole book, such as the
gang of four patterns book
. For Java specifically, and also just OO programming in general, I would recommend
Effective Java 2nd Edition
. The first is general and a lot of popular programming patterns, when they apply and their benefits. Effective Java is Java centered, but parts of it is general enough to apply to any programming language.


Question: Rather than rewriting the entire contents of an xml file when a single element is updated, is there a better alternative to updating the file?

Answer:
I would recommend using VTD-XML
http://vtd-xml.sourceforge.net/
From their FAQ (
http://vtd-xml.sourceforge.net/faq.html
):
Why should I use VTD-XML for large XML files?
For numerous reasons summarized below:
Performance: The performance of VTD-XML is far better than SAX
Ease to use: Random access combined with XPath makes application easy to write
Better maintainability: App code is shorter and simpler to understand.
Incremental update: Occasional, small changes become very efficient.
Indexing: Pre-parsed form of XML will further boost processing performance.
Other features: Cut, paste, split and assemble XML documents is only possible with VTD-XML.
In order to take advantage of VTD-XML, we recommended that developers split their ultra large XML documents into smaller, more manageable  chucks (<2GB).


Question: I have looked in vain for a good example or starting point to write a java based facebook application...  I was hoping that someone here would know of one.  As well, I hear that facebook will no longer support their java API is this true and if yes does that mean that we should no longer use java to write facebook apps??

Answer:
Facebook stopped supporting the official Java API on 5 May 2008 according to their
developer wiki
.
In no way does that mean you shouldn't use Java any more to write FB apps. There are several alternative Java approaches outlined on the wiki.
You might also want to check
this project
out; however, it only came out a few days ago so YMMV.


Question:
I load some XML from a servlet from my Flex application like this:

_loader = new URLLoader();
_loader.load(new URLRequest(_servletURL+"?do=load&id="+_id));

As you can imagine _servletURL is something like http://foo.bar/path/to/servlet

In some cases, this URL contains accented characters (long story). I pass the unescaped string to URLRequest, but it seems that flash escapes it and calls the escaped URL, which is invalid. Ideas?

Answer:
I'm not sure if this will be any different, but this is a cleaner way of achieving the same URLRequest:
```
```
var request:URLRequest = new URLRequest(_servletURL)
request.method = URLRequestMethod.GET;
var reqData:Object = new Object();

reqData.do = "load";
reqData.id = _id;
request.data = reqData;

_loader = new URLLoader(request);
```
```


Question:
Nokia has stopped offering its Developer's Suite, relying on other IDEs, including Eclipse. Meanwhile, Nokia changed its own development tools again and EclipseMe has also changed. This leaves most documentation irrelevant.

I want to know what does it take to make a simple Hello-World?

(I already found out myself, so this is a Q&A for other people to use)

Answer:
Here's what's needed to make a simple hello world -
Get
Eclipse
IDE for Java. I used Ganymede. Set it up.
Get Sun's
Wireless Toolkit
. I used 2.5.2. Install it.
Get Nokia's SDK (
found here
), in my case for S40 6230i Edition, and install it choosing the option to
integrate with Sun's WTK
Follow the instructions at
http://www.eclipseme.org/
to download and install Mobile Tools Java (MTJ). I used version 1.7.9.
When configuring devices profiles in MTJ (inside Eclipse) use the Nokia device from the WTK folder and NOT from Nokia's folder.
Set the WTK root to the main installation folder - for instance c:\WTK2.5.2; Note that the WTK installer creates other folders apparently for backward compatibility.
Get
Antenna
and set its location in MTJ's property page (in Eclipse).
Here's an HelloWorld sample to test the configuration.
Note: It worked for me on WindowsXP.
Also note: This should work for S60 as well. Just replace the S40 SDK in phase 3 with S60's.


Question:
I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using STL techniques such as vectors.

Essentially I want my integer array dimensions to look like:

[ x ][ y ][ z ]

x and y are in the range 20-6000
z is known and equals 4.

Answer:
Have a look at the Boost
multi-dimensional array
library. Here's an example (adapted from the Boost documentation):
```
```
#include "boost/multi_array.hpp"

int main() {
  // Create a 3D array that is 20 x 30 x 4
  int x = 20;
  int y = 30;
  int z = 4;

  typedef boost::multi_array<int, 3> array_type;
  typedef array_type::index index;
  array_type my_array(boost::extents[x][y][z]);

  // Assign values to the elements
  int values = 0;
  for (index i = 0; i != x; ++i) {
    for (index j = 0; j != y; ++j) {
      for (index k = 0; k != z; ++k) {
        my_array[i][j][k] = values++;
      }
    }
  }
}
```
```


Question: What is the dependency inversion principle and why is it important?

Answer:
Check this document out:
The Dependency Inversion Principle
.
It basically says:
High level modules should not depend upon low-level modules. Both should depend upon abstractions.
Abstractions should never depend upon details. Details should depend upon abstractions.
As to why it is important, in short: changes are risky, and by depending on a concept instead of on an implementation, you reduce the need for change at call sites.
Effectively, the DIP reduces coupling between different pieces of code. The idea is that although there are many ways of implementing, say, a logging facility, the way you would use it should be relatively stable in time. If you can extract an interface that represents the concept of logging, this interface should be much more stable in time than its implementation, and call sites should be much less affected by changes you could make while maintaining or extending that logging mechanism.
By also making the implementation depend on an interface, you get the possibility to choose at run-time which implementation is better suited for your particular environment. Depending on the cases, this may be interesting too.


Question:
I would like to move a file or folder from one place to another within the same repository without having to use Repo Browser to do it, and without creating two independent add/delete operations.  Using Repo Browser works fine except that your code will be hanging in a broken state until you get any supporting changes checked in afterwards (like the .csproj file for example).

Update: People have suggested "move" from the command line. Is there a TortoiseSVN equivalent?

Answer:
From the command line, you can type
```
svn mv path1 path2
```
. This will create an add and a delete operation, but there's not really a way around that - as far as I know - in Subversion.


Question:
How do you define your UserControls as being in a namespace below the project namespace, ie. [RootNameSpace].[SubSectionOfProgram].Controls?

Edit due to camainc's answer: I also have a constraint that I have to have all the code in a single project.

Edit to finalise question: As I suspected it isn't possible to do what I required so camainc's answer is the nearest solution.

Answer:
I'm not sure if this is what you are asking, but this is how we do it.
We namespace all of our projects in a consistent manner, user controls are no different. We also namespace using the project settings window, although you could do it through a combination of the project window and in code.
Each solution gets a namespace like this:
```
```
[CompanyName].[SolutionName].[ProjectName]
```
```
So, our user controls are normally in a project called "Controls," which would have a namespace of:
```
```
OurCompany.ThisSolution.Controls
```
```
If we have controls that might span several different solutions, we just namespace it like so:
```
```
OurCompany.Common.Controls
```
```
Then, in our code we will import the library, or add the project to the solution.
```
```
Imports OurCompany
Imports OurCompany.Common
Imports OurCompany.Common.Controls
```
```
We also name the folders where the projects live the same as the namespace, down to but not including the company name (all solutions are assumed to be in the company namespace):
\Projects
\Projects\MySolution
\Projects\MySolution\Controls
-- or --
\Projects\
\Projects\Common
\Projects\Common\Assemblies
\Projects\Common\Controls
etc.
Hope that helps...


Question:
I'm trying to install Laconica, an open-source Microblogging application on my Windows development server using XAMPP as per the instructions provided.

The website cannot find PEAR, and throws the below errors:

Warning: require_once(PEAR.php) [function.require-once]: failed to open stream: No such file or directory in C:\xampplite\htdocs\laconica\lib\common.php on line 31

Fatal error: require_once() [function.require]: Failed opening required 'PEAR.php' (include_path='.;\xampplite\php\pear\PEAR') in C:\xampplite\htdocs\laconica\lib\common.php on line 31

PEAR is located in C:\xampplite\php\pear

phpinfo() shows me that the include path is .;\xampplite\php\pear

What am I doing wrong? Why isn't the PEAR folder being included?

Answer:
Try adding the drive letter:
```
```
include_path='.;c:\xampplite\php\pear\PEAR'
```
```
also verify that PEAR.php is actually there, it might be in \php\ instead:
```
```
include_path='.;c:\xampplite\php'
```
```


Question: What Direct3D render states should be used to implement Java's Porter-Duff compositing rules (CLEAR, SRC, SRCOVER, etc.)?

Answer:
I'm haven't used Java too much, but based on the
white paper from 1984
, it should be a fairly straightforward mapping of render state blend modes.
There are of course more that you can do than just these, like normal alpha blending (SourceAlpha, InvSourceAlpha) or additive (One, One) to name a few.
(I assume that you are asking about these specifically because you are porting some existing functionality? In that cause you may not care about other combinations...)
Anyway, these assume a BlendOperation of Add and that AlphaBlendEnable is true.
Clear
```
```
SourceBlend = Zero
DestinationBlend = Zero
```
```
A
```
```
SourceBlend = One
DestinationBlend = Zero
```
```
B
```
```
SourceBlend = Zero
DestinationBlend = One
```
```
A over B
```
```
SourceBlend = One
DestinationBlend = InvSourceAlpha
```
```
B over A
```
```
SourceBlend = InvDestinationAlpha
DestinationBlend = One
```
```
A in B
```
```
SourceBlend = DestinationAlpha
DestinationBlend = One
```
```
B in A
```
```
SourceBlend = Zero
DestinationBlend = SourceAlpha
```
```
A out B
```
```
SourceBlend = InvDestinationAlpha
DestinationBlend = Zero
```
```
B out A
```
```
SourceBlend = Zero
DestinationBlend = InvSourceAlpha
```
```
A atop B
```
```
SourceBlend = DestinationAlpha
DestinationBlend = InvSourceAlpha
```
```
B atop A
```
```
SourceBlend = InvDestinationAlpha
DestinationBlend = SourceAlpha
```
```
A xor B
```
```
SourceBlend = InvDestinationAlpha
DestinationBlend = InvSourceAlpha
```
```
Chaining these is a little more complex and would require either multiple passes or multiple texture inputs to a shader.


Question:
I'm trying to implement a data compression idea I've had, and since I'm imagining running it against a large corpus of test data, I had thought to code it in C (I mostly have experience in scripting languages like Ruby and Tcl.)

Looking through the O'Reilly 'cow' books on C, I realize that I can't simply index the bits of a simple 'char' or 'int' type variable as I'd like to to do bitwise comparisons and operators.

Am I correct in this perception?   Is it reasonable for me to use an enumerated type for representing a bit (and make an array of these, and writing functions to convert to and from char)?  If so, is such a type and functions defined in a standard library already somewhere?  Are there other (better?) approaches?   Is there some example code somewhere that someone could point me to?

Thanks -

Answer:
It is possible.
To set the nth bit, use OR:
```
```
x |= (1 << 5); // sets the 5th-from right
```
```
To clear a bit, use AND:
```
```
x &= ~(1 << 5); // clears 5th-from-right
```
```
To flip a bit, use XOR:
```
```
x ^= (1 << 5); // flips 5th-from-right
```
```
To get the value of a bit use shift and AND:
```
```
(x & (1 << 5)) >> 5 // gets the value (0 or 1) of the 5th-from-right
```
```
note: the shift right 5 is to ensure the value is either 0 or 1. If you're just interested in 0/not 0, you can get by without the shift.


Question: Is there a way to draw a line along a curved path with a gradient that varies in a direction perpendicular to the direction of the line? I am using the GDI+ framework for my graphics.

Answer: The simple answer is no. You can create a GraphicsPath in order to describe what you would like to draw, using AddPoint/AddLine/AddBezier and so forth as needed to describe the complex path of what you want to draw. When you draw the path you can provide a Brush which can be something like LinearGradientBrush or RadialGradientBrush. Neither of those gradient brushes reacts to the actual path being drawn in the sense of changing direction as the drawing occurs. You have to specify the angles etc as constant for the entire gradient area.


Question:
How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?

I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel.

What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard.

Help, please.

Answer:
It seems to me that you might be better off breaking this into smaller tasks/questions.
You have a few issues you are stuck on from the way it sounds.
You have multiple 'child' windows open. Is this an MDI application?
When an action is performed on one of those child windows, it should fire an event in that window's event handlers. That is your first thing to set up. If this is a datagridview I would suggest a simple test to start. Try trapping the
DataGridView.SelectionChanged
event. Just throw in something like
```
MessageBox.Show("I copied your datas!");
```
for now.
This should get you started where you will at least understand how this event will be raised to you.
From here, we will need to know a little more about your datagrid, and the rows and child controls in those rows. Then we can likely create events in the render events that will be raised at the appropriate times, with the appropriate scope.


Question:
I've been using some basic AOP style solutions for cross-cutting concerns like security, logging, validation, etc.  My solution has revolved around Castle Windsor and DynamicProxy because I can apply everything using a Boo based DSL and keep my code clean of Attributes. I was told at the weekend to have a look at PostSharp as it's supposed to be a "better" solution.  I've had a quick look at PostSharp, but I've been put off by the Attribute usage.

Has anyone tried both solutions and would care to share their experiences?

Answer:
I only looked at castle-windsor for a short time (yet) so I can't comment on that but I did use postsharp.
Postsharp works by weaving at compile time. It ads a post-compile step to your build where it modifies your code. The code is compiled as if you just programmed the cross cutting concerns into you code. This is a bit more performant than runtime weaving and because of the use of attributes Postsharp is very easy to use. I think using attributes for AOP isn't as problematic as using it for DI. But that's just my personal taste.
But...
If you already use castle for dependency injection I don't see a good reason why you shouldn't also use it for AOP stuff. I think though the AOP at runtime is a bit slower than at compile time it's also more powerful. AOP and DI are in my opinion related concepts so I think it's a good idea to use one framework for both. So I'll probably look at the castle stuff again next project I need AOP.


Question:
Is there a standard library method that converts a string that has duration in the standard ISO 8601 Duration (also used in XSD for its duration type) format into the .NET TimeSpan object?

For example, P0DT1H0M0S which represents a duration of one hour, is converted into New TimeSpan(0,1,0,0,0).

A Reverse converter does exist which works as follows:
Xml.XmlConvert.ToString(New TimeSpan(0,1,0,0,0))
The above expression will return P0DT1H0M0S.

Answer:
This will convert from xs:duration to TimeSpan:
```
```
System.Xml.XmlConvert.ToTimeSpan("P0DT1H0M0S")
```
```
See
http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.totimespan.aspx


Question: Is there any difference between a binary semaphore and mutex or are they essentially the same?

Answer:
A
mutex
can be released only by
the thread that had acquired it
.
A
binary semaphore
can be signaled
by any thread
(or process).
so semaphores are more suitable for some synchronization problems like producer-consumer.
On Windows, binary semaphores are more like event objects than mutexes.


Question:
My initial tests have shown that Robot won't work without an active, visible desktop. For example, while a scheduled task (or executed command from the continuous integration server) may be able to start robot as a command-line process, Robot will actually fail to execute the recorded script.

Logging into the build machine to allow it an "active desktop" is not an acceptable solution.

Am I missing something? Is it possible to run a pre-recorded Rational Robot script on a continuous integration server in a manner that doesn't require the machine to be physically logged into?

Answer:
You can run Rational Robot from the command line, so you should be able to set up a scheduled task to run a .BAT file to do this for you. The command is something like:
[path to Rational Robot]\rtrobo [script file] /user "user name" /project [project file] /play /build "build name" /nolog /close
The Robot documentation will have other arguments you can pass in, depending on your situation.
If a simple scheduled task doesn't work, then you can try setting up a STAF (
http://staf.sourceforge.net/index.php
) environment and create a job to run this.
Good luck :)


Question:
I am working with Cognos8 Report Studio. In my report there are two date prompts: START date and END date. Users can select two different dates or make them both the same date. But the report has valid data only for the last business date of each month. For example, if Jan 31 is Sunday, valid data is available only for Jan 29 which is Friday (the last business day of the month).

Can I have a customized "Date Prompt" where I can disable all other dates except the last business day of each month? Users should be able to select only month-end dates and no other dates?

Answer:
You can run Rational Robot from the command line, so you should be able to set up a scheduled task to run a .BAT file to do this for you. The command is something like:
[path to Rational Robot]\rtrobo [script file] /user "user name" /project [project file] /play /build "build name" /nolog /close
The Robot documentation will have other arguments you can pass in, depending on your situation.
If a simple scheduled task doesn't work, then you can try setting up a STAF (
http://staf.sourceforge.net/index.php
) environment and create a job to run this.
Good luck :)


Question:
Is it possible to determine the MAC address of the originator of a remote connection under Windows NT 4? The remote PC opens a socket connection into my application and I can get the IP address. However I need to determine the MAC address from the information available from the socket such as the IP address of the remote device.

I have tried using SendARP but this doesn't seem to be supported in Windows NT4.

Answer: Try GetIpNetTable. This function is documented as supported as of NT 4.0 SP4.


Question:
Developer looking for best method to identify a deadlock on a specific transaction inside a specific thread.  We are getting deadlock errors but these are very general in FB 2.0

Deadlocks happening and they are leading to breakdowns in the DB connection between client and the DB.

We send live ( once a second) data to the DB.

We open a thread pool of around 30 threads and use them to ingest the data ( about 1-2 kB each second).

Sometimes the DB can only take so much that we use the next thread in the pool to keep the stream current as possible.

On occasion this produces a deadlock in addition to reaching the max thread count and breaking the connection.

So we really need opinions on if this is the best method to ingest this amount of data every second.  We have up to 100 on these clients hitting the DB at the same time.

Average transactions are about 1.5 to 1.8 million per day.

Answer:
I don't know of a specific way to identify the particular thread or statement. I've had to deal with FB deadlocks many times. You probably have two theads that are trying to update the same row in some table but they are doing it in separate transactions.
The best solution I've found is to design things so threads never have to update a row that any other thread might update. Sometimes that means having a thread that just exists to update a common table/row. The worker threads send a message to this thread. (The message could be done via another table.)
We run FB in many systems in the field that generate transactions (not millions per day) and we have found FB to be rock solid once we get the design correct.


Question: Hessian is a custom binary serialization protocol, (which is open-source - I think), that forms the basis for a binary cross platform remoting framework. I'd like to know if anyone here has used it, and if so, what sort of performance can we expect from a solution that bridges a Java app on one side with a C# app on the other. (Let us consider that we are serializing simple classes, and may be arrays, lists, dictionaries of simple classes.)

Answer:
This is the sort of problem that web services were designed to solve.  Although no longer simple, the SOAP format allows you to serialize objects to an XML representation on a Java/C# application, transmit them across the wire and deserialize them in the corresponding Java/C# application (Java/C# may be replaced with virtually any language that can translate an XML document).  Although "serialize" is used here, it is also common for this process to be referred as "marshalling".
However, moving away from SOAP for web services is currently being considered by many.  Find out more about web services from Wikipedia:
http://en.wikipedia.org/wiki/Web_services


Question:
For example: man(1), find(3), updatedb(2)?

What do the numbers in parentheses (Brit. "brackets") mean?

Answer:
The section the command is documented in the manual. The list of sections is documented on man's manual. For example:
```
```
man 1 man
man 3 find
```
```
This is useful for when similar or exactly equal commands exist on different sections


Question:
Need to show a credits screen where I want to acknowledge the many contributors to my application.

Want it to be an automatically scrolling box, much like the credits roll at the end of the film.

Answer: A quick and dirty method would be to use a Panel with a long list of Label controls on it that list out the various people and contributions. Then you need to set the Panel to be AutoScroll so that it has a vertical scrollbar because the list of labels goes past the bottom of the displayed Panel. Then add a time that updates the AutoScrollOffset by 1 vertical pixel each timer tick. When you get to the bottom you reset the offset to 0 and carry on. The only downside is the vertical scrollbar showing.


Question:
Could someone write-up a step by step guide to developing a C++ based plugin for FireFox on Windows?

The links and examples on http://www.mozilla.org/projects/plugins/ are all old and inaccurate - the "NEW" link was added to the page in 2004.

The example could be anything, but I was thinking a plugin that lets JavaScript set the name and then displays "Hello {Name}".  To show 2-way communication, it could have a property that returns the full salutation.

Though not as important, it would be nice if the plugin would work in Chrome too.

Answer:
It's fairly simple to make a plugin using NPAPI.  The key header files you'll need from the Gecko distribution are npapi.h and npupp.h.  You'll export functions from your plugin DLL or shared library with the names NP_Initialize, NP_Shutdown, NP_GetMIMEDescription, and NP_GetValue, and you'll need to also fill in the symbol table given to you in the NP_Initialize call with handlers for all of the NPP functions.
The key functions to implement from that set are NPP_New and NPP_Destroy.  Those define the lifecycle of a plugin instance.  If you're going to handle a media file linked from an <object> or <embed>, you'll need to also deal with NPP_NewStream, NPP_WriteReady, NPP_Write, and NPP_DestroyStream as a way for your plugin to get the file's data from the browser.  There's plenty more in
the Gecko Plugin developer's guide
.


Question:
I'm displaying a set of images as an overlay using Google Maps. Displaying these images should be in an endless loop but most most browsers detect this, and display a warning.

Is there a way to make a endless loop in JavaScript so that it isn't stopped or warned against by the browser?

Answer:
Try
setInterval
or
setTimeout
.
Here is an example:
```
```
(show = (o) => setTimeout(() => {

  console.log(o)
  show(++o)

}, 1000))(1);
```
```
```
```
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
```


Question: I've just started developing an ExtJS application that I plan to support with a very lightweight JSON PHP service.  Other than that, it will be standalone. My question is, what is the best way to organize the files and classes that will inevitably come into existence?  Anyone have any experience with large ExtJS projects (several thousand lines).

Answer:
While developing your application your file and folder structure shouldn't really matter as you're probably going to want to minimize the release code and stick it in a single JS file when you're done. An automated handler or build script is probably going to be the best bet for this (see
http://extjs.com/forum/showthread.php?t=44158
).
That said, I've read somewhere on the ExtJS forums that a single file per class is advisable, and I can attest to that from my own experience.


Question:
Sorry for the subject line sounding like an even nerdier Harry Potter title.

I'm trying to use AS3's Socket class to write a simple FTP program to export as an AIR app in Flex Builder 3.  I'm using an FTP server on my local network to test the program.  I can successfully connect to the server (the easy part) but I can't send any commands.  I'm pretty sure that you have to use the ByteArray class to send these commands but there's some crucial piece of information that I'm missing apparently.  Does anyone know how to do this?  Thanks!
Dave

Answer:
We will need more info to resolve this.. What you're saying here appears correct to me. You're using the Socket class to send data though, not ByteArray.
Are you sure data is not being sent? How are you receiving the response? It may be that it's working fine but you're just not aware of it? As i said, tell us more about what you're doing..
Lee Brimelow has a
screencast on gotoAndLearn
of writing an POP3 client. It's essentially the same of what you're doing so take a look.


Question: I'm a very experienced Java programmer who has spent my entire time working with Java 1.4 and earlier.  Where can I find a quick reference that will give me everything I need to know about the new features in Java5 and later in a quick reference?

Answer:
Here's a good place to start:
https://docs.oracle.com/javase/1.5.0/docs/relnotes/features.html
http://java.sun.com/developer/technicalArticles/releases/j2se15/


Question:
When a previous Vim session crashed, you are greeted with the "Swap file ... already exists!" for each and every file that was open in the previous session.

Can you make this Vim recovery prompt smarter? (Without switching off recovery!) Specifically, I'm thinking of:

If the swapped version does not contain unsaved changes and the editing process is no longer running, can you make Vim automatically delete the swap file?

Can you automate the suggested process of saving the recovered file under a new name, merging it with file on disk and then deleting the old swap file, so that minimal interaction is required? Especially when the swap version and the disk version are the same, everything should be automatic.

I discovered the SwapExists autocommand but I don't know if it can help with these tasks.

Answer:
I have vim store my swap files in a single local directory, by having this in my .vimrc:
```
```
set directory=~/.vim/swap,.
```
```
Among other benefits, this makes the swap files easy to find all at once.
Now when my laptop loses power or whatever and I start back up with a bunch of swap files laying around, I just run my
```
cleanswap
```
script:
```
```
TMPDIR=$(mktemp -d) || exit 1
RECTXT="$TMPDIR/vim.recovery.$USER.txt"
RECFN="$TMPDIR/vim.recovery.$USER.fn"
trap 'rm -f "$RECTXT" "$RECFN"; rmdir "$TMPDIR"' 0 1 2 3 15
for q in ~/.vim/swap/.*sw? ~/.vim/swap/*; do
  [[ -f $q ]] || continue
  rm -f "$RECTXT" "$RECFN"
  vim -X -r "$q" \
      -c "w! $RECTXT" \
      -c "let fn=expand('%')" \
      -c "new $RECFN" \
      -c "exec setline( 1, fn )" \
      -c w\! \
      -c "qa"
  if [[ ! -f $RECFN ]]; then
    echo "nothing to recover from $q"
    rm -f "$q"
    continue
  fi
  CRNT="$(cat $RECFN)"
  if diff --strip-trailing-cr --brief "$CRNT" "$RECTXT"; then
      echo "removing redundant $q"
      echo "  for $CRNT"
      rm -f "$q"
  else
      echo $q contains changes
      vim -n -d "$CRNT" "$RECTXT"
      rm -i "$q" || exit
  fi
done
```
```
This will remove any swap files that are up-to-date with the real files.  Any that don't match are brought up in a vimdiff window so I can merge in my unsaved changes.
--Chouser


Question:
I would like to add a DataGridViewTextBoxCell cell to a DataGridViewCell control, but as well as being able to type in the text cell as normal it must also contain a '...' button that once clicks brings up the OpenFileDialog window to allow the user to select a file. Once selected, the text cell will be populated with the full file path.

What is the best way to go about this?

Thanks

Answer:
This
MSDN article explains how to add a custom control to a
```
DataGridView
```
.
You should be able to make a
```
UserControl
```
that has a textbox and button on it and embed that in the
```
DataGridView
```
.


Question: What is the Reuse/Release Equivalence Principle and why is it important?

Answer:
The Reuse/Release Equivalence Principle (REP) says:
The unit of reuse is the unit of release. Effective reuse requires tracking of releases from a change control system. The package is the effective unit of reuse and release.
The unit of reuse is the unit of release
Code should not be reused by copying it from one class and pasting it into another. If the original author fixes any bugs in the code, or adds any features, you will not automatically get the benefit. You will have to find out what's changed, then alter your copy. Your code and the original code will gradually diverge.
Instead, code should be reused by including a released library in your code. The original author retains responsibility for maintaining it; you should not even need to see the source code.
Effective reuse requires tracking of releases from a change control system
The author of a library needs to identify releases with numbers or names of some sort. This allows users of the library to identify different versions. This requires the use of some kind of release tracking system.
The package is the effective unit of reuse and release
It might be possible to use a class as the unit of reuse and release, however there are so many classes in a typical application, it would be burdensome for the release tracking system to keep track of them all. A larger-scale entity is required, and the package fits this need well.
See also Robert Martin's article on
Granularity
.


Question: If Java application requires certain JRE version then how can I check its availability on Mac OS X during installation?

Answer:
It should be as simple as looking at /System/Library/Frameworks/JavaVM.framework/Versions/
E.g. from my machine:
```
```
manoa:~ stu$ ll /System/Library/Frameworks/JavaVM.framework/Versions/
total 56
774077 lrwxr-xr-x  1 root  wheel    5 Jul 23 15:31 1.3 -> 1.3.1
167151 drwxr-xr-x  3 root  wheel  102 Jan 14  2008 1.3.1
167793 lrwxr-xr-x  1 root  wheel    5 Feb 21  2008 1.4 -> 1.4.2
774079 lrwxr-xr-x  1 root  wheel    3 Jul 23 15:31 1.4.1 -> 1.4
166913 drwxr-xr-x  8 root  wheel  272 Feb 21  2008 1.4.2
168494 lrwxr-xr-x  1 root  wheel    5 Feb 21  2008 1.5 -> 1.5.0
166930 drwxr-xr-x  8 root  wheel  272 Feb 21  2008 1.5.0
774585 lrwxr-xr-x  1 root  wheel    5 Jul 23 15:31 1.6 -> 1.6.0
747415 drwxr-xr-x  8 root  wheel  272 Jul 23 10:24 1.6.0
167155 drwxr-xr-x  8 root  wheel  272 Jul 23 15:31 A
776765 lrwxr-xr-x  1 root  wheel    1 Jul 23 15:31 Current -> A
774125 lrwxr-xr-x  1 root  wheel    3 Jul 23 15:31 CurrentJDK -> 1.5
manoa:~ stu$
```
```


Question: How would you make the contents of Flex RIA applications accessible to Google, so that Google can index the content and shows links to the right items in your Flex RIA. Consider a online shop, created in Flex, where the offered items shall be indexed by Google. Then a link on Google should open the corresponding product in the RIA.

Answer:
There is a massive thread available here:
http://tech.groups.yahoo.com/group/flexcoders/message/58926
But essentially, google already indexes .SWF files (you can test this out yourself by restricting search results to just .SWF files). It can search any text content within the SWF file.
However, if the text information in your site comes from a database / web server. Then it won't be able to access this information easily.
One example of getting this to work is using an XML file as your index page, then using an XSLT transform to render it using Flex. "Ted On Flex" has good information about this.
http://flex.org/consultants


Question: How do I select all the columns in a table that only contain NULL values for all the rows?  I'm using MS SQL Server 2005.  I'm trying to find out which columns are not used in the table so I can delete them.

Answer:
```
```
SELECT cols
FROM table
WHERE cols IS NULL
```
```


Question:
I have Sun webserver iws6 (iplanet 6) proxying my bea cluster.
My cluster is under /portal/yadda.
I want anyone who goes to

http://the.domain.com/

to be quickly redirected to

http://the.domain.com/portal/

I have and index.html that does a post and redirect, but the user sometimes sees it.
Does anyone have a better way?

Aaron

I have tried the 3 replies below. None of them worked for me. Back to the drawing board.
A

Answer:
Does this help?
http://docs.sun.com/source/816-5691-10/essearch.htm#25618
To map a URL, perform the following steps:
Open the Class Manager and select the server instance from the drop-down list.
Choose the Content Mgmt tab.
Click the Additional Document Directories link.
The web server displays the Additional Document Directories page.
(Optional) Add another directory by entering one of the following.
URL prefix.
For example: plans.
Absolute physical path of the directory you want the URL mapped to.
For example:
C:/iPlanet/Servers/docs/marketing/plans
Click OK.
Click Apply.
Edit one of the current additional directories listed by selecting one of the following:
Edit
Remove
If editing, select edit next to the listed directory you wish to change.
Enter a new prefix using ASCII format.
(Optional) Select a style in the Apply Style drop-down list if you want to apply a style to the directory:
For more information about styles, see Applying Configuration Styles.
Click OK to add the new document directory.
Click Apply.
Choose Apply Changes to hard start /restart your server.


Question: I have a case where a VB.Net winforms app needs to play WMV files from across the network. The user running the app cannot be given direct access to the network share. Through impersonation, I can see that the files exist (without impersonation, File.Exists returns false for the files on the network share). When I then try to load the file into a Windows Media Player control, the control just remains black. I have deduced that when the Windows Media Player control is loaded into memory, it is running on a separate unmanaged thread than the .Net managed thread. Is there any way to pass that security token from the managed thread to the unmanaged thread? Am I missing something completely?

Answer:
I suppose you tried using
```
```
[DllImport("advapi32.dll", SetLastError=true)]
public static extern int LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
```
```
to log in the network share.
In my experience it doesn't care about threads.
I can show you a usage example if you think it can be useful at all. Kind of a long shot to mention it here.


Question: How can I programatically cause a control's tooltip to show in a Winforms app without needing the mouse to hover over the control?  (P/Invoke is ok if necessary).

Answer:
This is the code I use:
```
```
static HWND hwndToolTip = NULL;

void CreateToolTip( HWND hWndControl, TCHAR *tipText )
{
    BOOL success;

  if( hwndToolTip == NULL )
  {
    hwndToolTip = CreateWindow(  TOOLTIPS_CLASS,
                                 NULL,
                                 WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
                                 CW_USEDEFAULT, CW_USEDEFAULT,
                                 CW_USEDEFAULT, CW_USEDEFAULT,
                                 NULL, NULL,
                                 hInstResource,
                                 NULL );
  }

  if( hwndToolTip )
  {
    TOOLINFO ti;

    ti.cbSize   = sizeof(ti);
    ti.uFlags   = TTF_TRANSPARENT | TTF_SUBCLASS;
    ti.hwnd     = hWndControl;
    ti.uId      = 0;
    ti.hinst    = NULL;
    ti.lpszText = tipText;

    GetClientRect( hWndControl, &ti.rect );

    success = SendMessage( hwndToolTip, TTM_ADDTOOL, 0, (LPARAM) &ti );
  }
}
```
```
Call CreateToolTip function to create a tool tip for a certain control.


Question:
How do I perform an IF...THEN in an SQL SELECT statement?

For example:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product

Answer:
```
```
SELECT
(CASE
     WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
                                            ELSE 'NO'
 END) as Salable
, *
FROM Product
```
```


Question:
Let's say I have a web page that currently accepts a single ID value via a url parameter:

    http://example.com/mypage.aspx?ID=1234

I want to change it to accept a list of ids, like this:

    http://example.com/mypage.aspx?IDs=1234,4321,6789

So it's available to my code as a string via context.Request.QueryString["IDs"].  What's the best way to turn that string value into a List<int>?

Edit: I know how to do .split() on a comma to get a list of strings, but I ask because I don't know how to easily convert that string list to an int list.  This is still in .Net 2.0, so no lambdas.

Answer:
You can use string.Split() to split the values once you have extracted them from the URL.
```
```
string[] splitIds = ids.split(',');
```
```


Question:
I'm absolutely stunned by the fact that MS just couldn't get it right to navigate to the definition of a method, when you're combining C# and VB projects in one solution.  If you're trying to navigate from VB to C#, it brings up the "Object Explorer", and if from C# to VB, it generates a metadata file.

Honestly, what is so complicated about jumping between different languages, especially if they're supposedly using the same CLR?

Does anyone know why this is, or if there's any workaround?
Did they get it right in VS 2008?

@Keith, I am afraid you may be right about your answer.  I am truly stunned that Microsoft screwed this up so badly.  Does anyone have any ideas for a workaround?

@Mladen Mihajlovic - that's exactly the situation I'm describing.  Try it out yourself; project references don't make a shred of difference.

Answer:
This is general to both languages.
F12 in VB.Net always takes you to the object browser
F12 in C# always takes you to a meta-data definition
This is a deliberate mechanism to try and match expected behaviour for upgrading users. The C# way gives you the right information, but the VB way is what users of VBA or VB6 will expect.
The behaviour is the same in VS2008.
These are the rules for external projects, both should take you to the code if it is in the same solution.
You're quite right - VB projects treat C# projects as external and vice versa - you can't navigate from code in one to the other. I've tested this in the latest VS2008 and it's still an issue.
It also fails to get complete meta-data. Add a method to your C# code and it won't appear in VB's intellisense until you compile the C# assembly.
This is similar to how components appear in the toolstrip, so I figure the normal navigate to code functionality is a feature of code with a common compilers, and everything else uses some kind of reflection.
As long as you're still building a PDB it should be able to find the files, I guess it doesn't because they need it to support release builds too. It couldn't find the line of code without the PDB lookups.


Question: Would like to programmically change the connecton string for a database which utilizes the membership provider of asp.net within a windows application. The system.configuration namespace allows changes to the user settings, however, we would like to adjust a application setting? Does one need to write a class with utilizes XML to modify the class? Does one need to delete the current connections (can one select a connection to clear) and add a new one? Can one adjust the existing connection string?

Answer:
You can programatically open the configuration with using the System.configuration namespace:
```
Configuration myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
```
Then you can access the connection strings collection at:
```
myConfig.ConnectionStrings.ConnectionStrings
```
You can modify the collection however you want, and when done call
```
.Save()
```
on the configuration object.


Question: Shoes has some built in dump commands (Shoes.debug), but are there other tools that can debug the code without injecting debug messages throughout?  Something like gdb would be great.

Answer:
Have you looked at the ruby-debug gem?
```
```
% sudo gem install ruby-debug
```
```
The rdebug executable gives you a similar interface to gdb (breakpoint setting, etc).  You just simply execute your script with rdebug instead of ruby.
You can also do something like this to avoid manually setting breakpoints:
```
```
class Foo
  require 'ruby-debug'
  def some_method_somewhere
    debugger # acts like a breakpoint is set at this point
  end
end
```
```
Here's a tutorial on ruby-debug:
http://www.datanoise.com/articles/2006/7/12/tutorial-on-ruby-debug


Question:
I would like to save the programs settings every time the user exits the program. So I need a way to call a function when the user quits the program. How do I do that?

I am using Java 1.5.

Answer:
You can add a shutdown hook to your application by doing the following:
```
```
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run() {
        // what you want to do
    }
}));
```
```
This is basically equivalent to having a try {} finally {} block around your entire program, and basically encompasses what's in the finally block.
Please note the
caveats
though!


Question:
Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data?

In other words, let's assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic operations are well defined. So, I would like to be able to write Fraction<int> frac = new Fraction<int>(1,2) and/or Fraction<double> frac = new Fraction<double>(0.1, 1.0).

Unfortunately there is no interface representing the four basic operations (+,-,*,/). Has anybody found a workable, feasible way of implementing this?

Answer:
First, your class should limit the generic parameter to primitives ( public class Fraction where T : struct, new() ).
Second, you'll probably need to create
implicit cast overloads
so you can handle casting from one type to another without the compiler crying.
Third, you can overload the four basic operators as well to make the interface more flexible when combining fractions of different types.
Lastly, you have to consider how you are handling arithmetic over and underflows.  A good library is going to be extremely explicit in how it handles overflows; otherwise you cannot trust the outcome of operations of different fraction types.


Question: Is there a way I can configure the MidPointRounding enumeration default setting in a config file (I.e. web.config or app.config)  I have a considerable source code base, and I need to configure at the application scope how rounding will occur, whether used in Math.Round or decimal type rounding...  I would like to do this in order to get consistent rounding results throughout the application without changing every line that works with a decimal type or uses Math.Round....

Answer:
Enum.Parse() is your friend here
```
```
MyEnum GetEnumValue(string enumString) {
  return (MyEnum)Enum.Parse(typeof(MyEnum),enumString);
}
```
```
Obviously you'd also need some error-checking on the string you're getting from you're config file in which case you might want to return a default.


Question:
Why does the default IntelliJ default class javadoc comment use non-standard syntax? Instead of creating a line with "User: jstauffer" it could create a line with "@author jstauffer". The other lines that it creates (Date and Time) probably don't have javadoc syntax to use but why not use the javadoc syntax when available?

For reference here is an example:

/**
 * Created by IntelliJ IDEA.
 * User: jstauffer
 * Date: Nov 13, 2007
 * Time: 11:15:10 AM
 * To change this template use File | Settings | File Templates.
 */

Answer:
I'm not sure why Idea doesn't use the
```
@author
```
tag by default.
But you can change this behavior by going to
```
File -> Settings -> File Templates
```
and editing the
```
File Header
```
entry in the
```
Includes
```
tab.
As of IDEA 14 it's:
```
File -> Settings -> Editor -> File and Code Templates -> Includes -> File Header
```


Question:
I am developing a web page code, which fetches dynamically the content from the server and then places this content to container nodes using something like

container.innerHTML = content;

Sometimes I have to overwrite some previous content in this node. This works fine, until it happens that previous content occupied more vertical space then a new one would occupy AND a user scrolled the page down -- scrolled more than new content would allow, provided its height.

In this case the page redraws incorrectly -- some artifacts of the old content remain. It works fine, and it is even possible to get rid of artifacts, by minimizing and restoring the browser (or force the window to be redrawn in an other way), however this does not seem very convenient.

I am testing this only under Safari (this is a iPhone-optimized website).

Does anybody have the idea how to deal with this?

Answer:
It sounds like you are having a problem with the browser itself.  Does this problem only occur in one browser?
One thing you might try is using a lightweight library like
jQuery
.  It handles browser differences fairly nicely.  To set the inner HTML for a div with the ID of
container
you would simply write this:
```
```
$('#container').html( content );
```
```
That will work in most browsers.  I do not know if it will fix your problem specifically or not but it may be worth a try.


Question:
I want to implement in Java a class for handling graph data structures. I have a Node class and an Edge class. The Graph class maintains two list: a list of nodes and a list of edges. Each node must have an unique name. How do I guard against a situation like this:

Graph g = new Graph();

Node n1 = new Node("#1");
Node n2 = new Node("#2");

Edge e1 = new Edge("e#1", "#1", "#2");

// Each node is added like a reference
g.addNode(n1);
g.addNode(n2);
g.addEdge(e1);

// This will break the internal integrity of the graph
n1.setName("#3");
g.getNode("#2").setName("#4");

I believe I should clone the nodes and the edges when adding them to the graph and return a NodeEnvelope class that will maintain the graph structural integrity. Is this the right way of doing this or the design is broken from the beginning ?

Answer:
In my opinion you should never clone the element unless you explicitly state that your data structure does that.
The desired functionality of most things needs the actual object to be passed into the data structure by-reference.
If you want to make the
```
Node
```
class safer, make it an inner class of the graph.


Question:
The SQL Server Express 2008 setup allow you to assign different user account for each service.

For a development environment, would you use a domain user, local user, NT Authority\NETWORK SERCVICE, NT Authority\Local System or some other account and why?

Answer:
It depends.
Local System - Never, it's too high
a privilege.
Network Service -
Perhaps, if you need to connect to
network resources, but that's
doubtful.
Local Service - Probably
the best choice, limited privileges,
do not unlock network connections
Local interactive user? Does it
truly need to have login rights, or
act as a user?
Domain user? Goodness
no, not unless you're accessing
network drives from within it; if
SQL runs amok then an attacker is
authenticated against the domain.


Question: Semantically speaking, is there an appropriate place in today's websites (late 2008+) where using the bold <b> and italic <i> tags are more useful than the more widely used <strong> and <em> tags?

Answer:
Never. They are removed in XHTML 2.0 as they are presentational tags.  CSS should be used to bold/italicise content.
edit:
If you're looking for a purely presentational tag, that's what the
```
SPAN
```
tag with a class and a little CSS is for.


Question:
I have a Java application that launches another java application.  The launcher has a watchdog timer and receives periodic notifications from the second VM.  However, if no notifications are received then the second virtual machine should be killed and the launcher will perform some additional clean-up activities.

The question is, is there any way to do this using only java? so far I have to use some native methods to perform this operation and it is somehow ugly.

Thanks!

Answer:
You should be able to do that
```
java.lang.Runtime.exec
```
and shell commands.


Question: How can I find what databases I have a minimum of read access to in either basic SQL, MySQL specific or in PHP?

Answer:
In MySQL, you can execute
```
SHOW DATABASES;
```
Description
```
SHOW DATABASES;
```
to see what you have at least minimal access to. Are you looking for something more programmatic?


Question:
As I build *nix piped commands I find that I want to see the output of one stage to verify correctness before building the next stage but I don't want to re-run each stage. Does anyone know of a program that will help with that? It would keep the output of the last stage automatically to use for any new stages. I usually do this by sending the result of each command to a temporary file (i.e. tee or run each command one at a time) but it would be nice for a program to handle this.

I envision something like a tabbed interface where each tab is labeled with each pipe command and selecting a tab shows the output (at least a hundred lines) of applying that command to to the previous result.

Answer:
Use 'tee' to copy the intermediate results out to some file as well as pass them on to the next stage of the pipe, like so:
```
```
cat /var/log/syslog | tee /tmp/syslog.out | grep something | tee /tmp/grep.out | sed 's/foo/bar/g' | tee /tmp/sed.out | cat >>/var/log/syslog.cleaned
```
```


Question: I talked to a few friends who say that Drupal is amazing, and it is a way better than Joomla. What are the major differences/advantages?

Answer:
The
API
. Every form and pretty much every bit of functionality can be modified via a module that hooks into the API, without having touch core code.  This makes upgrades
much
easier, as your customisations aren't overwritten.
The code it outputs by default is much nicer, as well.


Question:
Does Java impose any extra restrictions of its own. Windows (upto Vista) does not allow names to include

\ / < > ? * :

I know HOW to validate names (a regular expression).

I need to validate filenames entered by users.

My application does not need to run on any other platform, though, of course, I would prefer to be platform independent!

Answer:
No, you can escape any character that Java doesn't allow in String literals but the filesystem allows.
Also, if trying to port an Windows app to Mac or Unix it is best to use:
```
```
File.separator
```
```
To determine the correct file separator to use on each platform.


Question: As a programmer I have no idea how one would go about programming menus for a DVD, I have heard that this is possible, and even seen basic games using DVD menus - although it may very well be a closed-system. Is it even possible and if so, what language, compilers etc exist for this?

Answer:
There are a couple of open source projects that can create DVDs plus menus. I recently used
dvd-slideshow
to create a simple dvd with menus etc. Another one is
DVD Styler
. All of these programs are basically a front-end for various command-line tools for encoding, menu creation etc. Since these are open source projects you can have a look at the source and check out how they accomplish this.


Question: Is there a preferred way to handle animation when using Flex -- For instance, if I want to render a ball and bounce it around the screen?

Answer:
I prefer to use a tweening library for things like this.  Check these out:
Tweener
TweenLite / TweenMax
KitchenSync
I've had good luck actually using the first two, and have read great things about the last one.


Question: Struts 1.3 application.  Main website is NOT served by struts/Java.  I need to forward the result of a struts action to a page in the website, that is outside of the struts context.  Currently, I forward to a JSP in context and use a meta-refresh to forward to the real location.  That seems kinda sucky.  Is there a better way?

Answer:
You can't "forward", in the strict sense. Just call
```
sendRedirect()
```
on the
```
HttpServletResponse
```
object in your
```
Action
```
class's
```
execute()
```
method and then,
```
return null
```
.
Alternately, either call
```
setModule()
```
on the
```
ActionForward
```
object (that you are going to return) or set the path to an absolute URI.


Question: Out of the box SSRS reports cannot have data exposed in the page header.  Is there a way to get this data to show?

Answer: You have to do it through Parameters. Add a parameter for each piece of data you would like to display, then set the parameter to Hidden. Then set the default value to "From Query" and set the Dataset and Value field to the appropriate values.


Question:
Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.

Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.

See also:

Hidden features of C#

Hidden features of Java

Hidden features of JavaScript

Hidden features of Ruby on Rails

Hidden features of Python

(Please, just one hidden feature per answer.)

Thank you

Answer:
I find using the
define_method
command to dynamically generate methods to be quite interesting and not as well known.  For example:
```
```
((0..9).each do |n|
    define_method "press_#{n}" do
      @number = @number.to_i * 10 + n
    end
  end
```
```
The above code uses the 'define_method' command to dynamically create the methods "press1" through "press9."  Rather then typing all 10 methods which essentailly contain the same code, the define method command is used to generate these methods on the fly as needed.


Question:
I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be outdated.

How would I make the year update automatically with PHP 4 or PHP 5?

Answer:
```
```
<?php echo date("Y"); ?>
```
```


Question: Is there a way to auto discover a specific WCF service in the network? I don't want to config my client with the address if this is possible.

Answer:
What you want to look at is the WS-Discovery protocol.  I found a sample on
netfx3's
website of using the
specification
.  I would recommend searching services based on scope, by probing for services based on a specific endpoint.


Question: It's a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?

Answer:
A safe way is to serialize the object, then deserialize.  This ensures everything is a brand new reference.
Here's an article
about how to do this efficiently.
Caveats: It's possible for classes to override serialization such that new instances are
not
created, e.g. for singletons.  Also this of course doesn't work if your classes aren't Serializable.


Question: How do I change font size on the DataGridView?

Answer:
Use the Font-property on the gridview. See MSDN for details and samples:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.font.aspx


Question:
I have a small diagnostic VB.Net application ( 2 forms, 20 subs & functions) written using VB.Net 2008 that targets Framework 2.0 and higher, but now I realize I need to support Framework 1.1.   I'm looking for the most efficient way to accomplish this given these constraints:

I don't know which parts of the application are 2.0-specific.

I could reconstruct the forms without too much trouble.

I need to support SharpZipLib

My current idea is to find and install VB.Net 2003, copy over my code and iteratively re-create the tool.  Are there better options?

Answer: Probably not. If you don't understand which bits are 2.0-specific, you're probably going to have to go the trial-and-error route. However, you can probably save yourself quite a bit of work if you go looking for generics beforehand. In my experience, those are the most numerous 1.1-incompatible bits that tend to make it into my code.


Question:
In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class?

So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class.

The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable.

Answer:
A class is a template, it allows you to create a blueprint, you can then have multiple instances of a class each with different numbers, like so.
```
```
class dog(object):
    def __init__(self, height, width, lenght):
        self.height = height
        self.width = width
        self.length = length

    def revert(self):
        self.height = 1
        self.width = 2
        self.length = 3

dog1 = dog(5, 6, 7)
dog2 = dog(2, 3, 4)

dog1.revert()
```
```


Question:
When a script is saved as a bundle, it can use the localized string command to find the appropriate string, e.g. in Contents/Resources/English.lproj/Localizable.strings. If this is a format string, what is the best way to fill in the placeholders? In other words, what is the AppleScript equivalent of +[NSString stringWithFormat:]?

One idea I had was to use do shell script with printf(1). Is there a better way?

Answer:
As ugly as it is, calling out to
```
printf(1)
```
is the common solution.
A cleaner, though somewhat more complex, solution is to use AppleScript Studio, which allows you to call into Objective-C objects/classes from your AppleScript code with the
```
call method
```
syntax documented
here
.
With that, you'd be able to use something like this:
```
```
call method "stringWithFormat:" of class "NSString" with parameters {formatString, arguments}
```
```
The downside of this, of course, is that you need to write an AppleScript Studio app instead of just writing a simple script. You do get a good bit more flexibility in general with Studio apps, though, so it's not all together a terrible route to go.


Question:
I'm reading lines of text that can come in any order. The problem is that the output can actually be indentical to the previous output. How can I detect this, without sorting the output first?

Is there some kind of hash function that can take identical input, but in any order, and still produce the same result?

Answer:
So you have input like
```
```
A B C D
D E F G
C B A D
```
```
and you need to detect that the first and third lines are identical?


Question:
I'm using an identical call to "CryptUnprotectData" (exposed from Crypt32.dll) between XP and Vista. Works fine in XP. I get the following exception when I run in Vista:

"Decryption failed. Key not valid for use in specified state."

As expected, the versions of crypt32.dll are different between XP and Vista (w/XP actually having the more recent, possibly as a result of SP3 or some other update).

More specifically, I'm encrypting data, putting it in the registry, then reading and decrypting using "CryptUnprotectData". UAC is turned off.

Anyone seen this one before?

Answer:
The
CryptUnprotectData function
documentation states that it usually only works when the user has the same logon credentials as the encrypter.
This suggests to me that maybe the key is tied to the user's current token. Since you mention Vista, this makes me think UAC and restricted tokens.
Can you show us some code? Can you give us more information about what you're doing with the data -- i.e. are you moving it between processes, or users, or computers?


Question:
We create new sites in IIS 6 (Windows Server 2003) using IIS Manager.  When these sites are created in IIS 6, the ASP.NET version defaults to ASP.NET 1.1.  We would like it to default to ASP.NET 2.0.  The reason this is a problem for us is that when you take any site on the server and switch the ASP.NET version from ASP.NET 1.1 to ASP.NET 2.0, all web sites recycle.

Is there a setting in the IIS metabase that controls this or a way to create a site via script that sets the ASP.Net version correctly so that we can avoid the IIS reset when setting up each site?

Answer:
Find the directory for the version of .Net you want, for example;
C:\Windows\Microsoft.NET\Framework\v2.0.50727
Get a cmd prompt there and then run aspnet_regiis -i.
Further info @
http://weblogs.asp.net/owscott/archive/2006/05/30/ASPNet_5F00_regiis.exe-tool_2C00_-setting-the-default-version-without-forcing-an-upgrade-on-all-sites.aspx
Ryan


Question: Does emacs have something like vi's “set number”, so that each line starts with its line number?

Answer:
Take a look at this article. It explains various ways to add line numbers to emacs:
http://www.emacswiki.org/cgi-bin/wiki/LineNumbers


Question: The design for the website I am working on calls for a custom image on lists instead of a bullet.  Using the image is fine, but I have been having difficulties ensuring that it is centered against the text of the list item across all browsers.  Does anyone know of a standard solution for this?

Answer:
Have you tried adding the following code in your CSS file?
```
```
li
{
   background-image: URL('custom.png');
   background-repeat: no-repeat;
   background-position: center;
}
```
```


Question:
I'm trying to load a page that is basically an edit form inside a
dialog (ui.dialog).  I can load this page fine from an external (I'm
using asp.net) page.

The problem is that inside of my "popup" form, I need to $(function()
{my function here}); syntax to do some stuff when the page loads,
along with registering some .fn extensions for some dynamic dropdowns
using ajax calls.

I have created my <script type="text/javascript" src="jquery.js"> but
I don't think these are being included, and also my $(function) is not
being called.

Is this possible to do or do I need to find another way of
accomplishing what I need to do?

Answer:
If you really need to load that form via AJAX you could to do all the Javascript stuff in  $.ajax callback itself.
So, you load the popup form like this:
```
```
$.ajax({
   //...
   success: function(text) {
       // insert text into container
       // the code from $(function() {});
   }
});
```
```


Question:
Emacs:  C-U (79) # » a pretty 79 character length divider

VIM:  79-i-# » see above

Textmate: ????

Or is it just assumed that we'll make a Ruby call or have a snippet somewhere?

Answer:
I would create a bundle command to do this.
You can take editor selection as input to your script, then replace it with the result of execution.  This command, for example, will take a selected number and print the character '#' that number of times.
```
```
python -c "print '#' * $TM_SELECTED_TEXT"
```
```
Of course this example doesn't allow you to specify the character, but it gives you an idea of what's possible.


Question: I want to serve a lot of big files in a Plone site. By big files I mean around 5MB (music) and a lot of them. I've already do it straight to the ZODB, not a good idea. I'm running Plone 3.1.1 and Zope 2.10.6.

Answer:
As you may already know, the long-term solution for this is supposed to be the ZODB BLOB support.
Ticket 6805
is probably the most authorative source on this. Unfortunately, the milestone is set to 4.0, and running it in production on an older release is perhaps not a good solution.
There has, historically, existed a lot of Plone products for storing files externally, keeping only metadata in the ZODB. I have tried several of them, and from my experience, there is not a single one that works well with current Plone/Zope releases. Don't trust me on this, though, I have not tried any products of this type the last year or so.
Personally, I would go for a solution that is as simple as possible and doesn't involve Plone more than neccesary. Storing the music files on disk, serving them directly from apache/whatever web server you use, keeping only metadata in Plone - in a product you write yourself, will give you a robust solution with good performance. That is, your product should produce links to a path on your web server where the music files are available.
If you require authorization for download of the music files and assuming that you run lighthttpd or apache in front of your Zope, looking at a solution based on X-sendfile is probably the best option. With X-sendfile, you keep the files on disk, and add a header (X-sendfile) to the response when a music file should be sent to the client browser. The web server will pick this header up and send the file to the client, without Plone being involved.
Some pointers:
http://tn123.ath.cx/mod_xsendfile/
(The apache module)
http://john.guen.in/past/2007/4/17/send_files_faster_with_xsendfile/
(Ruby example)


Question: I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients.  Security is also an issue - so secure login would be a plus.  I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.

Answer:
Pyro
(Python Remote Objects) is fairly clever if all your server/clients are going to be in Python. I use
XMPP
alot though since I'm communicating with hosts that are not always Python. XMPP lends itself to being extended fairly easily too.
There is an excellent XMPP library for python called
PyXMPP
which is reasonably up to date and has no dependancy on Twisted.


Question: I'd like to convert a Parallels Virtual Machine image on my mac into an image usable by Virtual PC 2007.  Does anyone know how to do that, or if it is possible?

Answer:
It looks like qemu-img from
qemu
can do this, at least looking at its commandline help on a Ubuntu 8.04 machine where it claims support for, among others, the "parallels" and the "vpc" format.
Have not tried myself, though. Hope this helps.


Question: Is there a good .Net implementation of the NNTP protocol?

Answer:
There is a C# tutorial for reading posts using NNTP
here
.  It should be enough to get you started but if you wish to start getting into processing binary posts, you're probably going to have to deal with some mime-type content too.  I don't think this article covers that.


Question: I'd like to use alternatives to System Center Virtual Machine Manager 2008 is possible, in other words, any FREE tools?

Answer:
Google "Pysical to virtual conversion" or P2V.  There are several solutions available.  Unfortunately it sounds as though not many have had success with Microsoft's solution.
Try the following:
1. Download and install the VMWare Converter and follow the instructions to convert the physical machine.
2. Download the VMWare to VHD conversion utility from VMToolkit.com and convert the image.
This didn't work for me when I tried it last week, but I think it is because the drive I converted used PGP.