q:
I need a function like this:

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

Can anyone suggest how I could write this?

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


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

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

s: huggingface

c: devops

d: intermediate


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

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

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


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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

    return buffer;
}

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

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

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

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


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

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


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

Class code here:

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

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


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

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


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

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

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

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

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

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

[A]
Try this:
```
```
#!/usr/bin/env python

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

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

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


q:
Considering the following architecture:

a base object 'Entity'

a derived object 'Entry:Base'

and a further derived object 'CancelledEntry:Entry'

In EntitySQL I can write the following:

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

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

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

EntityContext.EntitySet.OfType<Entry>()

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

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


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

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

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

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

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


q:
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:

[A]
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.


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

Here is how it is done in photoshop

[A]
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
.


q:
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.

[A]
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.


q:
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.

[A]
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
.


q: 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?

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


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

[A]
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


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

[A]
“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.


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

[A]
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();
}
```
```


q:
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.

[A]
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.


q:
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

[A]
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.


q:
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?

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


q:
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?

[A]
```
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.


q:
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?

[A]
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.


q:
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?

[A]
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


q:
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

[A]
```
```
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.


q:
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.

[A]
```
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()
```
.


q:
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.

[A]
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'])
```
```


q:
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?

[A]
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
.


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

[A]
Processing
```
```
var p = Processing(CanvasElement);
p.size(100, 100);
p.background(0);
p.fill(255);
p.ellipse(50, 50, 50, 50);
```
```


q:
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.

[A]
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.


q:
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?

[A]
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.


q: 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?

[A]
```
imagesx()
```
and
```
imagesy()
```
functions seem to work with images made with
```
imagecreatefromstring()
```
, too.


q: 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)?

[A]
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


q:
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.

[A]
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;.


q:
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.

[A]
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")
```
```


q:
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

[A]
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.


q: 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.

[A]
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.


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

[A] 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...


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

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


q:
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.

[A]
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


q:
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?

[A]
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;
}
```
```


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

[A]
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]);
     }
 }
```
```


q:
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?

[A]
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.


q:
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.

[A]
Use the
```
stripslashes
```
function.
That should make them all single slashes.


q:
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*.

[A]
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.


q:
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>

[A]
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.


q:
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.

[A]
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/>

```
```


q: 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?

[A]
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).


q:
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).

[A]
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.


q: 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?

[A] 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.


q:
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

[A]
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


q:
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.

[A]
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.


q:
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.

[A]
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
???


q:
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?

[A]
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.


q:
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.

[A]
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.


q:
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?

[A]
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.


q:
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.

[A]
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.


q:
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.

[A]
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()
    {
    }
```
```


q:
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?

[A]
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...


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

[A]
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


q:
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);
}

[A]
```
```
from item in items
where someConditionOnItem
select
{
     propertyOne,
     propertyTwo
};
```
```


q:
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.

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


q: 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.

[A]
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...


q: 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?

[A]
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));
```
```


q:
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?

[A] 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.


q: 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?

[A]
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!


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

[A]
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.


q: 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?

[A]
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.


q:
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?

[A]
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. :)


q:
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?

[A]
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
```
.


q:
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.)

[A]
The SGI STL has an extension called
```
select1st
```
. Too bad it's not in standard STL!


q:
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,

[A]
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.


q:
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.

[A]
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()
```
```


q:
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.

[A]
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.


q:
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 ?


q:
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;
}

[A]
```
```
.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;}
```
```


q: 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.

[A]
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 )
```
```


q:
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?

[A]
```
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" }
```
```


q:
I want to do this:

e.className = t;

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

[A]
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. :-)


q:
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...

[A]
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.


q:
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");
        }
    }
}

[A]
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" };
    }
}
```
```


q:
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.

[A]
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.


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

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


q:
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?

[A]
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.


q: 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?

[A]
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.


q:
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.

[A]
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


q:
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();
    }

[A]
Have you looked at
this
article by Ton Stegeman?


q: 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.

[A]
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


q:
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.

[A]
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.


q: Excluding the Micro Framework Emulator ;)

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


q:
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...

[A]
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
```
```


q:
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.

[A]
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'].


q:
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.

[A]
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()
```
```


q:
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.

[A]
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. :)


q:
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?

[A]
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
.


q:
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?

[A]
```
```
def quit()
    root.quit()
```
```
or
```
```
def quit()
    root.destroy()
```
```


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

Thanks.

[A]
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
.


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

Thanks

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
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/


q:
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.

[A]
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
.


q: Just wondering

[A]
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.


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

[A]
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 :)


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

[A]
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()
```
```