q:
I'm writing a function to find triangle numbers and the natural way to write it is recursively:

function triangle (x)
   if x == 0 then return 0 end
   return x+triangle(x-1)
end

But attempting to calculate the first 100,000 triangle numbers fails with a stack overflow after a while.  This is an ideal function to memoize, but I want a solution that will memoize any function I pass to it.

[A]
```
```
function memoize (f)
   local cache = {}
   return function (x)
             if cache[x] then
                return cache[x]
             else
                local y = f(x)
                cache[x] = y
                return y
             end
          end
end

triangle = memoize(triangle);
```
```
Note that to avoid a stack overflow, triangle would still need to be seeded.


q:
What property in Netbeans to I need to change to set the name of my java swing app in the OS X menubar and dock? I found info.plist, but changing @PROJECTNAMEASIDENTIFIEER@ in multiple keys here had no effect.

Thanks,
hating netbeans.

[A]
Check:
```
```
nbproject/project.properties

nbproject/project.xml
```
```
in project.xml look for the name element...
But... Why not just select the main project and right click and do rename?

s: huggingface

c: devops

d: intermediate


q: I've heard the term MVC (Model View Controller) tossed about with a ton of Buzz lately, but what really is it?

[A]
Wikipedia seems to describe it best so far:
http://en.wikipedia.org/wiki/Model-view-controller
Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements


q:
I have a page in my vb.net web application that needs to toss a bunch of data into a text file and then present it to the user for download.  What's the best / most efficient way to build such a text file on a .net web server?

Edit: to answer a question down below, this is going to be a download once and then throw-away kind of file.

Update: I glued together the suggestions by John Rudy and DavidK, and it worked perfectly.  Thanks, all!

[A]
Use a StringBuilder to create the text of the file, and then send it to the user using Content-Disposition.
Example found here:
http://www.eggheadcafe.com/community/aspnet/17/76432/use-the-contentdispositi.aspx
```
```
private void Button1_Click(object sender, System.EventArgs e)
{
        StringBuilder output = new StringBuilder;
        //populate output with the string content
        String fileName = "textfile.txt";

        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.WriteFile(output.ToString());

}
```
```


q: Can someone explain what exactly the string "0 but true" means in Perl? As far as I understand, it equals zero in an integer comparison, but evaluates to true when used as a boolean. Is this correct? Is this a normal behavior of the language or is this a special string treated as a special case in the interpreter?

[A]
In an integer context, it evaluates to 0 (the numeric part at the beginning of the string) and is zero.  In a scalar context, it's a non-empty value, so it is true.
```
if (int("0 but true")) { print "zero"; }
```
(no output)
```
if ("0 but true") { print "true"; }
```
(prints true)


q: Is it possible to convert a com.vividsolutions.jts.geom.Geometry (or a subclass of it) into a class that implements java.awt.Shape? Which library or method can I use to achieve that goal?

[A]
According to:
http://lists.jump-project.org/pipermail/jts-devel/2007-May/001954.html
There's a class:
```
```
com.vividsolutions.jump.workbench.ui.renderer.java2D.Java2DConverter
```
```
which can do it?


q:
We've developed a Java application and would like to use this application from a C# client. The application has dependencies on Spring, Log4j, ...

What would be the most efficient mechanism - make DLL(s) from Java code, ... - to achieve this ?

[A]
IKVM!
It is really awesome.  The only problem is that it DOES add ~30MB to the project.
log4net and Spring .NET are available as well, but if living with existing code, go the ikvm route.


q:
I have a Rails 2.0.2 application running with a postgresql db. The machine will receive data on a TCP port. I already have coded a working ruby multithreaded tcp server to receive the requests, but I need this code to run alongside my Rails app.

So I guess I need to know how to span a new process inside Rails, or how to create a worker thread that will run my threaded tcp server loop. My ruby tcp server could have access to ActiveRecord, but it's not necessary (I can always create an http request, posting the received data to the original Rails server)

[A]
Why complicate things?  Just run the applications -- your TCP server and the Rails application -- side by side.
Either pull the model tier (and ActiveRecord) into your TCP server (svn::externals or Piston might work well for that) and let the communication between the two applications happen through the database, or let the Rails application be the "master" and communicate with it via HTTP as you suggest.
To turn a Ruby application into a Windows service, see the
```
win32-service
```
gem available from the
```
win32utils
```
project:
http://rubyforge.org/projects/win32utils/


q: Can anyone recommend a dropdownlist control for asp.net (3.5) that can render option groups? Thanks

[A]
I've used the standard control in the past, and just added a simple
ControlAdapter
for it that would override the default behavior so it could render <optgroup>s in certain places. This works great even if you have controls that don't need the special behavior, because the additional feature doesn't get in the way.
Note that this was for a specific purpose and written in .Net 2.0, so it may not suit you as well, but it should at least give you a starting point. Also, you have to hook it up using a .browserfile in your project (see the end of the post for an example).
```
```
'This codes makes the dropdownlist control recognize items with "--"
'for the label or items with an OptionGroup attribute and render them
'as <optgroup> instead of <option>.
Public Class DropDownListAdapter
    Inherits System.Web.UI.WebControls.Adapters.WebControlAdapter

    Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
        Dim list As DropDownList = Me.Control
        Dim currentOptionGroup As String
        Dim renderedOptionGroups As New Generic.List(Of String)

        For Each item As ListItem In list.Items
            Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value)
            If item.Attributes("OptionGroup") IsNot Nothing Then
                'The item is part of an option group
                currentOptionGroup = item.Attributes("OptionGroup")
                If Not renderedOptionGroups.Contains(currentOptionGroup) Then
                    'the header was not written- do that first
                    'TODO: make this stack-based, so the same option group can be used more than once in longer select element (check the most-recent stack item instead of anything in the list)
                    If (renderedOptionGroups.Count > 0) Then
                        RenderOptionGroupEndTag(writer) 'need to close previous group
                    End If
                    RenderOptionGroupBeginTag(currentOptionGroup, writer)
                    renderedOptionGroups.Add(currentOptionGroup)
                End If
                RenderListItem(item, writer)
            ElseIf item.Text = "--" Then 'simple separator
                RenderOptionGroupBeginTag("--", writer)
                RenderOptionGroupEndTag(writer)
            Else
                'default behavior: render the list item as normal
                RenderListItem(item, writer)
            End If
        Next item

        If renderedOptionGroups.Count > 0 Then
            RenderOptionGroupEndTag(writer)
        End If
    End Sub

    Private Sub RenderOptionGroupBeginTag(ByVal name As String, ByVal writer As HtmlTextWriter)
        writer.WriteBeginTag("optgroup")
        writer.WriteAttribute("label", name)
        writer.Write(HtmlTextWriter.TagRightChar)
        writer.WriteLine()
    End Sub

    Private Sub RenderOptionGroupEndTag(ByVal writer As HtmlTextWriter)
        writer.WriteEndTag("optgroup")
        writer.WriteLine()
    End Sub

    Private Sub RenderListItem(ByVal item As ListItem, ByVal writer As HtmlTextWriter)
        writer.WriteBeginTag("option")
        writer.WriteAttribute("value", item.Value, True)
        If item.Selected Then
            writer.WriteAttribute("selected", "selected", False)
        End If

        For Each key As String In item.Attributes.Keys
            writer.WriteAttribute(key, item.Attributes(key))
        Next key

        writer.Write(HtmlTextWriter.TagRightChar)
        HttpUtility.HtmlEncode(item.Text, writer)
        writer.WriteEndTag("option")
        writer.WriteLine()
    End Sub
End Class
```
```
Here's a C# implementation of the same Class:
```
```
/* This codes makes the dropdownlist control recognize items with "--"
 * for the label or items with an OptionGroup attribute and render them
 * as <optgroup> instead of <option>.
 */
public class DropDownListAdapter : WebControlAdapter
{
    protected override void RenderContents(HtmlTextWriter writer)
    {
        //System.Web.HttpContext.Current.Response.Write("here");
        var list = (DropDownList)this.Control;
        string currentOptionGroup;
        var renderedOptionGroups = new List<string>();

        foreach (ListItem item in list.Items)
        {
            Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value);
            //Is the item part of an option group?
            if (item.Attributes["OptionGroup"] != null)
            {
                currentOptionGroup = item.Attributes["OptionGroup"];
                //Was the option header already written, then just render the list item
                if (renderedOptionGroups.Contains(currentOptionGroup))
                    RenderListItem(item, writer);
                //The header was not written,do that first
                else
                {
                    //Close previous group
                    if (renderedOptionGroups.Count > 0)
                        RenderOptionGroupEndTag(writer);

                    RenderOptionGroupBeginTag(currentOptionGroup, writer);
                    renderedOptionGroups.Add(currentOptionGroup);
                    RenderListItem(item, writer);
                }
            }
            //Simple separator
            else if (item.Text == "--")
            {
                RenderOptionGroupBeginTag("--", writer);
                RenderOptionGroupEndTag(writer);
            }
            //Default behavior, render the list item as normal
            else
                RenderListItem(item, writer);
        }

