Question:
I want to create a box shape and I am having trouble.
I want the box to have a background color, and then different color inside the box.

The box will then have a list of items using ul and li, and each list item will have a background of white, and the list item's background color is too stretch the entire distance of the inner box.
Also, the list items should have a 1 px spacing between each one, so that the background color of the inside box color is visible.

Here is a rough sketch of what I am trying to do:

Answer:
So if you have source:
```
```

Some other stuff

Item 1

Item 2

```
```
You can use CSS:
```
```
div.panel { background-color: #A74; border: solid 0.5em #520; width: 10em;
            border-width: 0.75em 0.25em 0.75em 0.25em; }
div.panel div { padding: 2px; height: 4em; }
div.panel ul li { display: block; background-color: white;
                      margin: 2px; padding: 1px 4px 1px 4px; }
div.panel ul { margin: 0; padding-left: 0; }
```
```
To get the CSS to work properly (particularly on Internet Explorer), make sure you have an appropriate DOCTYPE definition in your document.  See
w3c recommended doctypes
for a list.


Question:
Is there a way of wrapping text in a non-rectangular container in WPF?

Here is how it is done in photoshop

Answer:
Have you looked at the
UIElement.Clip
property?
For non-rectangular text wrapping, you could try setting a TextBlock.Clip property to a non-rectangular Geometry object. I haven't tried this; either it will not draw text outside the clip region or it will wrap text to fit within the clip.
Charles Petzold
mentions this technique
.


Question:
There is a well-known debate in Java (and other communities, I'm sure) whether or not trivial getter/setter methods should be tested. Usually, this is with respect to code coverage.  Let's agree that this is an open debate, and not try to answer it here.

There have been several blog posts on using Java reflection to auto-test such methods.

Does any framework (e.g. jUnit) provide such a feature? e.g. An annotation that says "this test T should auto-test all the getters/setters on class C, because I assert that they are standard".

It seems to me that it would add value, and if it were configurable, the 'debate' would be left as an option to the user.

Answer:
I'm not aware of any readily available library or class that does this. This may mainly be because I don't care as I am on the side of strongly opposing such tests. So even though you asked there
must
be a bit of justification for this view:
I doubt that autotesting getters and setters benefit your code quality or your coverage: Either these methods are used from other code (and tested there, e.g. 100% covered) or not used at all (and could be removed). In the end you'll leave getters and setters in because they are used from the test but nowhere else in the application.
It should be easy to write such a test, e.g. with Apache Commons BeanUtils, but I doubt you really need it if you have good tests otherwise.


Question:
Is there a good object-relational-mapping library for PHP?

I know of PDO/ADO, but they seem to only provide abstraction of differences between database vendors not an actual mapping between the domain model and the relational model. I'm looking for a PHP library that functions similarly to the way Hibernate does for Java and NHibernate does for .NET.

Answer:
Look into
Doctrine
.
Doctrine 1.2
implements Active Record.
Doctrine 2+
is a DataMapper ORM.
Also, check out
Xyster
. It's based on the Data Mapper pattern.
Also, take a look at
DataMapper vs. Active Record
.


Question: I am redesigning a command line application and am looking for a way to make its use more intuitive.  Are there any conventions for the format of parameters passed into a command line application?  Or any other method that people have found useful?

Answer:
-operation [parameters] -command [your command] -anotherthings [otherparams]....
For example,
```
```
YourApp.exe -file %YourProject.prj% -Secure true
```
```


Question: Do you still use session or entity EJBs in your project? Why?

Answer:
Yes, but EJB were stupidly complex for most use cases. Very clever, but real overkill in most cases. Hence the lightweight approach taken now-a-days.
Justin


Question: How would you define testing? In the interest of full disclosure, I'm posting this because I already have some answers I like.

Answer:
“Testing is the process of comparing the invisible to the ambiguous, so as to avoid the unthinkable happening to the anonymous.”–
James Bach
It sounds funny, but if you parse out each word, it's right on the money.


Question: How can I Handler 404 errors without the framework throwing an Exception 500 error code?

Answer:
http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx
gives the following explanation:
Add a wildcard routing rule as your final rule:
```
```
routes.MapRoute("Error",
                "{*url}",
                new { controller = "Error", action = "Http404" });
```
```
Any request that doesn't match another rule gets routed to the Http404 action of the Error controller, which you also need to configure:
```
```
public ActionResult Http404(string url) {
    Response.StatusCode = 404;
    ViewData["url"] = url;
    return View();
}
```
```


Question:
I would like to wipe out all data for a specific kind in Google App Engine. What is the
best way to do this?
I wrote a delete script (hack), but since there is so much data is
timeout's out after a few hundred records.

Answer:
Presumably your hack was something like this:
```
```
# Deleting all messages older than "earliest_date"
q = db.GqlQuery("SELECT * FROM Message WHERE create_date < :1", earliest_date)
results = q.fetch(1000)

while results:
    db.delete(results)
    results = q.fetch(1000, len(results))
```
```
As you say, if there's sufficient data, you're going to hit the request timeout before it gets through all the records. You'd have to re-invoke this request multiple times from outside to ensure all the data was erased; easy enough to do, but hardly ideal.
The admin console doesn't seem to offer any help, as (from my own experience with it), it seems to only allow entities of a given type to be listed and then deleted on a page-by-page basis.
When testing, I've had to purge my database on startup to get rid of existing data.
I would infer from this that Google operates on the principle that disk is cheap, and so data is typically orphaned (indexes to redundant data replaced), rather than deleted. Given there's a fixed amount of data available to each app at the moment (0.5 GB), that's not much help for non-Google App Engine users.


Question:
How would I go about writing some code to allow access to a Java class in my webapp from the command line.

E.g. I have a java class with command line interface, that can runs code in the context of the webapp, with access to the DB etc. I want to log on the machine hosting my WARred app in tomcat and be able to interact with it

Where should i start looking ?

Thanks

Answer:
A suggestion:
Your command line interface class should accept an InputStream as it's input and provide an OutputStream (it can't hardcode output to System.out and input to System.in) that it's output will be written to.  Then you'll have to write a server class that listens for connections on a certain port.  When a connection is made the server would take the InputStream from the connection and give it to the command line class which would provide the OutputStream that data written to will be passed to the client that made the connection.


Question:
I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.

I.e., the same script is included on /, /help, /whatever, and so on, while it will always need to request from /data.json. Additionally, the same site is run on different servers, where the /-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself.

Are there small scripts that will work on all browsers made for this?

Answer:
```
document.location.href
```
will give you the current URL, which you can then manipulate using JavaScript's string functions.


Question:
Is there a version of memset() which sets a value that is larger than 1 byte (char)? For example, let's say we have a memset32() function, so using it we can do the following:

int32_t array[10];
memset32(array, 0xDEADBEEF, sizeof(array));

This will set the value 0xDEADBEEF in all the elements of array. Currently it seems to me this can only be done with a loop.

Specifically, I am interested in a 64 bit version of memset(). Know anything like that?

Answer:
```
wmemset(3)
```
is the wide (16-bit) version of memset. I think that's the closest you're going to get in C, without a loop.


Question:
On a company that I've worked, me and my colleagues, implemented a tailored document distribution system on top of XSL-FO.

My task was to get the script to deliver the documents and configure the CUPS print server and the Fax server, so I never had the time to get my hands dirty on XSL-FO.

I'm thinking of implementing something in the region that was made there but I'll need some templates to work with while testing.

Where can I find some good tutorials on XSL-FO, since the fop process I've mastered already?

Answer:
This might not be exactly what you need, but if you just want to have some XSL-FO test templates, you can use
this
transformation in Word to generate XSL-FO.
The book that I used to learn is from O'Reilly (
XSL-FO
), because frankly there are very little resources on the subject.


Question:
Could you recommend me a way to place a coundown timer on ASP.NET page?

Now I use this code:

Default.aspx

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
    <asp:Label ID="Label1" runat="server">60</asp:Label>
    <asp:Timer ID="Timer1" runat="server" Interval="1000"
        ontick="Timer1_Tick">
    </asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>

Default.aspx.cs

protected void Timer1_Tick(object sender, EventArgs e)
{
    int seconds = int.Parse(Label1.Text);
    if (seconds > 0)
        Label1.Text = (seconds - 1).ToString();
    else
        Timer1.Enabled = false;
}

But it is traffic expensive. I would prefer pure client-side method. Is it possible in ASP.NET?

Answer:
You might add something like this in your .aspx page
```
```
<form name="counter"><input type="text" size="8"
name="d2"></form>

<script>
<!--
//
 var milisec=0
 var seconds=30
 document.counter.d2.value='30'

function display(){
 if (milisec<=0){
    milisec=9
    seconds-=1
 }
 if (seconds<=-1){
    milisec=0
    seconds+=1
 }
 else
    milisec-=1
    document.counter.d2.value=seconds+"."+milisec
    setTimeout("display()",100)
}
display()
-->
</script>
```
```
Found
here


Question:
I found this guide for using the flash parameters, thought it might be useful to post here, since Flash CS3 lacks a usage example for reading these parameters.

See answers for the link

Answer:
```
```
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
```
```
The entire article is at:
http://blogs.adobe.com/pdehaan/2006/07/using_flashvars_with_actionscr.html
Important note! This will only work in the main class. If you'll try to load the parameters in a subclass you'll get nothing.


Question:
I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?

I want the user to be able to stop the repeated refresh of data.

Answer:
```
setInterval()
```
returns an interval ID, which you can pass to
```
clearInterval()
```
:
```
```
var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);
```
```
See the docs for
```
setInterval()
```
and
```
clearInterval()
```
.


