Question:
I've read on Wikipedia and other sites about OSGi, but I don't really see the big picture. It says that it's a component-based platform, and that you can reload modules at runtime. Also the "practical example" given everywhere is the Eclipse Plugin Framework.

My questions are:

What is the clear and simple definition of OSGi?

What common problems does it solve?

By "common problems" I mean problems we face everyday, like "What can OSGi do for making our jobs more efficient/fun/simple?"

Answer:
edited for clarity. OSGi page gave a better simple answer than mine
A simple answer: An OSGi Service Platform provides a standardized, component-oriented computing environment for cooperating networked services. This architecture significantly reduces the overall complexity of building, maintaining and deploying applications.
The OSGi Service Platform provides the functions to change the composition dynamically on the device of a variety of networks, without requiring a restarts.
In a single application structure, say the Eclipse IDE, it's not a big deal to restart when you install a new plugin. Using the OSGi implementation completely, you should be able to add plugins at runtime, get the new functionality, but not have to restart eclipse at all.
Again, not a big deal for every day, small application use.
But, when you start to look at multi-computer, distributed application frameworks, that's where it starts to get interesting. When you have to have 100% uptime for critical systems, the capability to hotswap components or add new functionality at runtime is useful. Granted, there are capabilities for doing this now for the most part, but OSGi is trying to bundle everything into a nice little framework with common interfaces.
Does OSGi solve common problems, I'm not sure about that. I mean, it can, but the overhead may not be worth it for simpler problems. But it's something to consider when you are starting to deal with larger, networked, applications.


Question:
lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data.

What are some of the most common and useful ways of using lsof, and which command-line switches are used for that?

Answer:
```
lsof -i
```
will provide a list of open network sockets. The
```
-n
```
option will prevent DNS lookups, which is useful when your network connection is slow or unreliable.


Question:
I have an application where a Hilbert R-Tree (wikipedia) (citeseer) would seem to be an appropriate data structure.  Specifically, it requires reasonably fast spatial queries over a data set that will experience a lot of updates.

However, as far as I can see, none of the descriptions of the algorithms for this data structure even mention how to actually calculate the requisite Hilbert Value; which is the distance along a Hilbert Curve to the point.

So any suggestions for how to go about calculating this?

Answer:
Fun question!
I did a bit of googling, and the good news is, I've found an implementation of Hilbert Value.
The potentially bad news is, it's in Haskell...
http://www.serpentine.com/blog/2007/01/11/two-dimensional-spatial-hashing-with-space-filling-curves/
It also proposes a Lebesgue distance metric you might be able to compute more easily.


Question:
In my model I have:

validate :my_custom_validation

def my_custom_validation
 errors.add_to_base("error message") if condition.exists?
end

I would like to add some parameters to mycustomer vaildation like so:

validate :my_custom_validation, :parameter1 => x, :parameter2 => y

How do I write the mycustomvalidation function to account for parameters?

Answer:
You can just do something like this:
```
```
def validate
  errors.add('That particular field', 'can not be the value you presented') if !self.field_to_check.blank? && self.field_to_check == 'I AM COOL'
end
```
```
No need to call reference it, as I believe the validate method is processed (if it exists) after any validates_uniqueness_of -like validations.
Added: More information in the Rails API docs
here
.


Question:
I'm at a point in my freelance career where I've developed several web applications for small to medium sized businesses that support things such as project management, booking/reservations, and email management.

I like the work but find that eventually my applications get to a point where the overhear for maintenance is very high. I look back at code I wrote 6 months ago and find I have to spend a while just relearning how I originally coded it before I can make a fix or feature additions. I do try to practice using frameworks (I've used Zend Framework before, and am considering Django for my next project)

What techniques or strategies do you use to plan out an application that is capable of handling a lot of users without breaking and still keeping the code clean enough to maintain easily?
If anyone has any books or articles they could recommend, that would be greatly appreciated as well.

Answer:
You should consider maybe using SharePoint. It's an environment that is already designed to do all you have mentioned, and has many other features you maybe haven't thought about (but maybe you will need in the future :-) )
Here
's some information from the official site.
There are 2 different SharePoint environments you can use: Windows Sharepoint Services (WSS) or Microsoft Office Sharepoint Server (MOSS). WSS is free and ships with Windows Server 2003, while MOSS isn't free, but has much more features and covers almost all you enterprise's needs.


Question: Anyone have a good set of sqlplus configuration directives to help transform a given sql query into nicely tab separated output for pulling into a spreadsheet or further processing?

Answer:
Check out the Oracle documentation:
Formatting SQLPlus Reports
Generating HTML Reports from SQLPlus
You can generate a tab in Oracle by using the tab's ASCII value 9 and the chr function:
```
```
select chr(9) from dual;
```
```


Question:
With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.

Any place where we still have to use delegates and lambda expressions won't work?

Answer:
lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:
```
```
delegate(int i) { Console.WriteLine(i.ToString()) }
```
```
can be replaced with
```
```
f => Console.WriteLine(f.ToString())
```
```


Question:
I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds?

FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.

Answer:
Just call
```
.getClass()
```
on each
```
Object
```
in a loop.
Unfortunately, Java doesn't have
```
map()
```
. :)


Question:
I have a list of ranked users, and would like to select the top 50. I also want to make sure one particular user is in this result set, even if they aren't in the top 50. Is there a sensible way to do this in a single mysql query? Or should I just check the results for the particular user and fetch him separately, if necessary?

Thanks!

Answer:
If I understand correctly, you could do:
```
```
select * from users order by max(rank) desc limit 0, 49
union
select * from users where user = x
```
```
This way you get 49 top users plus your particular user.


Question:
The built-in PHP extension for SOAP doesn't validate everything in the incoming SOAP request against the XML Schema in the WSDL. It does check for the existence of basic entities, but when you have something complicated like simpleType restrictions the extension pretty much ignores their existence.

What is the best way to validate the SOAP request against XML Schema contained in the WSDL?

Answer:
Typically one doesn't validate against the WSDL.  If the WSDL is designed properly there should be an underlying xml schema (XSD) to validate the body of the request against.  Your XML parser should be able to do this.
The rest is up to how you implement the web service and which SOAP engine you are using.  I am not directly familiar with the PHP engine.  For WSDL/interface level "validation" I usually do something like this:
Does the body of the request match a known request type and is it valid (by XSD)?
Does the message make sense in this context and can i map it to an operation/handler?
If so, start processing it
Otherwise: error


Question: How can I load an external JavaScript file using a bookmarklet?  This would overcome the URL length limitations of IE and generally keep things cleaner.

Answer:
2015 Update
Content security policy
will prevent this from working in many sites now. For example, the code below won't work on Facebook.
2008 answer
Use a bookmarklet that creates a script tag which includes your external JS.
As a sample:
```
```
javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})();
```
```


Question:
Before you answer: Yes I have read the jtable tutorial over at Sun. No, it did not help me. Yes, I am a dolt. Please don't answer with a reference to that document. What I am specifically interested in is how to dynamically add rows and columns to my Jtable via the Netbeans IDE. I already have an object that contains a hashmap with my data. I can't figure out where or what object I should be passing that object to. Thanks for your time!

I have a vector that contains a series (of length l) of objects (each one corresponding to a row). How do I get that vector object to display on the JTable?

Answer:
A
```
JTable
```
uses a
```
TableModel
```
to hold its data. Your hash/vector of data will need to be adapted to be used; you can write a
```
TableModel
```
implementation, using the hash/vector as backing data, or, if you won't be dynamically updating the hash/vector and needing it to show automatically, you can simply copy everything into an instance of
```
DefaultTableModel
```
, and use that.
If you do use an adapter, and dynamically update the hash/vector, remember that all updates must be done in the event dispatch thread. :-)


Question:
I have a setup executable that I need to install. When I run it, it launches a msi to do the actual install and then dies immediately. The side effect of this is it will return control back to any console you call it from before the install finishes. Depending on what machine I run it on, it can take from three to ten minutes so having the calling script sleep is undesirable. I would launch the msi directly but it complains about missing components.

I have a WSH script that uses WMI to start a process and then watch until it's pid is no longer running. Is there some way to determine the pid of the MSI the initial executable is executing, and then watch for that pid to end using WMI? Is the launching process information even associated with a process?

Answer:
Would doing a WMI lookup of processes that have the initial setup as the parent process do the trick?  For example, if I launch an MSI from a command prompt with process id 4000, I can execute the following command line to find information about msiexec process:
```
```
c:\>wmic PROCESS WHERE ParentProcessId=4000 GET CommandLine, ProcessId
CommandLine                                                 ProcessId
"C:\Windows\System32\msiexec.exe" /i "C:\blahblahblah.msi"  2752
```
```
That may be one way to find the information you need.  Here is a demo of looking up that information in vbs:
```
```
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("select * from Win32_Process where ParentProcessId = 4000")
For Each objProcess in colProcesses
    Wscript.Echo "Process ID: " & objProcess.ProcessId
Next
```
```
I hope this helps.


Question:
I have this line in a javascript block in a page:

res = foo('<%= @ruby_var %>');

What is the best way to handle the case where @ruby_var has a single-quote in it? Else it will break the JavaScript code.

