q:
What is the time complexity? Why?

(define (mult a b)
      (define (internal a accum)
        (if (= a 1) accum
            (internal (- a 1) (+ accum b))))
      (internal a b))

(define (to-the-power-of m n)
  (define (internal x accum)
    (if (= x 0) accum
        (internal (- x 1) (mult accum m))))
  (internal n 1))

[A]
Assuming addition and multiplication are both counted as a single operation, this function performs O(m^n) operations.
First consider the mult function. It (mult a b) will perform exactly a-1 additions. Since, the asymptotic growth is the same, lets approximate this by a, for mathematical simplicity.
Now for the to-the-power-of function, this performs n calls to the mult function. These calls are to (mult 1 m), yield m, then to (mult m m), yielding m^2, then to (mult m^2 m), yielding m^3 and so on upto m^n. So the total number of operations performed here is the sum m^0 + m^1 + ... + m^n. This is (m^n - 1) / (m-1) which grows as m^n.


q:
Let's suppose I have an applet running within a page in a browser.
What happens when the browser is closed by the user?

Is the applet notified so that it can perform some kind of close action on its side (closing connections opened to a server, cleaning static variables, ...)?

Also, I assume the same behavior would apply for a page refresh or page navigation (instead of browser close). The browser remains opened but the applet is gone. Although when you close the browser you also close the JVM so I'm unsure at this point.

Thanks,
JB

[A]
Yes, the
destroy() method
should be called before the
browser unloads the object
.
destroy()
is the last of four "
life-cycle methods
" of the Java applet (the others are
init()
,
start()
, and
stop()
).  They're actually called at different times depending on your
browser
and
virtual machine
.  If you'd like to know exactly when each is called, implement each method within your applet, and System.out some feedback.
Ideally, destroy() should be
called by the environment
, and should only be called once.  If it seems like destroy() is not being called, you might declare a public finalize() method, which calls destroy.  You could also try to call destroy() from javascript as the window object unloads, but again, be sure that you're not calling destroy() unnecessarily.
```
```
public void finalize () {
    destroy();
}
```
```

s: huggingface

c: devops

d: intermediate


q:
I'm having difficulty parsing some JSON data returned from my server using jQuery.ajax()

To perform the AJAX I'm using:

$.ajax({
  url: myUrl,
  cache: false,
  dataType: "json",
  success: function(data){
    ...
  },
  error: function(e, xhr){
    ...
  }
});

And if I return an array of items then it works fine:

[ { title: "One", key: "1" }, { title: "Two", key: "2" } ]

The success function is called and receives the correct object.

However, when I'm trying to return a single object:

{ title: "One", key: "1" }

The error function is called and xhr contains 'parsererror'.  I've tried wrapping the JSON in parenthesis on the server before sending it down the wire, but it makes no difference.  Yet if I paste the content into a string in Javascript and then use the eval() function, it evaluates it perfectly.

Any ideas what I'm doing wrong?

Anthony

[A]
Is your server sending data as Content-Type
```
"*/json"
```
? If not, modify the response headers accordingly. Sending
```
"application/json"
```
would be fine, for example.


q:
Has anyone tested sorting with Selenium? I'd like to verify that sorting a table in different ways work (a-z, z-a, state, date, etc.). Any help would be very much appreciated.

/Göran

[A]
You can get value of fields like this:
```
```
//div[@id='sortResult']/div[1]/div  (this'd be row 1 of the search result)
 //div[@id='sortResult']/div[2]/div   ( row 2)
```
```
(I'm making some assumptions about the HTML structure here, but you get my drift...)
These can be quite fragile assertions, I'd recommend you anchor these xpath references to an outer container element (not the root of your document, as lots of "automatic" tools do).
When you click sort, the value changes. You'll have to find out what the values are supposed to be.
Also watch out for browser compatibility with such xpaths. They're not always ;)


q:
How can i, in a bash script, execute a command when the user stops the script (with ctrl - c)?

Currently, i have this:

afplay file.mp3

while true:
do osascript -e "set volume 10"
end

But i would like it to execute killall afplay when the user is finished with it, regardless if it is command-c or another keypress.

[A]
```
trap 'killall afplay' EXIT
```


q: How can I customise the Site Actions menu to remove or rename 'standard' menu items? Where are the site actions menu items defined?

[A]
The site actions menu is defined in the Siteaction.xml in Template\layouts\editingMenu under the 12 hive.  The following link shows how to manually remove items.
Customize Site Actions Menu
I have added options to the menu using features, but have never tried to hide OTB option in code.  I would be interested in your results.
Good luck!


q:
There is this example code, but then it starts talking about millisecond / nanosecond problems.

The same question is on MSDN, Seconds since the Unix epoch in C#.

This is what I've got so far:

public Double CreatedEpoch
{
  get
  {
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    TimeSpan span = (this.Created.ToLocalTime() - epoch);
    return span.TotalSeconds;
  }
  set
  {
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    this.Created = epoch.AddSeconds(value);
  }
}

[A]
A Unix tick is 1 second (if I remember well), and a .NET tick is 100 nanoseconds.
If you've been encountering problems with nanoseconds, you might want to try using AddTick(10000000 * value).


q:
Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?

What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:

target_directory = "/Volumes/externalDrive/something/"
input_foldername, input_filename = os.path.split(input_file)
if same_partition(input_foldername, target_directory):
    copy(input_file, target_directory)
else:
    move(input_file, target_directory)

[A]
In C, you would use
```
stat()
```
and compare the
```
st_dev
```
field. In python,
```
os.stat
```
should do the same.
```
```
import os
def same_partition(f1, f2):
    return os.stat(f1).st_dev == os.stat(f2).st_dev
```
```


q:
I'm using a BindingList<T> in my Windows Forms that contains a list of "IComparable<Contact>" Contact-objects. Now I'd like the user to be able to sort by any column displayed in the grid.

There is a way described on MSDN online which shows how to implement a custom collection based on BindingList<T> which allows sorting. But isn't there a Sort-event or something that could be caught in the DataGridView (or, even nicer, on the BindingSource) to sort the underlying collection using custom code?

I don't really like the way described by MSDN. The other way I could easily apply a LINQ query to the collection.

[A] Not for custom objects. In .Net 2.0, I had to roll my on sorting using BindingList. There may be something new in .Net 3.5 but I have not looked into that yet. Now that there is LINQ and the sorting options that come with if this now may be easier to implement.


q:
I'm at a client doing some quick fixes to their access application. It was a while I had a go with access, but I'm recovering quickly. However, I've discovered an interesting problem:

For some reports, I get a "Record is deleted" error. I've checked the reports, and it seems like there's a problem with one table. When opening that table, I find a record where all columns are marked "#deleted". So obviously, this row seems to be the culprit. However, when I try to delete that row, nothing really happens. If I re-open the table, the row still exists.

Is there a corruption in the db? How can I remove this record for good?

Edit: It's a MS2000-version

Solution: Simply compress/repair did not work. I converted the database to the 2003 file format instead, which did the trick. I've marked the first answer suggesting compress/repair, since it pointed me in the right direction. Thanks!

[A]
Have you tried the built in Access compact/repair tool? This should flush deleted records from the database.
The exact location varies according to the version of Access you're running, but on Access 2003 it's under Tools > Database Utilities > Compact and repair database. Some earlier versions of Access had two separate tools - one for compact, one for repair - but they were accessed from a similar location. If they are separate on the version the client has, you need to run both.
This should be a non-destructive operation, but it would be best to test this on a copy of the MDB file (apologies for stating the obvious).


q:
I am in the process of moving from VSS to SVN and I'm not sure how to share files in SVN.

Basically we have the following structure in VSS

$MOSS
  - Components
    - ComponentA
      - bin
    - ComponentB
      - bin
  - GAC Mirror

GAC Mirror holds a shared copy of all the Dlls from the bin folders of the components to allow for easy copying to the GAC.

In VSS all you do is drag the Dll from the bin folder to the GAC Mirror folder and it works it's life out.

How would I do this in SVN?

Thanks in advance.

[A]
We had the same problem.  The simple answer is that you can't share files in SVN - in the end we had to restructure our directories and use batch files.
e.g. for source code files that were shared, we moved them to an Include folder, and have all the projects reference that folder.
For binary files that need to be copied to more than one location we store them just once in SVN, and then use batch files to copy them across to the target locations on each developers machine (or also on the build machine).


q:
How do I get the substring " It's big \"problem  " using a regular expression?

s = ' function(){  return " It\'s big \"problem  ";  }';


q: I'me looking for a function that would receive a time and would round it to the next/previous hour / half-hour / quarter / minute.

[A]
Try this function
```
```
CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float)
RETURNS datetime
AS
BEGIN
   DECLARE @RoundedTime smalldatetime
   DECLARE @Multiplier float

   SET @Multiplier= 24.0/@RoundTo

   SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier

   RETURN @RoundedTime
END

select dbo.roundtime('13:15',0.5)
```
```
The 1st param is the time to be rounded and the 2nd will be base on your list (0.5-half hour, 1-one hour, ...)


q:
I'm currently using the ActiveRecord-based session store for my Rails app and I have a background process which clears out inactive sessions every 30 minutes.

I'd like to switch to Rails' new cookie-based session store but how do I set the expiry time of the session to 30 minutes, as opposed to the default 'at end of session' value?