Question:
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:

class hi:
  def __init__(self):
    self.ii = "foo"
    self.kk = "bar"

Is there a way for me to do this:

>>> mystery_method(hi)
["ii", "kk"]

Edit: I originally had asked for class variables erroneously.

Answer:
Every object has a
```
__dict__
```
variable containing all the variables and its values in it.
Try this
```
```
>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()
```
```
Output
```
```
dict_keys(['ii', 'kk'])
```
```


Question:
Is it possible to run an external process from Perl, capture its stderr, stdout AND the process exit code?

I seem to be able to do combinations of these, e.g. use backticks to get stdout, IPC::Open3 to capture outputs, and system() to get exit codes.

How do you capture stderr, stdout, and the exit code all at once?

Answer:
If you reread the documentation for IPC::Open3, you'll see a note that you should call
waitpid
to reap the child process. Once you do this, the status should be available in
```
$?
```
. The exit value is
```
$? >> 8
```
. See
```
$?
```
in perldoc perlvar
.


Question: What's the best javascript framework for drawing (lines, curves whatnot) on images?

Answer:
Processing
```
```
var p = Processing(CanvasElement);
p.size(100, 100);
p.background(0);
p.fill(255);
p.ellipse(50, 50, 50, 50);
```
```


Question:
This question is about the difference between ReadWrite and NonStrictReadWrite cache concurrency strategies for NHibernate's second level cache.

As I understand it, the difference between these two strategies is relevant when you have a distributed replicated cache - nonstrict won't guarantee that one cache has the exact same value as another cache, while strict read/write should - assuming the cache provider does the appropriate distributed locking.

The part I don't understand is how the strict vs nonstrict distinction is relevant when you have a single cache, or a distributed partitioned (non replicated) cache. Can it be relevant? It seems to me that in non replicated scenarios, the timestamps cache will ensure that stale results are not served.  If it can be relevant, I would like to see an example.

Answer:
What you assume is right, in a single target/thread environment there's little difference.  However if you look at the cache providers there is a bit going on even in a multi-threaded scenario.
How an object is re-cached from it's modified state is different in the non-strict.  For example, if your object is much heftier to reload but you'd like it to after an update instead of footing the next user with the bill, then you'll see different performance with strict vs non-strict.  For example: non-strict simply dumps an object from cache after an update is performed...price is paid for the fetch on the next access instead of a post-update event handler.  In the strict model, the re-cache is taken care of automatically.  A similar thing happens with inserts, non-strict will do nothing where strict will go behind and load the newly inserted object into cache.
In non-strict you also have the possibility of a dirty read, since the cache isn't locked at the time of the read you would not see the result of another thread's change to the item.  In strict the cache key for that item would lock and you would be held up but see the absolute latest result.
So, even in a single target environment, if there is a large amount of concurrent reads/edits on objects then you have a chance to see data that isn't really accurate.
This of course becomes a problem when a save is performed and an edit screen is loading:  the person thinking they're editing the latest version of the object really isn't, and they're in for a nasty surprise when they try to save the edits to the stale data they loaded.


Question:
We are setting up a new SharePoint for which we don't have a valid SSL certificate yet. I would like to call the Lists web service on it to retrieve some meta data about the setup. However, when I try to do this, I get the exception:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

The nested exception contains the error message:

The remote certificate is invalid according to the validation procedure.

This is correct since we are using a temporary certificate.

My question is: how can I tell the .Net web service client (SoapHttpClientProtocol) to ignore these errors?

Answer:
The approach I used when faced with this problem was to add the signer of the temporary certificate to the trusted authorities list on the computer in question.
I normally do testing with certificates created with CACERT, and adding them to my trusted authorities list worked swimmingly.
Doing it this way means you don't have to add any custom code to your application and it properly simulates what will happen when your application is deployed. As such, I think this is a superior solution to turning off the check programmatically.


Question: Normally I use imagecreatefromjpeg() and then getimagesize(), but with Firefox 3 I need to go round this different. So now im using imagecreatefromstring(), but how do I retreive the image dimensions now?

Answer:
```
imagesx()
```
and
```
imagesy()
```
functions seem to work with images made with
```
imagecreatefromstring()
```
, too.


Question: What is the best way (performance wise) to paginate results in SQL Server 2000, 2005, 2008, 2012 if you also want to get the total number of results (before paginating)?

Answer:
You didn't specify the language nor which driver you are using. Therefore I'm describing it abstractly.
Create a scrollable resultset / dataset. This required a primary on the table(s)
jump to the end
request the row count
jump to the start of the page
scroll through the rows until the end of the page


Question:
I have a .NET 2.0 Windows Forms application. On this app there is a Form control with a Menu bar and a status bar. Also there's a ListView on this form.

If I add a context menu to this form, the context menu will open when the user right clicks any part of the form, including the menu bar and the status bar.

How can I prevent the context menu from opening when the click happened on the menu bar / status bar? I want it to open only when clicking the "gray area" of the form.

If the click happened above a control on this form (for example, on the ListView), how can I identify this? I'd like to know if the user right clicked above the gray area or above the ListView, so I can enable/disable some menu items based on this.

Answer:
I found the answer:
```
```
Point clientPos = this.PointToClient(Form.MousePosition);
Control control = this.GetChildAtPoint(clientPos);
```
```
This should give the underlying control that was clicked on the Form, or null if the click was on the gray area. So we just need to test for the type of the control on the Opening event of the context menu. If it's MenuStrip, ToolStrip or StatusStrip, do e.Cancel = true;.


Question:
Is it possible to test the use of a given layout using RSpec with Rails, for example I'd like a matcher that does the following:

response.should use_layout('my_layout_name')

I found a use_layout matcher when Googling but it doesn't work as neither the response or controller seem to have a layout property that matcher was looking for.

Answer:
I found an example of
how to write a
```
use_layout
```
matcher
that will do just that.  Here's the code in case that link goes away:
```
```
# in spec_helper.rb

class UseLayout
   def initialize(expected)
     @expected = 'layouts/' + expected
   end
   def matches?(controller)
     @actual = controller.layout
     #@actual.equal?(@expected)
     @actual == @expected
   end
   def failure_message
     return "use_layout expected #{@expected.inspect}, got #
{@actual.inspect}", @expected, @actual
   end
   def negeative_failure_message
     return "use_layout expected #{@expected.inspect} not to equal #
{@actual.inspect}", @expected, @actual
   end
end

def use_layout(expected)
   UseLayout.new(expected)
end

# in controller spec
   response.should use_layout("application")
```
```


Question:
This is a shameless information gathering exercise for my own book.

One of the talks I give in the community is an introduction to web site vulnerabilities. Usually during the talk I can see at least two members of the audience go very pale; and this is basic stuff, Cross Site Scripting, SQL Injection, Information Leakage, Cross Site Form Requests and so on.

So, if you can think back to being one, as a beginning web developer (be it ASP.NET or not) what do you feel would be useful information about web security and how to develop securely? I will already be covering the OWASP Top Ten