Answer:
```
```
@ruby_var.gsub(/[']/, '\\\\\'')
```
```
That will escape the single quote with an apostrophe, keeping your Javascript safe!
Also, if you're in Rails, there are a bunch of
Javascript-specific tools
.


Question: What is a smart pointer and when should I use one?

Answer:
http://en.wikipedia.org/wiki/Smart_pointer
In computer science, a smart pointer
  is an abstract data type that
  simulates a pointer while providing
  additional features, such as automatic
  garbage collection or bounds checking.
  These additional features are intended
  to reduce bugs caused by the misuse of
  pointers while retaining efficiency.
  Smart pointers typically keep track of
  the objects that point to them for the
  purpose of memory management. The
  misuse of pointers is a major source
  of bugs: the constant allocation,
  deallocation and referencing that must
  be performed by a program written
  using pointers makes it very likely
  that some memory leaks will occur.
  Smart pointers try to prevent memory
  leaks by making the resource
  deallocation automatic: when the
  pointer to an object (or the last in a
  series of pointers) is destroyed, for
  example because it goes out of scope,
  the pointed object is destroyed too.


Question:
The default rails XML builder escapes all HTML, so something like:

atom_feed do |feed|
  @stories.each do |story|
    feed.entry story do |entry|
      entry.title story.title
      entry.content "<b>foo</b>"
    end
  end
end

will produce the text:

<b>foo</b>

instead of: foo

Is there any way to instruct the XML builder to not escape the XML?

Answer:
turns out you need to do
```
```
entry.content "<b>foo</b>", :type => "html"
```
```
althought wrapping it in a CDATA stops it working.


Question:
I use this code in my Windows Service to be notified of USB disk drives being inserted and removed:

WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent",
    "TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2");
query.WithinInterval = TimeSpan.FromSeconds(1);
_deviceWatcher = new ManagementEventWatcher(query);
_deviceWatcher.EventArrived += new EventArrivedEventHandler(OnDeviceEventArrived);
_deviceWatcher.Start();

It works on XP and Vista, but on XP I can hear the very noticeable sound of the hard drive being accessed every second. Is there another WMI query that will give me the events without the sound effect?

Answer:
Not sure if this applies to your case but we've been using RegisterDeviceNotification in our C# code (which I can't post here) to detect when USB devices are plugged in. There's a handful of native functions you have to import but it generally works well. Easiest to make it work in C++ first and then see what you have to move up into C#.
There's some stuff on koders Code search that appears to be a whole C# device management module that might help:
http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx


Question:
I have a Perl script where I maintain a very simple cache using a hash table. I would like to clear the hash once it occupies more than n bytes, to avoid Perl (32-bit) running out of memory and crashing.

I can do a check on the number of keys-value pairs:

if (scalar keys %cache > $maxSize)
 {
 %cache = ();
 }

But is it possible to check the actual memory occupied by the hash?

Answer:
You're looking for
Devel::Size
NAME
Devel::Size - Perl extension for finding the memory usage of Perl variables
SYNOPSIS
```
```
use Devel::Size qw(size total_size);

my $size = size("A string");
my @foo = (1, 2, 3, 4, 5);
my $other_size = size(\@foo);
my $foo = {a => [1, 2, 3],
        b => {a => [1, 3, 4]}
       };
my $total_size = total_size($foo);
```
```


Question:
There is a lot of relativity involved in working with exceptions. Beyond low level APIs where exceptions cover errors raised from hardware and the OS there is a shady area where the programmer decides what constitutes an exception and what is a normal condition.

How do you decide when to use exceptions? Do you have a consistent policy regarding exceptions?

Answer:
Exceptions are expensive in processing time, so they should only be thrown when something happens that really shouldn't happen in your app.
Sometimes you can predict what kind of things might happen and code to recover from them, in which case it is appropriate to throw and catch an exception, log and recover, then continue.  Otherwise they should just be used to handle the unexpected and exit gracefully, while capturing as much information as possible to help with debugging.
I'm a .NET developer, and for catch and throw, my approach is:
Only try/catch in public methods (in general; obviously if you are trapping for a specific error you would check for it there)
Only log in the UI layer right before suppressing the error and redirecting to an error page/form.


Question:
At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.

Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?

Answer:
“… the volatile modifier guarantees that any thread that reads a field will see the most recently written value.”
- Josh Bloch
If you are thinking about using
```
volatile
```
, read up on the package
```
java.util.concurrent
```
which deals with atomic behaviour.
The Wikipedia post on a
Singleton Pattern
shows volatile in use.


Question:
Possible Duplicates:

  Learn Obj-C Memory Management

  Where are the best explanations of memory management for iPhone?

I come from a C/C++ background and the dynamic nature of Objective-C is somewhat foreign to me, is there a good resource anyone can point me to for some basic memory management techniques in Objective-C? ex. retaining, releasing, autoreleasing

For instance, is it completely illegal to use a pointer to an Objective-C object and treat it as an array? Are you forced to use NSArray and NSMutableArray for data structures?

I know these are pretty newbie questions, thanks for any help you can offer me.

Answer:
Here you go
:
Application memory management is the process of allocating memory during your program’s runtime, using it, and freeing it when you are done with it. A well-written program uses as little memory as possible. In Objective-C, it can also be seen as a way of distributing ownership of limited memory resources among many pieces of data and code. When you have finished working through this guide, you will have the knowledge you need to manage your application’s memory by explicitly managing the life cycle of objects and freeing them when they are no longer needed.
Although memory management is typically considered at the level of an individual object, your goal is actually to manage object graphs. You want to make sure that you have no more objects in memory than you actually need...


Question:
Strange question, but: Sharepoint 2007 greets you with the Administrator Tasks on the Central Administration after installation.

I just wonder if this list is "safe" to be used for my own Administration Tasks? The reason why i'm asking is because I found that Sharepoint uses a lot of "black magic" and unlogical behaviour and breaks rather easily, so I do not want risk breaking anything if i'm entering my own tasks into the task list.

Answer:
```
unicode
```
does not guess the encoding of your text. If your object can print itself as
```
unicode
```
, define the
```
__unicode__()
```
method that returns a Unicode string.
The secret is that
```
unicode(r)
```
is not actually calling
```
__str__()
```
itself. Instead, it's looking for a
```
__unicode__()
```
method. The default implementation of
```
__unicode__()
```
will call
```
__str__()
```
and then attempt to decode it using the
```
ascii
```
charset. When you pass the encoding,
```
unicode()
```
expects the first object to be something that can be decoded -- that is, an instance of
```
basestring
```
.
Behavior is weird because it tries to decode as ascii if I don't pass 'utf-8'. But if I pass 'utf-8' it gives a different error...
That's because when you specify "utf-8", it treats the first parameter as a string-like object to be decoded. Without it, it treats the parameter as an object to be coerced to unicode.
I do not understand the confusion. If you know that the object's
```
text
```
attribute will always be UTF-8 encoded, just define
```
__unicode__()
```
and then everything will work fine.


Question: What I'm trying to do with MRS is to teach myself some basic AI; what I want to do is to make a rocket entity, with things such as vectored exhaust, and staging. Anyone have an idea on how to make an entity that can fly? Or do I just need to constantly apply a force upwards?

Answer:
Hey TraumaPony, your question looked lonely :)
I took a look at an MSDN article about MRS 2.0
here
I believe you'll actually need to create a Rocket entity of some kind and then a Thruster entity that it can use. In the article they were able to reuse a DifferentialDrive entity to propel their bot forward. I hope that helps. I'm more or less shooting in the dark since no else has tried to help ya out yet. Cheers! :)


Question:
I have a VB.NET Windows Forms project that at one point paints text directly to onto the form at runtime. Before I paint with the font though, I want to make sure that the font and font-size exists on the user's machine. If they don't, I'll try a few other similar fonts, eventually defaulting with Arial or something.

What's the best way to test and validate a font on a user's computer?

Answer:
From an MSDN article titled "How To: Enumerate Installed Fonts", I found this code:
```
```
InstalledFontCollection installedFontCollection = new InstalledFontCollection();

// Get the array of FontFamily objects.
FontFamily[] fontFamilies = installedFontCollection.Families;
```
```


Question:
It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam.  The web is littered with similar, yet still slightly different implementations of this type of solution.

Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)?  Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution?

Answer:
As toolkit mentions above, Apache Commons IO is the way to go, specifically
FileUtils
.
copyFile()
; it handles all the heavy lifting for you.
And as a postscript, note that recent versions of FileUtils (such as the 2.0.1 release) have added the use of NIO for copying files;
NIO can significantly increase file-copying performance
, in a large part because the NIO routines defer copying directly to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer.  So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils.


Question:
Intel's Threading Building Blocks (TBB) open source library looks really interesting.  Even though there's even an O'Reilly Book about the subject I don't hear about a lot of people using it.  I'm interested in using it for some multi-level parallel applications (MPI + threads) in Unix (Mac, Linux, etc.) environments.  For what it's worth, I'm interested in high performance computing / numerical methods kinds of applications.

Does anyone have experiences with TBB?  Does it work well?  Is it fairly portable (including GCC and other compilers)?  Does the paradigm work well for programs you've written?  Are there other libraries I should look into?

Answer:
I've looked into TBB but never used it in a project. I saw no advantages (for my purposes) over
ZThread
. A brief and somewhat dated overview can be found
here
.
It's fairly complete with several thread dispatch options, all the usual synchronization classes and a very handy exception based  thread "interrupt" mechanism . It's easily extendable, well written and documented. I've used it on 20+ projects.
It also plays nice with any *NIX that supports POSIX threads as well as Windows.
Worth a look.


Question:
I am using Adobe Captivate 3 and am having trouble disabling the typing noise when using a recording.  Sometimes when I have this 'feature' disabled and make a recording, it doesn't make the typing sound, but when I publish the project, the typing sound returns.  Also, I have other projects I am working on where the typing sound wasn't initially disabled during the recording and I can't get it to stop making that typing noise.

Any suggestions on how to disable the typing sound permanently within a new or existing Captivate project?

Answer:
I've looked into TBB but never used it in a project. I saw no advantages (for my purposes) over
ZThread
. A brief and somewhat dated overview can be found
here
.
It's fairly complete with several thread dispatch options, all the usual synchronization classes and a very handy exception based  thread "interrupt" mechanism . It's easily extendable, well written and documented. I've used it on 20+ projects.
It also plays nice with any *NIX that supports POSIX threads as well as Windows.
Worth a look.


Question:
I have a table that is dynamically created using DIVs. Each row of the table has two images. I want to set the height for the div (that represents a particular row) to the height of image that is greater of the two images being displayed in that particular row. The images to displayed will always change, and they are from an external server.

How do I set the height for my div so that I can fit images?

