q: I have a message broker with some topics, and some set of applications running on it. Now I want to run a new set of the same applications (say for QA environment) on the same topics (on the same broker, if I could). What is the best way to do this. Creating a new broker and or creating a new set of topics is cumbersome, as our environments are under tight bureaucracy.

[A]
AFAIK EMS does not support anything like what you suggest.  There are a few options to get what you are looking for.
Having independent EMS servers would be the
ideal
solution.  This would allow your non-production environment to have some hickups without causing problems in your production environment.
Using the same server you can have an environment-specific prefix tacked onto all the queue/topic names.  There would need to be some application level setting for which prefix to use (qa, dev, test, prod, ...).  This would make for pretty good isolation of the environments, but would probably not work too well if any of the environments are really heavily loaded.
For topics you can use some JMS header property and messages subscriptions to determine which environment to route them to.  I would not recommend this as it would be pretty easy to screw it up and corrupt both environments.


q:
Wondering if anybody out there has any success in using the JDEdwards XMLInterop functionality. I've been using it for a while (with a simple PInvoke, will post code later). I'm looking to see if there's a better and/or more robust way.

Thanks.

[A]
As promised, here is the code for integrating with JDEdewards using XML. It's a webservice, but could be used as you see fit.
```
```
namespace YourNameSpace
```
```
{
```
```
/// <summary>
/// This webservice allows you to submit JDE XML CallObject requests via a c# webservice
/// </summary>
[WebService(Namespace = "http://WebSite.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class JdeBFService : System.Web.Services.WebService
{
    private string _strServerName;
    private UInt16 _intServerPort;
    private Int16 _intServerTimeout;

    public JdeBFService()
    {
        // Load JDE ServerName, Port, & Connection Timeout from the Web.config file.
        _strServerName = ConfigurationManager.AppSettings["JdeServerName"];
        _intServerPort = Convert.ToUInt16(ConfigurationManager.AppSettings["JdePort"], CultureInfo.InvariantCulture);
        _intServerTimeout = Convert.ToInt16(ConfigurationManager.AppSettings["JdeTimeout"], CultureInfo.InvariantCulture);

    }

    /// <summary>
    /// This webmethod allows you to submit an XML formatted jdeRequest document
    /// that will call any Master Business Function referenced in the XML document
    /// and return a response.
    /// </summary>
    /// <param name="Xml"> The jdeRequest XML document </param>
    [WebMethod]
    public XmlDocument JdeXmlRequest(XmlDocument xmlInput)
    {
        try
        {
            string outputXml = string.Empty;
            outputXml = NativeMethods.JdeXmlRequest(xmlInput, _strServerName, _intServerPort, _intServerTimeout);

            XmlDocument outputXmlDoc = new XmlDocument();
            outputXmlDoc.LoadXml(outputXml);
            return outputXmlDoc;
        }
        catch (Exception ex)
        {
            ErrorReporting.SendEmail(ex);
            throw;
        }
    }
}

/// <summary>
/// This interop class uses pinvoke to call the JDE C++ dll.  It only has one static function.
/// </summary>
/// <remarks>
/// This class calls the xmlinterop.dll which can be found in the B9/system/bin32 directory.
/// Copy the dll to the webservice project's /bin directory before running the project.
/// </remarks>
internal static class NativeMethods
{
    [DllImport("xmlinterop.dll",
        EntryPoint = "_jdeXMLRequest@20",
        CharSet = CharSet.Auto,
        ExactSpelling = false,
        CallingConvention = CallingConvention.StdCall,
        SetLastError = true)]
    private static extern IntPtr jdeXMLRequest([MarshalAs(UnmanagedType.LPWStr)] StringBuilder server, UInt16 port, Int32 timeout, [MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, Int32 length);

    public static string JdeXmlRequest(XmlDocument xmlInput, string strServerName, UInt16 intPort, Int32 intTimeout)
    {
        StringBuilder sbServerName = new StringBuilder(strServerName);
        StringBuilder sbXML = new StringBuilder();
        XmlWriter xWriter = XmlWriter.Create(sbXML);
        xmlInput.WriteTo(xWriter);
        xWriter.Close();

        string result = Marshal.PtrToStringAnsi(jdeXMLRequest(sbServerName, intPort, intTimeout, sbXML, sbXML.Length));

        return result;
    }
}
```
```
}
You have to send it messages like the following one:
```
```
<jdeRequest type='callmethod' user='USER' pwd='PWD' environment='ENV'>
  <callMethod name='GetEffectiveAddress' app='JdeWebRequest' runOnError='no'>
    <params>
      <param name='mnAddressNumber'>10000</param>
    </params>
  </callMethod>
</jdeRequest>
```
```

s: huggingface

c: devops

d: intermediate


q:
Can this be done by setting a property?

I'd prefer that approach then to remove all security before re-adding it.
(As this may have other consequences.)

Another option I can think of is to replace the particular webpart dll with a temporary one, and restart the .net process, but that's not an approach I like at all.

What other options are there? AM I missing something obvious?

What i'm trying to do is find a way to disable a webpart while we update the underlying database schema it's using, for example.
So we'd ideally like to disable a specific webpart for all users, whether it's on a mysite, or a community site, make the required changes and then re-enable it.
Thus decreasing the downtime for users.

Whatever the solution is, we need to be able to do it across multiple front end servers, on potentially two farms easily.

Thanks for your help.

[A]
Go to Site Actions -> Edit Page
You get all the web parts edited. Click on the "Edit" dropdown of the Web Part you want to disable and choose "Close".
The web part disappears, but don't fear! It's not gone for good!
To have it back:
-> click to Add a new Web Part -> Advanced Web Part Gallery and Options.
The very first option you have is to choose among "Closed Web Parts". When clicking on that link, you will have displayed a list of all the web parts you had closed. Just add the one you want back!


q:
I'm looking for a way to stream a PDF file from my server to the browser using .NET 2.0 (in binary).

I'm trying to grab an existing PDF file from a server path and push that up as binary to the browser.

[A]
Write the binary to the output stream,
```
Response.OutputStream
```
. Then just add the header
```
Content-Disposition
```
header.


q:
I am wrapping a native C++ class, which has the following methods:

class Native
{
    public:
    class Local
    {
        std::string m_Str;
        int m_Int;
    };

    typedef std::vector<Local> LocalVec;
    typedef LocalVec::iterator LocalIter;

    LocalIter BeginLocals();
    LocalIter EndLocals();

    private:
        LocalVec m_Locals;
};

1) What is the ".NET way" of representing this same kind of interface? A single method returning an array<>? Does the array<> generic have iterators, so that I could implement BeginLocals() and EndLocals()?

2) Should Local be declared as a value struct in the .NET wrapper?

I'd really like to represent the wrapped class with a .NET flavor, but I'm very new to the managed world - and this type of information is frustrating to google for...

[A]
Iterators aren't exactly translatable to "the .net way", but they are roughly replaced by IEnumerable < T > and IEnumerator < T >.
Rather than
```
```
vector<int> a_vector;
  vector<int>::iterator a_iterator;
  for(int i= 0; i < 100; i++)
  {
    a_vector.push_back(i);
  }

  int total = 0;
  a_iterator = a_vector.begin();
  while( a_iterator != a_vector.end() ) {
    total += *a_iterator;
    a_iterator++;
  }
```
```
you would see (in c#)
```
```
List<int> a_list = new List<int>();
for(int i=0; i < 100; i++)
{
  a_list.Add(i);
}
int total = 0;
foreach( int item in a_list)
{
  total += item;
}
```
```
Or more explicitly (without hiding the IEnumerator behind the foreach syntax sugar):
```
```
List<int> a_list = new List<int>();
for (int i = 0; i < 100; i++)
{
    a_list.Add(i);
}
int total = 0;
IEnumerator<int> a_enumerator = a_list.GetEnumerator();
while (a_enumerator.MoveNext())
{
    total += a_enumerator.Current;
}
```
```
As you can see, foreach just hides the .net enumerator for you.
So really, the ".net way" would be to simply allow people to create List< Local > items for themselves.   If you do want to control iteration or make the collection a bit more custom, have your collection implement the IEnumerable< T > and/or ICollection< T > interfaces as well.
A near direct translation to c# would be pretty much what you assumed:
```
```
public class Native
{
  public class Local
  {
     public string m_str;
     public int m_int;
  }

  private List<Local> m_Locals = new List<Local>();

  public List<Local> Locals
  {
    get{ return m_Locals;}
  }
}
```
```
Then a user would be able to
```
```
foreach( Local item in someNative.Locals)
{
 ...
}
```
```


q:
I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.

Bonus if I can output in the user's locale date format.

[A]
Don't know how to do locale, but javascript is a client side technology.
```
```
usersLocalTime = new Date();
```
```
will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at).  It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.


q:
I know you can do redirection based on the domain or path to rewrite the URI to point at a site-specific location and I've also seen some brutish if and elif statements for every site as shown in the following code, which I would like to avoid.

if site == 'site1':
    ...
elif site == 'site2:
    ...

What are some good and clever ways of running multiple sites from a single, common Python web framework (i.e., Pylons, TurboGears, etc)?

[A]
Django has this built in.  See
the sites framework
.
As a general technique, include a 'host' column in your database schema attached to the data you want to be host-specific, then include the
```
Host
```
HTTP header in the query when you are retrieving data.


q:
On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only Sleep with millisecond granularity.

On Unix, I can use the use the select system call to create a microsecond sleep which is pretty straightforward:

int usleep(long usec)
{
    struct timeval tv;
    tv.tv_sec = usec/1000000L;
    tv.tv_usec = usec%1000000L;
    return select(0, 0, 0, 0, &tv);
}

How can I achieve the same on Windows?

[A]
On Windows the use of
```
select
```
forces you to include the
Winsock
library which has to be initialized like this in your application:
```
```
WORD wVersionRequested = MAKEWORD(1,0);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
```
```
And then the select won't allow you to be called without any socket so you have to do a little more to create a microsleep method:
```
```
int usleep(long usec)
{
    struct timeval tv;
    fd_set dummy;
    SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    FD_ZERO(&dummy);
    FD_SET(s, &dummy);
    tv.tv_sec = usec/1000000L;
    tv.tv_usec = usec%1000000L;
    return select(0, 0, 0, &dummy, &tv);
}
```
```
All these created usleep methods return zero when successful and non-zero for errors.


q:
Say I have a class named Frog, it looks like:

public class Frog
{
     public int Location { get; set; }
     public int JumpCount { get; set; }

     public void OnJump()
     {
         JumpCount++;
     }

}

I need help with 2 things:

I want to create an event named Jump in the class definition.

I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.

[A]
```
```
public event EventHandler Jump;
public void OnJump()
{
    EventHandler handler = Jump;
    if (null != handler) handler(this, EventArgs.Empty);
}
```
```
then
```
```
Frog frog = new Frog();
frog.Jump += new EventHandler(yourMethod);

private void yourMethod(object s, EventArgs e)
{
     Console.WriteLine("Frog has Jumped!");
}
```
```


q: MonoDevelop 1.0 doesn't appear to have a code-formatter like Eclipse does for Java.  Is there a preferred shell script (or MonoDevelop add-in?) that you've found to work well?

[A]
At the moment, source code formatting in MonoDevelop is marked as a future enhancement:
https://bugzilla.novell.com/show_bug.cgi?id=321946
In the meantime, you may want to check out Artistic Style for C# formatting:
http://astyle.sourceforge.net/
I'm planning to see how this might be wired up as an external tool within MonoDevelop.  If I get to that, I will edit my answer with the information.
UPDATE: I don't have enough reputation to leave a comment, so I'll make one here: Nice job, Dustin, and patch for MonoDevelop too :-)  I wonder how recent the version is that is included with Ubuntu... Either way, I'm glad you found something that works for you.