(And yes this means stackoverflow will be in the acknowledgements list if someone comes up with something I haven't thought of yet!)

It's all done now, and published, thank you all for your responses

Answer:
Defensive programming as an archetypal topic which covers all the particular attacks, as most, if not all, of them are caused by not thinking defensively enough.
Make that subject the central column of the book . What would've served me well back then was knowing about techniques to never trust anything, not just one stop tips, like "do not allow SQL comments or special chars in your input".
Another interesting thing I'd love to have learned earlier is how to actually test for them.


Question: I have an ASP.Net GridView control that I need to remain a fixed size whether there are 0 records or n records in the grid.  The header and the footer should remain in the same position regardless of the amount of data in the grid.  Obviously, I need to implement paging for larger datasets but how would I achieve this fixed sized GridView?  Ideally I would like this to be a reusable control.

Answer:
You may have to drop the headers and footers from the GridView altogether and add them to the page as separate table elements. You will need to make sure each table cell in the header and footer tables have fixed widths that correspond to the widths of the cells in your GridView.
The GridView itself would probably be nested in a DIV tag of a fixed height. Something like as follows.
```
```

Header 1	Header 2

<asp:GridView>.....</asp:GridView>

Footer 1	Footer 2

```
```
You will probably have to tweak the margin and padding value to get it all to line up exactly though.


Question:
Using .Net what limitations (if any) are there in using the XmlSerializer?
For example, can you serialize Images to XML?

Answer: Not sure if there's any limitation.. But there was a memory leak bug in XmlSerialization in .NET 1.1, you sort of had to create a cache serializer object to get around with this issue... In fact, Im not sure if this issue has been fixed in .net 2.0 or newer...


Question: How do you perform the equivalent of Oracle's DESCRIBE TABLE in PostgreSQL (using the psql command)?

Answer:
The psql equivalent of
```
DESCRIBE TABLE
```
is
```
\d table
```
.
See the psql portion of the PostgreSQL manual for more details.


Question:
I'm trying to find/make an algorithm to compute the intersection (a new filled object) of two arbitrary filled 2D objects. The objects are defined using either lines or cubic beziers and may have holes or self-intersect. I'm aware of several existing algorithms doing the same with polygons, listed here. However, I'd like to support beziers without subdividing them into polygons, and the output should have roughly the same control points as the input in areas where there are no intersections.

This is for an interactive program to do some CSG but the clipping doesn't need to be real-time. I've searched for a while but haven't found good starting points.

Answer:
There are a number of academic research papers on doing bezier clipping:
http://www.andrew.cmu.edu/user/sowen/abstracts/Se306.html
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.61.6669
http://www.dm.unibo.it/~casciola/html/research_rr.html
I recommend the interval methods because as you describe, you don't have to divide down to polygons, and you can get guaranteed results as well as define your own arbitrary precision for the resultset.  For more information on interval rendering, you may also refer to
http://www.sunfishstudio.com


Question:
I am relatively new to Java, and often find that I need to sort a Map<Key, Value> on the values.

Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key.

Is there an easier way?

Answer:
From
http://www.programmersheaven.com/download/49349/download.aspx
```
```
private static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
    List<Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Object>() {
        @SuppressWarnings("unchecked")
        public int compare(Object o1, Object o2) {
            return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Iterator<Entry<K, V>> it = list.iterator(); it.hasNext();) {
        Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
        result.put(entry.getKey(), entry.getValue());
    }

    return result;
}
```
```


Question: I populated a datagridview from a datatable. How do I read from the datagridview when the application is running?

Answer:
how did you populate it? is the DataSource something useful like a BindlingList?
If it is then something like:
```
```
BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource;
//substitute your business object type for T
T entity = bindingSource.Current as T;
```
```
would get you the entity bound to the row.
Otherwise there is always the datagridview.Columns[n].Cells[n].Value but really I'd look at using the objects in the DataSource
Edit: Ah... a datatable... righto:
```
```
var table = dataGridView1.DataSource as DataTable;

 foreach(DataRow row in table.Rows)
 {
     foreach(DataColumn column in table.Columns)
     {
         Console.WriteLine(row[column]);
     }
 }
```
```


Question:
In which parts of a project writing unit tests is nearly or really impossible? Data access? ftp?

If there is an answer to this question then %100 coverage is a myth, isn't it?

Answer:
Data access is possible because you can set up a test database.
Generally the 'untestable' stuff is FTP, email and so forth. However, they are generally framework classes which you can rely on and therefore do not need to test if you hide them behind an abstraction.
Also, 100% code coverage is not enough on its own.


Question:
Okay so im working on this php image upload system  but for some reason internet explorer turns my basepath into the same path, but with double backslashes instead of one; ie:

C:\\Documents and Settings\\kasper\\Bureaublad\\24.jpg

This needs to become C:\Documents and Settings\kasper\Bureaublad\24.jpg.

Answer:
Use the
```
stripslashes
```
function.
That should make them all single slashes.


Question:
Is there a (cross-platform) way to get a C FILE* handle from a C++ std::fstream ?

The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE*.

Answer:
Well, you can get the file descriptor - I forget whether the method is fd() or getfd().
The implementations I've used provide such methods, but the language standard doesn't require them, I believe - the standard shouldn't care whether your platform uses fd's for files.
From that, you can use fdopen(fd, mode) to get a FILE*.
However, I think that the mechanisms the standard requires for synching STDIN/cin, STDOUT/cout and STDERR/cerr don't have to be visible to you.  So if you're using both the fstream and FILE*, buffering may mess you up.
Also, if either the fstream OR the FILE closes, they'll probably close the underlying fd, so you need to make sure you flush BOTH before closing EITHER.


Question:
In tomcat 6 i have a servlet running openbluedragon, everything compiles and servers up quik, with the exception of images, they really lag significantly.  Any suggestions optimization for image serving?

Here is my server.xml:

    <Service name="Catalina">

      <Connector port="8009" protocol="AJP/1.3" />
      <Connector port="8080" maxThreads="100" protocol="HTTP/1.1" connectionTimeout="20000" />
      <Engine name="Standalone" defaultHost="hostname.whatever" jvmRoute="ajp13">

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
      <Host name="hostname.whatever"  appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
        ...context
      </Host>

    </Engine>
  </Service>

Answer:
If you have the option, you could add a reverse proxy in advance of your application.  At work I have an Apache web server that receives all inbound HTTP connections.  Based on the URL, it either forwards the request to another server or serves up the content itself.  I've used this approach to accelerate serving up static content for a Trac site.  The ProxyPass and ProxyPassReverse directives are a good place to start looking if you want to go this route.
As a simple example, if you have a virtual directory called /images, Apache could serve up any request for something in that directory and forward everything else to your Tomcat instance.  The syntax is pretty comprehensive.  If there is any method at all to the way your static content is identified this is an approach that will work.
Apache isn't the only choice here.  I think all modern web servers include similar functionality.  If I was starting today I'd probably look at LigHTTPd instead, just because it does less.
There may even be caching reverse proxies that figure this out for you automatically.  I'm not familiar with any of them though.


Question:
I want the following layout to appear on the screen:

FieldName 1             [Field input 1]
FieldName 2 is longer   [Field input 2]
    .                         .
    .                         .
FieldName N             [Field input N]

Requirements:

Field names and field inputs must align on the left edges

Both columns must dynamically size themselves to their content

Must work cross-browsers

I find this layout extremely simple to do using HTML tables, but since I see a lot of CSS purists insisting that tables only be used for tabular data I figured I'd find out if there was a way to do it using CSS.

Answer:
FieldName objects should be contained in SPANs with style attributes of float: left and a width that is wide enough for your labels.
Inputs should be contained within a span styled to float: left. Place a
```
<div style="clear: both"/>
```
or
```
<br/>
```
after each field input to break the floating.
You may enclose the aforementioned objects into a div with the width style attribute set that is wide enough for both labels and inputs, so that the "table" stays small and contained.
Example:
```
```
FieldName1<input/>

FieldName2<input/>

FieldName3<input/>

```
```


Question: I've been developing Winforms applications in C# for a few years now and have been interested in moving future development toward WPF, mainly because of the positive things I've been hearing about it.  But, I'm wondering what sort of hurdles others have had to overcome as they migrated to WPF.  Was there a significant hit to your productivity or any particular issues which you found challenging?

Answer:
I'm not sure I can give you just one hurdle, because it is a complete departure from WinForms.  My suggestion is get Adam Nathan's WPF Unleashed, forget everything you know about building UI's with any previous technology (Winforms, MFC, Java) and begin again at square one.
If you try and do it any other way it will cause utter frustration.
ETA: the reason I say to just start from scratch is because sometimes it's easier to learn new concepts if you go in with a clean slate.  In the past, I've discovered that I can be my own worst enemy when it comes to learning something new if I try to carry knowledge from technology to technology (e.g. thinking that doing asmx web services for years precludes me from reading the first couple chapters of a WCF book).


Question:
I've been digging through some parts of the Linux kernel, and found calls like this:

if (unlikely(fd < 0))
{
    /* Do something */
}

or

if (likely(!err))
{
    /* Do something */
}

I've found the definition of them:

#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)

I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course).

Answer:
They're hints to the compiler to generate the hint prefixes on branches.  On x86/x64, they take up one byte, so you'll get at most a one-byte increase for each branch.  As for performance, it entirely depends on the application -- in most cases, the branch predictor on the processor will ignore them, these days.
Edit: Forgot about one place they can actually really help with.  It can allow the compiler to reorder the control-flow graph to reduce the number of branches taken for the 'likely' path.  This can have a marked improvement in loops where you're checking multiple exit cases.


Question: I'm designing  my website and was curious, before I go rip someone else's ideas, what were the salient considerations and questions one should ask in designing a database?

Answer: I think the most important question is, "Why are you doing it (the CMS, not the web site)?"  This is very well-trod ground.  Unless you have some really innovative ideas and unique insights into how you want it to be done ... and your question suggests that you probably don't ... you would probably be better-served by choosing an existing solution.


Question:
I've just switched an application to use ar_mailer and when I run ar_sendmail (after a long pause) I get the following error:

Unhandled exception 530 5.7.0 Must issue a STARTTLS command first. h7sm16260325nfh.4

I am using Gmail SMTP to send the emails and I haven't changed any of the ActionMailer::Base.smtp_settings just installed ar_mailer.

Versions:

Rails: 2.1, ar_mailer: 1.3.1

Answer:
What version of ar_mailer are you using? A gmail specific bug was fixed in 1.3.1, as shown here:
http://rubyforge.org/forum/forum.php?forum_id=16364


Question:
What's the most elegant way to select out objects in an array that are unique with respect to one or more attributes?

These objects are stored in ActiveRecord so using AR's methods would be fine too.

Answer:
I had originally suggested using the
```
select
```
method on Array. To wit:
```
[1, 2, 3, 4, 5, 6, 7].select{|e| e%2 == 0}
```
gives us
```
[2,4,6]
```
back.
But if you want the first such object, use
```
detect
```
.
```
[1, 2, 3, 4, 5, 6, 7].detect{|e| e>3}
```
gives us
```
4
```
.
I'm not sure what you're going for here, though.


Question:
What VM technologies exist for Linux, their pros and cons, and which is recommended for which application?

Since this kind of question can be asked for X other than "VM technologies for Linux", and since the answer changes with progress, I suggest to define a template for this kind of pages.  Those pages will have the tag 'stateoftheart' and they will be revisited each month and each month there will be up-to-date list of technologies, up-to-date reviews and up-to-date recommendations.

Answer:
2008 Oct
To be filled in at October to reflect the market status then.
2008 Sept
Products/services/technologies currently existing
VMware
Xen
VirtualBox
VServer
???
Comparisons
???
Recommendations for particular application areas
Home multi-boot replacement
Small business which has MS-Windows legacy applications
Datacenter of multinational corporation
???


Question:
Should I bind directly to objects returned from a webservice or should I have client-side objects that I bind to my gridcontrols? For instance if I have a service that returns object Car should I have a client side Car object that I populate with values from the webservice Car object?
What is considered best-practice?
In C# do I need to mark my classes as serializable or do something special to them?