        if (renderedOptionGroups.Count > 0)
            RenderOptionGroupEndTag(writer);
    }

    private void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer)
    {
        writer.WriteBeginTag("optgroup");
        writer.WriteAttribute("label", name);
        writer.Write(HtmlTextWriter.TagRightChar);
        writer.WriteLine();
    }
    private void RenderOptionGroupEndTag(HtmlTextWriter writer)
    {
        writer.WriteEndTag("optgroup");
        writer.WriteLine();
    }
    private void RenderListItem(ListItem item, HtmlTextWriter writer)
    {
        writer.WriteBeginTag("option");
        writer.WriteAttribute("value", item.Value, true);
        if (item.Selected)
            writer.WriteAttribute("selected", "selected", false);

        foreach (string key in item.Attributes.Keys)
            writer.WriteAttribute(key, item.Attributes[key]);

        writer.Write(HtmlTextWriter.TagRightChar);
        HttpUtility.HtmlEncode(item.Text, writer);
        writer.WriteEndTag("option");
        writer.WriteLine();
    }
}
```
```
My browser file was named "App_Browsers\BrowserFile.browser" and looked like this:
```
```
<!--
    You can find existing browser definitions at
    <windir>\Microsoft.NET\Framework\<ver>\CONFIG\Browsers
-->
<browsers>
   <browser refID="Default">
      <controlAdapters>
        <adapter controlType="System.Web.UI.WebControls.DropDownList"
               adapterType="DropDownListAdapter" />
      </controlAdapters>
   </browser>
</browsers>
```
```


q: Is there a built-in editor for a multi-line string in a PropertyGrid.

[A]
No, you will need to create what's called a modal UI type editor. You'll need to create a class that inherits from UITypeEditor. This is basically a form that gets shown when you click on the ellipsis button on the right side of the property you are editing.
The only drawback I found, was that I needed to decorate the specific string property with a specific attribute. It's been a while since I had to do that. I got this information from a book by Chris Sells called "Windows Forms Programming in C#"
There's a commercial propertygrid called
Smart PropertyGrid.NET
by VisualHint.


q:
I mean, I always was wondered about how the hell somebody can develop algorithms to break/cheat the constraints of legal use in many shareware programs out there.

Just for curiosity.

[A]
The bad guys search for the key-check code using a disassembler. This is relative easy if you know how to do this.
Afterwards you translate the key-checking code to C or another language (this step is optional). Reversing the process of key-checking gives you a key-generator.
If you know assembler it takes roughly a weekend to learn how to do this. I've done it just some years ago (never released anything though. It was just research for my game-development job. To write a hard to crack key you have to understand how people approach cracking).


q:
python's time module seems a little haphazard.  For example, here is a list of methods in there, from the docstring:

time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone

Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ?

Bonus questions: what would you name the method ? How would you implement it ?

[A]
I always thought the time and datetime modules were a little incoherent.  Anyways, here's the inverse of mktime
```
```
import time
def mkgmtime(t):
    """Convert UTC tuple to seconds since Epoch"""
    return time.mktime(t)-time.timezone
```
```


q: How can you get the directory of the script that was run and use it within the .cmd file?

[A]
Raymond Chen has a few ideas:
https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573
Quoted here in full because MSDN archives tend to be somewhat unreliable:
The easy way is to use the
```
%CD%
```
pseudo-variable. It expands to the
  current working directory.
```
set OLDDIR=%CD%
```
```
.. do stuff ..
```
```
chdir /d %OLDDIR% &rem restore current directory
```
(Of course, directory save/restore could more easily have
  been done with
```
pushd
```
/
```
popd
```
, but that's not the point here.)
The
```
%CD%
```
trick is handy even from the command line. For example, I
  often find myself in a directory where there's a file that I want to
  operate on but... oh, I need to chdir to some other directory in order
  to perform that operation.
```
set _=%CD%\curfile.txt
```
```
cd ... some other directory ...
```
```
somecommand args %_% args
```
(I like to use
```
%_%
```
as my scratch environment variable.)
Type
```
SET /?
```
to see the other pseudo-variables provided by the command
  processor.
Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):
http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741
This covers the use of %~dp0:
If you want to know where the batch file lives:
```
%~dp0
```
```
%0
```
is the name of the batch file.
```
~dp
```
gives you the drive and path of
  the specified argument.


q: How can I read the first line from a text file using a Windows batch file? Since the file is large I only want to deal with the first line.

[A]
You might give this a try:
```
```
@echo off

for /f %%a in (sample.txt) do (
  echo %%a
  exit /b
)
```
```
edit
Or, say you have four columns of data and want from the 5th row down to the bottom, try this:
```
```
@echo off

for /f "skip=4 tokens=1-4" %%a in (junkl.txt) do (
  echo %%a %%b %%c %%d
)
```
```


q:
Has anyone worked with the StarTeam COM API (Specifically, intergrating with C#).

I need to write a helper function that returns a directory structure out of Starteam, but all I've been able to retrieve using this API has been a list of views.

Has anyone else tried this?

[A]
the Starteam object model is heirachical, projects contain views, views contain folders, folders contain items (child folders, files, cr's etc)
So once you have your view list you can get the folders that belong to the view, then you have a few properties that determine how they map to the local file system, both the view object and the folder objects have a readonly path property. There are 4 other properties of interest though, on the view object read up on the DefaultPath and AlternatePath properties and on the folder object the DefaultPathFragment and AlternatePathFragment.


q: I am trying to write a macro that would "click" a command button that is in another workbook. Is that possible? Without changing any of the code within that other workbook?

[A]
You can use
```
Application.Run
```
for that:
```
```
Run "OtherWorkbook.xls!MyOtherMacro"
```
```


q:
Assuming I have only the class name of a generic as a string in the form of "MyCustomGenericCollection(of MyCustomObjectClass)" and don't know the assembly it comes from, what is the easiest way to create an instance of that object?

If it helps, I know that the class implements IMyCustomInterface and is from an assembly loaded into the current AppDomain.

Markus Olsson gave an excellent example here, but I don't see how to apply it to generics.

[A]
Once you parse it up, use
Type.GetType(string)
to get a reference to the types involved, then use
Type.MakeGenericType(Type[])
to construct the specific generic type you need.  Then, use
Type.GetConstructor(Type[])
to get a reference to a constructor for the specific generic type, and finally call
ConstructorInfo.Invoke
to get an instance of the object.
```
```
Type t1 = Type.GetType("MyCustomGenericCollection");
Type t2 = Type.GetType("MyCustomObjectClass");
Type t3 = t1.MakeGenericType(new Type[] { t2 });
ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes);
object obj = ci.Invoke(null);
```
```


q:
I started using subversion for one of my projects and it would be absolutely amazing if I could just export the latest version from the repository on my production server by for example running a php or perl script.

The production site is hosted with a shared hosting provider who doesn't allow shell access or for example the php exec() function. (I don't know much about perl; I only know that my hoster allows perl and custom cgi scripts).

Is it possible to perform a SVN export in this environment?

[A]
SVN supports access over WebDAV (i.e. HTTPS). This means for simple read access you don't actually need an SVN client to access an SVN repository. You can even use a web browser, or in your case any PHP function that accepts a URL as its argument. SVN has to be set up on the server side to work with apache, for more info check out the
svn red book


q:
The Python list comprehension syntax makes it easy to filter values within a comprehension.  For example:

result = [x**2 for x in mylist if type(x) is int]

Will return a list of the squares of integers in mylist.  However, what if the test involves some (costly) computation and you want to filter on the result?  One option is:

result = [expensive(x) for x in mylist if expensive(x)]

This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x.  Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?

[A]
Came up with my own answer after a minute of thought.  It can be done with nested comprehensions:
```
```
result = [y for y in (expensive(x) for x in mylist) if y]
```
```
I guess that works, though I find nested comprehensions are only marginally readable


q:
Background

Normal rails eager-loading of collections works like this:

Person.find(:all, :include=>:companies)

This generates some sql which does

LEFT OUTER JOIN companies ON people.company_id = companies.id

Question

However, I need a custom join (this could also arise if I was using find_by_sql) so I can't use the vanilla :include => :companies

The custom join/sql will get me all the data I need, but how can I tell activerecord that it belongs to the associated Company objects rather than just being a pile of extra rows?

Update

I need to put additional conditions in the join. Something like this:

SELECT blah blah blah
LEFT OUTER JOIN companies ON people.company_id = companies.id AND people.magical_flag IS NULL
<Several other joins>
WHERE blahblahblah

[A]
Can you not add the join conditions using ActiveRecord?
For example, I have a quite complex query using several dependent records and it works fine by combining conditions and include directives
```
```
Contractors.find(
  :all,
  :include => {:council_areas => :suburbs},
  :conditions => ["suburbs.postcode = ?", customer.postcode]
)
```
```
Assuming that:
Contractors have_many CouncilAreas
CouncilAreas have_many Suburbs
This join returns the Contractors in the suburb identified by
customer.postcode
.
The generated query looks like:
```
```
SELECT contractors.*, council_areas.*, suburbs.*
FROM `contractors`
LEFT OUTER JOIN `contractors_council_areas` ON `contractors_council_areas`.contractor_id = `contractors`.id
LEFT OUTER JOIN `council_areas` ON `council_areas`.id = `contractors_council_areas`.council_area_id
LEFT OUTER JOIN `council_areas_suburbs` ON `council_areas_suburbs`.council_area_id = `council_areas`.id
LEFT OUTER JOIN `suburbs` ON `suburbs`.id = `council_areas_suburbs`.suburb_id WHERE (suburbs.postcode = '5000')
```
```
(Note: I edited the column list for brevity).


q:
I have a server that sends data via a socket, the data is a wav 'file'. I can easily write the data to disk and then play it in WMP, but I have no idea how I can play it as I read it from the socket. Is it possible?

Bonus question: how would I do it if the stream was in mp3 or other format?

This is for windows in native C++.