Answer:
Pre-load them into javascript image objects then just reference the height and width.
Might take some clever devilry to work in all browsers...
```
```
function getSize(imgSrc){

    var aImg = new Image();

    aImg.src = imgSrc;

    aHeight = newImg.height;
    aWidth = newImg.width;

}
```
```


Question:
How do you draw a custom button next to the minimize, maximize and close buttons within the Titlebar of the Form?

I know you need to use Win32 API calls and override the WndProc procedure, but I haven't been able to figure out a solution that works right.

Does anyone know how to do this? More specifically, does anyone know a way to do this that works in Vista?

Answer:
Drawing seems to be the easy part, the following will do that:
[Edit: Code removed, see my other answer]
The real problem is changing the state and detecting clicks on the button... for that you'll need to hook into the global message handler for the program, .NET seems to hide the mouse events for a form while not in the actual container areas (ie. mouse moves and clicks on the title bar). I'm looking for info on that, found it now, I'm working on it, shouldn't be too hard... If we can figure out what these messages are actually passing.


Question:
I'm a pretty new C# and .NET developer. I recently created an MMC snapin using C# and was gratified by how easy it was to do, especially after hearing a lot of horror stories by some other developers in my organisation about how hard it is to do in C++.

I pretty much went through the whole project at some point and made every instance of the "public" keyword to "internal", except as required by the runtime in order to run the snapin. What is your feeling on this, should you generally make classes and methods public or internal?

Answer:
I believe in blackboxes where possible. As a programmer, I want a well defined blackbox which I can easily drop into my systems, and have it work. I give it values, call the appropriate methods, and then get my results back out of it.
To that end, give me only the functionality that the class needs to expose to work.
Consider an elevator. To get it to go to a floor, I push a button. That's the public interface to the black box which activates all the functions needed to get the elevator to the desired floor.


Question: I have been using IoC for a little while now and I am curious if I should use Microsoft's Unity framework (official name "Unity Application Block").  Does anyone have experience using it?  So for I have been copying my IoC container code from project to project, but I think it would be better to using something standard.  I think IoC can make a HUGE difference in keeping component based applications loosely coupled and therefore changeable but I am by no means an expert on IoC, so I am nervous to switch to a framework that will just paint me into a corner as a dependency I will one day want to walk away from.

Answer:
I've played with CompositeWPF (aka Prism) - successor of Composite app block. From my experience Unity works much better as compared with previous version of ObjectBuilder. However it's up to you to evaluate IoC frameworks and choose one suited for your needs.
Unity tutorials & samples
Unity IoC Screencast


Question:
I'm trying to implement an outdent of the first letter of the first paragraph of the body text. Where I'm stuck is in getting consistent spacing between the first letter and the rest of the paragraph.

For example, there is a huge difference in spacing between a "W" and an "I"

Anyone have any ideas about how to mitigate the differences? I'd prefer a pure CSS solution, but will resort to JavaScript if need be.

PS: I don't necessarily need compatibility in IE or Opera

Answer:
I tried using a fix-width font like 'courier new' and since the characters are more or less the same width it made it a lot less noticeable.
Edit - this font is decent but might only work for windows
```
```
p.outdent:first-letter {
    font-family: ms mincho;
    font-size: 8em;
    line-height: 1;
    font-weight: normal;
    float: left;
    margin: -0.1em 0 0 -.55em;
    letter-spacing: 0.05em;
}
```
```


Question: I noticed that you can call Queue.Synchronize to get a thread-safe queue object, but the same method isn't available on Queue<T>.  Does anyone know why?  Seems kind of weird.

Answer:
(I assume you mean Queue<T> for the second one.)
I can't specifically answer the question, except that the IsSynchronized and SyncRoot properties (but not Synchronise() explicitly) are inherited from the ICollection interface. None of the generic collections use this and the ICollection<T> interface does not include SyncRoot.
As to why it is not included, I can only speculate that they weren't being used either in the way intended by the library designers or they simply weren't being used enough to justify retaining them in the newer collections.


Question: It seems like you could use a mashup of Relector and a Debugger to be able to debug any .NET app WITHOUT having the source code at all.  Is this possible?  Has anyone seen this before?

Answer:
I tried this a long time ago without success. Reflector has improved alot since then so I imagine it may be possible today.
It's actually kind of scary if you think about it. Someone could decompile your app and have the full code, then modify it and distribute their own version of it. All without being open source. But then again that's why "they" created obfuscators.


Question:
As a follow up to "What are indexes and how can I use them to optimise queries in my database?" where I am attempting to learn about indexes, what columns are good index candidates? Specifically for an MS SQL database?

After some googling, everything I have read suggests that columns that are generally increasing and unique make a good index (things like MySQL's auto_increment), I understand this, but I am using MS SQL and I am using GUIDs for primary keys, so it seems that indexes would not benefit GUID columns...

Answer:
In general (I don't use mssql so can't comment specifically), primary keys make good indexes. They are unique and must have a value specified. (Also, primary keys make such good indexes that they normally have an index created automatically.)
An index is effectively a copy of the column which has been sorted to allow binary search (which is much faster than linear search). Database systems may use various tricks to speed up search even more, particularly if the data is more complex than a simple number.
My suggestion would be to not use any indexes initially and profile your queries. If a particular query (such as searching for people by surname, for example) is run very often, try creating an index over the relevate attributes and profile again. If there is a noticeable speed-up on queries and a negligible slow-down on insertions and updates, keep the index.
(Apologies if I'm repeating stuff mentioned in your other question, I hadn't come across it previously.)


Question:
How do I capture the event of the clicking the Selected Node of a TreeView?
It doesn't fire the SelectedNodeChanged since the selection has obviously not changed but then what event can I catch so I know that the Selected Node was clicked?

UPDATE:
When I have some time, I'm going to have to dive into the bowels of the TreeView control and dig out what and where it handles the click events and subclass the TreeView to expose a new event OnSelectedNodeClicked.

I'll probably do this over the Christmas holidays and I'll report back with the results.

UPDATE:
I have come up with a solution below that sub-classes the TreeView control.

Answer:
Easiest way - if it doesn't interfere with the rest of your code - is to simply set the node as not selected in the SelectedNodeChanged method.
```
```
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e){
  // Do whatever you're doing
  TreeView1.SelectedNode.Selected = false;
}
```
```


Question:
I'm asking more about what this means to my code.  I understand the concepts mathematically, I just have a hard time wrapping my head around what they mean conceptually.  For example, if one were to perform an O(1) operation on a data structure, I understand that the number of operations it has to perform won't grow because there are more items.  And an O(n) operation would mean that you would perform a set of operations on each element.  Could somebody fill in the blanks here?

Like what exactly would an O(n^2) operation do?

And what the heck does it mean if an operation is O(n log(n))?

And does somebody have to smoke crack to write an O(x!)?

Answer:
A lot of these are easy to demonstrate with something non-programming, like shuffling cards.
Sorting a deck of cards by going through the whole deck to find the ace of spades, then going through the whole deck to find the 2 of spades, and so on would be worst case n^2, if the deck was already sorted backwards. You looked at all 52 cards 52 times.
In general the really bad algorithms aren't necessarily intentional, they're commonly a misuse of something else, like calling a method that is linear inside some other method that repeats over the same set linearly.


Question: Has anyone out there got a good set of instructions for building/compiling Ruby from source of windows XP ?

Answer:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/184380
I normally get a binary installable for windows.. much faster if you just need Ruby installed. But you may be modifying ruby source.. anyways..
Update:
I ended up compiling Ruby from source today... here is what worked for me
http://madcoderspeak.blogspot.com/2009/06/how-to-compile-ruby-from-source-on.html


Question:
I want to debug an application in Visual Studio but I ONLY have the source code for 1 class.  I only need to step through a single function in that file, but I don't understand what I need to do it.  I think the steps are normally something like this:

Open a file in VS

Load in the "symbols" (.PDB file)

Attach to the running process

I know how to do #1 and #3, but I don't how to do #2 without the .PDB file.  Is it possible to generate the .PDB file for this to make it work?  Thanks!

Answer:
You need the symbol file (.PDB) file that belongs to the application you are trying to debug.
MSDN: PDB Files
The Visual Studio debugger uses the path to the PDB in the EXE or DLL file to find the project.pdb file. If the debugger cannot find the PDB file at that location, or if the path is invalid, for example, if the project was moved to another computer, the debugger searches the path containing the EXE followed by the symbol paths specified in the Options dialog box. This path is generally the Debugging folder in the Symbols node. The debugger will not load a PDB that does not match the binary being debugged.