Answer:
This really depends on what you are getting from the web service. If they are simple data transfer objects and you are only displaying data, then yes, you can bind. If you plan to edit the objects, it may not be usefull as you will need to track changes.
Do your objects and/or collections on the client track changes? If so you can use them.
If you have no change tracking, then you will need to track changes yourself, so you may need to translate the objects or wrap them in something to track changes.
Again, it really depends on what you are getting, what they support, what you are doing with them, as well as what response the server wants back for changes.


Question:
Who here is using WASP (http://wasp.sourceforge.net/content/) to in real world applications? What impressions do you have? Good? Bad? If you can provide any inputs, how good it is comparing with rails for example.

I'm really looking for MVC frameworks for PHP

Update: This comparation I found is good.

Answer:
I downloaded it a while ago and tried it out, but as the documentation is pretty terrible at the moment (consisting of some auto-generated 'documentation' that was useless) I gave up pretty quickly. I think one of the most important things to have in a framework is clear, thorough documentation - if you have to spend time digging through the code of the framework to find out if a class you want exists, the point of using a framework is lost. WASP does not seem to be ready for production environments just yet, as even their website admits that its not ready for enterprise applications.
If you're looking for a PHP framework I would recommend CodeIgniter, which has excellent documentation and a helpful community, or Zend, which is pretty mature.


Question:
I am reading a .NET book, and in one of the code examples there is a class definition with this field:

private DateTime? startdate

What does DateTime? mean?

Answer:
It's a nullable DateTime.
```
?
```
after a primitive type/structure indicates that it is the nullable version.
DateTime is a structure that can never be null. From
MSDN
:
The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini, or A.D. (also known as Common Era, or C.E.) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.)
```
DateTime?
```
can be null however.


Question:
Has anybody found a good solution for lazily-evaluated lists in Perl? I've tried a number of ways to turn something like

for my $item ( map { ... } @list ) {
}

into a lazy evaluation--by tie-ing @list, for example. I'm trying to avoid breaking down and writing a source filter to do it, because they mess with your ability to debug the code. Has anybody had any success. Or do you just have to break down and use a while loop?

Note: I guess that I should mention that I'm kind of hooked on sometimes long grep-map chains for functionally transforming lists. So it's not so much the foreach loop or the while loop. It's that map expressions tend to pack more functionality into the same vertical space.

Answer:
If I remember correctly, for/foreach do get the whole list first anyways, so a lazily evaluated list would be read completely and then it would start to iterate through the elements. Therefore, I think there's no other way than using a while loop. But I may be wrong.
The advantage of a while loop is that you can fake the sensation of a lazily evaluated list with a code reference:
```
```
my $list = sub { return calculate_next_element };
while(defined(my $element = &$list)) {
    ...
}
```
```
After all, I guess a tie is as close as you can get in Perl 5.


Question:
aspnet mvc has the HandleError filter that will return a view if an error occurs, but if an error occurs when calling a JsonResult Action how can I return a JSON object that represents an error?

I don't want to wrap the code in each action method that returns a JsonResult in a try/catch to accomplish it, I'd rather do it by adding a 'HandleJsonError' attribute or using the existing HandleError attribute to the required action methods.

Answer:
Maybe you could create your own Attribute and have a constructor value that takes an enum value of View or Json. Below is what Im using for  a custom Authorization Attribute to demonstrate what I mean. This way when authentication fails on a json request it responds with a json error and the same with if it returns a View.
```
```
public enum ActionResultTypes
   {
       View,
       Json
   }

    public sealed class AuthorizationRequiredAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
        public ActionResultTypes ActionResultType { get; set; }

        public AuthorizationRequiredAttribute(ActionResultTypes actionResultType)
        {
            this.ActionResultType = ActionResultType;
        }
    }

    //And used like
    [AuthorizationRequired(ActionResultTypes.View)]
    public ActionResult About()
    {
    }
```
```


Question:
To see what file to invoke the unrar command on, one needs to determine which file is the first in the file set.

Here are some sample file names, of which - naturally - only the first group should be matched:

yes.rar
yes.part1.rar
yes.part01.rar
yes.part001.rar

no.part2.rar
no.part02.rar
no.part002.rar
no.part011.rar

One (limited) way to do it with PCRE compatible regexps is this:

.*(?:(?<!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar)

This did not work in Ruby when I tested it at Rejax however.

How would you write one Ruby compatible regular expression to match only the first file in a set of RAR files?

Answer:
I am no regex expert but here is my attempt
```
```
^(yes|no)\.(rar|part0*1\.rar)$
```
```
Replace "yes|no" with the actual file name. I matched it against your examples to see if it would only match the first set hence the "yes|no" in the regex.
UPDATE: fixed as per the comment. Not sure why the user would not know the filename so i did not fix that part...


Question: How to implement multi-threading in visual basic 6.0. It would be great if someone can give an example.

Answer:
VB6 is not a really good environment for multi-threaded applications. There is no out-of-the-box support, you need to delve into standard
WinAPI
functions. Take a look at this article, which provides quite a comprehensive sample:
http://www.freevbcode.com/ShowCode.Asp?ID=1287


Question:
I've got a generic<> function that takes a linq query ('items') and enumerates through it adding additional properties. How can I select all the properties of the original 'item' rather than the item itself (as the code below does)?

So equivalent to the sql: select *, 'bar' as Foo from items

foreach (var item in items)
{
    var newItem = new {
        item, // I'd like just the properties here, not the 'item' object!
        Foo = "bar"
    };

    newItems.Add(newItem);
}

Answer:
```
```
from item in items
where someConditionOnItem
select
{
     propertyOne,
     propertyTwo
};
```
```


Question:
just a quick question:

I am a CS undergrad and have only had experience with the Eclipse, and Net Beans IDEs.  I have recently acquired a Macbook and was wanting to recompile a recent school project in Xcode just to test it out.  Right after the line where I declare a new instance of an ArrayList:

dictionary = new ArrayList<String>();

I get the following error: generics are not supported in -source 1.3.

I was just wondering if anybody could offer advice as to what the problem might be.  The same project compiles in Eclipse on the same machine.  I'm running OSX 10.5.4, with Java 1.5.0_13.

Thank you.

Answer: Generics are introduced in Java 5, so you can't use generics with -source 1.3 option.


Question: In the past, some of my projects have required me to create a movie version of a fullscreen Flash application. The easiest way to do this has been to get a screen capture. However, capturing anything over 1024x768 has resulted in choppy video, which is unacceptable. I understand that there are hardware based solutions for capturing fullscreen video, but I have not been able to find out what these are. My output needs to be scalable up to 1920x1080 and result in an uncompressed AVI file with no choppy-ness.

Answer:
With a bit of luck your graphic adapter already has a analog video output. You could hook up a dvd recorder and just digitze the video signal on a stand alone hardware box.
That won't give you 1920x1080 though.
If you really need to get captures higher than dvd resolution you need professional (and
incredible
expensive) video capture equipment.
edit:
Btw - if you want to capture 1920x1080 in true color at 30 frames per second uncompressed you have to somehow store around
237 megabytes per second
. Just to give you an idea how much data you have to deal with...


Question: I know that JTable can sort by a single column. But is it possible to allow for multiple column sort or do I need to write the code myself?

Answer:
You should be able to set the TableRowSorter and the Comparator associated with it.
Example:
```
```
TableModel myModel = createMyTableModel();
JTable table = new JTable(myModel);
TableRowSorter t = new TableRowSorter(myModel);
t.setComparator(column that the comparator works against, Comparator<?> comparator);
table.setRowSorter(new TableRowSorter(myModel));
```
```


Question:
Just bought a 2.4GHz Intel Core 2 Duo iMac with 2GB of memory and a 320GB hard drive. I plan on doing some .net development on it using a BootCamp/VMWare combo since VMWare grants access to the bootcamp partition.

What is a recommended size for a BootCamp partition and how much memory should I give VMWare? Any pitfalls to watch out for? What is your current configuration?

Answer: While this doesn't address your question directly, I wouldn't recommend running VS 2008 and all of the supporting tools on anything less than 2GB of RAM.


Question: Several questions about functional programming languages have got me thinking about whether XSLT is a functional programming language. If not, what features are missing? Has XSLT 2.0 shortened or closed the gap?

Answer:
For the most part, what makes XSLT not a 100% functional programming language is it's inability to treat functions as a first-class data type.
There may be some others -- but that's the obvious answer.
Good luck!


Question: Is a Star-Schema design essential to a data warehouse?  Or can you do data warehousing with another design pattern?

Answer:
The thing about star schemas is they are a natural model for the kinds of things most people want to do with a data warehouse. For instance it is easy to produce reports with different levels of granularity (month or day or year for example). It is also efficient to insert typical business data into a star schema, again a common and important feature of a data warehouse.
You certainly can use any kind of database you want but unless you know your business domain very well it is likely that your reports will not run as efficiently as they could if you had used a star schema.


Question: I'm planning to install Drupal. Is there any reason not to install the latest 6.x version as opposed to the 5.x branch? Are there any really good modules that are 5.x only?

Answer:
I've found enough modules to happily run my site on Drupal 6.x  I think the only 5.x module I miss is one that did very easy Google ad integration, and that may have been updated I just haven't checked recently.  I don't get enough traffic to make the ads worth the time in setting them up, so I just use the search part of the ad campaign.
Drupal 7.x is under development now, so I would expect that anything that hasn't been moved from 5.x to 6.x is just not being developed anymore, and is probably not really that needed.
Ultimately, take a look at what modules you may need.  With an account on Drupal's site, you can filter by install type.  I found that 6.x is much easier to work with in some regards (managing and upgrading modules) and overall I've had a much easier time maintaining my site under Drupal 6.x than I did under 4.x or 5.x.
I also think that 6.x runs much faster.


Question:
I'm fully aware that set division can be accomplished through a series of other operations, so my question is:

Is there a command for set division in SQL?

Answer:
http://vadimtropashko.files.wordpress.com/2007/02/ch3.pdf
From Page 32:
Relational Division is not a fundamental operator. It can be expressed in terms of projection, Cartesian product, and set difference.
So, no. :)