[A]
Because you've said WMP, I'm assuming the question applies to trying to play a wav file on a windows machine.  If not, this answer isn't relevant.
What you want to do isn't trivial.  There is a good article
here
on code project that describes the windows audio model.  It describes how to set up the audio device and how to stream data into the device for playback.  You "simply" need to supply data coming in from your socket as data for the playback buffers.  But that's where all of the tricky work is.  You have to be sure that
You have enough data to begin a playback
Handle the case when your socket is starved for data and you have nothing to send to the playback buffer
You are able to read data off of the socket with enough speed to keep the playback buffers full
It's an interesting exercise.  But tricky.


q:
What is the proper way to inject a data access dependency when I do lazy loading?

For example I have the following class structure

class CustomerDao : ICustomerDao
  public Customer GetById(int id) {...}

class Transaction {
  int customer_id; //Transaction always knows this value
  Customer _customer = null;
  ICustomerDao _customer_dao;
  Customer GetCustomer() {
    if(_customer == null)
      _customer = _customer_dao.GetById(_customer_id);
    return _customer
  }

How do I get the reference to _customer_dao into the transaction object?  Requiring it for the constructor seems like it wouldn't really make sense if I want the Transaction to at least look like a POCO.  Is it ok to have the Transaction object reference the Inversion of Control Container directly?  That also seems awkward too.

How do frameworks like NHibernate handle this?

[A]
I typically do the dependency injection in the constructor like you have above, but take the lazy loading a step further by acting only when the "get" is called like I have below.  Not sure if this is the pure approach you are looking for, but it does eliminate the "dirty" constructor DI/Lazy Loading in 1 step ;)
```
```
public class Product
{
    private int mProductID;
    private Supplier mSupplier;
    private ISupplierService mSupplierService;

    public Product()
    {
      //if you want your object to remain POCO you can use dual constr
      //this constr will be for app use, the next will be for testing
    }

    public Product(ISupplierService SupplierService)
    {
        mSupplierService = SupplierService;
    }

    public Supplier Supplier {
        get {
            if (mSupplier == null) {
                if (mSupplierService == null) {
                    mSupplierService = new SupplierService();
                }
                mSupplier = mSupplierService.GetSupplierByProductID(mProductID);
            }
            return mSupplier;
        }
        set { mSupplier = value; }
    }
}
```
```


q: I cant seem to find much info on haskells layout features, as I understand it is something like pythons formatting requirements except that is optional. How can I choose not to use this option correctly? Would it be a good idea to start without it so that I get a solid feel for the language itself?