q:
I have an object that implements IDisposable that is registered with the Windsor Container and I would like to dispose of it so it's Dispose method is called and next time Resolve is called it fetches a new instance.

Does

container.Release(obj);

automatically call Dispose() immediately?  Or do I need to do

obj.Dispose();
container.Release(obj);

Couldn't find anything in the documentation on what exactly Release does

EDIT:
See my answer below for the results of tests I ran.  Now the question becomes, how do I force the container to release an instance of a component with a singleton lifecycle?  This only needs to be done in one place and writing a custom lifecycle seems far too heavyweight, is there no built in way of doing it?

[A]
It depends on the lifestyle of the component you specified when you added it to the container.
You would use Release() If the lifestyle is Pooled.  This puts the component back in the pool for the next retrieval (the object is not destroyed, so disposing would be bad)
if the lifestyle is transient, a new object is created when you get the component.  In this case the disposal is up to you, and you do not need to call Release
If the lifestyle is Thread, the same component is used for each thread, not destroyed.
If the lifestyle is Singleton, only one component is created and not detroyed.
Most likely, you are using transient components? (if you are concerned about disposing of them in a timely manner)
in that case, just wrap it with a using and you're set (or call the dispose yourself somewhere)
```
```
using(ISomeService service = container.Resolve<ISomeService>())
{
 // Do stuff here
 // service.Dispose is automatically called
}
```
```
Edit
- Yes, in order to "refresh" or dispose and recreate your singleton you would need to either destroy the container or write a custom lifecycle.  Doing a custom lifecycle is not actually that difficult and keeps the logic to do so in one place.


q:
Is there an equivalent schema & data export/dumping tool for SQL Server as there is for MySQL with mysqldump.   Trying to relocate a legacy ASP site and I am way out of happy place with working on a windows server.

Note:  The DTS export utility own seems to export data, without table defs.
Using the Enterprise Manager and exporting the db gets closer with exporting the schema & data... but still misses stored procedures.

Basically looking for a one does it all solution that grabs everything I need at once.

[A]
Well, Mysqldump is a series of SQL statements. You can do this with DTS, but why not just create a backup and restore it on your new machine?
If you want to do it via SQL:
http://msdn.microsoft.com/en-us/library/aa225964(SQL.80).aspx
Or just right click the DB and hit Tasks -> Backup (
http://msdn.microsoft.com/en-us/library/ms187510.aspx
)


q:
Consider:

List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList

for (String item : someList) {
    System.out.println(item);
}

What would the equivalent for loop look like without using the for each syntax?

[A]
```
```
for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
    String item = i.next();
    System.out.println(item);
}
```
```
Note that if you need to use
```
i.remove();
```
in your loop, or access the actual iterator in some way, you cannot use the
```
for ( : )
```
idiom, since the actual iterator is merely inferred.
As was noted by Denis Bueno, this code works for any object that implements the
```
Iterable
```
interface
.
Also, if the right-hand side of the
```
for (:)
```
idiom is an
```
array
```
rather than an
```
Iterable
```
object, the internal code uses an int index counter and checks against
```
array.length
```
instead. See the
Java Language Specification
.


q:
I'm working on a game where I create a random map of provinces (a la Risk or Diplomacy).  To create that map, I'm first generating a series of semi-random points, then figuring the Delaunay triangulations of those points.

With that done, I am now looking to create a Voronoi diagram of the points to serve as a starting point for the province borders.  My data at this point (no pun intended) consists of the original series of points and a collection of the Delaunay triangles.

I've seen a number of ways to do this on the web, but most of them are tied up with how the Delaunay was derived.  I'd love to find something that doesn't need to be integrated to the Delaunay, but can work based off the data alone.  Failing that, I'm looking for something comprehensible to a relative geometry newbie, as opposed to optimal speed.  Thanks!

[A]
The Voronoi diagram is just the dual graph of the Delaunay triangulation.
So, the edges of the Voronoi diagram are along the perpendicular bisectors of the edges of the Delaunay triangulation, so compute those lines.
Then, compute the vertices of the Voronoi diagram by finding the intersections of adjacent edges.
Finally, the edges are then the subsets of the lines you computed which lie between the corresponding vertices.
Note that the exact code depends on the internal representation you're using for the two diagrams.


q:
In the Vim and Emacs terminal apps, the color schemes look horrid. How do I enable the colors to be as vibrant as the GUI version (or more than 8 colors for that matter)?

Should I just give up, and move over to their respective GUI applications? And if so, which?

[A]
You can't have
more
colors in the terminal, because there are only ANSI codes for 8 colors (16 if you count bold/light).  If you want to customize the colors, you can use the TerminalColours plugin from
http://ciaranwal.sh/2007/11/01/customising-colours-in-leopard-terminal
Personally, I prefer to use the so-called Carbon Emacs on my Mac.  There are several builds available; Google is your friend.  I get mine from
http://www.porkrind.org/emacs/


q:
I'm having problems deciding on what is the best way is to handle and store time measurements.

I have an app that has a textbox that allows the users to input time in either hh:mm:ss or mm:ss format.

So I was planning on parsing this string, tokenizing it on the colons and creating TimeSpan (or using TimeSpan.Parse() and just adding a "00:" to the mm:ss case) for my business logic. Ok?

How do I store this as in a database though? What would the field type be? DateTime seems wrong. I don't want a time of 00:54:12 to be stored as 1901-01-01 00:54:12 that seems a bit poor?

[A] I think the simplest is to just convert user input into a integer number of seconds. So 54:12 == 3252 seconds, so store the 3252 in your database or wherever. Then when you need to display it to the user, you can convert it back again.


q:
What is the best (or as good as possible) general SVN ignore pattern to use?

There are a number of different IDE, editor, compiler, plug-in, platform, etc. specific files and some file types that "overlap" (i.e. desirable for some types projects and not for others).

There are however, a large number of file types that you just never want included in source control automatically regardless the specifics of your development environment.

The answer to this question would serve as a good starting point for any project - only requiring them to add the few environment specific items they need. It could be adapted for other Version Control Systems (VCS) as well.

[A]
Used for my Visual Studio projects
```
```
*/bin */obj *.user *.suo
```
```
You can expand more file types from there.


[A]
The key is to use
DATEADD
and
DATEDIFF
along with the appropriate SQL timespan enumeration.
```
```
declare @datetime datetime;
set @datetime = getdate();
select @datetime;
select dateadd(year,datediff(year,0,@datetime),0);
select dateadd(month,datediff(month,0,@datetime),0);
select dateadd(day,datediff(day,0,@datetime),0);
select dateadd(hour,datediff(hour,0,@datetime),0);
select dateadd(minute,datediff(minute,0,@datetime),0);
select dateadd(second,datediff(second,'2000-01-01',@datetime),'2000-01-01');
select dateadd(week,datediff(week,0,@datetime),-1); --Beginning of week is Sunday
select dateadd(week,datediff(week,0,@datetime),0); --Beginning of week is Monday
```
```
Note that when you are flooring by the second, you will often get an arithmetic overflow if you use 0. So pick a known value that is guaranteed to be lower than the datetime you are attempting to floor.


q: I need to take a Word document that is a template of sorts...collect user input to populate specific fields in that template..then generate a PDF file that includes the completed template as well as a few other document types. Does anyone have a good suggestion on a component to achieve this? Preferably one that does not require Microsoft Office to be installed on the web server.

[A]
Is there a reason to use Word? If you start with a PDF with Form fields, you can either allow the user to fill out the fields, or do it programatically with iTextSharp's PDF stamper.
If you need to use MSOffice 2000/2003 components programmatically, you can try Office Web Components. They do need to be installed on the server, but can be used by .NET and Com apps to interact with office file types. More info here...
http://en.wikipedia.org/wiki/Office_Web_Components
If you dig about on an office CD you should find the OWC installer for your version. I haven't worked with 2007, but I assume there is something similar available.
iTextSharp and OWC are no-cost, check the licensing for more details.


q:
I am trying to inherit from my generated datacontext in LinqToSQL - something like this

public class myContext : dbDataContext {
 public System.Data.Linq.Table<User>() Users {
  return (from x in base.Users() where x.DeletedOn.HasValue == false select x);
 }
}

But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated.

Hal

[A]
You could use discriminator column inheritance on the table, ie. a DeletedUsers table and ActiveUsers table where the discriminator column says which goes to which.  Then in your code, just reference the Users.OfType ActiveUsers, which will never include anything deleted.
As a side note, how the heck do you do this with markdown?
```
```
Users.OfType<ActiveUsers>
```
```
I can get it in code, but not inline


q:
Say I've got this table (SQL Server 2005):

Id => integer
MyField => XML

Id  MyField