Question:
I'm using ASP.NET Web Forms for blog style comments.

Edit 1: This looks way more complicated then I first thought.  How do you filter the src?

I would prefer to still use real html tags but if things get too complicated that way, I might go a custom route.  I haven't done any XML yet, so do I need to learn more about that?

Answer:
Use an XML parser to validate your input, and drop or encode all elements, and attributes, that you do not want to allow. In this case, delete or encode all tags except the
```
<img>
```
tag, and all attributes from that except
```
src
```
, alt
```
and title
```
.


Question:
This is one of the possible ways I come out:

struct RetrieveKey
{
    template <typename T>
    typename T::first_type operator()(T keyValuePair) const
    {
        return keyValuePair.first;
    }
};

map<int, int> m;
vector<int> keys;

// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());

// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n"));

Of course, we can also retrieve all values from the map by defining another functor RetrieveValues.

Is there any other way to achieve this easily? (I'm always wondering why std::map does not include a member function for us to do so.)

Answer:
The SGI STL has an extension called
```
select1st
```
. Too bad it's not in standard STL!


Question:
Since VS 2005, I see that it is not possible to simply build a dll against MS runtime and deploy them together (http://www.ddj.com/windows/184406482). I am deeply confused by manifest, SxS and co: MSDN documentation is really poor, with circular references; specially since I am more a Unix guy, I find all those uninformative. My core problem is linking a dll against msvc9 or msvc8: since those runtime are not redistributable, what are the steps to link and deploy such a dll ? In particular, how are the manifest generated (I don't want mt.exe, I want something which is portable across compilers), how are they embedded, used ? What does Side by side assembly mean ?

Basically, where can I find any kind of specification instead of MS jargon ?

Thank you to everyone who answered, this was really helpful,

Answer:
Well, I've encountered some of these issues, so perhaps some of my comments will be helpful.
The manifest is an xml file.  While VS can and will make one for you when you compile, the other solution is to produce a resource file (.rc) and compile it into a compiled resource file (.res) using the resource compiler (rc.exe) included with VS.  You'll want to run the VS commandline from the tools menu, which will cause rc to be in the path, as well as setting various environmental variables correctly. Then compile your resource.  The resulting .res file can be used by other compilers.
Make sure your manifest xml file's size is divisible by 4.  Add whitespace in the middle of it to achieve this if needed.  Try to avoid having any characters before the openning xml tag or after the closing xml tag.  I've sometimes had issues with this.  If you do step 2 incorrectly, expect to get side by side configuration errors.  You can check if that is your mistake by openning the exe in a resource editor (e.g. devenv.exe) and examining the manifest resource.  You can also see an example of a correct manifest by just opening a built file, though note that dlls and exes have tiny differences in what id the resource should be given.
You'll probably want to test on Vista to make sure this is working properly.


Question:
I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory.
Google search shows a commercial one is Python Memory Validator (Windows only).

And open source ones are PySizer and Heapy.

I haven't tried anyone, so I wanted to know which one is the best considering:

Gives most details.

I have to do least or no changes to my code.

Answer:
I recommend
Dowser
. It is very easy to setup, and you need zero changes to your code. You can view counts of objects of each type through time, view list of live objects, view references to live objects, all from the simple web interface.
```
```
# memdebug.py

import cherrypy
import dowser

def start(port):
    cherrypy.tree.mount(dowser.Root())
    cherrypy.config.update({
        'environment': 'embedded',
        'server.socket_port': port
    })
    cherrypy.server.quickstart()
    cherrypy.engine.start(blocking=False)
```
```
You import memdebug, and call memdebug.start. That's all.
I haven't tried PySizer or Heapy. I would appreciate others' reviews.
UPDATE
The above code is for
```
CherryPy 2.X
```
,
```
CherryPy 3.X
```
the
```
server.quickstart
```
method has been removed and
```
engine.start
```
does not take the
```
blocking
```
flag. So if you are using
```
CherryPy 3.X
```
```
```
# memdebug.py

import cherrypy
import dowser

def start(port):
    cherrypy.tree.mount(dowser.Root())
    cherrypy.config.update({
        'environment': 'embedded',
        'server.socket_port': port
    })
    cherrypy.engine.start()
```
```


Question:
I'm using VMware Workstation 6.0 for simulation of tight clusters of "blades" in a "chassis". Both the host and target OSs are Linux. Each "chassis" uses a vmnet switch as a virtual backplane, to which the virtual blades connect. Other vmnet switches are used to mediate point-to-point connections between mutiple virtual ethernet adapters on each blade VM. The chassis, and thus the VMs, are brought up and shutdown rather frequently. My scripts (python) make heavy use of the VIX api, and also manipulate the .vmx config file.

What do I gain and/or lose going from VMware Workstation to ESX? Do my scripts that use the VIX api still work? Do my rather complicated virtual network topologies, with lots of vmnet switches defined as "custom", still work the same way? Is the syntax and semantics of the .vmx config file the same between Workstation and ESX?

Thanks in advance for your help.

Answer:
The first thing you'll gain by switching will be a substantially more powerful platform that's running directly on the bare-metal of your server.
From my experience, moving
up
the VMware application stack has never been problematic (Server to Workstation to ESX). However, I would verify this by exporting all of your VMs from the workstation install to an ESX install to make sure you're not seeing any 'weird' issues related to running the high-end tool from VMware.
From my [limited] experience, scripts also carry-over cleanly: each offering moving up their product line doesn't break lower-level tools, but do add substantial improvements.


Question:
I've been wondering, as a lone game developer,
or to say a part of team which has only got programmers and people who like to play games...
How do I manage the void created by lack of artists (sprites/tiles/animations) in such a situation???

What do you do in that case? and suppose I am a student, with no money to hire artists, is there a place where I can get these resources legally & free ?

Answer:
The first thing you'll gain by switching will be a substantially more powerful platform that's running directly on the bare-metal of your server.
From my experience, moving
up
the VMware application stack has never been problematic (Server to Workstation to ESX). However, I would verify this by exporting all of your VMs from the workstation install to an ESX install to make sure you're not seeing any 'weird' issues related to running the high-end tool from VMware.
From my [limited] experience, scripts also carry-over cleanly: each offering moving up their product line doesn't break lower-level tools, but do add substantial improvements.


Question:
How can I make a style have all of the properties of the style defined in .a .b .c except for background-color (or some other property)? This does not seem to work.

.a .b .c
{
    background-color: #0000FF;
    color: #ffffff;
    border: 1px solid #c0c0c0;
    margin-top: 4px;
    padding: 3px;
    text-align: center;
    font-weight: bold;
}

.a .b .c .d
{
   background-color: green;
}

Answer:
```
```
.a, .b, .c {color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; }

.a {background-color: red;}

.b {background-color: blue;}

.c {background-color: green;}
```
```


Question: Obviously I can use BCP but here is the issue. If one of the records in a Batch have an invalid date I want to redirect that to a separate table/file/whatever, but keep the batch processing running. I don't think SSIS can be installed on the server which would have helped.

Answer:
Create a trigger that processes on INSERT. This trigger will do a validation check on your date field. If it fails the validation, then do an insert into your separate table, and you can also choose to continue the insert or not allow it to go through.
an
important
note: by default triggers do not fire on bulk inserts (BCP & SSIS included). To get this to work, you'll need to specify that you want the trigger to fire, using something like:
```
```
BULK INSERT your_database.your_schema.your_table FROM your_file WITH (FIRE_TRIGGERS )
```
```


Question:
I have an NSArray and I'd like to create a new NSArray with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a BOOL.

I can create an NSMutableArray, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it.

Is there a better way?

Answer:
```
NSArray
```
and
```
NSMutableArray
```
provide methods to filter array contents.
```
NSArray
```
provides
filteredArrayUsingPredicate:
which returns a new array containing objects in the receiver that match the specified predicate.
```
NSMutableArray
```
adds
filterUsingPredicate:
which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example.
```
```
NSMutableArray *array =
    [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];

NSPredicate *bPredicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
NSArray *beginWithB =
    [array filteredArrayUsingPredicate:bPredicate];
// beginWithB contains { @"Bill", @"Ben" }.

NSPredicate *sPredicate =
    [NSPredicate predicateWithFormat:@"SELF contains[c] 's'"];
[array filteredArrayUsingPredicate:sPredicate];
// array now contains { @"Chris", @"Melissa" }
```
```


Question:
I want to do this:

e.className = t;

Where t is the name of a style I have defined in a stylesheet.

Answer:
Yes, that works (with the class name as a string, as jonah mentioned). Also, you can set style attributes directly on an object, using the
DOM Level 2 Style
interface. e.g.,
```
```
button.style.fontFamily = "Verdana, Arial, sans-serif";
```
```
where
```
button
```
is (presumably) a button object. :-)


Question:
How can I change the width of a textarea form element if I used ModelForm to create it?

Here is my product class:

class ProductForm(ModelForm):
    long_desc = forms.CharField(widget=forms.Textarea)
    short_desc = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Product

And the template code...

{% for f in form %}
    {{ f.name }}:{{ f }}
{% endfor %}

f is the actual form element...

Answer:
The easiest way for your use case is to use CSS
. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS.
Example for
```
long_desc
```
field in your ProductForm (when your form does not have a custom prefix):
```
```
#id_long_desc {
    width: 300px;
    height: 200px;
}
```
```
Second approach
is to pass the
```
attrs
```
keyword to your widget constructor.
```
```
class ProductForm(ModelForm):
    long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))
    short_desc = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Product