[A]
See
http://en.wikibooks.org/wiki/Programming:Haskell_indentation
and
http://www.haskell.org/onlinereport/lexemes.html#sect2.7
(both contain examples).
Pros:
less typing
less to read, nicer-looking (if you're comfortable with it)
Cons:
you might get it wrong, especially if you're not familiar with it. Braces make things crystal clear if you're not sure.


q:
Is there a way to use constants in JavaScript?

If not, what's the common practice for specifying variables that are used as constants?

[A]
No, not in general. Firefox implements
```
const
```
but I know IE doesn't.
@John
points to a common naming practice for consts that has been used for years in other languages, I see no reason why you couldn't use that. Of course that doesn't mean someone will not write over the variable's value anyway. :)


q:
I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging.

I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI.

All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.

[A]
In
```
Firebug
```
, if you just
```
console.debug ("%o", my_object)
```
you can click on it in the console and enter an interactive object explorer. It shows the entire object, and lets you expand nested objects.


q:
How does AOP (Aspect Oriented Programming) work in Drupal?

I have learned about AOP in terms of using it for logging and security, but how does it apply to Drupal?

[A]
Drupal mimics AOP paradigms through hooks, which basically allow developers to weave in bits of code during the flow of execution. You can take a look at the hooks a developer can implement on the
list of Drupal hooks
shown in the Drupal documentation site, which just lists the hooks invoked from Drupal core and its modules.
As a quick example, if I were developing a new node based module (nodes being the basic data form in Drupal), I have instant access to comments and taxonomy with no additional work on my part. the comment and taxonomy modules have the ability to hook into nodes, and provide that added functionality. So in that sense, I don't have to account for such features in my program but I am able to take advantage of that flexibility.


q:
Does a hash shrink in Perl as you delete elements.

More specifically I had a perl program that I inherited that would parse a huge file ( 1 GB ) and load up a hash of hashes. it would do that same for another file and then do a comparison of different elements. The memory consumption was huge during this process and even though I added deleting hash elements has they were used the memory consumption seemed to be unaffected.

The script was extremely slow and such a memory hog. I know it was not well designed but any ideas about the hash memory usage?

[A]
In general, Perl cannot return memory to the operating system. It may be able to reuse memory internally, though, which could reduce the amount of memory needed by a program.
See perlfaq3:
How can I free an array or hash so my program shrinks?
If the memory used by the hashes is excessive (i.e. > physical memory) you could
```
tie
```
them to a file on disk. This would greatly reduce your memory usage but be warned that accessing a structure on disk is much slower than accessing one in memory. (So is disk thrashing.)


q: I use the commercial version of Jalopy for my Java projects but it doesn't work on Groovy files.  IntelliJ has a serviceable formatter but I don't like requiring a particular IDE.

[A]
Try "BUSL"
2022-10-26 NOTE:
HISTORIC. "BUSL" seems to be dead.
Last archived webpage is from 2020
.
I've found that
BUSL
works really well on Groovy files. It's standalone too, so you can use it from your text editor or whatever.


q: I'd really like to get into some D3D coding, but I don't have the time lately to learn C++ for what will amount to a hobby project.

[A]
The number that your application needs; no more, and no less.
Obviously, if you're writing an application which contains some parallelisable algorithm, then you can probably start benchmarking to find a good balance in the number of threads, but bear in mind that hundreds of threads won't speed up any operation.
If your algorithm can't be parallelised, then no number of additional threads is going to help.


q:
I am building an application where a page will load user controls (x.ascx) dynamically based on query string.

I have a validation summary on the page and want to update it from the User Controls. This will allow me to have multiple controls using one Validation Summary. How can I pass data between controls and pages.

I know I can define the control at design time and use events to do that but these controls are loaded dynamically using Page.LoadControl.

Also, I want to avoid using sessions or querystring.

[A]
Assuming you're talking about asp's validator controls, making them work with the validation summary should be easy: use the same Validation Group. Normally, I derive all usercontrols from a base class that adds a ValidationGroup property whose setter calls a overriden method that changes all internal validators to the same validation group.
The tricky part is making them behave when added dynamically. There are some gotchas you should be aware of, mainly concerning the page cycle and when you add them to your Page object. If you know all the possible user controls you'll use during design time, I'd try to add them statically using EnableViewState and Visible to minimize overhead, even if there are too many of them.


q: I am writing a page where I need an HTML table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter how many rows are added to the table. Think a mini version of excel. This seems like a simple task but almost every solution I have found on the web has some drawback. How can I solve this?

[A]
Have you tried using thead and tbody, and setting a fixed height on tbody with overflow:scroll?
What are your target browsers?
EDIT: It worked well (almost) in firefox - the addition of the vertical scrollbar caused the need for a horizontal scrollbar as well - yuck.  IE just set the height of each td to what I had specifed the height of tbody to be.  Here's the best I could come up with:
```
```

    <title>Blah</title>

              One	Two

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

```
```


q:
We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it.

We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently.

We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again.

Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?

[A]
There are MSI properties you can look at that will tell you if a product is already installed or if an uninstall is taking place. The Installed property will be true if the product is already there, so you can use it in a Boolean expression (Ex: Not Installed). The REMOVE property will be set to "ALL" if an uninstall is taking place. You might be able to condition your Firebird installation logic on these properties, which you can retrieve using the
MsiGetProperty
function.
Note: Property names mean different things based on case, so make sure you use the cases above.
I couldn't find any reference in the IS online help or Google to the DefaultFeatureInstalled event. Is your InstallShield project Basic MSI or InstallScript?


q:
How do they compare to the DevXpress ones or the original MSOffice ones.

Are they worth investing time in them (for practical usage now, not academic curiosity which I'll do anyway)?

[A]
From my experience, the new ribbon control implements the entire specification as laid out by Microsoft.  The only issue I noticed was a slight flicker when the form was resized which caused one of the sections to collapse or expand.
Worth spending time in?  Definitely, as they are lighter weight and its a matter of time before someone gets rid of the flicker (could be as simple as a lockwindowupdate inserted in the source?).  It doesn't hurt to use the Delphi action manager, from which all is based.


q:
I've never used CI tools before, but from what I've read, I'm not sure it would provide any benefit to a solo developer that isn't writing code every day.

First - what benefits does CI provide to any project?

Second - who should use CI? Does it benefit all developers?

[A]
The benefit of CI lies in the ability to discover early when a check in has broken the build. You can also run your suite of automated tests against the build, as well as run any kind of tools to give you metrics and such.
Obviously, this is very valuable when you have a team of commiters, not all of whom are diligent to check for breaking changes. As a solo developer, it is not quite as valuable. Presumably, you run your unit tests, and even maybe integration tests.  However, I have seen a number of occasions where the developer forgets to checkin a file out of a set.
The CI build can also be thought of as your "release" build.  The environment should be stable, and unaffected by whatever development gizmo you just add to your machine.  It should allow you to always reproduce a build.
This can be valuable if you add a new dependency to your project, and forget to setup the release build environment to take that into account.


q:
I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that.

ie.

50 + 100 = 150

int.Max + 50 = int.Max and not int.Min + 50

[A]
```
```
int penaltySum(int a, int b)
{
    return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}
```
```
Update: If your penalties can be negative, this would be more appropriate:
```
```
int penaltySum(int a, int b)
{
    if (a > 0 && b > 0)
    {
        return (int.MaxValue - a < b) ? int.MaxValue : a + b;
    }

    if (a < 0 && b < 0)
    {
        return (int.MinValue - a > b) ? int.MinValue : a + b;
    }

    return a + b;
}
```
```


q:
I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example:

select *
from   [User]
where  UserRolesBitmask | 22 = 22

This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.

[A]
I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV.
```
```
from u in DataContext.Users
where UserRolesBitmask | 22 == 22
select u
```
```


q:
I've got a dictionary, something like

Dictionary<Foo,String> fooDict

I step through everything in the dictionary, e.g.

foreach (Foo foo in fooDict.Keys)
    MessageBox.show(fooDict[foo]);

It does that in the order the foos were added to the dictionary, so the first item added is the first foo returned.

How can I change the cardinality so that, for example, the third foo added will be the second foo returned? In other words, I want to change its "index."

[A]
I am
not fully educated in the domain
to properly answer the question, but I have
a feeling
that the dictionary sorts the values according to the key, in order to perform quick key search. This would suggest that the dictionary is sorted by key values according to key comparison. However, looking at
object
methods, I assume they are using hash codes to compare different objects considering there is no requirement on the type used for keys. This is only a guess. Someone more knowledgey should fill in with more detail.
Why are you interested in manipulating the "index" of a dictionary when its purpose is to index with arbitrary types?


q:
I'm trying to start a service as a user and things work fine, until I try a user that doesn't have a password. Then, it fails to start (due to log-on error).

Am I doing something wrong or is this "by design"?

The code to register this service:

    SC_HANDLE schService = CreateService(
        schSCManager,
        strNameNoSpaces,
        strServiceName,
        SERVICE_ALL_ACCESS,
        SERVICE_WIN32_OWN_PROCESS,
        SERVICE_AUTO_START,
        SERVICE_ERROR_NORMAL,
        szPath,
        NULL,
        NULL,
        NULL,
        strUser,
        (strPassword.IsEmpty())?NULL:strPassword);

[A]
You need to specify an empty string, not NULL if there is no password. NULL is not a valid empty string, "" is. Probably you should just pass
```
strPassword
```
for the last parameter.
```
```
SC_HANDLE schService = CreateService(
            schSCManager,
            strNameNoSpaces,
            strServiceName,
            SERVICE_ALL_ACCESS,
            SERVICE_WIN32_OWN_PROCESS,
            SERVICE_AUTO_START,
            SERVICE_ERROR_NORMAL,
            szPath,
            NULL,
            NULL,
            NULL,
            strUser,

// change this line to:
            strPassword.IsEmpty() ? L"" : strPassword);
// or maybe
            strPassword);
```
```


q:
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to:

if (datetime.now() - self.timestamp) > 100
# Where 100 is either seconds or minutes

This generates a type error.

What is the proper way to do date time comparison in python? I already looked at WorkingWithTime which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison.

Please post lists of datetime best practices.

[A]
You can subtract two
datetime
objects to find the difference between them.
You can use
```
datetime.fromtimestamp
```
to parse a POSIX time stamp.


q:
I want to wrap a Perl one-liner in a batch file. For a (trivial) example, in a Unix shell, I could quote up a command like this:

perl -e 'print localtime() . "\n"'

But DOS chokes on that with this helpful error message:

Can't find string terminator "'" anywhere before EOF at -e line 1.

What's the best way to do this within a .bat file?

[A]
For Perl stuff on Windows, I try to use the generalized quoting as much as possible so I don't get leaning toothpick syndrome. I save the quotes for the stuff that DOS needs:
```
```
perl -e "print scalar localtime() . qq(\n)"
```
```
If you just need a newline at the end of the print, you can let the
```
-l
```
switch do that for you:
```
```
perl -le "print scalar localtime()"
```
```
For other cool things you can do with switches, see the
perlrun
documentation.


q:
I wonder how long it would usually take for:

Professional

Average

Beginner

to setup and configure CI for a new project?

[A]
CI Factory
TeamCity
CC.NET sample configs
Try.


q:
It's been a while since I've had to do any HTML-like code in Vim, but recently I came across this again. Say I'm writing some simple HTML:

<html><head><title>This is a title</title></head></html>

How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.

Of course I can use CtrlP to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.

[A]
Check this out..
closetag.vim
```
```
Functions and mappings to close open HTML/XML tags
```
```
https://www.vim.org/scripts/script.php?script_id=13
I use something similar.


q:
I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user.

The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value.

This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?

[A]
Yep, that's pretty much how I do it.  I would set the CheckedChanged event of both radio buttons to point at a single event handler and would place the following code to swap out the visible control.
```
```
private void OnRadioButtonCheckedChanged(object sender, EventArgs e)
{
    Control1.Visible = RadioButton1.Checked;
    Control2.Visible = RadioButton2.Checked;
}
```
```


q:
I want my Python script to copy files on Vista. When I run it from a normal cmd.exe window, no errors are generated, yet the files are NOT copied. If I run cmd.exe "as administator" and then run my script, it works fine.

This makes sense since User Account Control (UAC) normally prevents many file system actions.

Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")

If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?

[A]
It seems there's no way to elevate the application privileges for a while for you to perform a particular task. Windows needs to know at the start of the program whether the application requires certain privileges, and will ask the user to confirm when the application performs any tasks that
need
those privileges. There are two ways to do this:
Write a manifest file that tells Windows the application might require some privileges
Run the application with elevated privileges from inside another program
This
two
articles
explain in much more detail how this works.
What I'd do, if you don't want to write a nasty ctypes wrapper for the CreateElevatedProcess API, is use the ShellExecuteEx trick explained in the Code Project article (Pywin32 comes with a wrapper for ShellExecute). How? Something like this:
When your program starts, it checks if it has Administrator privileges, if it doesn't it runs itself using the ShellExecute trick and exits immediately, if it does, it performs the task at hand.
As you describe your program as a "script", I suppose that's enough for your needs.
Cheers.


q:
I have some C# code in an ASP.Net application that does this:

Bitmap bmp = new Bitmap(1184, 1900);

And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space.
Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free.

Anyone have any solutions?

[A]
You not only need enough memory, it needs to be contiguous.  Over time memory becomes fragmented and it becomes harder to find big blocks.  There aren't a lot of good solutions to this, aside from building up images from smaller bitmaps.
new Bitmap(x, y) pretty much just needs to allocate memory -- assuming that your program isn't corrupted in some way (is there any unsafe code that could corrupt the heap), then I would start with this allocation failing.  Needing a contiguous block is how a seemingly small allocation could fail.  Fragmentation of the heap is something that is usually solved with a custom allocator -- I don't think this is a good idea in IIS (or possible).
To see what error you get on out of memory, try just allocation a gigantic Bitmap as a test -- see what error it throws.
One strategy I've seen is to pre-allocate some large blocks of memory (in your case Bitmaps) and treat them as a pool (get and return them to the pool).  If you only need them for a short period of time, you might be able to get away with just keeping a few in memory and sharing them.


q:
There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However,

What is dependency injection and when/why should or shouldn't it be used?

[A]
Dependency Injection
is passing dependency to other
objects
or
framework
( dependency injector).
Dependency injection makes testing easier. The injection can be done through
constructor
.
```
SomeClass()
```
has its constructor as following:
```
```
public SomeClass() {
    myObject = Factory.getObject();
}
```
```
Problem
:
If
```
myObject
```
involves complex tasks such as disk access or network access, it is
hard
to do unit test on
```
SomeClass()
```
. Programmers have to mock
```
myObject
```
and might
intercept
the factory call.
Alternative solution
:
Passing
```
myObject
```
in as an argument to the constructor
```
```
public SomeClass (MyClass myObject) {
    this.myObject = myObject;
}
```
```
```
myObject
```
can be passed directly which makes testing easier.
One common alternative is defining a
do-nothing constructor
. Dependency injection can be done through setters. (h/t @MikeVella).
Martin Fowler
documents a third alternative (h/t @MarcDix), where
classes explicitly implement an interface
for the dependencies programmers wish injected.
It is harder to isolate components in unit testing without dependency injection.
In 2013, when I wrote this answer, this was a major theme on the
Google Testing Blog
. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.


q:
I'm using GNU autotools for the build system on a particular project. I want to start writing automated tests for verifcation. I would like to just type "make check" to have it automatically run these. My project is in C++, although I am still curious about writing automated tests for other languages as well.

Is this compatible with pretty much every unit testing framework out there (I was thinking of using cppunit)? How do I hook these unit testing frameworks into make check? Can I make sure that I don't require the unit test software to be installed to be able to configure and build the rest of the project?

[A]
You seem to be asking 2 questions in the first paragraph.
The first is about adding tests to the GNU autotools toolchain - but those tests, if I'm understanding you correctly, are for both validating that the environment necessary to build your application exists (dependent libraries and tools) as well as adapt the build to the environment (platform specific differences).
The second is about unit testing your C++ application and where to invoke those tests, you've proposed doing so from the autotools tool chain, presumably from the configure script.  Doing that isn't conventional though - putting a 'test' target in your Makefile is a more conventional way of executing your test suite.  The typical steps for building and installing an application with autotools (at least from a user's perspective, not from your, the developer, perspective) is to run the configure script, then run make, then optionally run make test and finally make install.
For the second issue, not wanting cppunit to be a dependency, why not just distribute it with your c++ application?  Can you just put it right in what ever archive format you're using (be it tar.gz, tar.bz2 or .zip) along with your source code.  I've used cppunit in the past and was happy with it, having used JUnit and other xUnit style frameworks.


q:
I'm not that up on VB.NET, the application I'm working on was not written by myself.

It works fine through the IDE but once I run it from the exe it gives me the above error.

Any clues?

This is really hacking me off!

[A]
The only user defined break point that I can think of is
```
```
Debugger.Break()
```
```
So, I would suspect that the .exe is compiled in debug mode.  I would recommend
Reflector
to look at the code and find out for sure whether or not there is a Debugger.Break() somewhere in there.


q:
I have 3 points in a 3D space of which I know the exact locations. Suppose they are: (x0,y0,z0), (x1,y1,z1) and (x2,y2,z2).

Also I have a camera that is looking at these 3 points and I know the 2D locations of those three points on camera view plane. So for example (x0,y0,z0) will be (x0',y0'), and (x1,y1,z1) will be (x1',y1') and (x2,y2,z2) will be (x2',y2') from the camera's point of view.

What is the easiest way to find the projection matrix that will project those 3D points into 2D points on camera view plane. We don't know anything about the camera location.

[A]
This gives you two sets, each of three equations in 3 variables:
```
```
a*x0+b*y0+c*z0 = x0'
a*x1+b*y1+c*z1 = x1'
a*x2+b*y2+c*z2 = x2'

d*x0+e*y0+f*z0 = y0'
d*x1+e*y1+f*z1 = y1'
d*x2+e*y2+f*z2 = y2'
```
```
Just use whatever method of solving simultaneous equations is easiest in your situation (it isn't even hard to solve these "by hand").  Then your transformation matrix is just ((a,b,c)(d,e,f)).
...
Actually, that is over-simplified and assumes a camera pointed at the origin of your 3D coordinate system and no perspective.
For perspective, the transformation matrix works more like:
```
```
( a, b, c, d )   ( xt )
( x, y, z, 1 ) ( e, f, g, h ) = ( yt )
               ( i, j, k, l )   ( zt )

( xv, yv ) = ( xc+s*xt/zt, yc+s*yt/zt ) if md < zt;
```
```
but the 4x3 matrix is more constrained than 12 degrees of freedom since we should have
```
```
a*a+b*b+c*c = e*e+f*f+g*g = i*i+j*j+k*k = 1
a*a+e*e+i*i = b*b+f*f+j*j = c*c+g*g+k*k = 1
```
```
So you should probably have 4 points to get 8 equations to cover the 6 variables for camera position and angle and 1 more for scaling of the 2-D view points since we'll be able to eliminate the "center" coordinates (xc,yc).
So if you have 4 points and transform your 2-D view points to be relative to the center of your display, then you can get 14 simultaneous equations in 13 variables and solve.
Unfortunately, six of the equations are not linear equations.  Fortunately, all of the variables in those equations are restricted to the values between -1 and 1 so it is still probably feasible to solve the equations.


q:
I'm still learning RegEx at the moment, but for the time being could someone help me out with this?  I have a few special requirements for formatting the string:

No directories.  JUST the file name.

File name needs to be all lowercase.

Whitespaces need to be replaced with underscores.

Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).

[A]
If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at
http://regexlib.com/
.
Edit to say:
Here's one that might work for you
:
```
```
([0-9a-z_-]+[\.][0-9a-z_-]{1,3})$
```
```


q: What function will let us know whether a date in VBA is in DST or not?

[A]
For non-current dates (DST 2007+):
First, you need a function to find the number of specific weekdays in a month:
```
```
Public Function NDow(Y As Integer, M As Integer, _
                N As Integer, DOW As Integer) As Date

' Returns Date of Nth Day of the Week in Month

NDow = DateSerial(Y, M, (8 - Weekday(DateSerial(Y, M, 1), _
              (DOW + 1) Mod 8)) + ((N - 1) * 7))

End Function
```
```
Then, you can check for the DST day versus the following function calls:
Fall:     NDow(Year(newdate), 11, 1, 1)
Spring:   NDow(Year(newdate), 3, 2, 1)
For the current date:
Call the Windows API function GetTimeZoneInformation,
and it will return an enum (integer) with the status.
I got the code for this from Chip Pearson's great Excel site.
Pearson's site


q: How can I perform list comprehensions in C#?

[A]
While this isn't a tutorial, here's some code that illustrates the concept:
```
```
public List<string> ValidUsers(List<User> users) {
  List<string> names = new List<string>();
  foreach(User user in users) {
    if(user.Valid) {
      names.Add(user.Name);
    }
  }
  return names;
}
```
```


q: Is it at the state where it is actually useful and can do more than rename classes?

[A]
CDT (C/C++ Development Tools - eclipse project) 5.0 has a bunch of new refactorings
```
```
* Declare Method
* Extract Baseclass
* Extract Constant
* Extract Method
* Extract Subclass
* Hide Method
* Implement Method
* Move Field / Method
* Replace Number
* Separate Class
* Generate Getters and Setters
```
```
There is a CDT refactoring
wiki


q:
I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this:

file = File.open("path-to-file.tar.gz")
contents = ""
file.each {|line|
  contents << line
}

I thought that would be enough to convert it to a string, but then when I try to write it back out like this...

newFile = File.open("test.tar.gz", "w")
newFile.write(contents)

It isn't the same file. Doing ls -l shows the files are of different sizes, although they are pretty close (and opening the file reveals most of the contents intact). Is there a small mistake I'm making or an entirely different (but workable) way to accomplish this?

[A]
You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can store in a plain text file. Then you can retrieve the tar file by decoding the text back.
You do something like:
```
```
require 'base64'

file_contents = Base64.encode64(tar_file_data)
```
```
Have look at the Base64
Rubydocs
to get a better idea.


q:
I have a table that has redundant data and I'm trying to identify all rows that have duplicate sub-rows (for lack of a better word). By sub-rows I mean considering COL1 and COL2 only.

So let's say I have something like this:

 COL1   COL2   COL3
 ---------------------
 aa     111    blah_x
 aa     111    blah_j
 aa     112    blah_m
 ab     111    blah_s
 bb     112    blah_d
 bb     112    blah_d
 cc     112    blah_w
 cc     113    blah_p

I need a SQL query that returns this:

 COL1   COL2   COL3
 ---------------------
 aa     111    blah_x
 aa     111    blah_j
 bb     112    blah_d
 bb     112    blah_d

[A]
Join on yourself like this:
```
```
SELECT a.col3, b.col3, a.col1, a.col2
FROM tablename a, tablename b
WHERE a.col1 = b.col1 AND a.col2 = b.col2 AND a.col3 != b.col3
```
```
If you're using postgresql, you can use the oid to make it return less duplicated results, like this:
```
```
SELECT a.col3, b.col3, a.col1, a.col2
FROM tablename a, tablename b
WHERE a.col1 = b.col1 AND a.col2 = b.col2 AND a.col3 != b.col3
  AND a.oid < b.oid
```
```


q:
I have a backroundrb scheduled task that takes quite a long time to run. However it seems that the process is ending after only 2.5 minutes.

My background.yml file:

:schedules:
  :named_worker:
    :task_name:
      :trigger_args: 0 0 12 * * * *
      :data: input_data

I have zero activity on the server when the process is running. (Meaning I am the only one on the server watching the log files do their thing until the process suddenly stops.)

Any ideas?

[A]
There's not much information here that allows us to get to the bottom of the problem.
Because backgroundrb operates in the background, it can be quite hard to monitor/debug.
Here are some ideas I use:
Write a unit test to test the worker code itself and make sure there are no problems there
Put "puts" statements at multiple points in the code so you can at least see some responses while the worker is running.
Wrap the entire worker in a begin..rescue..end block so that you can catch any errors that might be occurring and cutting the process short.


q:
I know there is a list-comprehension library for common lisp (incf-cl), I know they're supported natively in various other functional (and some non-functional) languages (F#, Erlang, Haskell and C#) - is there a list comprehension library for Scheme?

incf-cl is implemented in CL as a library using macros - shouldn't it be possible to use the same techniques to create one for Scheme?

[A]
Swindle
is primarily a CLOS emulator library, but it has list comprehensions too. I've used them, they're convenient, but the version I used was buggy and incomplete. (I just needed generic functions.)
However, you probably want
SRFI-42
. I haven't used it, but it HAS to have fewer bugs than the Swindle list comprehensions.
I don't know which Scheme you use.
PLT Scheme
bundles Swindle and SRFI-42. Both are supposed to be cross-Scheme compatible, though.
If you use PLT Scheme, here is SRFI-42's
man page
. You say
```
(require srfi/42)
```
to get it.


q:
Is it possible to do at least one of the following:

1) Detect a setting of a Local Security Policy (Accounts: Limit local account use of blank passwords to console logon only)

2) Modify that setting