1   < Object>< Type>AAA< /Type>< Value>10< /Value>< /Object>< Object>< Type>BBB< /Type><Value>20< /Value>< /Object>
2   < Object>< Type>AAA< /Type>< Value>15< /Value>< /Object>
3   < Object>< Type>AAA< /Type>< Value>20< /Value>< /Object>< Object>< Type>BBB< /Type>< Value>30< /Value>< /Object>

I need a TSQL query which would return something like this:

Id  AAA     BBB
1   10      20
2   15      NULL
3   20      30

Note that I won't know if advance how many 'Type' (eg AAA, BBB, CCC,DDD, etc.) there will be in the xml string.

[A]
You will need to use the
XML querying in sql server
to do that.
somethings like
```
```
select id, MyField.query('/Object/Type[.="AAA"]/Value') as AAA, MyField.query('/Object/Type[.="BBB"]/Value) AS BBB
```
```
not sure if that's 100% correct xquery syntax, but it's going to be something like that.


q: How do I perform a reverse DNS lookup, that is how do I resolve an IP address to its DNS hostname in Perl?

[A]
gethostbyaddr and similar calls. See
http://perldoc.perl.org/functions/gethostbyaddr.html


q:
First time working with UpdatePanels in .NET.

I have an updatepanel with a trigger pointed to an event on a FormView control. The UpdatePanel holds a ListView with related data from a separate database.

When the UpdatePanel refreshes, it needs values from the FormView control so that on the server it can use them to query the database.

For the life if me, I can't figure out how to get those values. The event I'm triggering from has them, but I want the updatepanel to refresh asynchronously. How do I pass values to the load event on the panel?

Googled this ad nauseum and can't seem to get to an answer here. A link or an explanation would be immensely helpful..

Jeff

[A]
Try
...looking in the Request and
Response.
...setting a breakpoint
on the Load() method and query Me or
this in the watch or immediate
window to see if the values you want
are maybe just not where you are
expecting them?
...Put a (For Each ctl as Control in Me/This.Controls)
and inspecting each control that is iterated and see if you are even getting the controls you expect.
... its not in Sender or EventArgs?
Try NOT using Update panels.... They can often cause more trouble than they are worth. It may be faster and less headache to use regular AJAX to get it done.


q: What does the option “convert to web application” do if I select it in visual studio? If I do convert my site to a web application what are the advantages? Can I go back?

[A]
Well, it converts your web site to a web application project. As for the advantages, here is some further reading:
MSDN comparison --
Comparing Web Site Projects and Web Application Projects
Webcast on ASP.NET --
Web Application Projects vs. Web Site Projects in Visual Studio 2008
"In this webcast, by request, we examine the differences between web application projects and web site projects in Microsoft Visual Studio 2008. We focus specifically on the reasons you would choose one over the other and explain how to make informed decisions when creating a Web solution
"
The primary difference (to me) between a web application project and a web site is how things gets compiled.  In web sites each page has its code-behind compiled into a separate library, whereas in web applications all code-behind gets compiled into a single library.
There are advantages and disadvantages to both, it really depends. It's also often a matter of
opinion
.


q: As you may know, Silverlight does not have the TileBrush found in WPF. Is there a workaround to do tiling?

[A]
Well, it would appear that Silverlight does support the TileBrush, as referenced on MSDN:
System.Windows.Media.TileBrush
. It first appears in Silverlight 2.0 Beta 2.


q:
I have a line of C# in my ASP.NET code behind that looks like this:

DropDownList ddlStates = (DropDownList)fvAccountSummary.FindControl("ddlStates");

The DropDownList control is explicitly declared in the markup on the page, not dynamically created. It is inside of a FormView control. When my code hits this line, I am getting an ArithmeticException with the message "Value was either too large or too small for an Int32." This code has worked previously, and is in production right now. I fired up VS2008 to make some changes to the site, but before I changed anything, I got this exception from the page. Anyone seen this one before?

[A] Are you 100% sure that's the line of code that's throwing the exception? I'm pretty certain that the FindControl method is not capable of throwing an ArithmeticException. Of course, I've been known to be wrong before... :)


q:
How do I remove a USB drive using the Win32 API? I do a lot of work on embedded systems and on one of these I have to copy my programs on a USB stick and insert it into the target hardware.

Since I mostly work on the console I don't like to use the mouse and click on the small task-bar icon hundred times a day.

I'd love to write a little program to do exactly that so I can put it into my makefiles, but I haven't found any API call that does the same thing.

Any ideas?

[A]
It looks like
Sync
lets you specify -e to eject removable drives. While not a win32 API, you could probably just call
```
sync -e [drive_letter]
```
from your makefile.


q:
I have two tables I would like to complare.  One of the columns is type CLOB.  I would like to do something like this:

select key, clob_value source_table
minus
select key, clob_value target_table

Unfortunately, Oracle can't perform minus operations on clobs.  How can I do this?

[A]
Can you access the data via a built in package? If so then perhaps you could write a function that returned a string representation of the data (eg some sort of hash on the data), then you could do
```
```
select key, to_hash_str_val(glob_value) from source_table
minus
select key, to_hash_str_val(glob_value) from target_table
```
```


q:
I'm building a group calendar application that needs to support recurring events, but all the solutions I've come up with to handle these events seem like a hack. I can limit how far ahead one can look, and then generate all the events at once. Or I can store the events as repeating and dynamically display them when one looks ahead on the calendar, but I'll have to convert them to a normal event if someone wants to change the details on a particular instance of the event.

I'm sure there's a better way to do this, but I haven't found it yet. What's the best way to model recurring events, where you can change details of or delete particular event instances?

(I'm using Ruby, but please don't let that constrain your answer. If there's a Ruby-specific library or something, though, that's good to know.)

[A]
You may want to look at iCalendar software implementations or the standard itself (
RFC 2445
RFC 5545
).
Ones to come to mind quickly are the Mozilla projects
http://www.mozilla.org/projects/calendar/
A quick search reveals
http://icalendar.rubyforge.org/
as well.
Other options can be considered depending on how you're going to store the events.  Are you building your own database schema?  Using something iCalendar-based, etc.?


q:
I want to have a "select-only" ComboBox that provides a list of items for the user to select from. Typing should be disabled in the text portion of the ComboBox control.

My initial googling of this turned up an overly complex, misguided suggestion to capture the KeyPress event.

[A]
To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList".  The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:
```
```
stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
```
```
Link to the documentation for the
ComboBox DropDownStyle property
on MSDN.


q: I have an external variable coming in as a string and I would like to do a switch/case on it. How do I do that in xquery?

[A]
XQuery doesn't have a function for switching on anything other than elements.
The first thing you do is convert your string to an element.
```
```
let $str := "kitchen"
let $room := element {$str} {}
```
```
Then just use typeswitch to do a normal switch:
```
```
return typeswitch($room)
  case element(bathroom) return "loo"
  case element(kitchen) return "scullery"
  default return "just a room"
```
```
Please note, this may be a MarkLogic only solution.


q:
here is the input  i am getting from my flash file

process.php?Q2=898&Aa=Grade1&Tim=0%3A0%3A12&Q1=908&Bb=lkj&Q4=jhj&Q3=08&Cc=North%20America&Q0=1