```
```
It's
described in Django documentation
.
Third approach
is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor.
```
```
class ProductForm(ModelForm):
    long_desc = forms.CharField(widget=forms.Textarea)
    short_desc = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Product

    # Edit by bryan
    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
        self.fields['long_desc'].widget.attrs['cols'] = 10
        self.fields['long_desc'].widget.attrs['rows'] = 20
```
```
This approach has the following advantages:
You can define widget attributes for fields that are generated automatically from your model without redefining whole fields.
It doesn't depend on the prefix of your form.


Question:
I am looking to set the result action from a failed IAuthorizationFilter.  However I am unsure how to create an ActionResult from inside the Filter.  The controller doesn't seem to be accible from inside the filter so my usual View("SomeView") isn't working.  Is there a way to get the controler or else another way of creating an actionresult as it doesn't appear to be instantiable?

Doesn't work:

    [AttributeUsage(AttributeTargets.Method)]
    public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
    public void OnAuthorization(AuthorizationContext context)
    {
        if (!context.HttpContext.User.Identity.IsAuthenticated)
        {
            context.Result = View("User/Login");
        }
    }
}

Answer:
You can instantiate the appropriate ActionResult directly, then set it on the context. For example:
```
```
public void OnAuthorization(AuthorizationContext context)
{
    if (!context.HttpContext.User.Identity.IsAuthenticated)
    {
        context.Result = new ViewResult { ViewName = "Whatever" };
    }
}
```
```


Question:
I'm attempting to use TinyXML to read and save from memory, instead of only reading and saving files to disk.

It seems that the documnent's parse function can load a char *. But then I need to save the document to a char * when I'm done with it. Does anyone know about this?

Edit: The printing & streaming functions aren't what I'm looking for. They output in a viewable format, I need the actual xml content.

Edit: Printing is cool.

Answer:
Don't quite get what you are saying; your question is not clear.  I'm guessing you are wanting to load a file into memory so that you can pass it to the document parse function.  In that case, the following code should work.
```
```
#include <stdio.h>
```
```
The following code reads a file into memory and stores it in a buffer
```
```
FILE* fd = fopen("filename.xml", "rb"); // Read-only mode
int fsize = fseek(fd, 0, SEEK_END); // Get file size
rewind(fd);
char* buffer = (char*)calloc(fsize + 1, sizeof(char));
fread(buffer, fsize, 1, fd);
fclose(fd);
```
```
The file is now in the variable "buffer" and can be passed to whatever function required you to provide a char* buffer of the file to it.


Question: Are there any Common Lisp implementations for .Net?

Answer:
If it's OK to go the other way around, you can access .Net from your favourite Lisp through
Edi Weitz' RDNZL
.


Question:
I'm currently running mongrel clusters with monit watching over them for 8 Rails applications on one server.

I'd like to move 7 of these applications to mod_rails, with one remaining on mongrel. The 7 smaller applications are low-volume, while the one I'd like to remain on mongrel is a high volume, app.

As I understand it, this would be the best solution - as the setting PassengerPoolIdleTime only can be applied at a global level.

What configuration gotchas should I look out for with this type of setup?

Answer:
I would probably just move all the apps to mod_rails, as the performance seems comparable to Mongrel and there's less administration overhead.
With regards to configuration gotchas, just make sure that you allow your public directory, or you'll find static assets failing:
```
```
<Directory "/var/www/app/current/public">
    Options FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
```
```
Aside from that, if you know how to configure Apache, mod_rails is very painless.


Question: Joel always said to be careful when using 3rd party libraries. From my initial impressions, jQuery is great.  What should I beware of when using it?  What are the limitations?  What headaches will I run into later on as I use it more?

Answer:
One thing I've run into with jQuery is that you end up chaining a lot of items together, and it tends to quickly get unreadable if you are not careful.
an example I can think of that illustrates this is on
John David Anderson's blog
:
There’s a guy who wrote a logging
  function so you can figure out
  whereYou(are).whenYoureCoding().inThe(middleOf).a(jQuery).trainWreck().
I can see the power of chaining things
  together, but my guess is you’ve
  probably gone too far if you’re
  needing to log things to the console
  mid-swing. There’s probably little to
  no chance you’re going to be able to
  read it a week from now, too.


Question:
Are there any favorite online references or good introductory and intermediate/advanced books on this topic that you could recommend to me?
I'm a java developer, so I'm looking for something which would be familiar as possible as to me.

Answer:
Essential ActionScript 3.0
, by Colin Moock
Programming Flex 3: The Comprehensive Guide to Creating Rich Internet Applications with Adobe Flex
, by Chafic Kazoun, Joey Lott
Also check the books section on Flex.org
There are some good video tutorials on lynda.com
http://www.flex.org
http://www.adobe.com/devnet/flex


Question:
I have a document library with about 50 available content types. This document library is divided into  several folders. When a user cliks the "New" button in a folder, all available content types are offered. I need to limit the content types according to the folder. For example, in the folder "Legal" a want to have only content types containing legal documents. I tried to use the UniqueContentTypeOrder property of SPFolder but it does not work. What is wrong?

private void CreateFolder(SPFolder parent,  string name)
        {
            SPFolder z = parent.SubFolders.Add(name);
            List col = new List();

        foreach (SPContentType type in myDocumentLibrary.ContentTypes)
        {
            if (ContentTypeMatchesName(name, type))
            {
                col.Add(type);
            }
        }
        z.UniqueContentTypeOrder = col;
        z.Update();
    }

Answer:
Have you looked at
this
article by Ton Stegeman?


Question: Spring DA helps in writing DAOs. When using iBATIS as the persistence framework, and extending SqlMapClientDaoSupport, a SqlMapClient mock should be set for the DAO, but I can't do it. SqlMapClientTemplate is not an interface and EasyMock cannot creates a mock for it.

Answer:
DAO and unit tests do not get along well !
That does not make sense to mock anything in a component that does not hold any business logic and is focused on database access.
You should try instead to write an integration test. Take a look at the spring reference documentation, chapter 8.3 :
http://static.springframework.org/spring/docs/2.5.x/reference/testing.html


Question:
Some years ago I was on a panel that was interviewing candidates for a relatively senior embedded C programmer position.

One of the standard questions that I asked was about optimisation techniques. I was quite surprised that some of the candidates didn't have answers.

So, in the interests of putting together a list for posterity - what techniques and constructs do you normally use when optimising C programs?

Answers to optimisation for speed and size both accepted.

Answer:
Collecting profiles of code execution get you 50% of the way there. The other 50% deals with analyzing these reports.
Further, if you use GCC or VisualC++, you can use "profile guided optimization" where the compiler will take info from previous executions and reschedule instructions to make the CPU happier.


Question: Excluding the Micro Framework Emulator ;)

Answer:
A well known one is
Tahoe
. Others are
http://www.sjjmicro.com/EDK.html
http://www.ghielectronics.com/details.php?id=107&sid=108


Question:
I've built a wrapper over NumbericUpDown control.
The wrapper is generic and can support int? and double?

I would like to write a method that will do the following.

public partial class NullableNumericUpDown<T> : UserControl where T : struct
{
  private NumbericUpDown numericUpDown;

  private T? Getvalue()
  {
    T? value = numericUpDown.Value as T?; // <-- this is null :) thus my question
    return value;
  }}

of course there is no cast between decimal and double? or int? so I need to use a certain way of converting.
I would like to avoid switch or if expressions.

What would you do?

To clarify my question I've provided more code...

Answer:
It's not clear how you gonna use it.
If you want double create GetDouble() method, for integers - GetInteger()
EDIT:
Ok, now I think I understand your use case
Try this:
```
```
using System;
using System.ComponentModel;

static Nullable<T> ConvertFromString<T>(string value) where T:struct
{
    TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
    if (converter != null && !string.IsNullOrEmpty(value))
    {
        try
        {
            return (T)converter.ConvertFrom(value);
        }
        catch (Exception e) // Unfortunately Converter throws general Exception
        {
            return null;
        }
    }

    return null;
}

...

double? @double = ConvertFromString<double>("1.23");
Console.WriteLine(@double); // prints 1.23

int? @int = ConvertFromString<int>("100");
Console.WriteLine(@int); // prints 100

long? @long = ConvertFromString<int>("1.1");
Console.WriteLine(@long.HasValue); // prints False
```
```


Question:
Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin?

It would be best if i didn't have to add any extra fields to the model, but if i really have to i can.

Answer:
In model class you would probably have to add "order" field, to maintain specific order (eg. item with order = 10 is the last one and order = 1 is the first one). Then you can add a JS code in admin change_list template (see
this
) to maintain drag&drop feature. Finally change ordering in Meta of model to something like ['order'].


Question:
In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?

I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.