Question: Most of the implementations I find require a hardware instruction to do this.  However I strongly doubt this is required (if it is, I can't figure out why...)

Answer:
You don't need a test and set instruction to get mutual exclusion locking, if thats what you're asking.
Dijkstra described the first mutual exclusion algorithm I am aware of, in 1965. The title of the paper was "Solution of a problem in concurrent programming control", search Google for a copy near you. The original algorithm required no special support from the hardware at all, but providing an atomic instruction in the CPU dramatically improves the performance.
Test-and-set, atomic swap, and load-linked + store-conditional are all common primitives for CPUs to provide. All can be used to implement mutual exclusion, which can then be used to implement whatever locking semantics you want.


Question:
I was reading Andrew Kennedy's blog post series on units of measurement in F# and it makes a lot of sense in a lot of cases.  Are there any other languages that have such a system?

Edit: To be more clear, I mean the flexible units of measurement system where you can define your own arbitrarily.

Answer:
I'm not sure if this really counts, but the
```
RPL
```
system on my HP-48 calculator does have similar features. I can write
```
40_gal 5_l +
```
and get the right answer of  156.416 liters.


Question:
How often should I commit changes to source control ? After every small feature, or only for large features ?

I'm working on a project and have a long-term feature to implement. Currently, I'm committing after every chunk of work, i.e. every sub-feature implemented and bug fixed. I even commit after I've added a new chunk of tests for some feature after discovering a bug.

However, I'm concerned about this pattern. In a productive day of work I might make 10 commits. Given that I'm using Subversion, these commits affect the whole repository, so I wonder if it indeed is a good practice to make so many ?

Answer: I like to commit changes every 30-60 minutes, as long as it compiles cleanly and there are no regressions in unit tests.


Question:
I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use new I am dynamically allocating memory.

My question is the following:

If i were to use cout << &p, it would display the "virtual memory location" of p.
Is there a way in which I could manipulate this "virtual memory location?"

For example, the following code shows an array of ints.

If I wanted to show the value of p[1] and I knew the "virtual memory location" of p, could I somehow do "&p + 1" and obtain the value of p[1] with cout << *p, which will now point to the second element in the array?

int *p;
p = new int[3];

p[0] = 13;
p[1] = 54;
p[2] = 42;

Answer:
Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself.
```
```
int *p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;

cout << *p << ' ' << *(p+1) << ' ' << *(p+2);
```
```
Each addition (or subtraction) mean the subsequent (prior) element in the array. If p points to a 4 byte variable (e.g.
int
on typical 32-bits PCs) at address say 12345, p+1 will point to 12349, and not 12346. Note you want to change the value of what p contains before dereferencing it to access what it points to.


Question: They both seem to be sending data to the server inside the body, so what makes them different?

Answer:
PUT is meant as a a method for "uploading" stuff to a particular URI, or overwriting what is already in that URI.
POST, on the other hand, is a way of submitting data RELATED to a given URI.
Refer to
the HTTP RFC


Question: What are the down sides of using a composite/compound primary key?

Answer:
Need more specificity.
Taken too far, it can overcomplicate Inserts (Every key MUST exist) and documentation and your joined reads could be suspect if incomplete.
Sometimes it can indicate a flawed data model (is a composite key REALLY what's described by the data?)
I don't believe there is a performance cost...it just can go really wrong really easily.


Question: What I'm trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if http://somedomain/foo/ will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know of an easy way of doing this?

Answer:
edit
: This answer works, but nowadays you should just use the
requests
library as mentioned by other answers below.
Use
httplib
.
```
```
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
```
```
There's also a
```
getheader(name)
```
to get a specific header.


Question:
I have a 3d object that I wish to be able to rotate around in 3d.  The easiest way is to directly translate X and Y mouse motion to rotation about the Y and X axes, but if there is some rotation along both axes, the way the model rotates becomes highly counterintuitive (i.e. if you flip the object 180 degrees about one axis, your motion along the other axis is reversed).

I could simply do the above method, but instead of storing the amount to rotate about the two axes, I could store the full rotation matrix and just further rotate it along the same axes for each mouse drag, but I'm concerned that that would quickly have precision issues.

Answer:
Create an accumulator matrix and initialize it with the identity.
Each frame, apply that to your modelview/world matrix state before drawing the object.
Upon mouse motion, construct a rotation matrix about the X axis with some sensitivity_constant * delta_x.  Construct another rotation matrix about the Y axis for the other component.  Multiply one, then the other onto the accumulator.
The accumulator will change as you move the mouse.  When drawing, it will orient the object as you expect.
Also, the person talking about quaternions is right; this will look good only for small incremental changes.  If you drag it quickly on a diagonal, it won't rotate quite the way you expect.


Question:
As a base SAS programmer, you know the drill:

You submit your SAS code, which contains an unbalanced quote, so now you've got not only and unclosed quote, but also unclosed comments, macro function definitions, and a missing run; or quit; statement.

What's your best trick for not having those unbalanced quotes bother you?

Answer:
As for myself, I usually
Google for "SAS unbalanced quote"
, and end up with submitting something like
this
:
```
```
*); */; /*’*/ /*”*/; %mend;
```
```
... to break out of unclosed comments, quotes and macro functions.


Question:
There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO."

Is JavaScript an object-oriented language?

Answer:
The short answer is Yes. For more information:
From
Wikipedia
:
JavaScript is heavily object-based.
  Objects are associative arrays,
  augmented with prototypes (see below).
  Object property names are associative
  array keys: obj.x = 10 and obj["x"] =
  10 are equivalent, the dot notation
  being merely syntactic sugar.
  Properties and their values can be
  added, changed, or deleted at
  run-time. The properties of an object
  can also be enumerated via a for...in
  loop.
Also, see
this series of articles
about OOP with Javascript.


Question:
When we compile a dll using __stdcall inside visual studio 2008 the compiled function names inside the dll are.

FunctionName

Though when we compile the same dll using GCC using wx-dev-cpp GCC appends the number of paramers the function has, so the name of the function using Dependency walker looks like.

FunctionName@numberOfParameters or == FunctionName@8

How do you tell GCC compiler to remove @nn from exported symbols in the dll?

Answer:
__stdcall decorates the function name by adding an underscore to the start, and the number of bytes of parameters to the end (separated by @).
So, a function:
```
```
void __stdcall Foo(int a, int b);
```
```
...would become _Foo@8.
If you list the function name (undecorated) in the EXPORTS section of your .DEF file, it is exported undecorated.
Perhaps this is the difference?


Question:
How do you unit test a large MFC UI application?

We have a few large MFC applications that have been in development for many years, we use some standard automated QA tools to run basic scripts to check fundamentals, file open etc. These are run by the QA group post the daily build.

But we would like to introduce procedures such that individual developers can build and run tests against dialogs, menus, and other visual elements of the application before submitting code to the daily build.

I have heard of such techniques as hidden test buttons on dialogs that only appear in debug builds, are there any standard toolkits for this.

Environment is C++/C/FORTRAN, MSVC 2005, Intel FORTRAN 9.1, Windows XP/Vista x86 & x64.

Answer:
Well we have one of these humongous MFC Apps at the workplace. Its a gigantic pain to maintain or extend... its a huge ball of mud now but it rakes in the moolah.Anyways
We use
Rational Robot
for doing smoke tests and the like.
Another approach that has had some success is to create a small product-specific language and
script tests
that use VBScript and some Control handle spying magic. Turn common actions into commands.. e.g. OpenDatabase would be a command that in turn will inject the required script blocks to click on Main Menu > File > "Open...". You then create excel sheets which are a series of such commands. These commands can take parameters too. Something like a FIT Test.. but more work. Once you have most of the common commands identified and scripts ready. It's pick and assemble scripts (tagged by CommandIDs) to write new tests. A test-runner parses these Excel sheets, combines all the little script blocks into a test script and runs it.
OpenDatabase "C:\tests\MyDB"
OpenDialog "Add Model"
AddModel "M0001", "MyModel", 2.5, 100
PressOK
SaveDatabase
HTH


Question: I need to load some fonts temporarily in my program. Preferably from a dll resource file.

Answer:
I found
this
with Google. I have cut & pasted the relevant code below.
You need to add the font to your resource file:
```
```
34 FONT "myfont.ttf"
```
```
The following C code will load the font from the DLL resource and release it from memory when you are finished using it.
```
DWORD   Count;
HMODULE Module   = LoadLibrary("mylib.dll");
HRSRC   Resource = FindResource(Module,MAKEINTRESOURCE(34),RT_FONT);
DWORD   Length   = SizeofResource(Module,Resource);
HGLOBAL Address  = LoadResource(Module,Resource);
HANDLE  Handle   = AddFontMemResourceEx(Address,Length,0,&Count);

/* Use the font here... */

RemoveFontMemResourceEx(Handle);
FreeLibrary(Module);
```


Question:
So the official XML-RPC standard doesn't support 64-bit values.  But in these modern times, 64-bit values are increasingly common.

How do you handle these?  What XML-RPC extensions are the most common?  What language bindings are there?  I'm especially interested in Python and C++, but all information is appreciated.

Answer:
I don't know anything about how XMLRPC could be extended but I did find
this mail
about the subject:
In XML-RPC, everything is transmitted
  as a string, so I don't think that
  choice is really that bad - except of
  course for the additional clumsiness
  for invoking explicit conversion
  functions.
But no, XML-RPC doesn't have a data
  type that can represent integers above
  2**32. If you can accept losing
  precision, you can use doubles (but
  you still would have to convert
  explicitly on the sender).


Question:
What is the best (regarding performance) way to compute the critical path of a directional acyclic graph when the nodes of the graph have weight?

For example, if I have the following structure:

            Node A (weight 3)
               /            \
     Node B (weight 4)      Node D (weight 7)
     /               \
Node E (weight 2)   Node F (weight 3)

The critical path should be A->B->F (total weight: 10)

Answer:
I have no clue about "critical paths", but I assume you mean
this
.
Finding the longest path in an acyclic graph with weights is only possible by traversing the whole tree and then comparing the lengths, as you never really know how the rest of the tree is weighted. You can find more about tree traversal at
Wikipedia
. I suggest, you go with pre-order traversal, as it's easy and straight forward to implement.
If you're going to query often, you may also wish to augment the edges between the nodes with information about the weight of their subtrees at insertion. This is relatively cheap, while repeated traversal can be extremely expensive.
But there's nothing to really save you from a full traversal if you don't do it. The order doesn't really matter, as long as you do a
traversal
and never go the same path twice.


Question:
I'd like to build a real quick and dirty administrative backend for a Ruby on Rails application I have been attached to at the last minute. I've looked at activescaffold and streamlined and think they are both very attractive and they should be simple to get running, but I don't quite understand how to set up either one as a backend administration page. They seem designed to work like standard Ruby on Rails generators/scaffolds for creating visible front ends with model-view-controller-table name correspondence.

How do you create a admin_players interface when players is already in use and you want to avoid, as much as possible, affecting any of its related files?

The show, edit and index of the original resource are not usuable for the administrator.

Answer:
I have used Streamlined pretty extensively.
To get Streamline working you create your own controllers - so you can actually run it completely apart from the rest of your application, and you can even run it in a separate 'admin' folder and namespace that can be secured with
.
Here is the Customers controller from a recent app:
```
```
class CustomersController < ApplicationController
  layout 'streamlined'
  acts_as_streamlined

  Streamlined.ui_for(Customer) do
    exporters :csv
    new_submit_button :ajax => false
    default_order_options :order => "created_at desc"
    list_columns :name, :email, :mobile, :comments, :action_required_yes_no
  end
end
```
```


Question:
I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using GAEUnit. How can I do this?

I'd like to use the webapp framework and GAEUnit, which runs within the App Engine sandbox (unfortunately WebTest does not work within the sandbox).

Answer:
Actually WebTest does work within the sandbox, as long as you comment out
```
```
import webbrowser
```
```
in webtest/__init__.py


Question:
Is output buffering enabled by default in Python's interpreter for sys.stdout?

If the answer is positive, what are all the ways to disable it?

Suggestions so far:

Use the -u command line switch

Wrap sys.stdout in an object that flushes after every write

Set PYTHONUNBUFFERED env var

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Is there any other way to set some global flag in sys/sys.stdout programmatically during execution?

Answer:
From
Magnus Lycka answer on a mailing list
:
You can skip buffering for a whole
python process using
```
python -u
```
or by
setting the environment variable
PYTHONUNBUFFERED.
You could also replace sys.stdout with
some other stream like wrapper which
does a flush after every call.
```
```
class Unbuffered(object):
   def __init__(self, stream):
       self.stream = stream
   def write(self, data):
       self.stream.write(data)
       self.stream.flush()
   def writelines(self, datas):
       self.stream.writelines(datas)
       self.stream.flush()
   def __getattr__(self, attr):
       return getattr(self.stream, attr)

import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Hello'
```
```


Question:
Are there any import and export tools that would let us move projects into and out of team system with full history and log? Our current SCM is SVN.

PS - Sorry, I know it's a repost, but I didn't get an answer before... :)