and in php i use this code
foreach ($_GET as $field => $label)
{
    $datarray[]=$_GET[$field];

echo  "$field :";
echo $_GET[$field];;
echo "<br>";

i get this out put

Q2 :898
Aa :Grade1
Tim :0:0:12
Q1 :908
Bb :lkj
Q4 :jhj
Q3 :08
Cc :North America
Q0 :1

now my question is how do i sort it alphabaticaly so it should look like this
Aa :Grade1
Bb :lkj
Cc :North America
Q0 :1
Q1 :908

and so on....before i can insert it into the DB

[A]
```
```
ksort($_GET);
```
```
This should
ksort
the
```
$_GET
```
array by it's keys.
krsort
for reverse order.


q:
How do you tell if a function in JavaScript is defined?

I want to do something like this

function something_cool(text, callback) {
    alert(text);
    if( callback != null ) callback();
}

But it gets me a

callback is not a function

error when callback is not defined.

[A]
```
```
typeof callback === "function"
```
```


q:
I've got just one page that I want to force to be accessed as an HTTPS page (PHP on Apache). How do I do this without making the whole directory require HTTPS? Or, if you submit a form to an HTTPS page from an HTTP page, does it send it by HTTPS instead of HTTP?

Here is my example:

http://www.example.com/some-page.php

I want it to only be accessed through:

https://www.example.com/some-page.php

Sure, I can put all of the links to this page pointed at the HTTPS version, but that doesn't stop some fool from accessing it through HTTP on purpose...

One thing I thought was putting a redirect in the header of the PHP file to check to be sure that they are accessing the HTTPS version:

if($_SERVER["SCRIPT_URI"] == "http://www.example.com/some-page.php"){
  header('Location: https://www.example.com/some-page.php');
}

But that can't be the right way, can it?

[A]
You could do it with a  directive and mod_rewrite on Apache:
```
```
<Location /buyCrap.php>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</Location>
```
```
You could make the Location smarter over time using
regular expressions
if you want.


q:
Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined.

I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this?

Edit: The following sniplet works like a charm:

fn_exists()
{
    LC_ALL=C type $1 | grep -q 'shell function'
}

[A]
Like this:
```
[[ $(type -t foo) == function ]] && echo "Foo exists"
```
The built-in
```
type
```
command will tell you whether something is a function, built-in function, external command, or just not defined.
Additional examples:
```
```
$ LC_ALL=C type foo
bash: type: foo: not found

$ LC_ALL=C type ls
ls is aliased to `ls --color=auto'

$ which type

$ LC_ALL=C type type
type is a shell builtin

$ LC_ALL=C type -t rvm
function

$ if [ -n "$(LC_ALL=C type -t rvm)" ] && [ "$(LC_ALL=C type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi
rvm is a function
```
```


q:
I'm trying to determine if there's a way in Visual Basic 2008 (Express edition if that matters) to do inline collection initialization, a la JavaScript or Python:

Dim oMapping As Dictionary(Of Integer, String) = {{1,"First"}, {2, "Second"}}

I know Visual Basic 2008 supports array initialization like this, but I can't seem to get it to work for collections... Do I have the syntax wrong, or is it just not implemented?

[A]
Visual Basic 9.0
doesn't support this yet. However,
Visual Basic 10.0
will
.


q:
I have an old .dot file with a few dozen styles in it.

I need to place them into another .dot file  that I received.  Is there a better way to get them in there than manually recreating each style?

[A]
There is a 'Style Organizer' tool within Word which will let you copy styles from one document to another if they are both open at once.
In Word 2007:
Open the styles dialog (Home tab -> Styles -> Bottom Right button).
Click the 'manage styles' button.
Click 'Import/Export...'
I can't remember what the option is in Word 2003. I think it was Tools -> Style Organizer or similar.


q: For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo.  I'm using Oracle 10G.

[A]
This should work (or something close):
```
```
select table_name
from all_constraints
where constraint_type='R'
and r_constraint_name in
  (select constraint_name
  from all_constraints
  where constraint_type in ('P','U')
  and table_name='<your table here>');
```
```


q:
How do I enumerate the properties of a JavaScript object?

I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.

[A]
Simple enough:
```
```
for(var propertyName in myObject) {
   // propertyName is what you want
   // you can get the value like this: myObject[propertyName]
}
```
```
Now, you will not get private variables this way because they are not available.
EDIT:
@bitwiseplatypus
is correct that unless you use the
```
hasOwnProperty()
```
method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.
Now, that said,
```
hasOwnProperty()
```
is
useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.
EDIT 2:
@bitwiseplatypus
brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use
```
hasOwnProperty()
```
. Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via
```
jQuery.extend
```
and
```
jQuery.fn.extend
```
).


q:
I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with  a clean install of Windows, without actually going on the net.  Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it.

I want my program to download the apps to program files\any name here\

So basically I need a function that checks if a folder exists, and if it doesn't it creates it.

[A]
Try this:
```
Directory.Exists(TheFolderName)
```
and
```
Directory.CreateDirectory(TheFolderName)
```
(You may need:
```
Imports System.IO
```
)


q:
How do i measure how long a client has to wait for a request.

On the server side it is easy, through a filter for example.
But if we want to take into accout the total time including latency and data transfer, it gets diffcult.

is it possible to access the underlying socket to see when the request is finished?
or is it neccessary to do some javascript tricks? maybe through clock synchronisation between browser and server? are there any premade javascripts for this task?

[A]
You could set a 0 byte socket send buffer  (and I don't exactly recommend this) so that when your blocking call to HttpResponse.send() you have a closer idea as to when the last byte left, but travel time is not included.
Ekk
--I feel queasy for even mentioning it.  You can do this in Tomcat with connector specific settings. (
Tomcat 6 Connector documentation
)
Or you could come up with some sort of javascript time stamp approach, but I would not expect to set the client clock.  Multiple calls to the web server would have to be made.
timestamp query
the real request
reporting the data
And this approach would cover latency, although you still have have some jitter variance.
Hmmm...interesting problem you have there.  :)


q:
If you are using HAML and SASS in your Rails application, then any templates you define in public/stylesheet/*.sass will be compiled into *.css stylesheets. From your code, you use stylesheet_link_tag to pull in the asset by name without having to worry about the extension.

Many people dislike storing generated code or compiled code in version control, and it also stands to reason that the public/ directory shouldn't contain elements that you don't send to the browser.

What is the best pattern to follow when laying out SASS resources in your Rails project?

[A]
If I can manage it, I like to store all of my styles in SASS templates when I choose HAML/SASS for a project, and I'll remove application.css and scaffold.css. Then I will put SASS in public/stylesheets/sass, and add /public/stylesheets/*.css to .gitignore.
If I have to work with a combination of SASS and CSS based assets, it's a little more complicated. The simplest way of handling this is to have an output subdirectory for generated CSS within the stylesheets directory, then exclude that subdirectory in .gitignore. Then, in your views you have to know which styling type you're using (SASS or CSS) by virtue of having to select the public/stylesheets/foo stylesheet or the public/stylesheets/sass-out/foo stylesheet.
If you have to go the second route, build a helper to abstract away the sass-out subdirectory.


q: I'm wondering the best way to start a pthread that is a member of a C++ class? My own approach follows as an answer...

[A] I usually use a static member function of the class, and use a pointer to the class as the void * parameter.  That function can then either perform thread processing, or call another non-static member function with the class reference.  That function can then reference all class members without awkward syntax.


q:
I have a WinForms application with a DataGridView control and a column of DataGridViewButtonCell cells within that. When I click on one of these buttons, it starts a background task, and I'd like to disable the buttons until that task completes.

I can disable the DataGridView control, but it gives no visual indication that the buttons are disabled. I want the user to see that the buttons are disabled, and to notice that the task has finished when the buttons are enabled again.

Bonus points for a method that allows me to disable the buttons individually, so I can leave one of the buttons enabled while the task runs. (Note that I can't actually give out bonus points.)

[A]
Here's the best solution I've found so far. This
MSDN article
gives the source code for a cell class that adds an Enabled property.
It works reasonably well, but there are two gotchas:
You have to invalidate the grid after setting the Enabled property on any cells. It shows that in the sample code, but I missed it.
It's only a visual change, setting the Enabled property doesn't actually enable or disable the button. The user can still click on it. I could check the enabled property before executing the click event, but it also seemed to be messing up the appearance when the user clicked on it. Instead, I just disabled the entire grid. That works alright for me, but I'd prefer a method that allows me to disable some buttons without disabling the entire grid.
There's a similar sample in the
DataGridView FAQ
.


q:
I can make a DAO recordset in VB6/Access do anything - add data, clean data, move data, get data dressed in the morning and take it to school. But I don't even know where to start in .NET.

I'm not having any problems retrieving data from the database, but what do real people do when they need to edit data and put it back?

What's the easiest and most direct way to edit, update and append data into related tables in .NET and SQL Server?

[A]
Look in the enclosing directories. They need to be at least mode 711. (
```
drwx--x--x
```
)
Also, look in
```
/var/log/apache2/error_log
```
(Or whatever the concatenation of
```
ServerRoot
```
and
```
ErrorLog
```
is from the
```
httpd.conf
```
) for a possibly more-detailed error message.
Finally, ensure you restart apache after messing with
```
httpd.conf
```
.


q: I need to get the default printer name. I'll be using C# but I suspect this is more of a framework question and isn't language specific.

[A]
The easiest way I found is to create a new
```
PrinterSettings
```
object.  It starts with all default values, so you can check its
Name
property to get the name of the default printer.
```
PrinterSettings
```
is in System.Drawing.dll in the namespace
```
System.Drawing.Printing
```
.
```
```
PrinterSettings settings = new PrinterSettings();
Console.WriteLine(settings.PrinterName);
```
```
Alternatively, you could maybe use the static
```
PrinterSettings.InstalledPrinters
```
method to get a list of all printer names, then set the
PrinterName
property and check the
IsDefaultPrinter
.  I haven't tried this, but the documentation seems to suggest it won't work.  Apparently
IsDefaultPrinter
is only true when
PrinterName
is not explicitly set.


q: Polyglot, or multiple language, solutions allow you to apply languages to problems which they are best suited for.  Yet, at least in my experience, software shops tend to want to apply a "super" language to all aspects of the problem they are trying to solve.  Sticking with that language come "hell or high water" even if another language is available which solves the problem simply and naturally. Why do you or do you not implement using polyglot solutions?

[A]
One issue that I've run into is that Visual Studio doesn't allow multiple languages to be mixed in a single project, forcing you to abstract things out into separate DLLs for each language, which isn't necessarily ideal.
I suspect the main reason, however, is the perception that switching back and forth between many different languages leads to programmer inefficiency.  There is some truth to this, I switch constantly between JavaScript, C#, VBScript, and VB.NET and there is a bit of lost time as I switch from one language to another, as I mix my syntax a bit.
Still, there is definitely room for more "polyglot" solutions particularly that extend beyond using JavaScript and whatever back-end programming language.


q:
Reading through the Flickr API documentation it keeps stating I require an API key to use their REST protocols. I am only building a photo viewer, gathering information available from Flickr's public photo feed (For instance, I am not planning on writing an upload script, where a API key would be required). Is there any added functionality I can get from getting a Key?

Update I answered the question below

[A]
The Flickr API is very nice and easy to use and will be much easier than scraping the feed yourself.
Getting a key takes about 2 minutes - you fill in a form on the website and then email it to you.


q:
Does anyone know of any 'standard' way to interface with a telephony system (think Cisco CCM) from a C/C++ app in *nix?  I have used MS TAPI in the past but this is Windows only and don't want to go the jTAPI (Java) route, which seems to be the only option on the face of it.

I want to monitor the phone system for logging purposes (so I know when users have made calls, received calls, etc.).  TAPI is good at this sort of thing but I can't be the first person who wants to do something similar without having a Windows server.

Note that I need to integrate with existing PABX systems - notably Cisco CCM and Nortel BCM.

[A]
I have experience with two telephony standards TAPI, and CSTA, as far as I know there is no such agreement between vendors (e.g. Cisco, Nortel, NEC) regarding THE standard API.
I would recommend looking at the availability of
SMDR
(Station Messaging Detail Recording) on the PBX platforms you are targeting, assuming that no call/device control is required. This will allow you to access the PBX activity as a text stream and you can parse the data for further manipulations to suit your purpose.
Most likely the format between the PBX vendors will be different but hopefully this could be abstracted away so that the core application functionality is re-usable.
This is likely to be a more portable option, again assuming no call/device control is required, as you are not relying on the vendor providing CTI connectivity on your platform of choice.


q:
I have a Perl script that I'm attempting to set up using Perl Threads (use threads).  When I run simple tests everything works, but when I do my actual script (which has the threads running multiple SQLPlus sessions), each SQLPlus session runs in order (i.e., thread 1's sqlplus runs steps 1-5, then thread 2's sqlplus runs steps 6-11, etc.).

I thought I understood that threads would do concurrent processing, but something's amiss.  Any ideas, or should I be doing some other Perl magic?

[A]
Actually, you have no way of guaranteeing in which order threads will execute. So the behavior (if not what you expect) is not really wrong.
I suspect you have some kind of synchronization going on here. Possibly SQL*Plus only let's itself be called once? Some programs do that...
Other possiblilties:
thread creation and process creation (you
are
creating subprocesses for SQL*Plus, aren't you?) take longer than running the thread, so thread 1 is finished before thread 2 even starts
You are using transactions in your SQL scripts that force synchronization of database updates.


q:
I normally run VS 2008 at home and LINQ is built in.  At work we are still using VS 2005 and I have the opportunity to start a new project that I would like to use LINQ to SQL.

After doing some searching all I could come up with was the MAY 2006 CTP of LINQ would have to be installed for LINQ to work in VS 2005.

Does someone know the proper add ins or updates I would need to install to use LINQ in VS 2005 (preferably without having to use the CTP mentioned above).


q: I am attempting to find xml files with large swaths of commented out xml.  I would like to programmatically search for xml comments that stretch beyond a given number of lines.  Is there an easy way of doing this?

[A]
Considering that XML doesn't use a line based format, you should probably check the number of characters. With a regular expression, you can create a pattern to match the comment prefix and match a minimum number of characters before it matches the first comment suffix.
http://www.regular-expressions.info/
Here is the pattern that worked in some preliminary tests:
```
```
<!-- (.[^-->]|[\r\n][^-->]){5}(.[^-->]|[\r\n][^-->])*? -->
```
```
It will match the starting comment prefix and everything including newline character (on a windows OS) and it's lazy so it will stop at the first comment suffix.
Sorry for the edits, you are correct here is an updated pattern. It's obviously not optimized, but in some tests it seems to resolve the error you pointed out.


q:
Let's say I have an aspx page with this calendar control:

<asp:Calendar ID="Calendar1" runat="server"  SelectedDate="" ></asp:Calendar>

Is there anything I can put in for SelectedDate to make it use the current date by default, without having to use the code-behind?

[A]
If you are already doing databinding:
```
```
<asp:Calendar ID="Calendar1" runat="server"  SelectedDate="<%# DateTime.Today %>" />
```
```
Will do it.  This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control).   If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.


q:
Would it not make sense to support a set of languages (Java, Python, Ruby, etc.) by way of a standardized virtual machine hosted in the browser rather than requiring the use of a specialized language -- really, a specialized paradigm -- for client scripting only?

To clarify the suggestion, a web page would contain byte code instead of any higher-level language like JavaScript.

I understand the pragmatic reality that JavaScript is simply what we have to work with now due to evolutionary reasons, but I'm thinking more about the long term.  With regard to backward compatibility, there's no reason that inline JavaScript could not be simultaneously supported for a period of time and of course JavaScript could be one of the languages supported by the browser virtual machine.

[A]
Well, yes. Certainly if we had a time machine, going back and ensuring a lot of the Javascript features were designed differently would be a major pastime (that, and ensuring the people who designed IE's CSS engine never went into IT). But it's not going to happen, and we're stuck with it now.
I suspect, in time, it will become the "Machine language" for the web, with other better designed languages and APIs compile down to it (and cater for different runtime engine foibles).
I don't think, however, any of these "better designed languages" will be Java, Python or Ruby. Javascript is, despite the ability to be used elsewhere, a Web application scripting language. Given that use case, we can do better than any of those languages.


q: I would like to reload an <iframe> using JavaScript. The best way I found until now was set the iframe’s src attribute to itself, but this isn’t very clean. Any ideas?

[A]
```
```
window.frames['frameNameOrIndex'].location.reload();
```
```


q:
I am re-building our poorly designed web application from scratch, and wanted to get into TDD and basically "do things right" as kind of a learning project.  What tools, processes, and resources are recommended to do it "right" from the start?  I will be working alone as the architect and developer, with the backup of a business analyst and business owners for usability testing and use cases.

EDIT:
Right now we use SourceSafe for source control, is there any reason technologically that I'd want to try to get us to switch to subversion?

EDIT #2:
Looks like the consensus is:
Cruise Control.NET
Subversion(if I want to stop using SourceSafe)
ASP.NET MVC
NUnit for unit testing
Resharper

[A]
I highly recommend that you take a look at
MVC for ASP.NET
if you want to make unit testing a high priority in your development process.  It sounds like it is perfect for what you are trying to do.
I would also recommend
CruiseControl.NET
for continuous integration (this is important if your team is going to grow).
Subversion is my favorite source control system when I am working on small teams.  Use
Tortoise SVN
for Windows Explorer integration.


q:
ASP.NET 2.0 provides the ClientScript.RegisterClientScriptBlock() method for registering JavaScript in an ASP.NET Page.

The issue I'm having is passing the script when it's located in another directory.  Specifically, the following syntax does not work:

ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "../dir/subdir/scriptName.js", true);

Instead of dropping the code into the page like this page says it should, it instead displays ../dir/subdir/script.js , my question is this:

Has anyone dealt with this before, and found a way to drop in the javascript in a separate file?  Am I going about this the wrong way?

[A]
Your script value has to be a full script, so put in the following for your script value.
```
```
<script type='text/javascript' src='yourpathhere'></script>
```
```


q:
I'm using CVS on Windows (with the WinCVS front end), and would like to add details of the last check in to the email from our automated build process, whenever a build fails, in order to make it easier to fix.

I need to know the files that have changed, the user that changed them, and the comment.

I've been trying to work out the command line options, but never seem to get accurate results (either get too many result rather than just from one checkin, or details of some random check in from two weeks ago)

[A]
CVS does not provide this capability. You can, however, get it by buying a license for
FishEye
or possibly by using
CVSTrac
(note: I have not tried CVS Trac).
Or you could migrate to SVN, which does provide this capability via atomic commits. You can check in a group of files and have it count as a single commit. In CVS, each file is a separate commit no matter what you do.


q: I have an Ant script that performs a copy operation using the 'copy' task. It was written for Windows, and has a hardcoded C:\ path as the 'todir' argument. I see the 'exec' task has an OS argument, is there a similar way to branch a copy based on OS?

[A]
You can't use a variable and assign it depending on the type? You could put it in a
```
build.properties
```
file. Or you could assign it using a
condition
.


q:
I have a application deployed through clickonce, but How can I modify the config file on the deployment server?.  I mean, once the product is tested, it should be deployed in our production server, but need to modify some of the config parameters to consume production resources?. I heard we should use MageUI.exe, but still not sure.

I appreciate for your help.

Thank

[A]
Yes, the best way to do it would probably be MageUI.  Just open your manifests with MageUI, click
Save
and it should prompt you to resign the manifests.
You have two options when signing manifests.  You can use a self-certificate or purchase a certificate.  Self certificates are easy to use but when the app is installed the publisher will appear as
Unknown
.  If you purchase a certificate, use these instructions to create the files needed to sign ClickOnce manifests -
http://www.softinsight.com/bnoyes/CommentView.aspx?guid=78d107d1-3937-4d8d-81d9-73cb6ae18eee
.


q: I've seen a few fixes for allowing PNG images to have transparency in Internet Explorer 6, but I've yet to find one that also allows you to set the background position in CSS. If you use sprites, it's a deal-breaker. I've resorted to using GIF's (which are not as high quality), not using transparent images at all, or serving a completely different stylesheet to IE6. Is there a fix for IE6 that allows for PNG transparencies AND background positioning?

[A]
Yes.  Convert your images to use indexed pallets (png256).  You can support transparency (just like gif), but not an alpha channel.
You can do this using
Irfanview
and the pngout plugin,
pngquant
or
pngnq
.
The YUI performance team also did a
great presentation
that covers this an many other image optimization concepts.


q: What do you think is the best way to create SEO friendly URLs (dynamically) in Rails?

[A]
Override the
```
to_param
```
method in your model classes so that the default numeric ID is replaced with a meaningful string. For example, this very question uses
best-permalinking-for-rails
in the URL.
Ryan Bates has a
Railscast on this topic
.


q:
I have two classes, and want to include a static instance of one class inside the other and access the static fields from the second class via the first.

This is so I can have non-identical instances with the same name.

Class A
{
    public static package1.Foo foo;
}

Class B
{
    public static package2.Foo foo;
}

//package1
Foo
{
    public final static int bar = 1;
}

// package2
Foo
{
    public final static int bar = 2;
}

// usage
assertEquals(A.foo.bar, 1);
assertEquals(B.foo.bar, 2);

This works, but I get a warning "The static field Foo.bar shoudl be accessed in a static way".
Can someone explain why this is and offer a "correct" implementation.

I realize I could access the static instances directly, but if you have a long package hierarchy, that gets ugly:

assertEquals(net.FooCorp.divisions.A.package.Foo.bar, 1);
assertEquals(net.FooCorp.divisions.B.package.Foo.bar, 2);

[A]
You should use:
```
```
Foo.bar
```
```
And not:
```
```
A.foo.bar
```
```
That's what the warning means.
The reason is that
```
bar
```
isn't a member of an
instance
of
```
Foo
```
.  Rather,
```
bar
```
is global, on the class
```
Foo
```
.  The compiler wants you to reference it globally rather than pretending it's a member of the instance.


q:
I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted.

Right now, I call to_json and my JSON is all on one line.  At times this can be difficult to see if there is a problem in the JSON output stream.

Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?

[A]
Use the
```
pretty_generate()
```
function, built into later versions of JSON. For example:
```
```
require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)
```
```
Which gets you:
```
```
{
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}
```
```


q:
I'm trying to create a build script for my current project, which includes an Excel Add-in.  The Add-in contains a VBProject with a file modGlobal with a variable version_Number.   This number needs to be changed for every build.  The exact steps:

Open XLA document with Excel.

Switch to VBEditor mode. (Alt+F11)

Open VBProject, entering a password.

Open modGlobal file.

Change variable's default value to the current date.

Close & save the project.

I'm at a loss for how to automate the process.  The best I can come up with is an excel macro or Auto-IT script.  I could also write a custom MSBuild task, but that might get... tricky.  Does anyone else have any other suggestions?

[A]
I'm not 100% sure how to do exactly what you have requested. But guessing the goal you have in mind there are a few possibilities.
1)
Make part (or all) of your Globals a separate text file that is distributed with the .XLA I would use this for external references such as the version of the rest of your app. Write this at build time and distribute, and read on the load of the XLA.
2)
I'm guessing your writing the version of the main component (ie: the non XLA part) of your application. If this is tru why store this in your XLA? Why not have the main part of the app allow certain version of the XLA to work. Version 1.1 of the main app could accept calls from Version 7.1 - 8.9 of the XLA.
3)
If you are just looking to update the XLA so it gets included in your version control system or similar (i'm guessing here) maybe just touch the file so it looks like it changed.
If it's the version of the rest of the app that you are controlling i'd just stick it in a text file and distribute that along with the XLA.


q:
Say I have two strings,

String s1 = "AbBaCca";
String s2 = "bac";

I want to perform a check returning that s2 is contained within s1. I can do this with:

return s1.contains(s2);

I am pretty sure that contains() is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:

return s1.toLowerCase().contains(s2.toLowerCase());

All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?

[A]
Yes, contains is case sensitive.  You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:
```
```
Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();
```
```
EDIT:
If s2 contains regex special characters (of which there are many) it's important to quote it first.  I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.


q:
I'm designing a web site navigation hierarchy. It's a tree of nodes.  Nodes represent web pages.

Some nodes on the tree are special.  I need a name for them.

There are multiple such nodes. Each is the "root" of a sub-tree with pages that have a distinct logo, style sheet, or layout. Think of different departments.

site map with color-coded sub-trees http://img518.imageshack.us/img518/153/subtreesfe1.gif

What should I name this type of node?

[A]
How about Root (node with children, but no parent), Node (node with children and parent) and Leaf (node with no children and parent)?
You can then distinguish by name and position within the tree structure (E.g. DepartmentRoot, DepartmentNode, DepartmentLeaf) if need be..
Update Following Comment from OP
Looking at your question, you said that "some" are special, and in your diagram, you have different nodes looking differently at different levels. The nodes may be different in their design, you can build a tree structure many ways. For example, a single abstract class that
can
have child nodes, if no children, its a leaf, if no parent, its a root but this can change in its lifetime. Or, a fixed class structure in which leafs are a specific class type that
cannot
have children added to them in any way.
IF your design does not need you to distinguish nodes differently depending on their position (relative to the root) it suggests that you have an abstract class used for them all.
In which case, it raises the question,
how is it different?
If it is simply the same as the standard node everywhere else, but with a bit of styling, how about
StyledNode
? Do you even need it to be seperate (no style == no big deal, it doesn't render).
Since I don't know the mechanics of how the tree is architected, there could possibly be several factors to consider when naming.


q: I've recently embarked upon the grand voyage of Wordpress theming and I've been reading through the Wordpress documentation for how to write a theme.  One thing I came across here was that the style.css file must contain a specific header in order to be used by the Wordpress engine.  They give a brief example but I haven't been able to turn up any formal description of what must be in the style.css header portion.  Does this exist on the Wordpress site?  If it doesn't could we perhaps describe it here?

[A]
You are probably thinking about this:
```
```
/*
THEME NAME: Parallax
THEME URI: http://parallaxdenigrate.net
VERSION: .1
AUTHOR: Martin Jacobsen
AUTHOR URI: http://martinjacobsen.no
*/
```
```
If I'm not way off, Wordpress uses this info to display in the "Activate Design" dialog in the admin backend.


q:
I'm using exim on both the sending and relay hosts, the sending host seems to offer:

HELO foo_bar.example.com

Response:

501 Syntactically invalid HELO argument(s)

[A]
Possibly a problem with underscores in the hostname?
http://www.exim.org/lurker/message/20041124.113314.c44c83b2.en.html


q:
I am looking for a tool that can serialize and/or transform SQL Result Sets into XML. Getting dumbed down XML generation from SQL result sets is simple and trivial, but that's not what I need.

The solution has to be database neutral, and accepts only regular SQL query results (no db xml support used). A particular challenge of this tool is to provide nested XML matching any schema from row based results. Intermediate steps are too slow and wasteful - this needs to happen in one single step; no RS->object->XML, preferably no RS->XML->XSLT->XML. It must support streaming due to large result sets, big XML.

Anything out there for this?

[A]
Not that I know of.  I would just roll my own.  It's not that hard to do, maybe something like this:
```
```
#!/usr/bin/env jruby

import java.sql.DriverManager

# TODO  some magic to load the driver
conn = DriverManager.getConnection(ARGV[0], ARGV[1], ARGV[2])
res = conn.executeQuery ARGV[3]

puts "<result>"
meta = res.meta_data
while res.next
  puts "<row>"

  for n in 1..meta.column_count
    column = meta.getColumnName n
    puts "<#{column}>#{res.getString(n)}</#{column}"
  end

  puts "</row>"
end
puts "</result>"
```
```
Disclaimer:
I just made all of that up, I'm not even bothering to pretend that it works.  :-)


q:
I have a simple xml document that looks like the following snippet. I need to write a XSLT transform that basically 'unpivots' this document based on some of the attributes.

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:z="foo">
    <z:row A="1" X="2" Y="n1" Z="500"/>
    <z:row A="2" X="5" Y="n2" Z="1500"/>
</root>

This is what I expect the output to be -

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:z="foo">
    <z:row A="1" X="2"  />
    <z:row A="1" Y="n1" />
    <z:row A="1" Z="500"/>
    <z:row A="2" X="5" />
    <z:row A="2" Y="n2"/>
    <z:row A="2" Z="1500"/>
</root>

Appreciate your help.

[A]
Here is a bit of a brute force way:
```
```
<xsl:template match="z:row">
    <xsl:element name="z:row">
        <xsl:attribute name="A">
            <xsl:value-of select="@A"/>
        </xsl:attribute>
        <xsl:attribute name="X">
            <xsl:value-of select="@X"/>
        </xsl:attribute>
    </xsl:element>
    <xsl:element name="z:row">
        <xsl:attribute name="A">
            <xsl:value-of select="@A"/>
        </xsl:attribute>
        <xsl:attribute name="Y">
            <xsl:value-of select="@Y"/>
        </xsl:attribute>
    </xsl:element>
    <xsl:element name="z:row">
        <xsl:attribute name="A">
            <xsl:value-of select="@A"/>
        </xsl:attribute>
        <xsl:attribute name="Z">
            <xsl:value-of select="@Z"/>
        </xsl:attribute>
    </xsl:element>
</xsl:template>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>
```
```


q: Unix.....>>netstat -al | grep 8787 (will see packets on port 8787)

[A] What is the nature of the question here? Are you trying to see packets on port 8787? Are you looking for services listening on port 8787? Most importantly, how is this a programming-related question?


q:
I have an application with multiple "pick list" entities, such as used to populate choices of dropdown selection boxes. These entities need to be stored in the database. How do one persist these entities in the database?

Should I create a new table for each pick list?  Is there a better solution?

[A]
Depending on your needs, you can just have an options table that has a list identifier and a list value as the primary key.
```
```
select optionDesc from Options where 'MyList' = optionList
```
```
You can then extend it with an order column, etc. If you have an ID field, that is how you can reference your answers back... of if it is often changing, you can just copy the answer value to the answer table.


q:
Where can I download the JSSE and JCE source code for the latest release of Java?  The source build available at https://jdk6.dev.java.net/ does not include the javax.crypto (JCE) packages nor the com.sun.net.ssl.internal (JSSE) packages.

Not being able to debug these classes makes solving SSL issues incredibly difficult.

[A]
there:
openjdk javax.net
in the security group
```
```
src/share/classes/javax/net
src/share/classes/com/sun/net/ssl
src/share/classes/sun/security/ssl
src/share/classes/sun/net/www/protocol/https
```
```
also on this page:
```
```
src/share/classes/javax/crypto
src/share/classes/com/sun/crypto/provider
src/share/classes/sun/security/pkcs11
src/share/classes/sun/security/mscapi
```
```
These directories contain the core
  cryptography framework and three
  providers (SunJCE, SunPKCS11,
  SunMSCAPI).
SunJCE
contains Java
  implementations of many popular
  algorithms, and the latter two
  libraries allow calls made through the
  standard Java cryptography APIs to be
  routed into their respective native
  libraries.


q: I've setup a new .net 2.0 website on IIS 7 under Win Server 2k8 and when browsing to a page it gives me a 404.17 error, claiming that the file (default.aspx in this case) appears to be a script but is being handled by the static file handler.  It SOUNDS like the module mappings for ASP.Net got messed up, but they look fine in the configurations.  Does anyone have a suggestion for correcting this error?

[A]
I had this problem on IIS6 one time when somehow the ASP.NET ISAPI stuff was broke.
Running
```
```
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i
```
```
to recreate the settings took care of it.


q: I had data in XML  that had line feeds, spaces, and tabs that I wanted to preserve in the output HTML (so I couldn't  use <p>) but I also wanted the lines to wrap when the side of the screen  was reached (so I couldn't use <pre>).

[A]
I and a co-worker (Patricia Eromosele) came up with the following solution:  (Is there a better solution?)
```
<p>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="text"/>
</xsl:call-template>
</p>
<xsl:template name="prewrap">
<xsl:param name="text" select="."/>
<xsl:variable name="spaceIndex" select="string-length(substring-before($text, '  '))"/>
<xsl:variable name="tabIndex" select="string-length(substring-before($text, '	'))"/>
<xsl:variable name="lineFeedIndex" select="string-length(substring-before($text, '
'))"/>
<xsl:choose>
<xsl:when test="$spaceIndex = 0 and $tabIndex = 0 and $lineFeedIndex = 0"><!-- no special characters left -->
<xsl:value-of select="$text"/>
</xsl:when>
<xsl:when test="$spaceIndex > $tabIndex and $lineFeedIndex > $tabIndex"><!-- tab -->
<xsl:value-of select="substring-before($text, '	')"/>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="substring-after($text,'	')"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="$spaceIndex > $lineFeedIndex and $tabIndex > $lineFeedIndex"><!-- line feed -->
<xsl:value-of select="substring-before($text, '
')"/>
<br/>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="substring-after($text,'
')"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="$lineFeedIndex > $spaceIndex and $tabIndex > $spaceIndex"><!-- two spaces -->
<xsl:value-of select="substring-before($text, '  ')"/>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="substring-after($text,'  ')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise><!-- should never happen -->
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
```
Source:
http://jamesjava.blogspot.com/2008/06/xsl-preserving-line-feeds-tabs-and.html


q:
There seems to be no good way to localize a WPF application.  MSDN seems to think that littering my XAML with x:Uid's, generating CSV files, and then generating new assemblies (using their sample code!) is the answer.  Worse, this process doesn't address how to localize images, binary blobs (say, PDF files), or strings that are embedded in code.

So, how might you localize an application that:

Contains several assemblies

Contains images and other binary blobs (eg: PDF docs) that need to be localized

Has string data that isn't in XAML (eg: MessageBox.Show("Hello World");)

[A]
Not an expert here, but "littering" your xaml with x:Uids is not worse than "littering" your Windows Forms code with all the string table nonsense you have to do for localizing them.
As far as I understand, WPF apps still support "all the Framework CLR resources including string tables, images, and so forth." which means you can have localized resources.
Of course, it would be much simpler if you created a markup extension that handled much of this nonsense for you.
You can find an example of someone doing this here.
And there was another, similar solution at
```
http://blog.taggersoft.com/2008/07/wpf-application-localization-pattern_29.html
```
, but that link no longer works.


q:
Does anyone know of a .NET library that will process HTML e-mails and can be used to trim out the reply-chain?  It needs to be able to accept HTML -or- text mails and then trim out everything but the actual response, removing the trail of messages that are not original content.  I don't expect it to be able to handle responseswhen they're interleaved into the previous mail ("responses in-line") - that case can fail.

We have a home-built one based on SgmlReader and a series of XSL transforms, but it requires constant maintenance to deal with new e-mail clients.  I'd like to find one I can buy... :)

Thanks,
Steve


q: After reading this description of late static binding (LSB) I see pretty clearly what is going on. Now, under which sorts of circumstances might that be most useful or needed?

[A]
I needed LSB this for the following scenario:
Imagine you're building a "mail processor" daemon that downloads the message from an email server, classifies it, parses it, saves it, and then does something, depending on the type of the message.
Class hierarchy: you have a base Message class, with children "BouncedMessage" and "AcceptedMessage".
Each of the message types has its own way to persist itself on disk. For example, all messages of type BouncedMessage try to save itself as BouncedMessage-id.xml. AcceptedMessage, on the other hand, needs to save itself differently - as AcceptedMessage-timestamp.xml. The important thing here is that the logic for determining the filename pattern is different for different subclasses, but
shared
for all items within the subclass. That's why it makes sense for it to be in a static method.
Base Message class has an abstract static method (yes, abstract
AND
static) "save". BouncedMessage implements this method with a concrete static method. Then, inside the class that actually retrieves the message, you can call "::save()"
If you want to learn more about the subject:
http://www.qcodo.com/forums/topic.php/2356
http://community.livejournal.com/php/585907.html
http://bugs.php.net/bug.php?id=42681


q:
It is obviosly some Perl extensions. Perl version is 5.8.8.

I found Error.pm, but now I'm looking for Core.pm.

While we're at it: how do you guys search for those modules. I tried Google, but that didn't help much. Thanks.

And finally, after I built everything, running:

./Build install

gives me:

Running make install-lib
/bin/ginstall -c -d /usr/lib/perl5/site_perl/5.8.8/i486-linux-thread-multi/Alien/SVN --prefix=/usr
/bin/ginstall: unrecognized option `--prefix=/usr'
Try `/bin/ginstall --help' for more information.
make: *** [install-fsmod-lib] Error 1
installing libs failed at inc/My/SVN/Builder.pm line 165.

Looks like Slackware's 'ginstall' really does not have that option. I think I'm going to Google a little bit now, to see how to get around this.

[A]
It should be compatible. The
CPAN Tester's matrix
shows no failures for Perl 5.8.8 on any platform.
Per the
README
, you can install it by doing:
```
```
perl Makefile.pl
make
make test
make install
```
```


q:
default is 49

how to edit to higher?

[A]
You will need to issue the following command (connected as a user that has alter system privileges, sys will do it)
alter system set sessions=
numberofsessions
scope=spfile;
Have you been getting an ORA-12516 or ORA-12520 error?
If so it's probably a good idea to increase the number of processes too
alter system set processes=
numberofprocesses
scope=spfile;
IIRC you'll need to bounce the database after issuing these commands.
This link
http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf
has some good information about configuring XE.
I consulted it when I ran into similar issues using XE.


q:
I need to find the frequency of a sample, stored (in vb) as an array of byte. Sample is a sine wave, known frequency, so I can check), but the numbers are a bit odd, and my maths-foo is weak.
Full range of values 0-255. 99% of numbers are in range 235 to 245, but there are some outliers down to 0 and 1, and up to 255 in the remaining 1%.
How do I normalise this to remove outliers, (calculating the 235-245 interval as it may change with different samples), and how do I then calculate zero-crossings to get the frequency?
Apologies if this description is rubbish!

[A]
Use the Fourier transform, it's much more noise insensitive than counting zero crossings
Edit: @WaveyDavey
I found an F# library to do an FFT:
From here
As it turns out, the best free
implementation that I've found for F#
users so far is still the fantastic
FFTW library. Their site has a
precompiled Windows DLL. I've written
minimal bindings that allow
thread-safe access to FFTW from F#,
with both guru and simple interfaces.
Performance is excellent, 32-bit
Windows XP Pro is only up to 35%
slower than 64-bit Linux.
Now I'm sure you can call F# lib from VB.net, C# etc, that should be in their docs


q:
Although I don't have an iPhone to test this out, my colleague told me that embedded
media files such as the one in the snippet below, only works when the iphone is connected over the
WLAN connection or 3G, and does not work when connecting via GPRS.

<html><body>
<object data="http://joliclic.free.fr/html/object-tag/en/data/test.mp3" type="audio/mpeg">
   <p>alternate text</p>
</object>
</body></html>

Is there an example URL with a media file, that will play in an iPhone browser
when the iphone connects using GPRS (not 3G)?

[A]
I wasn't aware of that limitation.  Although it does make sense to disable potentially data-hefty OBJECT or EMBED tags when on the cellular data service for which your provider may be charging by the byte, if that were the reason it wouldn't make sense that it would still work on 3G and only not on GPRS.
Perhaps the problem is one of basic data throughput?  Not having an iPhone yourself (or myself) makes it difficult to test your colleague's statement.
Remember that GPRS is much slower than Wi-Fi or 3G.  According to Wikipedia, GPRS will provide between 56 and 114 kbps of total duplex throughput, not all of which is in the download direction.  You can already see that's not fast enough to instantly stream a typical 128 kbps mp3, even if you were getting the optimal throughput and getting it all as download speed.
Looking at
this forum discussion
as an example that came up on Google, the GPRS customers (the ones not using Telestra, which is an EDGE provider in that area) are getting around 40 kbps.  So if as the question implies, you're stuck in EDGEland, NOT 3Gland or anything inbetween, it's going to take about 20 seconds of buffering to play a 30 second mp3.  And when you use a behaviour-ambiguous tag like OBJECT or EMBED, there's no guarantee in how the browser will interpret it and whether it's going to try to intelligently stream the file rather than having to download the whole thing before starting it.
So, it's quite possible your colleague just didn't wait long enough to see if whatever embedded media he chose as a test started to play (assuming he wasn't using your 17KB test mp3 there).  It's also possible that the iPhone does indeed have this limitation, though I'd think Google would be more forthcoming with it than my quick search uncovered, since people have been vocal enough with other things they don't like about iPhone.  Another possibility would be that it's a limitation in the build of Safari that currently ships with the iPhone which might be changed in future versions or in another browser.
Ultimately though, the question is, what kind of user experience do you really want?  Embedded audio on GPRS is going to take a long time to load, and users aren't going to enjoy the experience, or potentially even experience it at all if it's supposed to start playing on page visit and it doesn't load before they navigate away.  It might not be a goal worth striving towards in that case.


q:
What's a good algorithm for calculating frames per second in a game? I want to show it as a number in the corner of the screen. If I just look at how long it took to render the last frame the number changes too fast.

Bonus points if your answer updates each frame and doesn't converge differently when the frame rate is increasing vs decreasing.

[A]
You need a smoothed average, the easiest way is to take the current answer (the time to draw the last frame) and combine it with the previous answer.
```
```
// eg.
float smoothing = 0.9; // larger=more smoothing
measurement = (measurement * smoothing) + (current * (1.0-smoothing))
```
```
By adjusting the 0.9 / 0.1 ratio you can change the 'time constant' - that is how quickly the number responds to changes. A larger fraction in favour of the old answer gives a slower smoother change, a large fraction in favour of the new answer gives a quicker changing value.   Obviously the two factors must add to one!


q:
I need to get a list of attribute values from child elements in Python.

It's easiest to explain with an example.

Given some XML like this:

<elements>
    <parent name="CategoryA">
        <child value="a1"/>
        <child value="a2"/>
        <child value="a3"/>
    </parent>
    <parent name="CategoryB">
        <child value="b1"/>
        <child value="b2"/>
        <child value="b3"/>
    </parent>
</elements>

I want to be able to do something like:

>>> getValues("CategoryA")
['a1', 'a2', 'a3']
>>> getValues("CategoryB")
['b1', 'b2', 'b3']

It looks like a job for XPath but I'm open to all recommendations. I'd also like to hear about your favourite Python XML libraries.

[A]
I must admit I'm a fan of
xmltramp
due to its ease of use.
Accessing the above becomes:
```
```
import xmltramp

  values = xmltramp.parse('''...''')

  def getValues( values, category ):
    cat = [ parent for parent in values['parent':] if parent(name) == category ]
    cat_values = [ child(value) for child in parent['child':] for parent in cat ]
    return cat_values

  getValues( values, "CategoryA" )
  getValues( values, "CategoryB" )
```
```


q:
I have a test project using MbUnit and TestDriven.Net.

If I right-click on an individual test method and say "Run Tests" the test runs successfully.  Same thing if I click on a file name in the solution explorer.

However, if I right click and say run tests on the project or the solution, TestDriven.Net reports "0 Passed, 0 Failed, 0 Skipped."

I have other similar projects that work just fine, and yes, the classes are labeled [TestFixture] and the methods are labeled [Test].

[A]
You need to add testing attributes for your favorite testing framework.  TestDriven picks up these attributes by reflection in order to know what tests to run.
For example, using NUnit.Framework - each test class needs [TextFixture] and each test method needs [Test]
Here's an
example


q:
Are there any good resources for planning how exceptions will be used from an architecture perspective?  (Or provide your suggestions directly here.)  In projects on which I have worked I find that a few common Exceptions are used over and over again and tend to lose their meaning.
From: http://jamesjava.blogspot.com/2007/10/exception-plan.html

[A]
"Effective Java," 2nd. ed. Bloch
, has some good advice in chapter 9.
"Hardcore Java," Simmons
, has some good advice in chapter 5.
I'll also shamelessly mention that I've written
a small tool
to manage Java exception source code. Exception code is often very redundant, all that you usually care about is the type. My tool accepts a configuration file that names exception types, then generates code for those exceptions.


q:
I need to write a function that receives a string and a regex. I need to check if there is a match and return the start and end location of a match. (The regex was already compiled by qr//.)

The function might also receive a "global" flag and then I need to return the (start,end) pairs of all the matches.

I cannot change the regex, not even add () around it as the user might use () and \1. Maybe I can use (?:).

Example: given "ababab" and the regex qr/ab/, in the global case I need to get back 3 pairs of (start, end).

[A]
The pos function gives you the position of the match. If you put your regex in parentheses you can get the length (and thus the end) using
```
length $1
```
.  Like this
```
```
sub match_positions {
    my ($regex, $string) = @_;
    return if not $string =~ /($regex)/;
    return (pos($string) - length $1, pos($string));
}
sub all_match_positions {
    my ($regex, $string) = @_;
    my @ret;
    while ($string =~ /($regex)/g) {
        push @ret, [pos($string) - length $1, pos($string)];
    }
    return @ret
}
```
```


q:
After compiling a simple C++ project using Visual Studio 2008 on vista, everything runs fine on the original vista machine and other vista computers. However, moving it over to an XP box results in an error message: "The application failed to start because the application configuration is incorrect".

What do I have to do so my compiled EXE works on XP and Vista? I had this same problem a few months ago, and just fiddling with some settings on the project fixed it, but I don't remember which ones I changed.

[A]
You need to install the runtime redistributable files onto the machine you are trying to run the app on.
The redistributable for 2008 is
here
.
The redistributable for 2005 is
here
.
They can be installed side-by-side, in case you need both.


q:
I have a class with many embedded assets.

Within the class, I would like to get the class definition of an asset by name.  I have tried using getDefinitionByName(), and also ApplicationDomain.currentDomain.getDefinition() but neither work.

Example:

public class MyClass
{
  [Embed(source="images/image1.png")] private static var Image1Class:Class;
  [Embed(source="images/image2.png")] private static var Image2Class:Class;
  [Embed(source="images/image3.png")] private static var Image3Class:Class;

  private var _image:Bitmap;

  public function MyClass(name:String)
  {
    var ClassDef:Class = getDefinitionByName(name) as Class;  //<<-- Fails
    _image = new ClassDef() as Bitmap;
  }
}

var cls:MyClass = new MyClass("Image1Class");

[A]
This doesn't answer your question, but it may solve your problem.  I believe doing something like this should work:
```
```
public class MyClass
{
  [Embed(source="images/image1.png")] private static var Image1Class:Class;
  [Embed(source="images/image2.png")] private static var Image2Class:Class;
  [Embed(source="images/image3.png")] private static var Image3Class:Class;

  private var _image:Bitmap;

  public function MyClass(name:String)
  {
    _image = new this[name]() as Bitmap;
  }
}

var cls:MyClass = new MyClass("Image1Class");
```
```
I'm having a tough time remembering if bracket notation works on sealed classes.  If it doesn't, a simple solution is to mark the class as dynamic.


q:
Continuing my problem from yesterday, the Silverlight datagrid I have from this issue
is now causing Stack Overflow errors when sorting a column with a large amount of data (Like the text column that contains a where clause for a SQL statment).  When you sort, it'll fire the SelectedIndexChanged event for the datagrid and then still try to stort.  If you click the header again the stack overflow occours.

Does anyone have an idea on how to stop the sorting on this control for a column?  All the other columns sort fine (but still fire that darn SelectedIndexChanged event), but if I could shut off the column for whereClause it'd be perfect.

Does anyone have a better idea at how to get this to work?

[A]
Give this a shot:
```
```
dataGridView1.Columns[*Numberofthecolumnyoudontwantsorted*].SortMode
= DataGridViewColumnSortMode.NotSortable;
```
```


q:
I need to know if it is possible to dynamically bind a textbox residing within a datarepeater to a 'dynamically' created BindingSource.  I am using VB.net.  The database I am using is a MySQL database.

I have to use the connection dynamically due to the fact that the database my not permanently reside on the same server.

[edit]

ok, so it seams that I am a dolt when asking questions.  The app that I am making is not web based.  it is a simple (I hope) app that connects to a MySQL database, accesses a table so I can edit/view it.  Current setup is using the Add DataSource wizard.  I have successfully connected to the dbase dynamically using the mysql connector dll but without the textboxes set at design time to a datasource, I am unsure on how to 'link' them via the datarepeater.

[A]
Your connection string should be defined in your Web.Config, and if you move your database to a different server, it's just a matter of modifying the web.config entry. As long as you keep the connection string name the same, the BindingSource object will pick up the new value from the config.
edit
In truth, the same concept should apply here as it does in the web app answer listed above.
All of your data objects should be hard-coded, and it's just the connection string (which you'll have to either ask the user for, or push out as update when the DB moves) which will get modified.
For example, create a App.Config file in your project. Have one of your configuration values  be the connection string. This config value will be where you go to get the connection string whenever you need it. Then your wizard will be there to allow users to easily modify the connection.


q:
If the major axis of the ellipse is vertical or horizontal, it's easy to calculate the bounding box, but what about when the ellipse is rotated?

The only way I can think of so far is to calculate all the points around the perimeter and find the max/min x and y values. It seems like there should be a simpler way.

If there's a function (in the mathematical sense) that describes an ellipse at an arbitrary angle, then I could use its derivative to find points where the slope is zero or undefined, but I can't seem to find one.

Edit: to clarify, I need the axis-aligned bounding box, i.e. it should not be rotated with the ellipse, but stay aligned with the x axis so transforming the bounding box won't work.

[A]
I think the most useful formula is this one. An ellipsis rotated from an angle phi from the origin has as equation:
where (h,k) is the center, a and b the size of the major and minor axis and t varies from -pi to pi.
From that, you should be able to derive for which t dx/dt or dy/dt goes to 0.


q:
I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL.

Results would be something like:

TableName, ColumnName

[A]
sys.columns.is_identity = 1
e.g.,
```
```
select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1
```
```


q: How do you connect to Oracle using PHP on MAC OS X?

[A]
I would think OCI would be the way to go. PHP has a
module
for it.


q:
Say I have the following class

MyComponent : IMyComponent {
  public MyComponent(int start_at) {...}
}

I can register an instance of it with castle windsor via xml as follows

<component id="sample"  service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample">
  <parameters>
    <start_at>1</start_at >
  </parameters>
</component>

How would I go about doing the exact same thing but in code?  (Notice, the constructor parameter)

[A]
You need to pass in an IDictionary when you ask the container for the instance.
You'd use this Resolve overload of the IWindsorContainer:
```
```
T Resolve<T>(IDictionary arguments)
```
```
or the non generic one:
```
```
object Resolve(Type service, IDictionary arguments)
```
```
So, for example: (assuming container is an IWindsorContainer)
```
```
IDictionary<string, object> values = new Dictionary<string, object>();
values["start_at"] = 1;
container.Resolve<IMyComponent>(values);
```
```
Note that the key values in the dictionary are case sensitive.


q:
I am about to move to SVN as my RCS of choice (after many years using CVS) and have a basic question...

I have a number of shared projects - code that I want to use with lots of different projects.  Is it possible to 'link' these shared folders to the projects that need them, so checking out a project will also checkout the shared code?

For example, suppose my repository looks like this:

root

--project1

--project2

--shared

--smtp

When I checkout project1, I also want to checkout shared and smtp.

Back in my CVS days I would of used a Unix symbolic link in one of the project folders, but as my new SVN repository won't necessarily be hosted on a Unix box, I can't do the same.

[A]
SVN Externals are what you want to do. The SVN book explains it in great detail
here
. That's one thing I love about SVN, the wonderful documentation.


q:
I am trying to build a dependency graph of tables based on the foreign keys between them.  This graph needs to start with an arbitrary table name as its root.  I could, given a table name look up the tables that reference it using the all_constraints view, then look up the tables that reference them, and so on, but this would be horrible inefficient.  I wrote a recursive query that does this for all tables, but when I add:

START WITH Table_Name=:tablename

It doesn't return the entire tree.

[A]
Simplest way to do this is to copy all the FK info into a simple, 2-column (parent,child) table, and then use the following algorithm:
```
```
while (rows left in that table)
  list = rows where table name exists in child but not in parent
  print list
  remove list from rows
```
```
that's all. Basically, you first print and remove all the nodes that don't depend on anything. After that being done, some other nodes will get free and you can repeat process.
P.S. Make sure you don't insert self-referencing tables in the initial list (child=parent)


q:
anyone have any experience using this?
if so, is it worth while?

[A]
JDB is incredibly difficult to use. Placing System.outs or using an IDE debugger will produce better results. And for the more interesting features (e.g. tracking threads, heap size, etc.), you can get the information graphically with the
JConsole
tool.


q:
I am trying to build out a useful 3d game engine out of the Ogre3d rendering engine for mocking up some of the ideas i have come up with and have come to a bit of a crossroads. There are a number of scripting languages that are available and i was wondering if there were one or two that were vetted and had a proper following.

LUA and Squirrel seem to be the more vetted, but im open to any and all.

Optimally it would be best if there were a compiled form for the language for distribution and ease of loading.

[A]
I'd go with Lua since writing bindings is extremely easy, the license is very friendly (MIT) and existing libraries also tend to be under said license. Scheme is also nice and easy to bind which is why it was chosen for the Gimp image editor for example. But Lua is simply great. World of Warcraft uses it, as a very high profile example. LuaJIT gives you native-compiled performance. It's
less than an order of magnitude
from pure C.