[A]
The
session options
page on the Rails wiki hints that this is only possible through a plugin:
Set the session cookie expire time
Unfortunately Rails has no way to dynamically set the expiry time of the session cookie. So it is recommended that you use the following plugin, which allows you to accomplish it:
http://blog.codahale.com/2006/04/08/dynamic-session-expiration-times-with-rails/
Of course take into account that the plugin is old, and may not work with your current version of Rails (I haven't looked at the specifics)


q:
I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?

The scenario is as follows

pulbic class SillyClassName {

    object moo;
    ...
    public void method1(){
        synchronized(moo)
        {
            ....
            method2();
            ....
        }
    }

    public void method2(){
        synchronized(moo)
        {
            doStuff();
        }
    }
}

Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it's locked?

I don't think so because it's the same thread but I'm unsure of any other odd results that might occur.

[A]
In java, the
```
synchronized
```
keyword on a method basically synchronizes on the current object, so in effect it's doing what you suggest above implicitly.
You won't experience problems with synchronizing on one object in one method and then synchronizing on the same object in another method because, as you say, the current thread already holds the lock on that object.


q: I'd like to have a page in php that normally displays information based on the GET request sent to it. However, I'd like for it to also be able to process certain POST requests. So, how can I tell if any data was sent by POST so I can act on it?

[A]
Use
```
$_SERVER['REQUEST_METHOD']
```
to determine whether your page was accessed via a GET or POST request.
If it was accessed via post then check for any variables in
```
$_POST
```
to process.


q:
We have a CustomAction that sets some registry key HKEY LOCAL_MACHINE. This wasn't working on Vista with UAC, until we made the action "deferred". The installer worked in other cases. Anyone knows why?

We are using WIX to create the installer.

[A]
Your custom action was being run immediately when it was encountered in the InstallExecuteSequence; instead of when the actual install script was being executed.  This caused your custom action to be executed with the users permissions rather than with the system's elevated permissions.  This series of blog posts will explain in detail what is happening,
http://blogs.msdn.com/rflaming/archive/2006/09/23/768146.aspx
.  You shouldn't have custom actions that effect the state of the machine that do not run as deferred custom actions.


q: If it said "oneword", then I could write "#oneword", but what do I write when there is a space in the word?

[A]
You can't have multiple words for the id, but you can for class.
```
```

lalala

.one {
    color: black;
}

.two {
    font-weight: bold;
}
```
```


q:
I have two XML files with two different XSD schemas and different namespaces. They have both an identical substructure. And now i need to copy that node (and all childs) from one XML document to the other one.

Clone would do, if the namespaces were the same. Is there a nice way to do it?
(The substructure will change later on - but will be kept identical.)

[A]
Basically, you need an XSL transformation that creates new elements with equal names, but a different namespace.
Consider the following input XML:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<test xmlns="http://tempuri.org/ns_old">
    <child attrib="value">text</child>
</test>
```
```
Now you need a template that says "copy structure and name of everything you see, but declare a new namespace while you're at it":
```
```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:old="http://tempuri.org/ns_old"
>
  <xsl:output method="xml" version="1.0"
    encoding="UTF-8" indent="yes" omit-xml-declaration="no"
  />

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

  <xsl:template match="old:*">
    <xsl:element name="{local-name()}" namespace="http://tempuri.org/ns_new">
      <xsl:apply-templates select="node()|@*"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>
```
```
When you run the above XML through it, this produces:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<test xmlns="http://tempuri.org/ns_new">
  <child attrib="value">text</child>
</test>
```
```
All your
```
http://tempuri.org/ns_old
```
elements have effectively changed their namespace. When your input XML has more than one namespace at the same time, the XSL must most likely be extended a bit.


q:
What is the equivalent to web controls in frameworks other than ASP.Net?

Specifically I'd like to know about Java, PHP and Ruby on Rails.

What are the relative merits/faults of each of these frameworks for web development?

I've had some exposure to ASP.Net and have been asked to look into developing an app that will have configurable controls on it. I know how I'd do this in ASP.Net, but it's to run on a linux box and in my experience Mono is not mature/stable when running ASP.Net.

Clarification

Basicly what I mean by webcontrols is a set of reusable componenet that I can initialize with various values.

So if for example I want to have a reusable component which draws a graph of some kind on the page. and i want to lay out several of these to graph different things.

[A]
I believe there aren't.
ASP.NET Web controls are a hodgepodge of
```
<input>
```
and
```
<submit>
```
HTML elements put together to make use of the ASP.NET Web Forms Page Lifecycle. This in turn to facilitate windows-forms like behavior in a web application.
AFAIK in other frameworks they still make use of the plain HTML control elements coupled with Javascript to modify behavior.


q:
The java.net.InetAddress.GetByName(String host) method can only return A records so to lookup other record types I need to be able to send DNS queries using the dnsjava library.

However that normally relies on being able to parse /etc/resolv.conf or similar to find the DNS server addresses and that doesn't work on Android.

The current DNS settings on Android can apparently only be obtained from within a shell by using the getprop command.

Can anyone tell me how to get those settings from Java other than by spawning a shell with Runtime.exec() and parsing the output from getprop?

[A]
I don't think it's possible for general case. For WiFi I found this:
```
```
WiFiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE);
DhcpInfo info = wifi.getDhcpInfo();
```
```


q:
<a id="lblShowTimings"
     runat="server"
     title='<%# Eval("SHOW_Name") %>'
     onclick='PopulateTicketDiv(<%#Eval("SHOW_ID") %>)'>  <-- this is the problem
  %#Eval("SHOW_Time") %>
</a>

Can Eval be passed as an argument to a javascript function?
If so whats the syntax?

[A]
Yes.  What you want to do is this, though:
```
```
onclick='<%# "PopulateTicketDiv(" +Eval("SHOW_ID") + " );" %>'
```
```


q:
How can I restart(recycle) IIS Application Pool from C# (.net 2)?

Appreciate if you post sample code?

[A]
If you're on
IIS7
then this will do it if it is stopped.  I assume you can adjust for restarting without having to be shown.
```
```
// Gets the application pool collection from the server.
[ModuleServiceMethod(PassThrough = true)]
public ArrayList GetApplicationPoolCollection()
{
    // Use an ArrayList to transfer objects to the client.
    ArrayList arrayOfApplicationBags = new ArrayList();

    ServerManager serverManager = new ServerManager();
    ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools;
    foreach (ApplicationPool applicationPool in applicationPoolCollection)
    {
        PropertyBag applicationPoolBag = new PropertyBag();
        applicationPoolBag[ServerManagerDemoGlobals.ApplicationPoolArray] = applicationPool;
        arrayOfApplicationBags.Add(applicationPoolBag);
        // If the applicationPool is stopped, restart it.
        if (applicationPool.State == ObjectState.Stopped)
        {
            applicationPool.Start();
        }

    }

    // CommitChanges to persist the changes to the ApplicationHost.config.
    serverManager.CommitChanges();
    return arrayOfApplicationBags;
}
```
```
If you're on
IIS6
I'm not so sure, but you could try getting the web.config and editing the modified date or something.  Once an edit is made to the web.config then the application will restart.


q: We'd like to start our bug numbers to something other than 1 for a new Bugzilla installation.  Is there a way to do this?

[A]
I'm not sure about Bugzilla's backend, but if it uses a SQL database, you should be able to find the table that controls the bug ID number and set the autoincrement value to something else. That is, if Bugzilla uses autoincrement.
But I don't have a copy of Bugzilla to provide more info.


q: Can someone define what exactly 'POCO' means? I am encountering the term more and more often, and I'm wondering if it is only about plain classes or it means something more?

[A]
"Plain Old C# Object"
Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.
EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.
TO CLARIFY:  In other words, they don’t derive from
some special base class, nor do they return any special types for their properties.
See below for an example of each.
Example of a POCO:
```
```
public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}
```
```
Example of something that isn’t a POCO:
```
```
public class PersonComponent : System.ComponentModel.Component
{
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public string Name { get; set; }

    public int Age { get; set; }
}
```
```
The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is
not
just a plain old object anymore.


q:
I'd like to warn users when they try to close a browser window if they didn't save the changes they made in the web form.

I'm using ASP.NET 3.5 (with ASP.NET Ajax).

Is there a common solution which I could easily implement?

EDIT: maybe my question wasn't clear: I am specifically looking for a way which integrates gracefully in the ASP.NET Server Controls methodology.

[A]
On the Page_Unload event (or call this function in your body tag,
```
<body onunload="onPageUnload();">
```
), you can have a check if the form has data in it.  Then you could run some Java:
```
```
<script language="text/javascript">
   function onPageUnload() {
        var oConfirm = window.confirm("You have unsaved form data, are you sure you want to close this window?");
        if(oConfirm){
            //Close
        }else{
            //Dont
        }
    }
</script>
```
```
See how that works out for ya
EDIT:  It may not prevent the closing of the window, but it will alert your user that they have unsaved data in your form.
Confirmed does NOT work cross-browser, I will investigate a different method and post it up here.


q:
I have been using Flex for a while and have not used remoting as of yet. Currently my apps use a webservice that generates xml that I use for databinding.

What would be the benefit to using remoting over an xml webservice in this use case? Is there a general guideline when I should choose remoting over webservices?

Why would I want to use remoting?

I have downloaded http://www.fluorinefx.com/, but have yet to do any real tinkering...

Thanks.

[A]
Speaking personally I use remoting because I prefer AMF to SOAP/XML for the simple reason of speed and packet size.
Ted has a good discussion in the relative merits of XML vs. AMF
here
Something to consider is what you have already in place on the server and where you think the future of your clients lies.  Do you anticipate replacing or extending your clients?  If yes then Web Services are a good architectural choice.  If you are committing to Flex in the short/medium term then you may be able to squeeze better performance out of remoting with AMF3 vs. your web services.
P.S. I once had a link to a very good site which had measurements of the relative performance of AMF and SOAP - I'll see if I can find it and post a link.
P.P.S.
here it is
, but it seems not to be working at the moment.


q:
I have a makefile template to compile a single DLL (for a plugin system).
The makefile of the user looks like this:

EXTRA_SRCS=file1 file2
include makefile.in

In the makefile.in I have:

plugin.dll: plugin.os $(patsubst %,%.os,$(EXTRA_SRCS))

Where plugin.os is the main C++ file to be compiled. Btw, the files ending is .os are the object files compiled for shared library (i.e. using the -fpic option with gcc)

Now, the problem is that the extra sources will probably (but not necessarily) be header files. Ideally I would like to add them as dependencies for the target plugin.os and the file.cpp, but only if they exist.

The method should work for both windows and linux, or at least be adaptable to each. However, I only use the GNU version of make.

[A]
Use the "wildcard" function:
```
```
$(wildcard *.h)
```
```
EDIT: in order to match a specific list, do
```
```
$(wildcard $(HEADER_FILES))
```
```
There is no need to use $(filter ...), the wildcard function automatically filters files which don't exist.


q:
I'm trying to code opposite action to this:

std::ostream outs; // properly initialized of course
std::set<int> my_set; // ditto

outs << my_set.size();
std::copy( my_set.begin(), my_set.end(), std::ostream_iterator<int>( outs ) );

it should be something like this:

std::istream ins;

std::set<int>::size_type size;
ins >> size;

std::copy( std::istream_iterator<int>( ins ), std::istream_iterator<int>( ins ) ???, std::inserter( my_set, my_set.end() ) );

But I'm stuck with the 'end' iterator -- input interators can't use std::advance and neither I can use two streams with the same source...

Is there any elegant way how to solve this? Of course I can use for loop, but maybe there's something nicer :)

[A]
(Edited: I should have read the question closer...)
While somewhat suspect, you can get approximately the right behavior by having an entry in the file that will "fail" the first loop, then clear the fail bit on the stream and start reading more.
Data, without an explicit size, but like this
```
1 1 2 3 5 8 Fibb
```
Fed to the code below seems to do what I meant, at least on VS2005 with STLPort.
```
typedef std::istream_iterator < int, char, std::char_traits ,ptrdiff_t> is_iter;
std::copy( is_iter(cin), is_iter(), inserter(my_set,my_set.end()));
cin.clear();
std::cin >> instr;
```


q: What is the difference between int *a[3] and int (*a)[3]?

[A]
There is no difference between
```
int a[3]
```
and
```
int (a)[3]
```
, they both declare
```
a
```
as an array of 3
```
int
```
s.  There is a difference between
```
int *a[3]
```
and
```
int (*a)[3]
```
, the former declares an array of 3 pointers to
```
int
```
whereas the second declares a pointer to an array of 3
```
int
```
s.  The parenthesis make a difference here because in C brackets have a higher precedence than *.


q:
I have the following legacy code:

public class MyLegacyClass
{
    private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource"

    public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj)
    {
       // do stuff using jndiName
    }
}

This class is working in a J2EE-Container.

Now I would like to test the class outside of the container.

What is the best strategy?
Refactoring is basically allowed.

Accessing the LegacyDataSource is allowed (the test does not have to be a "pure" unit-test).

EDIT: Introducing additional runtime-frameworks is not allowed.

[A]
Refactor the code to use dependency injection.  Then use you preferred DI framework (Spring, Guice, ...) to inject your resources.  That will make it easy to switch between resource objects and strategies at runtime.
In this case, you can inject your datasource.
EDIT: Based on your new restriction, you can accomplish the same thing by using a strategy pattern to set your datasource at runtime.  You can probably just use a properties file to distinguish which strategy to create and supply the datasource.  This would require no new framework, you would just be hand coding the same basic functionality.  We used this exact idea with a ServiceLocator to supply a mock datasource when testing outside of the Java EE container.


q:
When you have a complex property, should you instantiate it or leave it to the user to instantiate it?

For example (C#)

A)

 class Xyz{
     List<String> Names {get; set;}
 }

When I try to use, I have to set it.

...
Xyz xyz = new Xyz();
xyz.Name = new List<String>();
xyz.Name.Add("foo");
...

Where as if I modify the code

B)

 class Xyz{
     public Xyz(){
         Names = new List<String>();
     }
     List<String> Names {get; }
 }

which in this case, I can make the List read-only.

Another scenario might arise, I suppose where you would intentionally not want to set it. For example in

C)

 class Xyz{
     String Name {get; set;}
 }

I would thing it bad practice to initialize.

Are there some rules of thumb for such scenarios?

[A]
This is my normal solution:
```
```
class XYZ
{
   public XYZ () { Names = new List<string>(); }
   public List<string> Names { get; private set; }
}
```
```
(Note that it doesn't work with XmlSerialization, as you need getters and setters on all XmlSerialized properties.) (You can override this, but it seems like too much work for little effort).
As
OregonGhost
pointed out - you need to add
```
[XmlArray]
```
for this to work with XmlSerialization.
This still breaks the rules of encapsulation, as if you wanted to be entirely correct, you would have:
```
```
class XYZ
{
   public XYZ () { AllNames = new List<string>(); }
   private List<string> AllNames { get; set; }
   public void AddName ( string name ) { AllNames.Add(name); }
   public IEnumerable<string> Names { get { return AllNames.AsReadOnly(); } }
}
```
```
As this goes against the design of almost all the rest of the .Net framework, I usually end up using the first solution.
However, this does have the added benefit that XYZ can track the changes to it's collection of names, and that XYZ is the only place where the collection of names can be modified.
I have implemented this for a few cases, but it causes too much friction with other programmers when I do it for everything.


q:
I have a menu of product brands that I want to split over 4 columns.  So if I have 39 brands, then I want the maximum item count for each column to be 10 (with a single gap in the last column.  Here's how I'm calculating the item count for a column (using C#):

int ItemCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(BrandCount) / 4m));

All that conversion seems really ugly to me.  Is there a better way to do math on integers in C#?

[A]
A longer alternative with Mod.
```
```
ItemCount = BrandCount / 4;
if (BrandCount%4 > 0) ItemCount++;
```
```


q:
How to host the WCF service in windows service?

Thanks
Sekar

[A]
I just saw this today come across Channel 9:
http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Hosting-WCF-Services-in-Windows-Services/


q:
I have a simple application with the following code:

   FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles();
   List<Thread> threads = new List<Thread>(files.Length);

   foreach (FileInfo f in files)
   {
       Thread t = new Thread(delegate()
       {
            Console.WriteLine(f.FullName);
       });
       threads.Add(t);
   }

   foreach (Thread t in threads)
       t.Start();

Lets say in 'I=initialDirectory' directory I have 3 files.  This application should then create 3 threads, with each thread printing off one of the file names; however, instead each thread will print off the name of the last file in the 'files' array.

Why is this?  Why is the current file 'f' variable not getting setup in the anonymous method correctly?

[A]
The anonymous method keeps a
reference
to the variable in the enclosing block -- not the actual value of the variable.
By the time the methods are actually executed (when you start the threads)
```
f
```
has been assigned to point to the last value in the collection, so all 3 threads print that last value.


q: How can I get the start and end positions of all matches using the re module? For example given the pattern r'[a-z]' and the string 'a1b2c3d4' I'd want to get the positions where it finds each letter. Ideally, I'd like to get the text of the match back too.

[A]
```
```
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
    print(m.start(), m.group())
```
```


q:
Is it better to write many small methods (or functions), or to simply write the logic/code of those small processes right into the place where you would have called the small method?  What about breaking off code into a small function even if for the time being it is only called from one spot?

If one's choice depends on some criteria, what are they; how should a programmer make a good judgement call?

I'm hoping the answer can be applied generally across many languages, but if necessary, answers given can be specific to a language or languages.  In particular, I'm thinking of SQL (functions, rules and stored procedures), Perl, PHP, Javascript and Ruby.

[A]
I always break long methods up into logical chunks and try to make smaller methods out of them.  I don't
normally
turn a few lines into a separate method until I need it in two different places, but sometimes I do just to help readability, or if I want to test it in isolation.
Fowler's
Refactoring
is all about this topic, and I highly recommend it.
Here's a handy rule of thumb that I use from Refactoring.  If a section of code has a comment that I could re-word into a method name, pull it out and make it a method.


q:
A VBScript cannot edit the registry by default on Vista.  How do I get elevation (even if the user has to do something when they run the script) so that the script can edit the registry?

The error is:

---------------------------
Windows Script Host
---------------------------
Script: blah blah blah.vbs
Line:   6
Char:   1
Error:  Permission denied
Code:   800A0046
Source:     Microsoft VBScript runtime error

---------------------------
OK
---------------------------

[A]
To make it work with native VBScript, you will most likely need a code signing certificate and sign your script with that. More info is in that thread at
tek-tips.com
.
You could try to write the intended changes to a .reg file and call
```
regedit.exe
```
with that. Maybe this triggers UAC. Did not tried that, though. I have no Vista around right now. :-)


q: I'm building a auto updater and I need to know what kind of upload speeds people get on a 56K modem?

[A]
Theoretically 33.6 kbit/s upload = 4.2 kB/s[1].
From own experience, I would say half of that :)
[1]
http://en.wikipedia.org/wiki/ITU-T_V-Series_Recommendations#Simultaneous_transmission_of_data_and_other_signals


q: How to optimize queries which are already written?

[A]
If you can not change the them:
Indexes and statistics.
So you don't optimize the query but their execution plan.


q:
We are ready to start a brand new project at work, no legacy code. We did use Subsonic in the past and we pretty happy with it. But that was before Linq.

Has anyone had to face this same issue (Linq x Subsonic)?

What was your decision? What were the reasons?

Any insight appreciated.

[A]
The one thing I love about LINQ, which I don't think SubSonic handles as gracefully, is automatically dealing with joins.
```
```
FROM a in db.Orders
where a.Total > 100
SELECT new {a.Item.Desc, a.Customer.Name};
```
```
will automatically generate SQL like thisL
```
```
select i.DESC, c.NAME
from  ORDERS o
inner join ITEMS on o.ItemID = i.ItemID
inner join CUSTOMERS c on o.CustomerID = c.CUSTOMERID
where o.TOTAL > 100
```
```


q:
With the Ajax Control Toolkit, one can easily drag and drop all types of great extender onto controls, but they register a boatload of JavaScript to do it.

How do I control this?

If the ScriptManager is in the MasterPage, is there anyway to control the loading of a script on one page that isn't in another?

For example: calendar extender is on one page, but the script for it gets loaded on every page that is a child of the master page.


q:
for some reason, templatetags do not render in templates for django admin.

with this snippet from:
http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#shortcut-for-simple-tags

{% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}

when placed in admin index.html, if a user is logged in, it shows "Please log in"

same with templatetags, can not get any app ones to show, do anything. there is no error/they do not get processed either

[A]
That's only an example, the
```
is_logged_in
```
variable is not actually defined in any templates unless you put it in the context.
If you added that line and got
```
Please log in.
```
it does mean that the tag is rendering.  If it fails the
```
if
```
and goes to the
```
else
```
it is clearly being run.  You need to find something in the template you can actually use for the
```
if
```
case, though.  I haven't messed with the admin templates in newforms-admin, but depending if they use RequestContext and on which ContextProcessors you have enabled - you might be able to say
```
{% if not request.user.is_anonymous %} ...
```
or something similar.