Answer:
Unfortunately, you probably didn't get an answer because there isn't a good one on offer...
I've looked into this a couple of times before, initially for the first TFS Betas.
(At the time we were eager to move away from VSS while waiting for TFS to be ready... the compromise we ended up with then was to use SVN in the interim, but used a post commit hook that kept a VSS repository in sync to allow for that migration path to TFS.)
These guys (ComponentSource)
were around back then with a VSS to TFS converter, and added a SVN to TFS one, but appear to have since discontinued the product.
These guys (Kyrosoft)
might have some promise, but I'm concerned that they don't post prices, and do post a customer list (of two).  If anyone has experience with the product, please let us all know.
More recently the TFS Migration and Synchronization Toolkit has been released on CodePlex, but to date no one has release a SVN plugin for it (there are 66 votes for the
request
)
So, you can look at rolling your own plugin for the toolkit, but even then you won't get the original dates for commits, as to my knowledge the TFS team haven't allowed a mechanism for importers to set this, so all migrated revisions will have the date of migration.
(The discontinued first tool above purportedly used to allow this, but how they got around the limitation (secret API? adjusting system time? database manipulation?) I don't know.)
In the end, I suspect most teams end up deciding to just switch systems at an appropriate time (eg new version or project), and manually deal with the bifurcated history lookup for the 6-12 months it remains particularly problematic...


Question:
(Jeopardy-style question, I wish the answer had been online when I had this issue)

Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed.

But I found that my program would leak memory over time. What am I doing wrong?

Answer:
This is a known bug in Java 1.4:
http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087
It's fixed in Java 1.5 but Sun doesn't intend to fix it in 1.4.
The issue is that, at construction time, a
```
Thread
```
is added to a list of references in an internal thread table. It won't get removed from that list until its start() method has completed. As long as that reference is there, it won't get garbage collected.
So, never create a thread unless you're definitely going to call its
```
start()
```
method. A
```
Thread
```
object's
```
run()
```
method should not be called directly.
A better way to code it is to implement the
```
Runnable
```
interface rather than subclass
```
Thread
```
. When you don't need a thread, call
```
```
myRunnable.run();
```
```
When you do need a thread:
```
```
Thread myThread = new Thread(myRunnable);
myThread.start();
```
```


Question: I don't want PHP errors to display /html, but I want them to display in /html/beta/usercomponent. Everything is set up so that errors do not display at all. How can I get errors to just show up in that one folder (and its subfolders)?

Answer:
I don't believe there's a simple answer to this
, but I'd certainly want to  be proven wrong.
edit: turns out this can be controlled from .htaccess files. Thanks people! :)
You can use error_reporting()
http://docs.php.net/manual/en/function.error-reporting.php
to switch the setting on a script by script basis, though. If you happen to have a single script which is included every time at /html/beta/usercomponent, this will do the trick.


Question:
I've encrypted the connectionstring in my web.config file using the steps in the link below:
http://www.codeproject.com/KB/database/WebFarmConnStringsNet20.aspx

However, whenever I call my application, it will give the following error:

Failed to decrypt using provider
  'CustomProvider'. Error message from
  the provider: The RSA key container
  could not be opened.

The server where I perform the encryption is a 64-bit Windows Server 2003 R2 SP2. Because of that I assign the ACL to NT Authority\Network Service. Yet it still doesn't work.

Hope someone has some ideas what else do I need to check to get this working.

PS. If I used the default rsa key NetFrameworkConfigurationKey for encryption, then the connection string will not have an access problem.

Answer:
Did you remember to add the
```
```
<configProtectedData>
```
```
to your web.config?


Question: How many lines of code can a .java file contain? Does it depend on the JVM being used?

Answer: I believe there is a 64kb limit on bytecode size per method.


Question: I have Laconica (self hosted twitter) configured on my local intranet and would like to integrate the public stream into SharePoint site with a web part.  How can I do this?