Using Win32/MFC?


q:
I installed mediawiki on my server as my personal knowledge base. Sometimes I copy some stuff from Web and paste to my wiki - such as tips & tricks from somebody's blog. How do I make the copied content appear in a box with border?

For example, the box at the end of this blog post looks pretty nice:

http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/

I could use the pre tag, but paragraphs in a pre tag won't wrap automatically.. Any ideas?

[A]
Mediawiki supports the div tag.  Combine the div tag with some styles:
```
```
<div style="background-color: cyan; border-style: dashed;">
A bunch of text that will wrap.
</div>
```
```
You can play around with whatever css attributes you want, but that should get you started.


q:
Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.

I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.

The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package.  Is this true?  And more importantly is it the best way to implement a singleton?

[A]
The pattern which is used by Cairngorm (which may not be the best) is to throw a runtime exception in the constructor if the constructor is being called a second time. For Example:
```
```
public class Foo {
  private static var instance : Foo;

  public Foo() {
    if( instance != null ) {
      throw new Exception ("Singleton constructor called");
    }
    instance = this;
  }

  public static getInstance() : Foo {
    if( instance == null ) {
      instance = new Foo();
    }
    return instance;
  }

}
```
```


q:
I have been getting an error in VB .Net

object reference not set to an instance of object.