q: As they are in .Net 3.5. I know they are in 4.0, as that's what the DLR works with, but I'm interested in the version we have now.

[A]
LINQ expression trees can represent anything you can put in a normal C# expression. As such, they can't be used to directly represent
```
while
```
loops,
```
for
```
loops, etc.
However, it's theoretically possible to use lambda expressions and recursion to carry out any iteration you may need. In practice it may be easier to drop
```
Enumerable
```
methods into your tree.


q: Can source code examples be kept in a SQL database while retaining all formatting (tabs, newlines, etc.)? If so what data type would be used?

[A]
Yes, use a
```
TEXT
```
type (or
```
MEDIUMTEXT
```
or
```
LONGTEXT
```
- you get the idea)


q:
I can't find any proper documentation on how to specify relations
using the declarative syntax of SQLAlchemy.. Is it unsupported? That is, should I use the "traditional" syntax?

I am looking for a way to specify relations at a higher level, avoiding having to mess with foreign keys etc.. I'd like to just declare "addresses = OneToMany(Address)" and let the framework handle the details.. I know that Elixir can do that, but I was wondering if "plain" SQLA could do it too.

Thanks for your help!

[A]
Assuming you are referring to
the declarative plugin
, where everything I am about to say is documented with examples:
```
```
class User(Base):
    __tablename__ = 'users'

    id = Column('id', Integer, primary_key=True)
    addresses = relation("Address", backref="user")

class Address(Base):
    __tablename__ = 'addresses'

    id = Column('id', Integer, primary_key=True)
    user_id = Column('user_id', Integer, ForeignKey('users.id'))
```
```


q:
If I write Session["asdf"] = 234;

In my asp.net web app, does this mean the client will have a cookie stored on their browser?

[A]
Yes, but 234 won't be stored in the cookie. The cookie will only contain a unique ID (for example,
```
lit3py55t21z5v55vlm25s55
```
). Every time ASP.NET sees that unique ID, it will look up the corresponding session information.
If you don't want to use cookies, you can put the session ID in the URL. Read this
MSDN article's
section on Cookieless SessionIDs.


q:
I need to write some registration data (unique computer number, and corresponding activation code).

The Computer Number needs to be visible from other programs and all accounts ({Admin|Non Admin} with User Access Control turned {On|Off} )

It's acceptable to write the Computer Number and Activation Code only from an Admin account, but it needs to be readable from any of the other accounts.

Currently (and I need to test this more) it seems that  if the the CN and Activation Code are written with UAC off then when the user switches UAC ON the Computer Number isn't visible.


q:
I am writing a macro for Visual studio that will generate some code.

I would like for the macro to generate for both C# and VB, is there a way to determine what language is being used in the active (current) document?

[A]
Have you considered using
T4
?
T4 is a code generator built right into Visual Studio. If you're using C#, you'll have a sub .cs file, or if you're using VB, a sub .vb file. That's the file that will hold the result of the generation. This is the same visual metaphor used to the express the template/generated file relationship with .designer files you've seen elsewhere in Visual Studio.


q:
I am developing a JSP application and am being forced to load a COM object. Can such a thing can be done?

If yes, how?

[A]
It is possible using a COM bridge like
JACOB
.
JACOB is a JAVA-COM Bridge that allows you to call COM Automation components from Java. It uses JNI to make native calls into the COM and Win32 libraries.


q:
It's rare that I hear someone using Inversion of Control (Ioc) principle with .Net. I have some friends that work with Java that use a lot more Ioc with Spring and PicoContainer.

I understand the principle of removing dependencies from your code... but I have a doubt that it's so much better.

Why do .Net programmers not use (or use less) those types of frameworks? If you do, do you really find a positive effect in the long term?

[A]
Lots of people use IOC in .NET, and there are several frameworks available to assist with using IoC.  You may see it less in the WinForms side of things, because it's harder to just let the container wire everything together when you are designing forms in Visual Studio, but I can say that for server-side .NET applications, where I work at least, IoC is used very successfully.
Why use it in .NET?  For the same reason you use it everywhere else.  The 2 biggest things I like are:
Designing for IoC tends to enforce good coding practice - designing to interfaces, low coupling, high cohesion.  This also leads to classes that are very easy to unit-test.
System configuration can often be changed without recompiling.
Some other posts discussing the different IoC/DI frameworks available for .NET:
Which C#/.net Dependency Injection frameworks are worth looking into?
Which Dependency Injection Tool Should I Use?


q:
We're running a lightweight web app on a single EC2 server instance, which is fine for our needs, but we're wondering about monitoring and restarting it if it goes down.

We have a separate non-Amazon server we'd like to use to monitor the EC2 and start a fresh instance if necessary and shut down the old one. All our user data is on Elastic Storage, so we're not too worried about losing anything.

I was wondering if anyone has any experience of using EC2 in this way, and in particular of automating the process of starting the new instance? We have no problem creating something from scratch, but it seems like it should be a solved problem, so I was wondering if anyone has any tips, links, scripts, tutorials, etc to share.

Thanks.

[A]
You should have a look at
puppet
and its support for
AWS
. I would also look at the
RightScale AWS library
as well as this post about
starting a server with the RightScale scripts
. You may also find this article on
web serving with EC2
useful. I have done something similar to this but without the external monitoring, the node monitored itself and shut down when it was no longer needed then a new one would start up later when there was more work to do.


q:
If this question has already been asked I appologies, please point me in the right direction.

I was wondering if anyone has any insight into how StackOverflow pops up the "n new answers have been posted, load new answers" thing at the top of a question when you are adding a post. This seems like a very useful function for my forum web-site and I would like to know how it is done. I assume some ajax or advanced javascript of some kind.

[A]
Look at this SO blog post:
https://blog.stackoverflow.com/2008/10/solving-the-fastest-gun-in-the-west-problem/
That said, the one implementable
recommendation that came out of this
discussion is an active, GMail like
notification when you are composing an
answer. We agreed with this feature
request, so Jarrod implemented it.
Here’s how it works:
When you start composing a reply, a timer is created.
Every minute, the page checks itself to see if new answers have
arrived.
If new answers arrive, the notification bar will tell you how
many, and offer to update the page for
you.
Answer updates are performed AJAX style, so they don’t interrupt
your current answer.


q:
I have an SQL database with multiple tables, and I am working on creating a searching feature.  Other than having multiple queries for the different tables, is there a different way to go about said searching function?

I should probably add that a lot of my content is database driven to make upkeep easier.  Lucene will not work for this, correct?

[A]
Different approaches to consider:
1) Multiple queries pre-baked, like you described.
2) Dynamic sql that you put together on the fly based on user-entered criteria.
3) If text is involved, based on SQL Server full text search or Lucene.
In my open source app BugTracker.NET, I do both 2 and 3 (using Lucene.NET).
I documented how I use Lucene.NET here:
http://www.ifdefined.com/blog/post/2009/02/Full-Text-Search-in-ASPNET-using-LuceneNET.aspx


q:
I made a class that derives from Component:

public class MyComponent: System.ComponentModel.Component
{

}

I saw that Visual Studio put this code in for me:

protected override void Dispose(bool disposing)
{
    try
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
    }
    catch
    {
        throw;
    }
    finally
    {
        base.Dispose(disposing);
    }
}

MyComponent has a member that is a DataSet and maybe there's some other members that implement IDisposable.  What, if anything, do i need to modify with the Dispose() method to make sure things are cleaned up properly?  Thanks for helping.

[A]
Change:
```
```
if (disposing && (components != null))
{
     components.Dispose();
}
```
```
to be:
```
```
if (disposing && (components != null))
{
    _dataset.Dispose();
    components.Dispose();
}
```
```


q: Is there a way that you can have SERVEROUTPUT set to ON in sqlplus but somehow repress the message "PL/SQL procedure successfully completed" that is automatically generated upon completed execution of a plsql procedure?

[A]
Use the command:
```
```
SET FEEDBACK OFF
```
```
before running the procedure.  And afterwards you can turn it back on again:
```
```
SET FEEDBACK ON
```
```


q: I see many different Java terms floating around.  I need to install the JDK 1.6.  It was my understanding that Java 6 == Java 1.6.  However, when I install Java SE 6, I get a JVM that reports as version 11.0!  Who can solve the madness?

[A]
JDK - Java Development Kit
JRE - Java Runtime Environment
Java SE - Java Standard Edition
SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).
The JDK includes the compiler and other tools needed to develop Java applications; JRE does not.  So, to run a Java application someone else provides, you need JRE; to develop a Java application, you need JDK.
Edited
:
As Chris Marasti-Georg pointed out in a comment, you can find out lots of information at Sun's
Java
web site, and in particular from the
Java SE
section, (2nd option, Java SE Development Kit (JDK) 6 Update 10).
Edited 2011-04-06:
The world turns, and Java is now managed by Oracle, which bought Sun.  Later this year, the
```
sun.com
```
domain is supposed to go dark.  The new page (based on a redirect) is this
Java
page at the Oracle Tech Network.  (See also
java.com
.)
Edited 2013-01-11:
And the world keeps on turning (2012-12-21 notwithstanding), and lo and behold, JRE 6 is about to reach its end of support.
Oracle
says no more public updates to Java 6 after February 2013.
Within a given version of Java, this answer remains valid.  JDK is the Java Development Kit, JRE is the Java Runtime Environment, Java SE is the standard edition, and so on.  But the version 6 (1.6) is becoming antiquated.
Edited 2015-04-29:
And with another couple of revolutions around the sun, the time has come for the end of support for Java SE 7, too.  In April 2015, Oracle
affirmed
that it was no longer providing public updates to Java SE 7.  The tentative end of public updates for Java SE 8 is March 2017, but that end date is subject to change (later, not earlier).


q:
Does anyone know of any specific DSL implementations used to import legacy Oracle database schemas. I have tried to just run db:schema:dump on my existing db I want to port to a new ruby app. However, the rake dies about halfway through with out any error. It kinda just locks up. I started looking for the best way to tackle this and found examples of how to override some stuff for SQLServer but not much for Oracle.