Answer:
You can point an RSS Viewer web part at the laconi.ca public stream RSS feed and use this XSLT to ensure attractive output.
Result screen shot:
XSL transform:
```
```
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" version="1.0" exclude-result-prefixes="xsl ddwrt msxsl rssaggwrt"
               xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
               xmlns:rssaggwrt="http://schemas.microsoft.com/WebParts/v3/rssagg/runtime"
               xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
               xmlns:msxsl="urn:schemas-microsoft-com:xslt"
               xmlns:rssFeed="urn:schemas-microsoft-com:sharepoint:RSSAggregatorWebPart"
               xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
               xmlns:dc="http://purl.org/dc/elements/1.1/"
               xmlns:rss="http://purl.org/rss/1.0/"
               xmlns:atom="http://www.w3.org/2005/Atom"
               xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
               xmlns:atom2="http://purl.org/atom/ns#"
               xmlns:ddwrt2="urn:frontpage:internal"
               xmlns:laconica="http://laconi.ca/ont/">
  <xsl:param name="rss_FeedLimit">5</xsl:param>
  <xsl:param name="rss_ExpandFeed">false</xsl:param>
  <xsl:param name="rss_LCID">1033</xsl:param>
  <xsl:param name="rss_WebPartID">RSS_Viewer_WebPart</xsl:param>
  <xsl:param name="rss_alignValue">left</xsl:param>
  <xsl:param name="rss_IsDesignMode">True</xsl:param>
  <xsl:template match="rdf:RDF">
    <xsl:call-template name="RDFMainTemplate"/>
  </xsl:template>
  <xsl:template name="RDFMainTemplate" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
    <xsl:variable name="Rows" select="rss:item"/>
    <xsl:variable name="RowCount" select="count($Rows)"/>

      <xsl:call-template name="RDFMainTemplate.body">
        <xsl:with-param name="Rows" select="$Rows"/>
        <xsl:with-param name="RowCount" select="count($Rows)"/>
      </xsl:call-template>

  </xsl:template>
  <xsl:template name="RDFMainTemplate.body" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
    <xsl:param name="Rows"/>
    <xsl:param name="RowCount"/>
    <xsl:for-each select="$Rows">
      <xsl:variable name="CurPosition" select="position()" />
      <xsl:variable name="RssFeedLink" select="$rss_WebPartID" />
      <xsl:variable name="CurrentElement" select="concat($RssFeedLink,$CurPosition)" />
      <xsl:if test="($CurPosition <= $rss_FeedLimit)">
        <xsl:element name="div">
          <xsl:if test="($CurPosition mod 2 = 1)">
            <xsl:attribute name="style"><![CDATA[background-color:#F9F9F9;]]></xsl:attribute>
          </xsl:if>
          <xsl:element name="table">
            <xsl:attribute name="cellpadding">0</xsl:attribute>
            <xsl:attribute name="border">0</xsl:attribute>
            <xsl:attribute name="style"><![CDATA[margin:0px;padding:0px;border-spacing:0px;background-color:transparent;]]></xsl:attribute>
            <xsl:element name="tr">
              <xsl:element name="td">
                <xsl:attribute name="style"><![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]></xsl:attribute>
                <xsl:attribute name="rowspan">2</xsl:attribute>
                <xsl:element name="img">
                  <xsl:attribute name="src"><xsl:value-of select="laconica:postIcon/@rdf:resource"/></xsl:attribute>
                  <xsl:attribute name="style"><![CDATA[margin:3px;height:48px;width:48px;]]></xsl:attribute>
                </xsl:element>
              </xsl:element>
              <xsl:element name="td">
                <xsl:attribute name="style"><![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]></xsl:attribute>

                  <xsl:value-of select="substring-before(rss:title, ':')"/>

                    <xsl:value-of select="substring-after(rss:title, ':')"/>

              </xsl:element>
            </xsl:element>
            <xsl:element name="tr">
              <xsl:element name="td">
                <xsl:attribute name="style"><![CDATA[padding:0px;background-color:transparent;]]></xsl:attribute>
                <xsl:element name="a">
                  <xsl:attribute name="href"><xsl:value-of select="rss:link"/></xsl:attribute>
                  <xsl:value-of select="ddwrt:FormatDate(dc:date,number($rss_LCID),15)"/>
                </xsl:element>
              </xsl:element>
            </xsl:element>
          </xsl:element>
        </xsl:element>
      </xsl:if>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
```
```


Question:
I have a legacy web site in ColdFusion MX 2004.  I'm re-writing it in .Net, so I don't want to pay $600+ for an upgrade to the latest version of ColdFusion, nor do I want to go through the (very large) site fixing version incompatibilities.

I often have to track down and fix bugs in the site.

A source-level debugger that would let me step through the code line-by-line and examine variables would be a HUGE time-saver.

Does anyone have experience using any of the third-party ColdFusion source-level debuggers?

Answer:
There's no such thing as ColdFusion MX 2004, neither in name nor release year (CFMX 6.1 was released in 2003, and CFMX 7 was released in 2005).
FusionDebug
supports all versions of CFMX from 6.1 onwards.
You may want to investigate
BlueDragon.NET
, which allows you to run CFML code on the .NET platform, and may make the transition easier for you.


Question:
On Linux/GCC I can use the -rpath flag to change an executables search path for shared libraries without tempering with environment variables.

Can this also  be accomplished on Windows? As far as I know, dlls are always searched in the executable's directory and in PATH.

My scenario: I would like to put shared libraries into locations according to their properties (32/64bit/Debug/Release) without taking care of unique names. On Linux, this is easily be done via rpath, but I haven't found any way doing this on Windows yet.

Thanks for any hints!

Answer:
The search order for DLLs in Windows is described on
this page
on MSDN. If you're using
run-time dynamic linking
, you can specify the folder when you call
```
LoadLibrary
```
.


Question:
I am using YUI reset/base, after the reset it sets the ul and li tags to list-style: disc outside;

My markup looks like this:

<div id="nav">
     <ul class="links">
         <li><a href="">Testing</a></li>
     </ul>

</div>

My CSS is:

#nav {}
#nav ul li {
    list-style: none;
 }

Now that makes the small disc beside each li disappear.

Why doesn't this work though?

 #nav {}
 #nav ul.links
 {
      list-style: none;
 }

It works if I remove the link to the base.css file, why?.

Updated: sidenav -> nav

Answer:
shouldn't it be:
```
```
#nav ul.links
```
```


Question:
The unzip command doesn't have an option for recursively unzipping archives.

If I have the following directory structure and archives:

/Mother/Loving.zip
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes.zip

And I want to unzip all of the archives into directories with the same name as each archive:

/Mother/Loving/1.txt
/Mother/Loving.zip
/Scurvy/Sea Dogs/2.txt
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes/3.txt
/Scurvy/Cures/Limes.zip

What command or commands would I issue?

It's important that this doesn't choke on filenames that have spaces in them.

Answer:
Here's one solution that extracts all zip files to the
working directory
and involves the find command and a while loop:
```
```
find . -name "*.zip" | while read filename; do unzip -o -d "`basename -s .zip "$filename"`" "$filename"; done;
```
```


Question:
I'm working on a simple multiplayer game in which 2-4 players are placed at separate entrypoints in a maze and need to reach a goal point.  Generating a maze in general is very easy, but in this case the goal of the game is to reach the goal before everyone else and I don't want the generation algorithm to drastically favor one player over others.

So I'm looking for a maze generation algorithm where the optimal path for each player from the startpoint to the goal is no more than 10% more steps than the average path.  This way the players are on more or less an equal playing field.  Can anyone think up such an algorithm?

(I've got one idea as it stands, but it's not well thought out and seems far less than optimal -- I'll post it as an answer.)

Answer: The easiest solution I can come up with is to randomly generate an entire maze like normal, then randomly pick the goal point and player startpoints.  Once this is done, calculate the shortest path from each startpoint to the goal.  Find the average and start 'smoothing' (remove/move barriers -- don't know how this will work) the paths that are significantly above it, until all of the paths are within the proper margin.  In addition, it could be possible to take the ones that are significantly below the average and insert additional barriers.


Question:
We are looking for a reliable "current weather" web service for Europe, with city resolution. We only need the current weather.

Since it is for a commercial web site, we don't mind paying a reasonable fee for the service.

What are our options? What service would you recommend or avoid based on previous experience?

Note: SOAP Web Service, XML RPC, REST, all are fine.

Answer:
You should be able to interface with
Yahoo weather Europe
like the team of the
weather plasmoid
did.
Or if you only need to add it to a web page you could use directly
this gadget


Question:
Could anybody explain in plain words how Cloud computing works?
I have read the Wikipedia article, but still not sure that I understand how cloud actually works.

Answer:
Aside from the latest marketing term?
Basically all the resources your program needs are held "somewhere" on the internet. You interact with them via a defined service contract; SOAP, REST, POX or whatever and what happens after that is up to the service provider. You don't care about how your information is stored or how the service is provided, just that it is.
If, for example, you wanted to store files, you may choose to use Amazon's S3 cloud system. You connect to the service and upload your files; you don't know or care where the files are stored, only the location of the entry point to that service.
If you have an application then it may also be ran in the cloud, assuming it's suitable. Live Mesh for example is a virtual machine which you can code against and run your software both locally and within the cloud, so your user simply goes to a URI and finds your program, you don't care where it is beyond it being available somewhere on the cloud.


Question: When I create a socket using accept() and make a FILE out of it using fdopen(), what do I have to do to clean everything up? Do I need to do fclose() on the FILE, shutdown() and close() on the socket, or only the shutdown() and or close() or fclose()? If I don't do fclose(), do I have to free() the FILE pointer manually?

Answer:
You have 2 things here you need to clean up: the stream represented by
```
FILE
```
and the file descriptor represented by the socket. You need to close the stream first, then the file descriptor. So, in general you will need to
```
fclose()
```
any
```
FILE
```
objects, then
```
close()
```
any file descriptors.
Personally I have never used
```
shutdown()
```
when I want to cleanup after myself, so I can't say.
edit
Others have correctly pointed out that
```
fdclose()
```
will also close the underlying file descriptor, and since calling
```
close()
```
on a close file descriptor will lead to an error, in this case you only need
```
fdclose()
```
.


Question:
I'm working on a large application (300K LOC) that is causing a memory leak in the Sun 1.6 JVM (1.6_05). Profiling the Java shows no leak. Are there any diagnostics available from the JVM that might detect the cause of the leak?

I haven't been able to create a simple, isolated Java test case. Is the only way to figure this out by using a C heap analyzer on the JVM?

The application creates a pool of sockets and does a significant amount of network I/O.

Answer:
Some profiler like profiler4j can show the managed and the unmanaged memory (live curve). Then you can see if you has a leak and when the leak occur. But you does not find more informations.
After this there are 2 possible solutions:
You can with the live curve isolate the problem and create a simpler test until you have find the cause of the problem.
You search your code for the typical problems like:
Instances of the class Thread that are never start.
Images or Graphics that never are dispose
ODBC Bridge Objects that are never close


Question: when they say the action controller in the struts framework is multi threaded, does it mean that there are multiple instances of the servlet taking the request and forwarding it to the model. OR does it mean that there is one single instance taking all the requests? Any visuals will be appreciated

Answer:
Some profiler like profiler4j can show the managed and the unmanaged memory (live curve). Then you can see if you has a leak and when the leak occur. But you does not find more informations.
After this there are 2 possible solutions:
You can with the live curve isolate the problem and create a simpler test until you have find the cause of the problem.
You search your code for the typical problems like:
Instances of the class Thread that are never start.
Images or Graphics that never are dispose
ODBC Bridge Objects that are never close


Question: Are there any good, cross platform (SBCL and CLISP at the very least) easy to install GUI libraries?

Answer:
Ltk
is quite popular, very portable, and reasonably well documented through the Tk docs.  Installation on SBCL is as easy as saying:
```
```
(require :asdf-install)
(asdf-install:install :ltk)
```
```
There's also
Cells-Gtk
, which is reported to be quite usable but may have a slightly steeper learning curve because of its reliance on Cells.
EDIT: Note that ASDF-INSTALL is integrated this well with SBCL
only
.  Installing libraries from within other Lisp implementations may prove harder.  (Personally, I always install my libraries from within SBCL and then use them from all implementations.)  Sorry about any confusion this may have caused.


Question:
Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"

So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?

So I have

typeof(int)
typeof(DateTime)
System.Type t = something;

and I want

int?
DateTime?

or

Nullable<int> (which is the same)
if (t is primitive) then Nullable<T> else just T

Is there a built-in method?

Answer:
Here is the code I use:
```
```
Type GetNullableType(Type type) {
    // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable.
    type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null
    if (type.IsValueType)
        return typeof(Nullable<>).MakeGenericType(type);
    else
        return type;
}
```
```


Question: What problems does MEF (Managed Extensibility Framework) solves that cannot be solved by existing IoC/DI containers?

Answer:
The principle purpose of MEF is extensibility; to serve as a 'plug-in' framework for when the author of the application and the author of the plug-in (
extension
) are different and have no particular knowledge of each other beyond a published interface (
contract
) library.
Another problem space MEF addresses that's different from the usual IoC suspects, and one of MEFs strengths, is [extension] discovery. It has a lot of, well, extensible discovery mechanisms that operate on metadata you can associate with extensions. From the MEF CodePlex site:
"MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering"
Combined with an ability to delay-load tagged extensions, being able to interrogate extension metadata
prior
to loading opens the door to a slew of interesting scenarios and substantially enables capabilities such as [plug-in] versioning.
MEF also has 'Contract Adapters' which allow extensions to be 'adapted' or 'transformed' (
from type > to type
) with complete control over the details of those transforms. Contract Adapters open up another creative front relative to just what 'discovery' means and entails.
Again, MEFs 'intent' is tightly focused on anonymous plug-in extensibility, something that very much differentiates it from other IoC containers. So while MEF can be used for composition, that's merely a small intersection of its capabilities relative to other IoCs, with which I suspect we'll be seeing a lot of incestuous interplay going forward.


Question:
I am using pyexcelerator Python module to generate Excel files.
I want to apply bold style to part of cell text, but not to the whole cell.
How to do it?

Answer:
This is an example from Excel documentation:
```
```
With Worksheets("Sheet1").Range("B1")
    .Value = "New Title"
    .Characters(5, 5).Font.Bold = True
End With
```
```
So the Characters property of the cell you want to manipulate is the answer to your question. It's used as Characters(
start
,
length
).
PS: I've never used the module in question, but I've used Excel COM automation in python scripts. The Characters property is available using win32com.


Question:
I know that it's possible to replace the browse button, which is generated in html, when you use input tag with type="file.

I'm not sure what is the best way, so if someone has experience with this please contribute.

Answer:
The best way is to make the file input control
almost
invisible (by giving it a very low opacity - do not do "
visibility: hidden
" or "
display: none
") and absolutely position something under it - with a lower
z-index
.
This way, the actual control will not be visible, and whatever you put under it will show through. But since the control is positioned above that button, it will still capture the click events (this is why you want to use opacity, not visibility or display - browsers make the element unclickable if you use those to hide it).
This article
goes in-depth on the technique.


Question:
Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?

EDIT:

Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.

Answer:
The following code will do what you want:
```
```
(define get-n-items
    (lambda (lst num)
        (if (> num 0)
            (cons (car lst) (get-n-items (cdr lst) (- num 1)))
            '()))) ;'

(define slice
    (lambda (lst start count)
        (if (> start 1)
            (slice (cdr lst) (- start 1) count)
            (get-n-items lst count))))
```
```
Example:
```
```
> (define l '(2 3 4 5 6 7 8 9)) ;'
()
> l
(2 3 4 5 6 7 8 9)
> (slice l 2 4)
(3 4 5 6)
>
```
```


Question:
class Tag(models.Model):
  name = models.CharField(maxlength=100)

class Blog(models.Model):
  name = models.CharField(maxlength=100)
  tags =  models.ManyToManyField(Tag)

Simple models just to ask my question.

I wonder how can i query blogs using tags in two different ways.

Blog entries that are tagged with "tag1" or "tag2":
Blog.objects.filter(tags_in=[1,2]).distinct()

Blog objects that are tagged with "tag1" and "tag2" : ?

Blog objects that are tagged with exactly "tag1" and "tag2" and nothing else : ??

Tag and Blog is just used for an example.

Answer:
You could use Q objects for #1:
```
```
# Blogs who have either hockey or django tags.
from django.db.models import Q
Blog.objects.filter(
    Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django')
)
```
```
Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to these.  The following examples are from a Django application called called
django-tagging
that provides the functionality.
Line 346 of models.py
:
For part two, you're looking for a union of two queries, basically
```
```
def get_union_by_model(self, queryset_or_model, tags):
    """
    Create a ``QuerySet`` containing instances of the specified
    model associated with *any* of the given list of tags.
    """
    tags = get_tag_list(tags)
    tag_count = len(tags)
    queryset, model = get_queryset_and_model(queryset_or_model)

    if not tag_count:
        return model._default_manager.none()

    model_table = qn(model._meta.db_table)
    # This query selects the ids of all objects which have any of
    # the given tags.
    query = """
    SELECT %(model_pk)s
    FROM %(model)s, %(tagged_item)s
    WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
      AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
      AND %(model_pk)s = %(tagged_item)s.object_id
    GROUP BY %(model_pk)s""" % {
        'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
        'model': model_table,
        'tagged_item': qn(self.model._meta.db_table),
        'content_type_id': ContentType.objects.get_for_model(model).pk,
        'tag_id_placeholders': ','.join(['%s'] * tag_count),
    }

    cursor = connection.cursor()
    cursor.execute(query, [tag.pk for tag in tags])
    object_ids = [row[0] for row in cursor.fetchall()]
    if len(object_ids) > 0:
        return queryset.filter(pk__in=object_ids)
    else:
        return model._default_manager.none()
```
```
For part #3 I believe you're looking for an intersection. See
line 307 of models.py
```
```
def get_intersection_by_model(self, queryset_or_model, tags):
    """
    Create a ``QuerySet`` containing instances of the specified
    model associated with *all* of the given list of tags.
    """
    tags = get_tag_list(tags)
    tag_count = len(tags)
    queryset, model = get_queryset_and_model(queryset_or_model)

    if not tag_count:
        return model._default_manager.none()

    model_table = qn(model._meta.db_table)
    # This query selects the ids of all objects which have all the
    # given tags.
    query = """
    SELECT %(model_pk)s
    FROM %(model)s, %(tagged_item)s
    WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
      AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
      AND %(model_pk)s = %(tagged_item)s.object_id
    GROUP BY %(model_pk)s
    HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % {
        'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
        'model': model_table,
        'tagged_item': qn(self.model._meta.db_table),
        'content_type_id': ContentType.objects.get_for_model(model).pk,
        'tag_id_placeholders': ','.join(['%s'] * tag_count),
        'tag_count': tag_count,
    }

    cursor = connection.cursor()
    cursor.execute(query, [tag.pk for tag in tags])
    object_ids = [row[0] for row in cursor.fetchall()]
    if len(object_ids) > 0:
        return queryset.filter(pk__in=object_ids)
    else:
        return model._default_manager.none()
```
```


Question:
I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.

BTW, this is an on-page Ajax search, so it has no button.

Answer:
You can add and remove a special CSS class and modify the input value
```
onfocus
```
/
```
onblur
```
with JavaScript:
```
```
<input type="text" class="hint" value="Search..."
    onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
    onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">
```
```
Then specify a
hint
class with the styling you want in your CSS for example:
```
```
input.hint {
    color: grey;
}
```
```


Question:
I want to add a column to an existing legacy database and write a procedure by which I can assign each record a different value. Something like adding a column and autogenerate the data for it.

Like, if I add a new column called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID column will have records from say 1 to 1000.

How do I do that?

Answer:
This will depend on the database but for SQL Server, this could be achieved as follows:
```
```
alter table Example
add NewColumn int identity(1,1)
```
```


Question:
As a novice, I've spent time learning a smattering of C and a fair bit of PHP. I've looked at writing desktop applications for Windows, but there seems to be a fair barrier to entry due to complexity of APIs. Is it worth learning this, or will native applications become less common in the future?

The way I see it, the only desktop application I ever use is a web browser and a text editor as well as the obviously the OS itself. Everything I need is online now.

Is learning to write non-web applications a useful skill going forwards? If so, what should I learn?

Answer:
You should learn whatever you
want
to learn.  If you don't you'll probably find it harder going than you need to.
I personally started writing desktop applications for Windows, because I used it at the time.  These days I do think that you're correct - you can produce a website / online-application without investing so much into the process.
But even writing a decent web application is going to be hard if you're new to programming.  A standalone page is simple, but when you add databases, security, and administration into the mix then things can grow.


Question:
I come from the Microsoft world (and I come in peace). I want to rapidly prototype a web app and if it works out, take it live - and I don't want to use ASP.Net.

I am not sure which web application toolkit to use though. Should I use GWT, DOJO...other recommendations?  I am open to any server-side language but am looking at RoR, Php or even Java (J2EE to be precise). I am not much of a Javascript/CSS guy so a toolkit that might make it relatively easy on me on those fronts would be preferable.

Also, I am a mac user at home. What IDEs go along with the framework you would recommend?

Any recommendations guys?

Answer:
If you're open to doing Java, GWT is the way to go. It allows you to have a relatively uniform codebase across client-server, and to only use one language on both.
There are some limitations to doing very off-the-beaten-path AJAXy things (which GWT makes difficult, but not impossible), but it doesn't sound like that's your use case anyway.
GWT will allow you to scale up by using more of its features as your app gets more complex - and your prototype won't be throwaway code.


Question:
I need a function like this:

// return true if 'n' is a power of 2, e.g.
// is_power_of_2(16) => true
// is_power_of_2(3) => false
bool is_power_of_2(int n);

Can anyone suggest how I could write this?

Answer:
A power of two will have just one bit set (for unsigned numbers). Something like
```
```
bool powerOfTwo = !(x == 0) && !(x & (x - 1));
```
```
Will work fine; one less than a power of two is all 1s in the less significant bits, so must AND to 0 bitwise.
As I was assuming unsigned numbers, the == 0 test (that I originally forgot, sorry) is adequate. You may want a > 0 test if you're using signed integers.


Question: What is the purpose of the code behind view file in ASP.NET MVC besides setting of the generic parameter of ViewPage ?

Answer:
There isn't a purpose. Just don't use it except for setting the model
```
```
ViewPage<Model>
```
```
See
this
blogpost for more info.


Question:
What are some good ways to do this? Is it even possible to do cleanly?

Ideally I'd like to use packet headers to decide which server should handle requests. However, if there is an easier/better way let me know.

Answer:
I found
this post
which suggested to have two separate IP addresses so that both could listen on port 80.
There was a caveat that you had to make a change in IIS because of socket pooling.  Here are the instructions based on the link above:
Extract the
```
httpcfg.exe
```
utility from the support tools area on the Win2003 CD.
Stop all IIS services:
```
net stop http /y
```
Have IIS listen only on the IP address I'd designated for IIS:
```
httpcfg set iplisten -i 192.168.1.253
```
Make sure:
```
httpcfg query iplisten
```
(The IPs listed are the only IP addresses that IIS will be listening on and no other.)
Restart IIS Services:
```
net start w3svc
```
Start the Apache service


Question:
It's really annoying that visual studio hides typos in aspx pages (not the code behind).
If the compiler would compile them, I would get a compile error.

Answer:
Resharper will catch errors in code  ofASPX pages, all without compiling. works well imo, and better than later compiling.
EDIT: Resharper also has a Solution wide error checker. 'Resharper->Windows->Errors in solution'. It will analyze your entire solution and give a consolidated list of everything it finds, INCLUDING aspx files.


Question:
At work we use Sandcastle for creation of help files. I have been using SandCastleGUI for some time and I'm looking for a way to create additional pages in the help file.
These pages are written in XML format called MAML.
The only problem is that I couldn't find any decent editor for these file format.

I'm looking for a WYSIWYG editor to create & edit additional documentation pages.

Answer:
You could use a generic XML editor with WYSIWYG support like
Oxygen
or
Serna
. You would need a Xml Schema or DTD for MAML, I assume there is one somewhere in an SDK or such. Probably the harder part is that you would need a stylesheet that renders the XML to an display format that can be used by the editor to provide a WYSIWYG view of the document.
It works rather well for standard XML formats such as Docbook, but I don't know how easy it is to find/create the needed stylesheets for MAML. But generally there is no reason why it couldn't be done.


Question:
I'm planning to create a data structure optimized to hold assembly code. That way I can be totally responsible for the optimization algorithms that will be working on this structure. If I can compile while running. It will be kind of dynamic execution. Is this possible? Have any one seen something like this?

Should I use structs to link the structure into a program flow. Are objects better?

struct asm_code {
   int type;
   int value;
   int optimized;
   asm_code *next_to_execute;
 } asm_imp;

Update: I think it will turn out, like a linked list.

Update: I know there are other compilers out there. But this is a military top secret project. So we can't trust any code. We have to do it all by ourselves.

Update: OK, I think I will just generate basic i386 machine code. But how do I jump into my memory blob when it is finished?

Answer:
It is possible. Dynamic code generation is even mainstream in some areas like software rendering and graphics. You find a lot of use in all kinds of script languages, in dynamic compilation of byte-code in machine code (.NET, Java, as far as I know Perl. Recently JavaScript joined the club as well).
You also find it used in very math-heavy applications as well, It makes a difference if you for example remove all multiplication with zero out of a matrix multiplication if you plan to do such a multiplication several thousand times.
I strongly suggest that you read on the SSA representation of code. That's a representation where each primitive is turned into the so called three operand form, and each variable is only assigned once (hence the same Static Single Assignment form).
You can run high order optimizations on such code, and it's straight forward to turn that code into executable code. You won't write that code-generation backend on a weekend though...
To get a feeling how the SSA looks like you can try out the LLVM compiler. On their web-site they have a little "Try Out" widget to play with. You paste C code into a window and you get something out that is close to the SSA form.
Little example how it looks like:
Lets take this integer square root algorithm in C. (arbitrary example, I just took something simple yet non-trivial):
```
```
unsigned int isqrt32 (unsigned int value)
{
    unsigned int g = 0;
    unsigned int bshift = 15;
    unsigned int b = 1<<bshift;
    do {
        unsigned int temp = (g+g+b)<<bshift;
        if (value >= temp) {
            g += b;
            value -= temp;
        }
        b>>=1;
    } while (bshift--);
    return g;
}
```
```
LLVM turns it into:
```
```
define i32 @isqrt32(i32 %value) nounwind  {
entry:
    br label %bb

bb:     ; preds = %bb, %entry
    %indvar = phi i32 [ 0, %entry ], [ %indvar.next, %bb ]
    %b.0 = phi i32 [ 32768, %entry ], [ %tmp23, %bb ]
    %g.1 = phi i32 [ 0, %entry ], [ %g.0, %bb ]
    %value_addr.1 = phi i32 [ %value, %entry ], [ %value_addr.0, %bb ]
    %bshift.0 = sub i32 15, %indvar
    %tmp5 = shl i32 %g.1, 1
    %tmp7 = add i32 %tmp5, %b.0
    %tmp9 = shl i32 %tmp7, %bshift.0
    %tmp12 = icmp ult i32 %value_addr.1, %tmp9
    %tmp17 = select i1 %tmp12, i32 0, i32 %b.0
    %g.0 = add i32 %tmp17, %g.1
    %tmp20 = select i1 %tmp12, i32 0, i32 %tmp9
    %value_addr.0 = sub i32 %value_addr.1, %tmp20
    %tmp23 = lshr i32 %b.0, 1
    %indvar.next = add i32 %indvar, 1
    %exitcond = icmp eq i32 %indvar.next, 16
    br i1 %exitcond, label %bb30, label %bb

bb30:       ; preds = %bb
    ret i32 %g.0
}
```
```
I know it looks horrible at first. It's not even pure SSA-Form. The more you read on that representation the more sense it will make. And you will also find out why this representation is so widely used these days.
Encapsulating all the info you need into a data-structure is easy. In the end you have to decide if you want to use enums or strings for opcode names ect.
Btw - I know I didn't gave you a data-structure but more a formal yet practical language and the advice where to look further.
It's a very nice and interesting research field.
Edit: And before I forget it: Don't overlook the built in features of .NET and Java. These languates allow you to compile from byte-code or source code from within the program and execute the result.
Cheers,
  Nils
Regarding your edit: How to execute a binary blob with code:
Jumping into your binary blob is OS and platform dependent. In a nutshell you have invalide the instruction cache,
maybe
you have to writeback the data-cache and you may have to enable execution rights on the memory-region you've wrote your code into.
On win32 it's relative easy as instruction cache flushing seems to be sufficient if you place your code on the heap.
You can use this stub to get started:
```
```
typedef void (* voidfunc) (void);

void * generate_code (void)
{
    // reserve some space
    unsigned char * buffer = (unsigned char *) malloc (1024);

    // write a single RET-instruction
    buffer[0] = 0xc3;

    return buffer;
}

int main (int argc, char **args)
{
    // generate some code:
    voidfunc func = (voidfunc) generate_code();

    // flush instruction cache:
    FlushInstructionCache(GetCurrentProcess(), func, 1024);

    // execute the code (it does nothing atm)
    func();

    // free memory and exit.
    free (func);
}
```
```


Question: I have a .z80 memory dump. How do I reverse engineer it? What do I need to know? How can I minimize manual labour?

Answer:
Most powerful disassembler -
IDA
supports z80.
Also list of disassemblers published at "
Software Development Tools for Z80 Family
" page


Question:
I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations?

Class code here:

class Enum(object):
'''Simple Enum Class
Example Usage:
>>> codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...'''
def __init__(self, names):
    for number, name in enumerate(names.split()):
        setattr(self, name, number)

Answer:
Enums have been proposed for inclusion into the language before, but were rejected (see
http://www.python.org/dev/peps/pep-0354/
), though there are existing packages you could use instead of writing your own implementation:
enum:
http://pypi.python.org/pypi/enum
SymbolType (not quite the same as enums, but still useful):
http://pypi.python.org/pypi/SymbolType
Or just do a search


Question:
Can a cookie be shared between two sites on the same top level domain? Say www.example.com and secure.example.com ?
We are looking into implementing a cache for non-secure content, and need to segregate secure content to another domain.
What parameters does the cookie need? I'm using asp.net

Answer:
Yes, you can. Use:
```
```
Response.Cookies("UID").Domain = ".myserver.com"
```
```


Question:
Data:  a dependency list, already verified to be acyclic.  So here, 'a' depends on 'b','c' (c depends on d), etc...

A = { 'a' :  dict(b=1, c=1),
    'c' : dict(d=1),
    'd' : dict(e=1,f=1,g=1),
    'h' : dict(j=1)
    }

I'd like to have a top-down, recursive solution to let's say, find the chain starting at
'a':  a, c, d, e, g, f, b

So, right now (a non-generator solution):

def get_all(D,k):
    L = []
    def get2(D,k):
        L.append(k)
        for ii in D.get(k,[]):
            get2(D, ii)
    get2(D,k)
    return L

Obviously, this is pretty weak :)  I've been banging my head about how to how to get yields inside there, and I'd appreciate any py-foo y'all can bring to this.

Answer:
Try this:
```
```
#!/usr/bin/env python

def get_all(D, k):
    yield k
    for ii in D.get(k, []):
        for jj in get_all(D, ii):
            yield jj

A = { 'a' : dict(b=1, c=1),
    'c' : dict(d=1),
    'd' : dict(e=1,f=1,g=1),
    'h' : dict(j=1)
    }

for ii in get_all(A,'a'):
    print ii
```
```
Gives me
```
steve@rei:~/code/tmp
$ python recur.py
a
c
d
e
g
f
b
```


Question:
Considering the following architecture:

a base object 'Entity'

a derived object 'Entry:Base'

and a further derived object 'CancelledEntry:Entry'

In EntitySQL I can write the following:

[...] where it is of (only MyEntities.Entry) [...]

to return only objects of type Entry and no Entity or CancelledEntry.

In linq to sql, the following command will return objects of type Entry and CancelledEntry.

EntityContext.EntitySet.OfType<Entry>()

What is the syntax/function to use to return only objects of type Entry?

Answer:
Ok, I have found a partial solution:
```
```
EntityContext.EntitySet.OfType<Entry>().Where( obj => !(obj is CancelledEntry) )
```
```
This is quite awful however, since if I create a new derived object, I have to go in all the queries and specifically add a condition to remove it.
There has to be a better solution


Question:
I'm struggling with a problem with the Script.aculo.us Autocompleter control in IE (I've tried it in IE6 & 7). The suggestions fail to appear for the first character is entered into the text box after the page has been loaded. After that initial failure, the control works as it should.

I've verified that the suggestions data is returned from the server correctly; the problem appears to have something to do with the positioning of the suggestions element, as other relatively positioned elements on the page move out of position at the moment that you'd expect the suggestions to appear.

Has anyone heard of such a problem or have any suggestions on how to fix it?

Edit: In response to Chris, I have set the partialChars parameter to 1 and the control works in all the other browsers I've tried, which are the latest versions of Firefox, Safari, Opera, and Chrome. I should probably have made that clear in the first place. Thanks.

Answer:
Is your problem just in IE, or in all browsers?  Ignoring the first char is actually the default for the Autocompleter.  In controls.js, there's a class called Autocompleter.Local which has a field called partialChars which defaults to 2.  The docs for that field say:
// - partialChars - How many characters to enter before triggering
//                   a partial match (unlike minChars, which defines
//                   how many characters are required to do any match
//                   at all). Defaults to 2.