Can you tell me what are the causes of this error ?

[A]
The object has not been initialized before use.
At the top of your code file type:
```
```
Option Strict On
Option Explicit On
```
```


q:
Not sure how to ask a followup on SO, but this is in reference to an earlier question:
Fetch one row per account id from list

The query I'm working with is:

SELECT *
FROM scores s1
WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score < s2.score)
ORDER BY score DESC

This selects the top scores, and limits results to one row per accountid; their top score.

The last hurdle is that this query is returning multiple rows for accountids that have multiple occurrences of their top score. So if accountid 17 has scores of 40, 75, 30, 75 the query returns both rows with scores of 75.

Can anyone modify this query (or provide a better one) to fix this case, and truly limit it to one row per account id?

Thanks again!

[A]
If you are selecting a subset of columns then you can use the DISTINCT keyword to filter results.
```
```
SELECT DISTINCT UserID, score
FROM scores s1
WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score < s2.score)
ORDER BY score DESC
```
```


q:
I would like to create a copy of a database with approximately 40 InnoDB tables and around 1.5GB of data with mysqldump and MySQL 5.1.

What are the best parameters (ie: --single-transaction) that will result in the quickest dump and load of the data?

As well, when loading the data into the second DB, is it quicker to:

1) pipe the results directly to the second MySQL server instance and use the --compress option

or

2) load it from a text file (ie: mysql < my_sql_dump.sql)

[A]
Pipe it directly to another instance, to avoid disk overhead. Don't bother with
```
--compress
```
unless you're running over a slow network, since on a fast LAN or loopback the network overhead doesn't matter.


q: I'm wondering if updating statistics has helped you before and how did you know to update them?

[A]
```
```
exec sp_updatestats
```
```
Yes, updating statistics can be very helpful if you find that your queries are not performing as well as they should.  This is evidenced by inspecting the query plan and noticing when, for example, table scans or index scans are being performed instead of index seeks.  All of this assumes that you have set up your indexes correctly.
There is also the
UPDATE STATISTICS
command, but I've personally never used that.


q:
If I have a Range object--for example, let's say it refers to cell A1 on a worksheet called Book1.  So I know that calling Address()  will get me a simple local reference: $A$1.  I know it can also be called as Address(External:=True) to get a reference including the workbook name and worksheet name: [Book1]Sheet1!$A$1.

What I want is to get an address including the sheet name, but not the book name.  I really don't want to call Address(External:=True) and try to strip out the workbook name myself with string functions.  Is there any call I can make on the range to get Sheet1!$A$1?

[A]
Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:
```
```
Dim cell As Range
Dim cellAddress As String
Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1)
cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False)
```
```
EDIT:
Modify last line to :
```
```
cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False)
```
```
if you want it to work even if there are spaces or other funny characters in the sheet name.


q:
Short version: I'm wondering if it's possible, and how best, to utilise CPU specific
instructions within a DLL?

Slightly longer version:
When downloading (32bit) DLLs from, say, Microsoft it seems that one size fits all processors.

Does this mean that they are strictly built for the lowest common denominator (ie. the
minimum platform supported by the OS)?
Or is there some technique that is used to export a single interface within the DLL but utilise
CPU specific code behind the scenes to get optimal performance? And if so, how is it done?

[A]
The DLL is expected to work on every computer WIN32 runs on, so you are stuck to the i386 instruction set in general. There is no official method of exposing functionality/code for specific instruction sets. You have to do it by hand and transparently.
The technique used basically is as follows:
 - determine CPU features like MMX, SSE in runtime
 - if they are present, use them, if not, have fallback code ready
Because you cannot let your compiler optimise for anything else than i386, you will have to write the code using the specific instruction sets in inline assembler. I don't know if there are higher-language toolkits for this. Determining the CPU features is straight forward, but could also need to be done in assembler.


q:
As much as I generally don't like the discussion/subjective posts on SO, I have really come to appreciate the "Hidden Secrets" set of posts that people have put together.  They provide a great overview of some commonly missed tools that you might now otherwise discover.

For this question I would like to explore the Visual Studio .NET debugger.  What are some of the "hidden secrets" in the VS.NET debugger that you use often or recently discovered and wish you would have known long ago?

[A]
```
$exception
```
in the watch window will show the exception that is currently being processed even if you don't have a catch that assign the
```
Exception
```
instance to a named variable.


q: I'm looking for resources that can help me determine which approach to use in creating a 2d data structure with C#.