I basically want to pull in the schema and generate a scaffold and model from it.

Is there a more simple way to do this or will I have to invent the wheel?

[A]
did you try
```
rake --trace
```
?
By the way Oracle legacy schemas is a small cottage industry.
http://github.com/rsim/legacy_oracle_sample.git/README.txt
http://blog.rayapps.com/2008/06/28/activerecord-oracle-enhanced-adapter-version-111-released/
http://www.oracle.com/technology/pub/articles/saternos-rails.html
http://redsquirrel.com/cgi-bin/dave/dynamic/rails.multiple.oracle.dbs.html


q:
I'd like something like

int minIndex = list.FindMin(delegate (MyClass a, MyClass b) {returns a.CompareTo(b);});

Is there a builtin way to do this in .NET?

[A]
Try looking at these:
Min
Max
As long as your class implements IComparable, all you have to do is:
```
```
List<MyClass> list = new List();
//add whatever you need to add

MyClass min = list.Min();
MyClass max = list.Max();
```
```


q:
What is the best plugin for Rails that gzips my webpage output?

Edit:
The company I am hosting with has stated they will not install mod_deflate.

[A]
Have you tried enabling compression in apache via
mod_deflate
?


q:
I have an Ant script with a junit target where I want it to start up the VM with a different working directory than the basedir. How would I do this?

Here's a pseudo version of my target.

<target name="buildWithClassFiles">
    <mkdir dir="${basedir}/UnitTest/junit-reports"/>
    <junit fork="true" printsummary="yes">
        <classpath>
            <pathelement location="${basedir}/UnitTest/bin"/>
            <path refid="classpath.compile.tests.nojars"/>
        </classpath>
        <jvmarg value="-javaagent:${lib}/jmockit/jmockit.jar=coverage=:html"/>
        <formatter type="xml" />
        <test name="GlobalTests" todir="${basedir}/UnitTest/junit-reports" />
    </junit>

</target>

[A]
Have you tried:
```
```
<junit fork="true" printsummary="yes" dir="workingdir">
```
```


q: I have a WPF TreeView with just 1 level of items.  The TreeView is data bound to an ObservableCollection of strings.  How can I ensure that the same icon appears to the left of each node in the TreeView?

[A]
I think the best approach is to set a Style on the TreeView that will change the Template of the TreeViewItems to have the Image that you want.
The Template will probably need to be a StackPanel with an Image and a label control, you bind the image to your icon, and the label text to the strings from the Observable collection.
I've copied the relevant code snippet from a
Code Project article
, which covers this in more detail, but I think the below is all you'll need (This code goes in the TreeView.Resources element).
```
```
<Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="HeaderTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Name="img"
                           Width="20"
                           Height="20"
                           Stretch="Fill"
                           Source="image.png"/>
                    <TextBlock Text="{Binding}" Margin="5,0" />
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
```
```


q:
I'd trying to style my ComboBoxes to match the rest of the UI but I'm having problems with the IsMouseOver highlighting. It highlights with the color I specify for a second and then fades back to the default color, kind of a cool effect but not what I'm going for. Here is my style:

<Style TargetType="ComboBox">
    <Style.Triggers>
        <Trigger Property="ComboBox.IsMouseOver" Value="True">
            <Setter Property = "Background" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

What can I do to make the background color stay?

[A]
The problem is indeed due to the default template for the ComboBox. If you use
Reflector
to open the PresentationFramework.Aero assembly you can take a look at the ButtonChrome class. There is a method called OnRenderMouseOverChanged that is hiding the Red background.
Even though it is a lot of work, for ComboBox at least, you probably will want to override the default template for the ComboBox. You can get the basic idea of what the ComboBox temlpate is like by using
Show Me The Template
or
Blend
.
You can use your same style to override the template.
```
```
<Style TargetType="{x:Type ComboBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">
                <!-- Template Here -->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
```
```


q:
I want to attach a 'click' event handler to the first child of an element with ID 'foo' using jQuery. I understand that the syntax for doing this is:

$('#foo:first-child').bind('click', function(event) {
    // I want to access the first child here
})

Within the handler body I want to access the element which caused the event to be fired. I've read somewhere that you can't simply refer to it via 'this', so how can I access it?


q:
I use _vimrc to configure my vim 7.2 (windows) default settings. One setting "set number" will display line numbers on the left side. My vim background color is white (I cannot find setting for this. Maybe the default is white. Anyway I accept this setting).

I would like the background color for line numbers to be Grey or dimmed color. What is the command I can put in my _vimrc to configure this default setting?

[A]
```
```
highlight LineNr ctermfg=grey ctermbg=white
```
```


q:
I'm having trouble getting a rails app on Dreamhost's Passenger to see compiled libraries in my ~/opt/lib directory.  I have to put them here because I don't have root access.

I can boot up my app in ./script/console and it sees them libraries just fine because I updated my .bash_profile's LD_LIBRARY_PATH environment variable to include ~/opt/lib.

I've tried putting ENV['LD_LIBRARY_PATH'] = '~/opt/lib' in my environment.rb file but it doesn't seem too help.  I get the following error from Passenger when I navigate to my site:
libodbcinst.so.1: cannot open shared object file: No such file or directory - /home/username/opt/lib/odbc.so

Anyone have experience with this?

Thanks

[A]
I had similar issue with Passenger that I described in
http://blog.rayapps.com/2008/05/21/using-mod_rails-with-rails-applications-on-oracle/
But in your case this migth not work as you will not be able to change Dreamhost's httpd.conf file.
Other thing that you can try is to set LD_LIBRARY_PATH in .bashrc - according to
http://www.wavethenavel.com/jonathanpenn/2008/09/08/bootstrapping-a-dreamhost-account-for-rails-and-git/
this has worked in Dreamhost's case. Have not verified that Passenger will execute .bashrc before launching ruby.


q:
I have the following HTML node structure:

<div id="foo">
  <div id="bar"></div>
  <div id="baz">
    <div id="biz"></div>
  </div>
  <span></span>
</div>

How do I count the number of immediate children of foo, that are of type div? In the example above, the result should be two (bar and baz).

[A]
```
```
$("#foo > div").length
```
```
Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.


q:
I'm building a class library that will have some public & private methods. I want to be able to unit test the private methods (mostly while developing, but also it could be useful for future refactoring).

What is the correct way to do this?

[A]
Declare them
```
internal
```
, and then use the
```
InternalsVisibleToAttribute
```
to allow your unit test assembly to see them.


q:
I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:

sudo mod args

where mod is a perl script; so in python I would do

proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE)

The problem is that this mod script needs a few questions answered. For this I thought that the traditional

(stdout, stderr) = proc.communicate(input='y')

would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?

[A]
The simplest thing to do would be the run the controlling script (the Python script) via
```
sudo
```
. Are you able to do that, or is that not an option?


q: I need to implement an OpenID Provider in .Net and wondered....Is there's any OpenSource code already written and available?

[A]
I just found
http://code.google.com/p/dotnetopenid/
Apologies for not search properly first.....
I don't seem to be able to delete this question (strange)
Instead, as penance, this question and answer will be marked community property so I don't benefit in any way from my stupidity..


q:
We have a software product that evolves at the rhythm of clients' needs and of a more general roadmap.

Because we are in a SCRUM project environment, it happens very regurlarly that a new feature makes its way to the product, and then we are confronted with the choice of:

implementing this feature in an already released branch (not really the point of having a branch, then)

making a new branch - but then we have a branch every three weeks, and it is just not maintanable anymore

Not releasing the new feature is not an option, the clients don't want to wait for a long term milestone plan to get the features they want, and it's not always faisible to move the feature in a client module - sometimes we need to change the core of the product...

Has anyone any feedback on a good practice given those kind of constraints ?

[A]
A new branch like( 'new_feature_branch') is there to materialize a
development effort
which is not compatible with the current branch (like 'release_branch')
So if your current release_branch is not very active, you can use it for the new feature (provided you define a label
before
developing this new feature, in case you need to cancel that process and go back to the state previous this new feature)
Making a new branch can be a good solution provided it is merged back on a regular basis (every 3 weeks) on the release branch, and then left out. It is especially recommended if you have some activities on the release_branch (like some hot bug-fixing). then the two efforts need to be kept separated.
Basically, it all comes down to your
merge workflow
definition.
Leave comments if you want me to detail some options you feel I did not address enough in depth.


q:
I'm trying to export a Crystal Report to an HTML file, but when I call the Export method, I immediately get this error:

Source: Crystal Reports ActiveX Designer

Description: Failed to export the report.

I have tried both crEFTHTML40 and crEFTHTML32Standard as export format types - and both result in the same error.

Here is a highly simplified version of what I'm doing:

Dim objCRReport As CRAXDRT.Report
[...]
objCRReport.ExportOptions.FormatType = 32 'crEFTHTML40
objCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile
objCRReport.ExportOptions.DiskFileName = "C:\reportInHtmlFormat.html"
objCRReport.Export False '<--- "Failed to export the report" error here

Please note that I am referencing the "Crystal Reports 9 ActiveX Designer Runtime Library" specifically.

[A]
I'm not sure what you have in the
```
[...]
```
section but your code should include a call to open the report with an instance of the CRAXDRT Application.
```
```
Dim objCRReport As CRAXDRT.Report

'***********************************
Dim objCRApp As New CRAXDRT.Application

objCRReport = objCRApp.OpenReport("<YOUR REPORT FILENAME>", 1)
'***********************************

[...]
objCRReport.ExportOptions.FormatType = 32 'crEFTHTML40
objCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile
objCRReport.ExportOptions.DiskFileName = "C:\reportInHtmlFormat.html"
objCRReport.Export False '<--- "Failed to export the report" error here
```
```


q:
It turns out install shield doesn't support file download resuming.

Is there a .net component that provides this functionality?

[A]
I don't think so,but it's not that hard to write one . There are a lot of
HTTP Clients
already . All that you would need to do is checking to see if the web server actually supports resuming . Check this blog entry for a little info about HTTP and download resuming :
http://www.west-wind.com/WebLog/posts/244.aspx
All you would need to do is store the number of bytes read so far somewhere ( file , database ) , and read that when you're starting your application again . Be sure to check the md5 for the file ( if it has one ) , to ensure no errors occured .