Answer:
If you're using your own transactions (not the default admin application), you can save the before and after versions of your object.  You can save the before version in the session, or you can put it in "hidden" fields in the form.  Hidden fields is a security nightmare.  Therefore, use the session to retain history of what's happening with this user.
Additionally, of course, you do have to fetch the previous object so you can make changes to it.  So you have several ways to monitor the differences.
```
```
def updateSomething( request, object_id ):
    object= Model.objects.get( id=object_id )
    if request.method == "GET":
        request.session['before']= object
        form= SomethingForm( instance=object )
    else request.method == "POST"
        form= SomethingForm( request.POST )
        if form.is_valid():
            # You have before in the session
            # You have the old object
            # You have after in the form.cleaned_data
            # Log the changes
            # Apply the changes to the object
            object.save()
```
```


Question:
I am searching for a tutorial (optimally with Zend Framework) on how to use PHPUnit.

I have found a couple on google but have not quiet understood it yet.

Answer:
For information about
PHPUnit
, be sure to read the
documentation
. It does not look too bad IMO. There is a blog entry about
Automatic testing of MVC applications created with Zend Framework
which looks quite good, too. :)


Question:
I've got C# code that accesses MySQL through ODBC.

It creates a transaction, does a few thousand insert commands, and then commits.
Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way?

Answer:
It's hard to say without seeing your code, but I'm assuming you are executing the statements one at a time. So, you will get one round trip per insert statement.
In MSSql you can execute multiple inserts in a single statement:
```
```
cmd.ExecuteNonQuery "insert table values (1)  insert table values (2)"
```
```
So you can create a big string and execute it (I think it will have a limit), I assume this will work for MySQL.
Also in MSSQL you have a batch inserter (lookup "SqlBulkCopy"), in MySQL perhaps try
loading the data from a temp file
.


Question:
How do I end a Tkinter program? Let's say I have this code:

from Tkinter import *

def quit():
    # code to exit

root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()

How should I define the quit function to exit my application?

Answer:
```
```
def quit()
    root.quit()
```
```
or
```
```
def quit()
    root.destroy()
```
```


Question:
I wish to know all the pros and cons about using these two methods. In particular the implications on web security.

Thanks.

Answer:
To choose between them I use this simple rule:
GET for reads. (reading data and displaying it)
POST for anything that writes (i.e updating a database table, deleting an entry, etc.)
The other consideration is that GET is subjected to the maximum URI length and of course can't handle file uploads.
This page has a good summary
.


Question:
Has anybody any useful links that can be used to consume a web service using flex?
The easier the solution the better

Thanks

Answer:
I found
this tutorial
pretty helpful - it gives clear examples of consuming a basic webservice, with code on both sides (server and flex).
One thing to remember when accessing remote webservices on a remote server from flex is the need for a
crossdomain.xml
- the security model in flex needs to be explicitly told to be allowed access a service from a remote domain.


Question:
How can I get a full call stack for a c++ application developed with Visual Studio 2005? I would like to have a full call stack including the code in the system libraries.

Do I have to change some settings in Visual Studio, or do I have to install additional software?

Answer:
Get debug information for all project dependencies. This is specified under the "Configuration Properties -> C/C++ -> General" section of the project properties.
On the menu, go to "Tools -> Options" then select "Debugging -> Symbols".
Add a new symbol location (the folder icon) that points to Microsoft's free symbol server “symsrv
symsrv.dll
c:\symbols*
http://msdl.microsoft.com/downloads/symbols
“
Fill out the "cache symbols" field with some place locally so you don't go to the internet all the time.


Question:
We have a large ASP (classic ASP) application and we would like to convert it to .NET in order to work on further releases. It makes no sense continuing to use ASP as it is obsolete, and we don't want to rewrite it from scratch (Joel Spolsky tells you why).

Is there a way to convert it from ASP to ASP.NET automatically?

Answer:
Microsoft has an article up on MSDN that talks about
Migrating ASP Pages to ASP.NET
. They basically tell you to install .net on your computer/server and the transform one page at a time. ASP and ASP.NET can co-exist so can can rename each page to "aspx" as you go. You should note, however, that session state and application state are not shared between ASP and ASP.NET pages (See
@mdb's answer
for a workaround on that problem.)
There is also
The ASP to ASP.NET Migration Assistant
, but I'm not sure that project/program is still active. You can try it by downloading from this page:
http://www.asp.net/downloads/archived/migration-assistants/asp-to-aspnet/


Question:
How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?

I have seen the Scheme example given on Wikipedia, but unfortunately it did not help.

Answer:
A closure is a pairing of:
A function and
A reference to that function's outer scope (lexical environment)
A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.
Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called.
If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.
In the following code,
```
inner
```
forms a closure with the lexical environment of the execution context created when
```
foo
```
is invoked,
closing over
variable
```
secret
```
:
```
```
function foo() {
  const secret = Math.trunc(Math.random() * 100)
  return function inner() {
    console.log(`The secret number is ${secret}.`)
  }
}
const f = foo() // `secret` is not directly accessible from outside `foo`
f() // The only way to retrieve `secret`, is to invoke `f`
```
```
In other words: in JavaScript, functions carry a reference to a private "box of state", to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.
And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.
If JavaScript did not have closures, then more states would have to be passed between functions
explicitly
, making parameter lists longer and code noisier.
So, if you want a function to always have access to a private piece of state, you can use a closure.
...and frequently we
do
want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating the state with functionality.
In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above,
```
secret
```
remains available to the function object
```
inner
```
,
after
it has been returned from
```
foo
```
.
Uses of Closures
Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.
Private Instance Variables
In the following code, the function
```
toString
```
closes over the details of the car.
```
```
function Car(manufacturer, model, year, color) {
  return {
    toString() {
      return `${manufacturer} ${model} (${year}, ${color})`
    }
  }
}

const car = new Car('Aston Martin', 'V8 Vantage', '2012', 'Quantum Silver')
console.log(car.toString())
```
```
Functional Programming
In the following code, the function
```
inner
```
closes over both
```
fn
```
and
```
args
```
.
```
```
function curry(fn) {
  const args = []
  return function inner(arg) {
    if(args.length === fn.length) return fn(...args)
    args.push(arg)
    return inner
  }
}

function add(a, b) {
  return a + b
}

const curriedAdd = curry(add)
console.log(curriedAdd(2)(3)()) // 5
```
```
Event-Oriented Programming
In the following code, function
```
onClick
```
closes over variable
```
BACKGROUND_COLOR
```
.
```
```
const $ = document.querySelector.bind(document)
const BACKGROUND_COLOR = 'rgba(200, 200, 242, 1)'

function onClick() {
  $('body').style.background = BACKGROUND_COLOR
}

$('button').addEventListener('click', onClick)
```
```
```
```
<button>Set background color</button>
```
```
Modularization
In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions
```
tick
```
and
```
toString
```
close over the private state and functions they need to complete their work. Closures have enabled us to modularize and encapsulate our code.
```
```
let namespace = {};

(function foo(n) {
  let numbers = []

  function format(n) {
    return Math.trunc(n)
  }

  function tick() {
    numbers.push(Math.random() * 100)
  }

  function toString() {
    return numbers.map(format)
  }

  n.counter = {
    tick,
    toString
  }
}(namespace))

const counter = namespace.counter
counter.tick()
counter.tick()
console.log(counter.toString())
```
```
Examples
Example 1
This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables
themselves
. It is as though the stack-frame stays alive in memory even after the outer function exits.
```
```
function foo() {
  let x = 42
  let inner = () => console.log(x)
  x = x + 1
  return inner
}

foo()() // logs 43
```
```
Example 2
In the following code, three methods
```
log
```
,
```
increment
```
, and
```
update
```
all close over the same lexical environment.
And every time
```
createObject
```
is called, a new execution context (stack frame) is created and a completely new variable
```
x
```
, and a new set of functions (
```
log
```
etc.) are created, that close over this new variable.
```
```
function createObject() {
  let x = 42;
  return {
    log() { console.log(x) },
    increment() { x++ },
    update(value) { x = value }
  }
}

const o = createObject()
o.increment()
o.log() // 43
o.update(5)
o.log() // 5
const p = createObject()
p.log() // 42
```
```
Example 3
If you are using variables declared using
```
var
```
, be careful you understand which variable you are closing over. Variables declared using
```
var
```
are hoisted. This is much less of a problem in modern JavaScript due to the introduction of
```
let
```
and
```
const
```
.
In the following code, each time around the loop, a new function
```
inner
```
is created, which closes over
```
i
```
. But because
```
var i
```
is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of
```
i
```
(3) is printed, three times.
```
```
function foo() {
  var result = []
  for (var i = 0; i < 3; i++) {
    result.push(function inner() { console.log(i) } )
  }

  return result
}