[A]
Do you mean multidimensional array? It's simple:
```
```
<type>[,] <name> = new <type>[<first dimenison>,<second dimension>];
```
```
Here is MSDN reference:
Multidimensional Arrays (C#)


q: I am going to install SVN for my personal projects. Is it better to install it on a spare machine(Win XP) or will I save myself grief if I install it on the machine I use for development(Vista).

[A]
Installing your repository on a separate machine is probably a better idea, since at a minimum, it will allow your source code to survive a hard drive crash on your development machine.
If you're new to SVN, you can't beat the free e-book from Red-Bean and O'Reilly ... Check out "Version Control with Subversion" here:
http://svnbook.red-bean.com/
.


q: I'm stuck on a PHP 4 server, and I would like to start moving an old legacy project to modern Design Patterns, including Dependency Injection.  Are there any dependency injection frameworks that will work with PHP 4?

[A]
I don't think a dependency injection framework will really work on PHP because of the way object-oriented programs are structured in it. First of all, it's not like C# or Java wherein the binaries are already there and you just have to find a way to instantiate this object and inject it into another. PHP has to load the class files and interpret them before it can use them. So if you have deep inheritance hierarchies with PHP I don't think that's a good idea.
Given that PHP is a scripting language, it's best to leverage it as that -- a scripting language. Which means, I would just make use of simple factory or builder methods to do something similar to dependency injection. I wouldn't burden it with a DI framework that will only add to the stuff the PHP runtime has to process for every web request (unless you do opcode caching, but there will still be overhead that's not incurred by web platforms for Java and .NET). If I have to change the objects that will be injected into objects or how they are created, it would be a simple task to just edit the script that contains the factory/builder methods. No need to recompile there anyway. So I have flexibility and I have a lightweight architecture that's suitable for the PHP way of doing things.


q:
There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice?

Here are a few methods that I know of:

var a = 2.5;
window.parseInt(a); // 2
Math.floor(a);      // 2
a | 0;              // 2

I'm sure there are others out there. Suggestions?

[A]
parseInt() is probably the best one.
```
a | 0
```
doesn't do what you really want (it just assigns 0 if a is an undefined or null value, which means an empty object or array passes the test), and Math.floor works by some type trickery (it basically calls parseInt() in the background).


q:
I've read JRM's Syntax-rules Primer for the Merely Eccentric and it has helped me understand syntax-rules and how it's different from common-lisp's define-macro.  syntax-rules is only one way of implementing a syntax transformer within define-syntax.

I'm looking for two things, the first is more examples and explanations of syntax-rules and the second is good sources for learning the other ways of using define-syntax.  What resources do you recommend?

[A]
To answer your second question:
```
syntax-case
```
is the other form that goes inside
```
define-syntax
```
. Kent Dybvig is the primary proponent of
```
syntax-case
```
, and
he has a tutorial on using it [PDF].
I also
read the PLT Scheme documentation
on
```
syntax-case
```
for a few more examples, and to learn about the variation in implementation.


q:
What does it take to get C++ tr1 members (shared_ptr especially, but we'd like function and bind and ALL the others) working with GCC 3.4.4 (for the Nokia N810 tablet computer).

Has anyone done this?  Attempted this?

It may not be feasible for us to upgrade to GCC 4.x to cross-compile for this device (but if you've done that, we'd love to know).

There may be many approaches, and I'd like to avoid dead ends others have hit.

We're trying to avoid bringing in boost, since it can be pretty interdependent (you bring in one boost header and you end up with 20 more), and keeping code size down is important to us.

Thank you!

[A]
Are you able to use
Boost
(
Smart Pointers
,
Bind
,
Function
) directly? From the
GCC changelogs
, the actual
```
std::tr1
```
stuff is only available from 4.0 onwards. :-(
I know there are differences between the Boost and
```
std::tr1
```
, but hopefully these can be worked around satisfactorily. Let me know how it works for you. :-)


q:
I have this code:

chars = #some list

try:
    indx = chars.index(chars)
except ValueError:
    #doSomething
else:
   #doSomethingElse

I want to be able to do this because I don't like knowfully causing Exceptions:

chars = #some list

indx = chars.index(chars)

if indx == -1:
    #doSomething
else:
   #doSomethingElse

Is there a way I can do this?

[A]
```
```
if element in mylist:
    index = mylist.index(element)
    # ... do something
else:
    # ... do something else
```
```


q:
How do I apply the MarshalAsAttribute to the return type of the code below?

public ISomething Foo()
{
    return new MyFoo();
}

[A]
According to
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx
:
```
```
[return: MarshalAs(<your marshal type>)]
public ISomething Foo()
{
    return new MyFoo();
}
```
```


q: I am just curious to know how long, in minutes, does the reporting service take to generate report when it returns 1MB of data. Maybe using views and table is properly index. SSRS reporting  and server side generation.

[A] How long is acceptable? Depends on what it's doing, how much it's run, things like that. Anything below 30 seconds would be fine if it's run once every day or two. If it's run once a week or once a month that number could be a lot higher.


q:
I have a web application using ASP.NET 2.0 and I want to know if I should be moving it to ASP.NET 3.5, particularly... what am I missing by not moving to ASP.NET 3.5?

I understand the disadvantages, but I don't understand the advantages.

What are the biggest benefits of migrating/rewriting?

Will I get a speed improvement?

Is MVC that much easier than my old-fashioned WebForm application?

Will it look cooler?

[A]
You will only miss access to the newer .NET 3.5 libraries, and cool syntax such as LINQ and lambda expressions. Performance wise they will run the same.
By the way, ASP.NET MVC is NOT included with .NET 3.5...yet.


q:
I've got a BPG file that I've modified to use as a make file for our company's automated build server. In order to get it to work I had to change

Uses                       *  Uses
  unit1 in 'unit1.pas'     *   unit1
  unit2 in 'unit2.pas'     *   unit2
   ...                     *    ...

in the DPR file to get it to work without the compiler giving me some guff about unit1.pas not found.
This is annoying because I want to use a BPG file to actually see the stuff in my project and every time I add a new unit, it auto-jacks that in 'unitx.pas' into my DPR file.

I'm running make -f [then some options], the DPR's that I'm compiling are not in the same directory as the make file, but I'm not certain that this matters. Everything compiles fine as long as the in 'unit1.pas is removed.

[A]
Well this work-around worked for me.
```
//{$define PACKAGE}
{$ifdef PACKAGE}
 uses
  unit1 in 'unit1.pas'
  unit2 in 'unit2.pas'
   ...
{$else}
 uses
  unit1
  unit2
   ...
{$endif}
```
The only problem is whenever you add a new unit, delphi erases your
```
ifdef package
```
at the top.


q:
In my ASP.Net 1.1 application, i've added the following to my Web.Config (within the System.Web tag section):

<httpHandlers>
  <add verb="*" path="*.bcn" type="Internet2008.Beacon.BeaconHandler, Internet2008" />
</httpHandlers>

This works fine, and the HTTPHandler kicks in for files of type .bcn, and does its thing.. however for some reason all ASMX files stop working.  Any idea why this would be the case?

Cheers
Greg

[A]
It sounds like it as an inherant <clear /> in it although I don't know if I've seen this behaviour before, you could just add the general handler back, let me find you the code.
```
```
<add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services" validate="false">
```
```
I think thats the right element, give it a shot.
EDIT: That is odd, I don't have a copy of 2003 on this machine so I can't open a 1.1 but I thought that was the right declaration.  You could try adding
```
validate="false"
```
into each element and see if that makes a difference.


q:
I am using VS 2008 with a very simple UpdatePanel scenario.
But i cannot get UpdatePanel to work and cant seem to find out why

I have in fact reverted to a very simple example to validate it is not my code:
http://ajax.net-tutorials.com/controls/updatepanel-control/

In this example I click on either button and both text links update.

I dont get any errors, the page just behaves like a normal ASPX page.
What things do i need to check. I've been googling this for an hour and not found what I need.

Edit: Works in Visual Studio web server but not in IIS

[A]
If it's working locally, but not when deployed to a remote server, that usually indicates that you're using ASP.NET 2.0 and the ASP.NET AJAX extensions aren't installed on the remote server.
If it's a server you have administrative control over, you can download the installer here:
http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en
If it's a web host, tell them to get their act together.


q:
Is there a way to search for multiple strings simultaneously in Vim? I recall reading somewhere that it was possible but somehow forgot the technique.

So for example, I have a text file and I want to search for "foo" and "bar" simultaneously (not necessarily as a single string, can be in different lines altogether).

How do I achieve that?


q:
I know that embedding CSS styles directly into the HTML tags they affect defeats much of the purpose of CSS, but sometimes it's useful for debugging purposes, as in:

<p style="font-size: 24px">asdf</p>

What's the syntax for embedding a rule like:

a:hover {text-decoration: underline;}

into the style attribute of an A tag? It's obviously not this...

<a href="foo" style="text-decoration: underline">bar</a>

...since that would apply all the time, as opposed to just during hover.

[A]
I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.
I should mention that
technically
you
should
be able to do it
according to the CSS spec
, but most browsers don't support it
Edit:
I just did a quick test with this:
```
```
Test
```
```
And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome.  Can anyone else test in any other browsers?


q: What is the right place to store program data files which are the same for every user but have to be writeable for the program? What would be the equivalent location on MS Windows XP? I have read that C:\ProgramData is not writeable after installation by normal users. Is that true? How can I retrieve that directory programmatically using the Platform SDK?

[A]
```
SHGetFolderPath()
```
with CSIDL of
```
CSIDL_COMMON_APPDATA
```
.
Read more at
http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx
If you need the path in a batch file, you can also use the
```
%ALLUSERSPROFILE%
```
environment variable.


q:
Several years back, I innocently tried to write a little app to save my tactically placed desktop icons because I was sick of dragging them back to their locations when some event reset them.  I gave up after buring WAY too much time having failed to find a way to query, much less save and reset, my icons' desktop position.

Anyone know where Windows persists this info and if there's an API to set them?

Thanks,
Richard

[A]
I have no idea about the API, but I know Ultramon (
http://www.realtimesoft.com/ultramon/
) has a feature included for preserving icon placement (although I've never used it for preserving icon location, it is indispensable for multiple monitor usage). The latest beta release works flawlessly with Vista (except for sometimes having a minor glitch or two when initially logging into my machine via RDP), and of course, haven't had any issues with XP. I've used it for over four years now.
And did I mention that it's the best utility for multiple monitor usage?


q:
How do I read the Response Headers that are being sent down in a page ? I want to be able to read the header values and modify some of them. This is for an ASP.NET 1.1 application but I would be curious to know if it can done in any version of ASP.NET.
The reason for doing this is someone may have added custom headers of their own before the point I am examining the response - so I cannot blindly clear all the headers and append my own - I need to read the all the headers so I can modify the appropriate ones only.

[A]
AFAIK it cannot be done in ASP.NET 1.1. There is no way for you to get at the response headers - request headers are available but not response headers.
I am not sure if you can do this in other stacks like Java, LAMP though and I am curious to find out...


q:
I'm using the Telerik RAD Controls RADEditor/WYSIWYG control as part of a Dynamic Data solution.

I would like to be able to upload files using the Document Manager of this control.

However, these files are larger than whatever the default setting is for maximum upload file size.

Can anyone point me in the right direction to fix this?

Thanks Yaakov Ellis, see your answer + the answer I linked through a comment for the solution.

[A]
The Telerik website has instructions
here
.
Short version: in Web.config set the maxRequestLength
```
```
<system.web>
  <httpRuntime maxRequestLength="102400" executionTimeout= "3600" />
</system.web>
```
```


q: I have an old Delphi codebase I have to maintain, lots of DLLs, some older than others. In some of these DLLs there is no version information in the Project Options dialog. The controls for adding a version are greyed out and I can't even add a version number by manually editing the .DOF file. How can I include a version number in these projects?

[A]
Check if the default .RES file exists in the project source location. Delphi includes the version number of the project in a .res file with the same name as the .dpr file. If the .RES file does not exist, the simplest way to recreate it is to add the {$R *.RES} compiler directive to the .DPR file, immediately after the uses clause.
```
```
library foolib;

uses
    foo in 'foo.pas',
    baz in 'baz.pas';

{$R *.RES}

exports
    foofunc name 'foofunc';

end;
```
```
As soon as you add the {$R *.RES} compiler directive Delphi will tell you it has recreated the foolib.res resource file.


q: I notice that modern C and C++ code seems to use size_t instead of int/unsigned int pretty much everywhere - from parameters for C string functions to the STL.  I am curious as to the reason for this and the benefits it brings.

[A]
The
```
size_t
```
type is the unsigned integer type that is the result of the
```
sizeof
```
operator (and the
```
offsetof
```
operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).
The
```
size_t
```
type may be bigger than, equal to, or smaller than an
```
unsigned int
```
, and your compiler might make assumptions about it for optimization.
You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in
pdf
format, or in the C11 standard, section 7.19, also available as a
pdf draft
.


q:
What is the SQL command to copy a table from one database to another database?
I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database.
Sorry if the question is too novice.

Thanks.

[A]
If you just want to copy the contents, you might be looking for
```
select into
```
:
http://www.w3schools.com/Sql/sql_select_into.asp
. This will not create an identical copy though, it will just copy every row from one table to another.


q:
Can someone explain why how the result for the following unpack is computed?

"aaa".unpack('h2H2')               #=> ["16", "61"]

In binary, 'a' = 0110 0001.  I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).

[A]
Check out the Programming Ruby
reference
on unpack. Here's a snippet:
Decodes str (which may contain binary
data) according to the format string,
returning an array of each value
extracted. The format string consists
of a sequence of single-character
directives, summarized in Table 22.8
on page 379. Each directive may be
followed by a number, indicating the
number of times to repeat with this
directive. An asterisk ("*") will
use up all remaining elements. The
directives sSiIlL may each be followed
by an underscore ("_") to use the
underlying platform's native size for
the specified type; otherwise, it uses
a platform-independent consistent
size. Spaces are ignored in the format
string. See also  Array#pack   on page
286.
And the relevant characters from your example:
H     Extract hex nibbles from each character (most significant first).
h     Extract hex nibbles from each character (least significant first).


q:
I want to calculate the time span between 2 times which I saved in a database.
So literally I want to know the length of time between the 2 values.

14:10:20 - 10:05:15 = 02:05:05

So the result would be 02:05:05.

How would I be able to achieve this using C#?

14:10:20 is the format I saved it in in my database.

[A]
Read the two time values into TimeSpan variables, then perform a
```
.Subtract()
```
on the bigger TimeSpan variable to get the TimeSpan result.
E.g.
```
TimeSpan difference = t1.Subtract(t2);
```
.


q:
I have an ellipse centered at (0,0) and the bounding rectangle is x = [-5,5], y = [-6,6]. The ellipse intersects the rectangle at (-5,3),(-2.5,6),(2.5,-6),and (5,-3)

I know nothing else about the ellipse, but the only thing I need to know is what angle the major axis is rotated at.

seems like the answer must be really simple but I'm just not seeing it... thanks for the help!

[A]
The gradient of the ellipse is identical to the gradient of the intersects with the bounding rectangle along one side of the ellipse.  In your case, that's the line from (-2.5,6) to (5,-3), the top side of your ellipse.  That line has a vertical drop of 9 and a horizontal run of 7.5.
So we end up with the following right-angled triangle.
```
```
(-2.5,6)
  *-----
  |\x
  | \
  |  \
9 |   \
  |    \
  |    x\
  +------* (5,-3)
    7.5
```
```
The angle we're looking for is x which is the same in both locations.
We can calculate it as:
```
```
-1
tan   (9/7.5)
```
```
which gives us an angle of -50.19 degrees


q: How do I read a time value and then insert it into a TimeSpan variables?

[A]
```
```
TimeSpan span = new TimeSpan(days,hours,minutes,seconds,milliseonds);
```
```
Or, if you mean DateTime:
```
```
DateTime time = new DateTime(year,month,day,minutes,seconds,milliseconds);
```
```
Where all of the parameters are ints.


q: See the question. I want to see the methods and classes offered by a DLLs library.

[A]
This is exactly what the Object Browser is for.
Add a reference to the DLL.
Right click it in the list.
Click
View in Object Browser
.


q:
Right now I have a visual studio project which contains a custom content type that I made. It also contains all the necessary files for making a sharepoint solution (wsp) file and a script to generate this.

Now, I would like to do 2 things.

First, I'd like to create a custom display form for the content type and include it in my solution so that it is automatically deployed when I deploy my solution. How do I include this in my solution and make my content type use it?

Secondly, you can query this type with the CQWP. I've thought about exporting it, adding more common view fields, and then modifying the XSL that is used to render it. How do I include this into my solution so that it is also deployed. I know i can export the CQWP webpart once it's all setup and include it in my project as a feature. But what abuot the XSL?

Looking forward to see your suggestions, cheers.

Did as described in the first answer. Worked like a charm.

[A]
Use
STSDev
to create the solution package.
That should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project.
To deploy the xslt, your feature will have an
```
<ElementManifest Location="mywebpartManifest.xml">
```
This then points to a files such as
```
```
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Yourfile.xslt" Url="Style Library" Path="" RootWebOnly="TRUE">
    <File Url="yourfile.xslt" Type="GhostableInLibrary" />
  </Module>
</Elements>
```
```
for the webpart:
```
```
<Module Name="myWebpart" List="113" Url="_catalogs/wp" RootWebOnly="FALSE">
   <File Url="myWebpart.webpart" Type="GhostableInLibrary" />
</Module>
```
```
Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project.
e.g.
```
```
<Resources>
    <Resource Location="SimpleFeature\Feature.xml"/>
```
```
The actual schemas are:
Site
Solution
Feature
and a link to someone else with the issue


q:
I am trying to implement in windows scripting host the same function as windows Send To/Mail Recipient does. Did not find anything usefull on google except steps to instantiate Outlook.Application and directly calling its methods.

I need to go the same path as windows do, as there is a mix of Outlook and Lotus Notes installed, I don't see it good to perform some sort of testing and deciding which object to talk to...

What I have found is that the actual work is done by sendmail.dll, there is a handler defined in registry under HKEY_CLASSES_ROOT\CLSID\{9E56BE60-C50F-11CF-9A2C-00A0C90A90CE}. I would like either to use this dll somehow or to simulate the same steps it does.

Thanks for your input.


q:
I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on).
I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals.

How can I check that I'll not delete data that should not be deleted?

I have a test database - just a copy of real one where I can do what I want :)

The only idea I have is dump database before and after and check it. But it not looks comfortable.
Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it?

Any other ideas how to solve the problem?

[A]
If the worry is keys left dangling (i.e.: pointing to a deleted record) then run the deletion on your test database, then use queries to find any keys that now point to invalid targets.  (while you're doing this you can also make sure the part that should be unaffected did not change)
A better solution would be to spend time mapping out the delete cascades so you know what to expect - knowing how your database works is pretty valuable so the effort spent on this will be useful beyond this particular deletion.
And no matter how sure you are back the DB up before doing big changes!


q:
I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done.

What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.

[A]
Here's a quick example:
I find the comma separated list syntax quite useful for building function calls:
```
```
% Build a list of args, like so:
args = {'a', 1, 'b', 2};
% Then expand this into arguments:
output = func(args{:})
```
```


q:
When you're using Tiles with Struts and do...

request.getRequestURL()

...you get the URL to e.g. /WEB-INF/jsp/layout/newLayout.jsp instead of the real URL that was entered/clicked by the user, something like /context/action.do.

In newer Struts versions, 1.3.x and after, you can use the solution mentioned on javaranch and get the real URL using the request attribute ORIGINAL_URI_KEY.

But how to do this in Struts 1.2.x?

[A]
I don't know if Struts 1.2.x has a similar Globals constant, but you could create your own in at least two ways:
get the original request URL in the Action and set it on the request, and call that from the JSP
use a Servlet Filter to do the same thing


q:
Does anyone know if IE6 ever misrenders pages with hidden divs? We currently have several divs which we display in the same space on the page, only showing one at a time and hiding all others.

The problem is that the hidden divs components (specifically option menus) sometimes show through. If the page is scrolled, removing the components from view, and then scrolled back down, the should-be-hidden components then disappear.

How do we fix this?

[A]
One hack you could use is to move your div outside the screen:
```
```
MyDiv.style.left = "-1000px";
```
```
And then put it back on its original position when you want to show it.


q:
I wish to test a function that will generate lorem ipsum text, but it does so within html tags. So I cant know in advance the textual content, but i know the html structure. That is what I want to test. And maybe that the length of the texts are within certain limits.
So what I am wondering is if the assertTags can do this in a way paraphrased bellow:

Result = "<p>Some text</p>";
Expected = array(
   '<p' ,
   'regex',
   '/p'
);
assertTags(resutl, expected)

I am using SimpleTest with CakePHP, but I think it should be a general question.

[A]
Extend the SimpleExpectation class and then use your new Expectation class in the assert statement
see:
http://www.lastcraft.com/expectation_documentation.php#extending
the example given is for validating an IP address but should be applicable to your problem:
```
```
class ValidIp extends SimpleExpectation {

  function test($ip) {
    return (ip2long($ip) != -1);
  }

  function testMessage($ip) {
    return "Address [$ip] should be a valid IP address";
  }
}
```
```
then in your test
```
```
$this->assert(new ValidIp(),$server->getIp());
```
```


q: When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?

[A]
Here is an example to boot strap spring for a Main method, simply grab the passed params as normal then make the function you call on your bean (in the case deployer.execute()) take them as Strings or via any format you feel suitable.
```
```
public static void main(String[] args) throws IOException, ConfigurationException {
    Deployer deployer = bootstrapSpring();

    deployer.execute();
}

private static Deployer bootstrapSpring()
{
    FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext("spring/deployerContext.xml");

    Deployer deployer = (Deployer)appContext.getBean("deployer");
    return deployer;
}
```
```


q:
Consider this case:

dll = LoadDLL()
dll->do()

...
void do() {
    char *a = malloc(1024);
}
...

UnloadDLL(dll);

At this point, will the 1k allocated in the call to malloc() be available to the host process again?
The DLL is statically linking to the CRT.

[A]
No, you do not leak.
If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe)
This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT.
If you'd linked with the dynamic version of the CRT, then you'd have a leak as the heap is shared amongst all dynamically-linked CRTs. It means you should always design your apps to use the dynamic CRTs, or ensure you never manage memory across a dll boundary (ie if you allocate memory in a dll, always provide a routine to free it in the same dll)


q: I compile my project with VIsual Studio 2005 Express Edition, and get this linking error. Can anyone suggest how to solve that?

[A]
That exact question is asked and answered at
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1512436&SiteID=1
.
Try re-installing.  It appears to be an install of the wrong service pack.


q: Is there anyone using Subsonic with asp.net mvc framework? If so, can you tell us something about your experience. Are there tips and tricks that can be shared?

[A]
If you're planning on doing database first design, and you don't need any mapping (i.e. you're in control of your db naming) then SubSonic is a decent option.
It's straight-forward, doesn't hide a lot from you.  On the same token, for advanced scenarios I have to side-step it a lot and execute raw sql (or a sproc).
If you're looking for a better object abstraction over the database, something that more closely matches your problem domain, then I'd look at NHibernate or Castle ActiveRecord.  This gives you a lot more flexibility in how you want your object model to look, and you have a powerful query API at your disposal.
None of this really has to do with ASP.NET MVC, other than you just use your objects in your web project.  I'd suggest putting the entities inside of a separate class library project anyway.


q: We want migrate from Delphi 7.0 to Delphi 2009, to stay up with a modern IDE and current technology. Our target platform is .NET. What is best way, to achieve this goal?

[A]
Migrating from Delphi 7 to Delphi 2009 is probably straight forward, there were only minor changes (such as the recently discussed move from ANSI to Unicode strings).
The move to .NET is not so straight forward, though. Although there's a VCL.NET which makes migrating GUIs possible, severeal other things will not work. So you might think of having Win32 code AND .NET code, bringing them together through COM.
(I hope you already know COM, otherwise this is probably not an option;-))