q:
I want to make some passages of a standard tooltip bold in a WinForms application. Is this possible?

If not, is there a (free) tooltip component that allows me to style them (preferably also border and background)?

Thanks!

[A]
You can use this type :
Balloon tool tip
. This let you have some bold title and some color option. You might be able to modify the source to get underline, italic and bold inside the message.
Update:
You can modify the drawing of the ToolTip (and the FONT object of the text).
This is how to do it
. The code in this link is for the normal ToolTip, not the Balloon I posted above.


q:
I'm currently running Lucene.net in a web application and am wondering about the best method, performance-wise.

I currently have it set up so that all index writes get processed together in a scheduled process, along with optimizing the index.

However for searching - I'm currently opening and closing the searcher per search, which I know isn't ideal.

What do you think would be the best approach in this situation?

I'll need to close and reopen the index searcher once the updates/optimization is processed so the scheduled process (which is a windows console app) needs to communicate it's finished to the web application.

[A]
I just integrated Lucene.NET into BugTracker.NET.  I'm not sure that what I did is the best, but it seems to be working well.
I create the index at app startup.
I create a searcher and keep it around so that the index isn't reloaded with each search.  All threads share the same searcher.  When the searcher searches, it grabs a lock.
Meanwhile, I have an IndexWriter that updates the index when there is a data change.  It is just changing a little bit so it does its task quick.   When it runs, it grabs the same lock, destroys the searcher, updates the index, and the re-recreates the searcher.   The new searcher stays around until the next update of the index.   The searcher always is working with an up-to-date index.
You can get the BugTracker.NET source and look at the files my_lucene.cs and search_text.aspx.   It's all in those two files, and there isn't that much code.


q:
I have a CSV data file with rows that may have lots of columns 500+ and some with a lot less.  I need to transpose it so that each row becomes a column in the output file.  The problem is that the rows in the original file may not all have the same number of columns so when I try the transpose method of array I get:

`transpose': element size differs (12 should be 5) (IndexError)

Is there an alternative to transpose that works with uneven array length?

[A]
I would insert nulls to fill the holes in your matrix, something such as:
```
```
a = [[1, 2, 3], [3, 4]]

# This would throw the error you're talking about
# a.transpose

# Largest row
size = a.max { |r1, r2| r1.size <=> r2.size }.size

# Enlarge matrix inserting nils as needed
a.each { |r| r[size - 1] ||= nil }

# So now a == [[1, 2, 3], [3, 4, nil]]
aa = a.transpose

# aa == [[1, 3], [2, 4], [3, nil]]
```
```


q:
So I'm creating some HTML using javascript based on where the user clicks on the page. On page load the script replaces an empty div with a ul and some data. The user clicks on that data to receive more and so on. Now when the user navigates off the page and then hits the back button to go back to the page, IE displays a blank page with the replaced divs, in all other browsers, FF, Opera, Safari, the page either reloads to the initial ul or goes back to the last state with the dynamic data in it.

Anyone have an idea as to what might be happening here? Any help is appreciated.


q:
We're looking for a way to log any call to stored procedures in Oracle, and see what parameter values were used for the call.

We're using Oracle 10.2.0.1

We can log SQL statements and see the bound variables, but when we track stored procedures we see bind variables B1, B2, etc. but no values.

We'd like to see the same kind of information we've seen in MS SQL Server Profiler.

Thanks for any help

[A]
You could take a look at the
DBMS_APPLICATION_INFO package
.  This allows you to "instrument" your PL/SQL code with whatever information you want - but it does entail adding calls to each procedure to be instrumented.
See also
this AskTom thread
on using DBMS_APPLICATION_INFO to monitor PL/SQL.


q:
A client has asked whether or not I can provide some support for his intranet which runs on Oracle Application Server Portal. Not having used this technology before I thought I'd ask if anyone else has and what they thought of developing for it.

I'm a c#/ASP.NET developer so I note with apprehension that there's no mention of .NET in the developers guide. Anyone tried to make the two work together and lived to tell the tale?

[A]
The only experience I've had with an Oracle Portal was obliquely, when I inherited a system that used one for a relatively simple maintenance web application.  A large part of my opinion of Oracle's stuff comes from my background with SQL Server/ASP.NET, but Oracle is just plain harder to set up and administer and keep running, and that applies not just to the database but also to auxiliary stuff like Oracle Portal, their SOA suite, their Mobility Server etc.  Even experienced Oracle people tend to agree with this, so hopefully I won't piss anyone off.
I would definitely not provide support for an Oracle Portal application (or any other Oracle product, for that matter) unless I had a lot of experience with the tools.


q:
How do I find a stored procedure in a Sybase database given a text string that appears somewhere in the proc? I want to see if any other proc in the db has similar logic to the one I'm looking at, and I think I have a pretty unique search string (literal)

Edit:

I'm using Sybase version 11.2

[A]
In SQL Anywhere and Sybase IQ:
```
```
select * from SYS.SYSPROCEDURE where proc_defn like '%whatever%'
```
```
I'm not that familiar with ASE, but according to the docs (available from sybooks.sybase.com), it's something like:
```
```
select * from syscomments where texttype = 0 and text like '%whatever%'
```
```


q:
I am loading some data from an XML document, modifying it, and writing back out to XML.  The reading is done using a SAX parser library and the writing is done with a piece of custom code.  Sometimes, the file is modified externally, and extra elements are added (such as references to stylesheets).  Rather than losing these extra elements when I load and save the file, I would like to pass through any unknown tags so that they appear

When unknown elements are separate from interpreted elements, it should be straightforward to save unknown elements and attributes as strings and output these afterwards, but when they are interspersed and nested inside interpreted elements, it becomes less obvious.

Can anybody suggest a succinct way to do this?  Would it be simpler to switch to a DOM parser?  Performance is not an issue.

NB. I am working in C++ with the Gnome Glib::Markup::Parser, but would prefer language/library agnostic answers.

[A]
I don't know how you've written your content handler, but it's methods should be called on all events, including on the external modifications you want to preserve.  Your
```
startElement()
```
and
```
endElement()
```
callbacks could test element name and attributes to decide whether to call specialized methods on the elements to be modified, but by default just reconstruct and output the event on which the callback was called.  In that way, any elements you don't specifically handle specially just get output by default.
You could also do the same kind of thing in XSLT.  Take an identity transform (a stylesheet that outputs exactly what it is given for input) and add to it templates with more specific match expressions for the custom modifications.  I find XSLT easier to work with for most applications than either SAX or DOM.


q:
Similar to the one here on StackOverFlow, I would be needing to implement a way for people to vote up and vote down comments in a forum like site.

However instead of having a generic overall score, we will display the total amount of "thumbs up" and "thumbs down". The overall score will be needed for filtering purposes, such as "sort by highest rated", "show only ratings with + 3"

What is the best implementation strategy?

As a user suggested, I would also be storing the information who casted the vote

[A]
Well you'll need to store ratings (Comment ID, UserID, Vote-Value) so you can calculate and stop duplicate voting but I would strongly suggest you also add a VotesUp and VotesDown fields on your main comment entity.
Why the duplication? Speed. You're going to be doing disgusting amounts of
```
SUM-WHERE
```
statements otherwise and they'll run your database server into the ground. A few extra bytes on the header record and you'll be able to sort and filter to your heart's content.
Edit: If you're going to also sort by overall score in some cases, you might want to add a third field (VoteTotal).
Edit 2: The duplication is pointless if you're able to cache all the comment headers in memory. That's a lot of data though and you'd need a ton of memory to effectively cache it. If you're not a billionaire, I'd just duplicate the data.


q: How do implement the iterator pattern in VB.NET, which does not have the yield keyword?

[A]
Hmm, looks like you might be
out of luck
:
I was struggling with an issue today when converting some C# to VB.NET. C# has a really cool "yield return" statement that is used in an iterator block to provide a value to the enumerator object. VB.NET does not have the "yield" keyword. So, there are a few solutions (none of which are really clean) to get around this. You could use a return statement to return the value if you are looping through and would like to break an enumerator and return a single value. However, if you'd like to return the entire enumeration, create a List() of the child type and return the list. Since you are usually using this with an IEnumerable, the List() will work nice.
That was written a year ago, not sure if anyone has come up with anything else better since then..
Edit: this will be possible in the version 11 of VB.NET (the one after VS2010), support for iterators is planned.  The spec
is available here
.


q:
I have a QDirModel whose current directory is set. Then I have a QListView which is supposed to show the files in that directory. This works fine.

Now I want to limit the files shown, so it only shows png files (the filename ends with .png). The problem is that using a QSortFilterProxyModel and setting the filter regexp will try to match every parent of the files as well. According to the documentation:

For hierarchical models, the filter is
  applied recursively to all children.
  If a parent item doesn't match the
  filter, none of its children will be
  shown.

So, how do I get the QSortFilterProxyModel to only filter the files in the directory, and not the directories it resides in?

[A]
We ran into something similar where I work, and ended up making our own proxy model to do our filtering.  However, looking through the documentation for what you want (which seems like it would be a more common case), I came across two possibilities.
You might be able to set a name filter on the QDirModel and filter things that way.  I have no idea if this will work like you want, or if the name filters apply to directories also.  The documentation is kind of sparse on these.
Subclass the QSortFilterProxyModel and override the
```
filterAcceptsRow
```
function.  From the documentation:
Custom filtering behavior can be achieved by reimplementing the filterAcceptsRow() and filterAcceptsColumn() functions.
Then you could presumably use the model index to check if the index item is a directory (automatically accept) or a file (filter on filename).


q: I was wondering what would be the best approach you guys would take to relocate an entire Eclipse workspace? Assuming it's either versioned and exported, what would you do? Import the file? Checkout the whole thing from the repo? Thanks much in advance!

[A]
Maybe I'm missing something, but wouldn't you just start Eclipse, and either select the new workspace to use or select
```
Switch workspace
```
from the
```
File
```
menu?


q:
I have an SQLite table that contains a BLOB I need to do a size/length check on. How do I do that?

According to documentation length(blob) only works on texts and will stop counting after the first NULL. My tests confirmed this. I'm using SQLite 3.4.2.

[A]
I haven't had this problem, but you could try
```
length(hex(glob))/2
```
Update (Aug-2012):
For SQLite 3.7.6 (released April 12, 2011) and later,
```
length(blob_column)
```
works as expected with both text and binary data.


q:
I am in a process of designing a custom SharePoint application. On a previous project, all the data was kept in SharePoint lists and that's the way I've been trying now. But, I'm getting to the point where the data model grows and I feel a need to normalize it and split one logical entity into several physical lists. I'm wondering if I should switch from the SP lists to a classic database. On one hand, I am happy with the SharePoint out-of-box New Item, Edit Item, All Items forms; on the other hand I'm worried that the performance will suffer once I have to query joined data (if it stays in SPLists).

If you have any insight or experience with this problem, please share. Thanks.

[A]
If you have complex queries, I suggest you put them into a separate database. Lists are good when the data model doesn't grow that often.
Extending the amount of fields inside the columns of a list includes updating the ContentTypes directly with an STSADM that you will have to code. However, querying the data directly from the database (with some cache of course) will lead to a faster development without having to update all ContentTypes linked to every lists associated with it.
Of course, if you activate the Caching, the data queryied from the database will be cached at the page output level.


q:
In this question, I was given a really cool answer to alternating an image and its description between left and right, respectively.  Now I want to apply styling to both, e.g. padding-top, padding-bottom etc. How do I apply a style to both the RowStyle and AlternatingRowStyle in this scenario.

<AlternatingRowStyle CssClass="ProductAltItemStyle" />
<RowStyle CssClass="ProductItemStyle" />
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <div class="Image"><asp:Image runat="server" ID="productImage" ImageUrl='<%# Eval("imageUrl") %>' /></div>
            <div class="Description"><asp:Label runat="server" ID="lblProductDesc" Width="100%" Text='<%# Eval("productDesc") %>'></asp:Label></div>
        </ItemTemplate>
    </asp:TemplateField>

[A]
Here's how you do it:
```
```
.ProductAltItemStyle, .ProductItemStyle {
    // CSS Rules that apply to both go here
}
```
```


q:
How can I convert a varchar field of the form YYYYMMDD to a datetime in T-SQL?

Thank you.


q: I like Vim's visual mode. v for highlight/select chars or lines, Ctrlv for rectangle highlighting, as far as I know (I am a beginner). Is there any way to use visual mode to highlight last two chars, for example, on each line for some selected lines? The selected lines are in different length. Basically, I would like to find a quick way to remove the last two chars for some selected lines. Not sure I can use visual mode to highlight irregular area.

[A]
I can't think of a way to do this in visual mode, but you could use a command like this to do it...
```
```
:10,20 normal $xx
```
```
This would go to each line between line number 10 and 20, use $ to go to the end of the line, and then use x twice to delete two characters.  Normal just tells vim to use the following symbols as if they were keyboard shortcuts entered in normal mode (i.e after hitting esc).
Does that help?


q:
I tried this:

ALTER TABLE My.Table DROP MyField

and got this error:

-MyField is not a constraint.

-Could not drop constraint. See previous errors.

There is just one row of data in the table and the field was just added.

EDIT:
Just to follow up, the sql was missing COLUMN indeed.
Now I get even more seriously looking errors though:

The object 'some_object__somenumbers' is dependent on column 'MyField'

ALTER TABLE DROP COLUMN MyField failed because one or more objects access this column.

EDIT:

ALTER TABLE TableName DROP Constraint ConstraintName

worked, after that I was able to use the previous code to remove the column. Credit goes to both of you, thanks.

[A]
I think you are just missing the COLUMN keyword:
```
```
ALTER TABLE TableName DROP COLUMN ColumnName
```
```
You will also need to make sure that any constraint that is depending on ColumnName is dropped first.
You can do this by:
```
```
ALTER TABLE TableName DROP ConstraintName
```
```
For each constraint that you have.
If you have indexes based on the column, you will also need to drop those indexes first.
```
```
DROP INDEX TableName.IndexName
```
```


q:
I have a DTS package that drops a table then creates it and populates it but sometimes something happens and the package fails after the drop table.  If it's rerun it fails cuz the table hasn't been created yet.

Is there something like "if exists" for SQLServer 2000 like in MySQL?

thanks.

[A]
```
```
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))
DROP TABLE TableName;
GO
```
```
You can check a
list of type definitions in the sys.objects table here
if you want to check if other objects in your database exist.


q:
I am developing a C# program, and i have one function that consumes too much CPU. I would like to know a way to control this by code (not with any external application) and restrict the percentage of CPU usage.
For example, if it uses 90% of the CPU usage, to make my app consume only a 20%, even if it becomes slower. It must be done automatically and from within the app.
If you provide a class, it would be fantastic.

[A]
I don't know if you can do that, but you can change the thread priority of the executing thread via the
Priority
property.  You would set that by:
```
```
Thread.CurrentThread.Priority = ThreadPriority.Lowest;
```
```
Also, I don't think you really want to cap it.  If the machine is otherwise idle, you'd like it to get busy on with the task, right?  ThreadPriority helps communicate this to the scheduler.


q: I want to fade out an element and all its child elements after a delay of a few seconds. but I haven't found a way to specify that an effect should start after a specified time delay.

[A]
```
```
setTimeout(function() { $('#foo').fadeOut(); }, 5000);
```
```
The 5000 is five seconds in milliseconds.


q: Sometimes you need to upgrade the database with many rows that you have in a datatable or you have an array full of data, instead of putting all this data together in a string and then splitting in SQL SERVER, or instead of iterating the datatable in the code row by row and updating database, is there any other way? Is there other type of variables besides the traditional ones in SQL SERVER 2005?

[A]
There's a few ways to do this.
If you're simply inserting rows, then I would create a DataTable object with the information in it, then use the SqlBulkCopy object:
```
```
SqlBulkCopy copier = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.Default);
copier.BatchSize = 500; //# of rows to insert at a time
copier.DestinationTableName = "dbo.MyTable";
copier.WriteToServer(myDataTable);
```
```
Another option is to wrap your data in xml (however you want to do that), and send it to your stored procedure (which does whatever you need it to do) using the sql 2005 'xml' data type


q:
I have a User object that has a Country object on it. I map this with a many-to-one tag in the User mapping file:

<many-to-one name="Country" column="CountryID" cascade="none"/>

How do I update a User's country?

At the moment my UI has a dropdown of countries and the ID of the new country is passed to the controller. The controller then sets the ID of the User's country from that value. So:

var user = session.Get<User>(userID);
user.Country.ID = Convert.ToInt32(Request.Form["Country_ID"]);

But when I call:

session.SaveOrUpdate(user);

I get an error saying that "identifier of an instance of Country was altered from 7 to 8". Presumably this is because the Country object is marked as dirty by NHibernate? I don't want to update the country object though, just the ID reference in the User. Is it possible to do it this way?

Thanks,
Jon

[A]
```
```
var user = session.Get<User>(userID);
user.Country = session.Get<Country>(Convert.ToInt32(Request.Form["Country_ID"]));
```
```
You must retrieve the country from the database and then set it to the user


q:
My co-founder is currently asking on our blog for an embeddable code widget.

http://devver.net/blog/2008/10/someone-please-build-an-awesome-embeddable-code-widget/

Basically we want something like http://pastie.org/ or http://codepad.org/ but we really want to embed the code section in our blog. We know there are plugins for common blogs and server side solutions, but it would be great to be able to just embed a little javascript and have nicely formatted code anywhere...

Does something like this exist? Have we just missed it?

[A]
I think you want a javascript syntax highlighter
http://code.google.com/p/syntaxhighlighter/
http://shjs.sourceforge.net/
http://www.google.com/search?q=javascript+syntax+highlighter
Sometimes you just keep thinking in the wrong keywords ;-)


q:
I noticed the specificaition for Collections.sort:

public static <T> void sort(List<T> list, Comparator<? super T> c)

Why is the "? super" necessary here?  If ClassB extends ClassA, then wouldn't we have a guarantee that a Comparator<ClassA> would be able to compare two ClassB objects anyway, without the "? super" part?

In other words, given this code:

List<ClassB> list = . . . ;
Comparator<ClassA> comp = . . . ;
Collections.sort(list, comp);

why isn't the compiler smart enough to know that this is OK even without specifying "? super" for the declaration of Collections.sort()?

[A]
Josh Bloch had a talk at Google I/O this year, called
Effective Java Reloaded
, which you may find interesting. It talks about a mnemonic called "Pecs" (producer
```
extends
```
, consumer
```
super
```
), which explains why you use
```
? extends T
```
and
```
? super T
```
in your input parameters (only; never for return types), and when to use which.


q:
Suppose you want to make an async request in JavaScript, but you want to pass some state along to the callback method. Is the following an appropriate use of closures in JavaScript?

function getSomethingAsync(someState, callback) {
    var req = abc.createRequestObject(someParams);
    req.invoke(makeCallback(someState, callback));
}

function makeCallback(someState, callback) {
    return function getSomethingCallback(data) {
        var result = processDataUsingState(data, someState);
        callback(result); // alternately/optionally pass someState along to result
    }
}

If not, is there a better or more idiomatic way?

[A]
its better (nicer) to use anonymous functions:
```
```
function getSomethingAsync (someState, callback) {
    req.invoke (function (data) {
       var result = processDataUsingState (data, someState);
       callback (result);
    });
}
```
```


q:
When I try to use curl or file_get_contents to read something like http://example.com/python/json/ from http://example.com/ I should be getting a JSON response, but instead I get a 404 error. Using curl or any other method outside my own domain works perfectly well.

echo file_get_contents('http://example.com/python/json/'); => 404
echo file_get_contents('http://google.com'); => OK

The same script works on my laptop, but I can't figure out what the difference is.

[A]
It looks like example.com is not the default domain for the IP address and that file_get_contents uses HTTP/1.0 instead of HTTP/1.1 and/or does not send a Host: header. Try the curl support in PHP instead:
```
```
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
```
```
Alternatively the /etc/hosts file sets the wrong IP address for example.com.


q:
How do I discover classes at runtime in the classpath which implements a defined interface?

ServiceLoader suits well (I think, I haven't used it), but I need do it in Java 1.5.

[A]
There is no reliable way to know what classes are in the classpath. According to its
documentation
, ServiceLoader relies on external files to tell it what classes to load; you might want to do the same. The basic idea is to have a file with the name of the class(es) to load, and then use reflection to instantiate it/them.


q:
I want to get the size of a drive (or UNC path pointing to a partition would be nice, but not required), as well as free space for said drive (or UNC path).  This doesn't need to work cross platform; only in Windows.

I know it's easy to do in Java 6, but that's not an option; I'm stuck with Java 5.

I can get the free space available by doing:

cmd.exe /c Z:\ /-c

or

cmd.exe /c \\server\share /-c

and just parsing out the resulting bytes free.  However I can't seem to find a way to get the total drive size.

Any suggestions?

[A]
One way to do it would be to use fsutil on the command line.  It returns something like this:
```
```
D:\>fsutil fsinfo ntfsinfo c:
NTFS Volume Serial Number :       0xd49cf9cf9cf9ac5c
Version :                         3.1
Number Sectors :                  0x0000000004a813ff
Total Clusters :                  0x000000000095027f
Free Clusters  :                  0x00000000002392f5
Total Reserved :                  0x0000000000000490
Bytes Per Sector  :               512
Bytes Per Cluster :               4096
Bytes Per FileRecord Segment    : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length :           0x000000000e70c000
Mft Start Lcn  :                  0x00000000000c0000
Mft2 Start Lcn :                  0x0000000000000010
Mft Zone Start :                  0x0000000000624ea0
Mft Zone End   :                  0x0000000000643da0
```
```
Multipy your number of sectors times the bytes per sector to get your size.


q:
Really simple question - how do I do a search to find all records where the name starts with a certain string in ActiveRecord. I've seen all sorts of bits all over the internet where verbatim LIKE SQL clauses are used - but from what I've heard that isn't the 'correct' way of doing it.

Is there a 'proper' Rails way?

[A]
If you're looking to do the search in the database then you'll need to use SQL.
And, of course, you'll need to do the search in the database otherwise you need to load
all
the objects into Ruby (which isn't a good thing).
So, you will need something like
```
```
MyModel.find(:all, :conditions => ["field LIKE ?", "#{prefix}%"])
```
```
where
```
prefix
```
is a variable with the string you're looking for.
In Rails 3.0+ this becomes:
```
```
MyModel.where("field LIKE :prefix", prefix: "#{prefix}%")
```
```


q:
What would be the best hashing algorithm if we had the following priorities (in that order):

Minimal hash collisions

Performance

It doesn't have to be secure. Basically I'm trying to create an index based on a combination of properties of some objects. All the properties are strings.

Any references to c# implementations would be appreciated.

[A]
There is no one single optimum hashing algorithm.  If you have a known input domain you can use a perfect-hashing generator such as
gperf
to generate a hashing algorithm that will get a 100% rate on that particular input set.  Otherwise, there is no 'right' answer to this question.


q:
I've been a C# programmer for about 2 years total, and professionally for a little more than 1. I work at a company as a developer on an application that began before the days of .NET 2. My question is this:

What is the benefit to use databinding from sql queries directly to a control over querying and manually adding items to the control? Is this approach generally considered cleaner, and simpler in terms of deploying? Will there still be cases where manually adding would give more fine grained control over the display / value of the data?

I'm asking because I've been assigned some bugs that deal with some controls that populate themselves based off query results, and would love to clean up unnecessary logic and push that off to the libraries to handle instead of me.

Note: We are using .NET 2.0

[A]
I personally find that using the
```
```
control.DataSource = YourSource;
control.DataBind();
```
```
process is much easier, you don't have to do the iteration, and overall reduces LOC.
If working with DropDownLists and other controls you will most likely set the DataValueField and DataTextField properties as well.


q:
The MSDN documentation says that

public class SomeObject
{
  public void SomeOperation()
  {
    lock(this)
    {
      //Access instance variables
    }
  }
}

is "a problem if the instance can be accessed publicly". I'm wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?

[A]
Because if people can get at your object instance (ie: your
```
this
```
) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on
```
this
```
internally, so this may cause problems (possibly a deadlock)
In addition to this, it's also bad practice, because it's locking "too much"
For example, you might have a member variable of
```
List<int>
```
, and the only thing you actually need to lock is that member variable. If you lock the entire object in your functions, then other things which call those functions will be blocked waiting for the lock. If those functions don't need to access the member list, you'll be causing other code to wait and slow down your application for no reason at all.


q:
Is there a library out there which I can use in my current ASP.NET app, to validate queryStrings?

Edit ~ Using Regex to look for patterns, like string, only, numeric only, string with length x,...etc

Thanks

[A]
Don't know about a library, but you can use to check if the querystring exists:
```
```
if (!String.IsNullOrEmpty(Request.Querystring["foo"]))
{
   // check further
}
else
{
   // not there, do something else
}
```
```
If you want to use Reglar Expressions to further validate, you can create a class that accepts the string and return a boolean.
```
```
public static Boolean IsValid(String s)
{
    const String sRegEx = @"regex here";

    Regex oRegEx = new Regex(sRegEx , RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
    MatchCollection oMatches = oRegEx.Matches(s);

    return (oMatches.Count > 0) ? true : false;
}
```
```
This is a good free program to help you build the regluar expressions:
Expresso


q:
Does anyone know of any DLLs (preferably .net) that encapsulate the lua 5.1 compiler?  I'm working on a .net project where part of it needs to compile lua scripts, and i would rather have a DLL that i could send script code to instead of sending the script to a temporary file and running luac.exe.

Edit: I'd need a .NET library that implements luac in such a way that it outputs standard lua bytecode (not a lua library that compiles to the CLR).  Compiling the lua c source code didn't work, as when i went to include a reference to the dll in a c# project, visual studio complained that it wasnt a valid assembly.  My searches so far haven't found anything.

[A]
Have you looked into using something like Spring's proxy functionality?  You tell it a bit about the webservice in a spring config file, and all your client code has to deal with is an interface that you create - it doesn't even have to know that there is a web service on the other side!
Example Spring config:
```
```
<bean id="myService" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean">
    <property name="serviceFactoryClass" value="org.apache.axis.client.ServiceFactory"/>
    <property name="wsdlDocumentUrl" value="classpath://META-INF/myService.wsdl"/>
    <property name="namespaceUri" value="http://com/myService"/>
    <property name="endpointAddress" value="http://server/MyService"/>
    <property name="serviceName" value="MyService"/>
    <property name="portName" value="MyService"/>
    <property name="serviceInterface" value="com.IMyService"/>
    <property name="lookupServiceOnStartup" value="false"/>
</bean>
<bean id="myClient" class="com.MyServiceClient">
    <property name="myService" ref="myService"/>
</bean>
```
```
Java:
```
```
public interface IMyService {
    Foo getFoo();
}

public class MyServiceClient {
    private IMyService myService;
    public void setMyService(IMyService myService) {
        this.myService = myService;
    }

    public void DoStuff() {
        Foo foo = myService.getFoo();
        ...
    }
}
```
```
For custom objects, you may need to subclass JaxRpcPortProxyFactoryBean:
```
```
public class MyServiceFactoryBean extends JaxRpcPortProxyFactoryBean {
protected void postProcessJaxRpcService(Service service) {
    TypeMappingRegistry registry = service.getTypeMappingRegistry();
    TypeMapping mapping = registry.createTypeMapping();
            QName qName = new QName("http://com/myService", "Foo");
    mapping.register(Foo.class, qName,
            new BeanSerializerFactory(Foo.class, qName),
            new BeanDeserializerFactory(Foo.class, qName));
    }
}
```
```
What I love about this is that code that
shouldn't
care about the implementation of the service
doesn't
.  Testing becomes a breeze, and the cohesion of your classes is
much
better.


q:
I want to have a map that has a homogeneous key type but heterogeneous data types.

I want to be able to do something like (pseudo-code):

boost::map<std::string, magic_goes_here> m;
m.add<int>("a", 2);
m.add<std::string>("b", "black sheep");

int i = m.get<int>("a");
int j = m.get<int>("b"); // error!

I could have a pointer to a base class as the data type but would rather not.

I've never used boost before but have looked at the fusion library but can't figure out what I need to do.

Thanks for your help.

[A]
How can I build a <favorite container> of objects of different types?
You can't, but you can fake it pretty well. In C/C++ all arrays are homogeneous (i.e., the elements are all the same type). However, with an extra layer of indirection you can give the appearance of a heterogeneous container (a heterogeneous container is a container where the contained objects are of different types).
There are two cases with heterogeneous containers.
The first case occurs when all objects you want to store in a container are publicly derived from a common base class. [...]
The second case occurs when the object types are disjoint — they do not share a common base class.
The approach here is to use a handle class. The container is a container of handle objects (by value or by pointer, your choice; by value is easier). Each handle object knows how to "hold on to" (i.e., maintain a pointer to) one of the objects you want to put in the container. You can use either a single handle class with several different types of pointers as instance data, or a hierarchy of handle classes that shadow the various types you wish to contain (requires the container be of handle base class pointers). The downside of this approach is that it opens up the handle class(es) to maintenance every time you change the set of types that can be contained. The benefit is that you can use the handle class(es) to encapsulate most of the ugliness of memory management and object lifetime. Thus using handle objects may be beneficial even in the first case.


q:
In MS SQL 2005 or T-SQL, you can do something like:

SELECT T.NAME, T.DATE
  FROM (SELECT * FROM MyTable WHERE ....) AS T

I failed to try the similar SQL on Oracle 9i DB. In MS SQL, the nested SQL is treated as a temporary/dynamic view created on fly and destroyed afterward. How can I do the similar thing in Oracle? I really don't want to create a view to do it.

[A]
I believe it chokes on the "as".
```
```
SELECT T.NAME, T.DATE
  FROM (SELECT * FROM MyTable WHERE ....)  T
```
```
should work.