const result = foo()
// The following will print `3`, three times...
for (var i = 0; i < 3; i++) {
  result[i]()
}
```
```
Final points:
Whenever a function is declared in JavaScript closure is created.
Returning a
```
function
```
from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.
Whenever you use
```
eval()
```
inside a function, a closure is used. The text you
```
eval
```
can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using
```
eval('var foo = …')
```
.
When you use
```
new Function(…)
```
(the
Function constructor
) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.
A closure in JavaScript is like keeping a reference (
NOT
a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.
A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
A new set of local variables is created every time a function is called.
Links
Douglas Crockford's simulated
private attributes and private methods
for an object, using closures.
A great explanation of how closures can
cause memory leaks in IE
if you are not careful.
MDN documentation on
JavaScript Closures
.


Question: Just wondering

Answer:
One of the most interesting things I have done with threads was write a multi-threaded application to solve a maze.
While it's nothing ground breaking, it was definitely interesting.


Question: Can someone explain me how it works, starting from when you select to run a test

Answer:
What do you mean how does it work?
You define your test classes with [TestFixture] and your tests with [Test]
It's nothing more than a testing framework, you still have to write the tests and all of that jazz :)


Question: How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?

Answer:
Tkinter supports a mechanism called
protocol handlers
. Here, the term
protocol
refers to the interaction between the application and the window manager. The most commonly used protocol is called
```
WM_DELETE_WINDOW
```
, and is used to define what happens when the user explicitly closes a window using the window manager.
You can use the
```
protocol
```
method to
install a handler
for this protocol (the widget must be a
```
Tk
```
or
```
Toplevel
```
widget):
Here you have a concrete example:
```
```
import tkinter as tk
from tkinter import messagebox

root = tk.Tk()

def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
```
```


Question: What would be a good local database for a Silverlight application?  The database's main purpose is for local data caching and synchronization services. I do not believe that SQL anywhere or SQLite will work since they use unmanaged code which will not run under the silverlight sandbox

Answer:
@Aaron Fischer,
I'm very interested in this question too. I'm looking DB for XBAP (WPF in browser) apps. Here is my question
"What embedded database with Isolated Storage support can you recommend?"
SQLite & MSSQL CE (aka SQL anywhere) wouldn't work.
VistaDB is implemented in .NET and can work under constraints (it has support for Isolated Storage) but I'm looking for alternatives.
Another option is Sybase iAnywhere - but I'm not sure how to deploy it on end-user machine.
I'm going to try DB4objects for Silverlight. If it would work, I'll update the post.


Question: The background should be transparent, but the text should not.

Answer:
By making an "Enso style" application you mean the Enso launcher?
Here is a screenshot of it:
alt text http://enscreenshots.softonic.com/s2en/68000/68880/3_ensolauncher03.jpg
I would suggest at looking at the open-source C#
Cropper
application.  He does a similar looking GUI with transparent background.  You can open up his project and see how he implements it.
alt text http://img352.imageshack.us/img352/726/cropperuijt3.png


Question:
Now that it's clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means.

I suppose everybody made once a mistake with parenthesis, resulting  in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.

Could you give me some explanations, including examples with the magic method ?

Answer:
A Callable is an object that has the
```
__call__
```
method.  This means you can fake callable functions or do neat things like
Partial Function Application
where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as
Currying
in functional programming circles).
Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string.  This can produce errors where the interpreter attempts to execute a non-callable application.  You can see this happening in a python interpreter by doing something like the transcript below.
```
```
[nigel@k9 ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 15:55:44)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'aaa'()    # <== Here we attempt to call a string.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>
```
```


Question: I'm looking for an .xsd schema file to drop into my Visual Studio directory to provide intellisense for the xml configuration file for the Castle Windsor IoC container. I've looked in the downloaded code for Windsor, as well as googled several different ways. I see many people asking the same question, but no answers. Anyone know if there is such a document?

Answer:
Perhaps this is what you are looking for:
http://jimblogdog.blogspot.com/2008/05/castlewindsor-schema-enables-visual.html
Here is the link to download the castle windsor schema:
http://www.projectdistributor.net/Releases/Release.aspx?releaseId=427
Good Luck!


Question:
The question of whether P=NP is perhaps the most famous in all of Computer Science. What does it mean? And why is it so interesting?

Oh, and for extra credit, please post a proof of the statement's truth or falsehood. :)

Answer:
A short summary from my humble knowledge:
There are some easy computational problems (like finding the shortest path between two points in a graph), which can be calculated pretty fast ( O(n^k), where n is the size of the input and k is a constant (in the case of graphs, it's the number of vertexes or edges)).
Other problems, like finding a path that crosses every vertex in a graph or getting the RSA private key from the public key is harder (O(e^n)).
But CS speak tells that the problem is that we cannot 'convert' a non-deterministic Turing-machine to a deterministic one, we can, however, transform non-deterministic finite automatons (like the regex parser) into deterministic ones (well, you can, but the run-time of the machine will take long). That is, we have to try every possible path (usually smart CS professors can exclude a few ones).
It's interesting because nobody even has any idea of the solution. Some say it's true, some say it's false, but there is no consensus. Another interesting thing is that a solution would be harmful for public/private key encryptions (like RSA). You could break them as easily as generating an RSA key is now.
And it's a pretty inspiring problem.


Question: I have an Interbase DB. How can I convert it to SQL Server?

Answer:
If you want to spend some money, this will do it:
http://www.spectralcore.com/fullconvert/tutorials/convert-interbase-firebird-to-mssql-sql-server.php


Question: Needs to be secure and able to handle thousands of users.

Answer:
Check out ADAM and AzMan.
ADAM is Active Directory Application Mode.  There is a how-to guide at:
http://msdn.microsoft.com/en-us/library/ms998331.aspx
AzMan is Authorization Manager.  There is a how-to guide at:
http://msdn.microsoft.com/en-us/library/ms998336.aspx


Question: From my own "key logger like" process I figured out that another process Locale is wrong (i.e. by sniffing few keys, I figured out that the foreground process Locale should be something while it is set to another). What's the best way to do this?

Answer:
I'd use
setLocale
from within that process to change it, and notify the process about this with some form of IPC like:
signals
sockets
pipes
from the process who knows


Question:
Is there a cheap way to get the dimensions of an image (jpg, png, ...)? Preferably, I would like to achieve this using only the standard class library (because of hosting restrictions). I know that it should be relatively easy to read the image header and parse it myself, but it seems that something like this should be already there. Also, I’ve verified that the following piece of code reads the entire image (which I don’t want):

using System;
using System.Drawing;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Image img = new Bitmap("test.png");
            System.Console.WriteLine(img.Width + " x " + img.Height);
        }
    }
}

Answer:
Have you tried using the WPF Imaging classes?
```
System.Windows.Media.Imaging.BitmapDecoder
```
, etc.?
I believe some effort was into making sure those codecs only read a subset of the file in order to determine header information. It's worth a check.


Question:
I have a Rails project which I neglected to build tests for (for shame!) and the code base has gotten pretty large. A friend of mine said that RSpec was a pain to use unless you use it from the beginning. Is this true? What would make him say that?

So, considering the available tests suites and the fact that the code base is already there, what would be my best course of action for getting this thing testable? Is it really that much different than doing it from the beginning?

Answer:
Maybe start with the models? They should be testable in isolation, which ought to make them the lowest-hanging fruit.
Then pick a model and start writing tests that say what it does. As you go along, think about other ways to test the code - are there edge cases that maybe you're not sure about? Write the tests and see how the model behaves. As you develop the tests, you may see areas in the code that aren't as clean and de-duplicated (DRY) as they might be. Now you have tests, you can refactor the code, since you know that you're not affecting behaviour. Try not to start improving design until you have tests in place - that way lies madness.
Once you have the models pinned down, move up.
That's one way. Alternatives might be starting with views or controllers, but you may find it easier to start with end-to-end transaction tests andwork your way into smaller and smaller pieces as you go along.


Question:
Should simple JavaBeans that have only simple getters and setters be unit tested??

What about Beans with some logic in getters and setters?

Answer:
If it's not worth testing, it's not worth writing.
That doesn't always mean you should write tests.  Sometimes it means you should delete code.  Do you need these beans?  Do they actually do anything important?  If you need them, you should write tests.  If not, delete the code and live a happier life knowing you have less to maintain.


Question:
Is it OK if the same OpenSSL context is used by several different accepting sockets?

In particular I'm using the same boost::asio::ssl::context with 2 different listening sockets.

Answer:
Yep, SSL_CTX--which I believe is the underlying data structure--is just a global data structure used by your program. From ssl(3):
SSL_CTX (SSL Context)
That's the global context structure which is created by a server or client once per program life-time and which holds mainly default values for the SSL structures which are later created for the connections.


Question:
I have some problems with Miktex installed on Windows Vista Business SP1/32 bit. I use miktex 2.7, ghostscript, and texniccenter 1 beta 7.50. When I compile a document with the following profiles: Latex=>DVI, Latex=>PDF everything works fine; the system crashes when I compile with profiles Latex=>PS and Latex=>PS=>PDF. The error is reported into a window that states: "Dvi-to-Postscript converter has stopped working". What can I do? I need Latex=>PS=>PDF to include my images into the final PDF.

Thanks in advance,
Yet another LaTeX user

Answer:
If everything you need is images, you could still compile directly to PDF. You only need to have an image in PNG or JPG format, and use the following code:
```
```
%in the document preamble
\usepackage{graphicx}

%in the document, in the place where you want to put your image
\includegraphics{image_filename_without_extension}
```
```
When the image is a PNG or JPG file (there are some more, I don't remember which ones ATM), you can compile the file with pdfLaTeX, but not with the normal LaTeX (i.e. you can produce a PDF, but not DVI or PS).
Of course normally, if everything works fine, it's nice to have one copy of the image in EPS, and another in, say, PNG -- this way you can compile easily both to PDF, and to PS.
Hope that helps.


Question:
I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect.  Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear.

Does anyone know of a fix for this?

Thanks!

Answer:
```
```
$(document).ready(function() {
    // Fix background image caching problem
    if (jQuery.browser.msie) {
        try {
            document.execCommand("BackgroundImageCache", false, true);
        } catch(err) {}
    }
};
```
```
Apparently
.


Question: What’s the difference between Response.Write() and Response.Output.Write()?

Answer:
Nothing really.
But.
```
Response.Write
```
takes the stream in the
```
Response.Output
```
property. You could set another Output stream, and in that way instead of writing back to the client, maybe write to a file or something crazy. So thats there relation.