Question: I'd like my application to have a full-screen mode. What is the easiest way to do this, do I need a third party library for this or is there something in the JDK that already offers this?

Answer:
Try the
Full-Screen Exclusive Mode API
.  It was introduced in the JDK in release 1.4.  Some of the features include:
Full-Screen Exclusive Mode
- allows you to suspend the windowing system so that drawing can be done directly to the screen.
Display Mode
- composed of the size (width and height of the monitor, in pixels), bit depth (number of bits per pixel), and refresh rate (how frequently the monitor updates itself).
Passive vs. Active Rendering
- painting while on the main event loop using the paint method is passive, whereas rendering in your own thread is active.
Double Buffering and Page Flipping
- Smoother drawing means better perceived performance and a much better user experience.
BufferStrategy and BufferCapabilities
- classes that allow you to draw to surfaces and components without having to know the number of buffers used or the technique used to display them, and help you determine the capabilities of your graphics device.
There are several full-screen exclusive mode examples in the linked tutorial.


Question:
I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?

String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = new [UnknownClass]().format(unformattedXml);

Note: My input is a String. My output is a String.

(Basic) mock result:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <tag>
    <nested>hello</nested>
  </tag>
</root>

Answer:
```
```
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
```
```
Note: Results may vary depending on the Java version. Search for workarounds specific to your platform.


Question:
Does anyone know how to get the HTML out of an IFRAME I have tried several different ways:

document.getElementById('iframe01').contentDocument.body.innerHTML
document.frames['iframe01'].document.body.innerHTML
document.getElementById('iframe01').contentWindow.document.body.innerHTML

etc

Answer:
If you take a look at
JQuery
, you can do something like:
```
```
<iframe id="my_iframe" ...></iframe>

$('#my_iframe').contents().find('html').html();
```
```
This is assuming that your iframe parent and child reside on the same server, due to the
Same Origin Policy
in Javascript.


Question:
i have a number of jsp files under web-inf folder. Inside my web.xml i specify an errorppage for 404 amd 403 and java.lang.exception. Do i need to include a page directive for each of my jsp's or will they automatically get forwarded to the exception handling page because they are under web-inf?

If this is true does this mean that jsps which are not placed under web-inf do need to have the page directive added in order to forward them to the exception handling page?

thank you ,  im just trying to understand the consequences of web-inf

Answer:
You just need to have whatever errorpage you would like to use in your app available with all the other jsps.  So in the following example you would just need to have the error pages in the root of the context path(where all of the other jsps are).  Anytime the webapp receives a 404 or 403 error it will try to display one of these pages. .
```
```
<error-page>
   <error-code>404</error-code>
   <location>/404Error.jsp</location>
</error-page>
<error-page>
   <error-code>403</error-code>
   <location>/403Error.jsp</location>
</error-page>
```
```
Just make sure 404Error.jsp and 403Error.jsp contain:
```
```
<%@ page isErrorPage="true" %>
```
```
If you are actually using jsps for error pages (instead of just static html)


Question:
I am building a menu in HTML/CSS/JS and I need a way to prevent the text in the menu from being highlighted when double-clicked on. I need a way to pass the id's of several divs into a function and have highlighting turned off within them.

So when the user accidentally (or on purpose) double clicks on the menu, the menu shows its sub-elements but its text does not highlight.

There are a number of scripts out there floating around on the web, but many seem outdated. What's the best way?

Answer:
You could:
Give it ("it" being your text) a onclick event
First click sets a variable to the current time
Second click checks to see if that variable is x time from the current, current time (so a double click over, for example, 500ms, doesn't register as a double click)
If it
is
a double click, do something to the page like adding hidden HTML, doing document.focus(). You'll have to experiment with these as some might cause unwanted scrolling.


Question:
I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.

I want to call the help function on each one. In Ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in Python?

e.g. something like:

from somemodule import foo
print(foo.methods)  # or whatever is the correct method to call

Answer:
You can use
```
dir(module)
```
to see all available methods/attributes.  Also check out PyDocs.


Question: So many different controls to choose from!  What are best practices for determining which control to use for displaying data in ASP.NET?

Answer:
It all comes down to how you want to layout your data.
If you need to control the layout (like tables versus CSS versus whatever), when use a Repeater or ListView. Between the two, ListView gives you a lot more events and built-in commands for editing, selecting, inserting. Additionally paging and grouping functionality. A Repeater is extremely simple, it repeats a layout with the data. Since you're building the layout by hand, Listview and Repeater require more code.
GridView is an updated DataGrid so there is hardly any reason to use DataGrid. GridView works really well when hooked up to standard ASP.NET datasources, but restricts you to a tabular layout with lots of layout rules. GridView requires less code since you're using a built-in layout.


Question:
Or do you populate your form controls manually by a method?

Is either considered a best practice?

Answer:
It all comes down to how you want to layout your data.
If you need to control the layout (like tables versus CSS versus whatever), when use a Repeater or ListView. Between the two, ListView gives you a lot more events and built-in commands for editing, selecting, inserting. Additionally paging and grouping functionality. A Repeater is extremely simple, it repeats a layout with the data. Since you're building the layout by hand, Listview and Repeater require more code.
GridView is an updated DataGrid so there is hardly any reason to use DataGrid. GridView works really well when hooked up to standard ASP.NET datasources, but restricts you to a tabular layout with lots of layout rules. GridView requires less code since you're using a built-in layout.


Question:
I've added cookie support to SOAPpy by overriding HTTPTransport.  I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service.  Without these cookies, the server will think it is an unauthorized request and it will fail.

How can I add cookies from a Python CookieJar to ZSI requests?

Answer:
If you read the
_Binding class in client.py of ZSI
you can see that it has a variable cookies, which is an instance of
Cookie.SimpleCookie
. Following the
ZSI example
and the
Cookie example
that is how it should work:
```
```
b = Binding(url='/cgi-bin/simple-test', tracefile=fp)
b.cookies['foo'] = 'bar'
```
```


Question:
The most egregiously redundant code construct I often see involves using the code sequence

if (condition)
    return true;
else
    return false;

instead of simply writing

return (condition);

I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java.  What other such constructs would you flag in a code review?

Answer:
Returning uselessly at the end:
```
```
// stuff
   return;
}
```
```


Question:
When you are learning a new language, what is there a particularly good/effective exercise to help get the hang of it? And why?

EDIT:
Preferably looking for things that are more complicated that 'Hello World'.

Answer:
'hello world!'
I really do think this a good place to start. Its basic and only takes a few seconds but you make sure your compiler is running and you have everything in place.  Once you have that done you can keep going. Add a variable, print to database, print to file.  Make sure you know how to leave comments.  This could all take a mater of 5 minutes. But its important stuff.


Question:
How to get the relative path in t sql? Take for example a .sql file is located in the folder D:\temp, I want to get path of the file hello.txt in the folder  D:\temp\App_Data. How to use the relative path reference?

Let's say I am executing the sql file inside the SQL server management studio.

Answer:
The .sql file is just.... a file.  It doesn't have any sense of its own location.  It's the thing that excutes it (which you didn't specify) that would have a sense of its location, the file's location.
I notice that you mentioned an App_Data folder, so I guess that ASP.NET is involved.  If you want to use relative paths in your web app, see MapPath
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx


Question:
what is an efficient way to get a certain time for the next day in Java?
Let's say I want the long for tomorrow 03:30:00.
Setting Calendar fields and Date formatting are obvious.
Better or smarter ideas, thanks for sharing them!

Okami

Answer:
I'm curious to hear what other people have to say about this one. My own experience is that taking shortcuts (i.e., "better or smarter ideas") with
```
Date
```
s almost always lands you in trouble. Heck, just using
```
java.util.Date
```
is asking for trouble.
Added: Many have recommended
Joda Time
in other Date-related threads.


Question: How to set all the values in a std::map to the same value, without using a loop iterating over each value?

Answer:
Using a loop
is
by far the simplest method. In fact, it’s a one-liner:
[C++17]
```
```
for (auto& [_, v] : mymap) v = value;
```
```
Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use
```
std::fill
```
.
To use them anyway (pre-C++20), we need to write adapters — in the case of
```
std::fill
```
, an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do
not
advise using it as-is. Use a library (such as
Boost.Iterator
) for a more general, production-strength implementation.
```
```
template <typename M>
struct value_iter : std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type> {
    using base_type = std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type>;
    using underlying = typename M::iterator;
    using typename base_type::value_type;
    using typename base_type::reference;

    value_iter(underlying i) : i(i) {}

    value_iter& operator++() {
        ++i;
        return *this;
    }

    value_iter operator++(int) {
        auto copy = *this;
        i++;
        return copy;
    }

    reference operator*() { return i->second; }

    bool operator ==(value_iter other) const { return i == other.i; }
    bool operator !=(value_iter other) const { return i != other.i; }

private:
    underlying i;
};

template <typename M>
auto value_begin(M& map) { return value_iter<M>(map.begin()); }

template <typename M>
auto value_end(M& map) { return value_iter<M>(map.end()); }
```
```
With this, we can use
```
std::fill
```
:
```
```
std::fill(value_begin(mymap), value_end(mymap), value);
```
```


Question: In a user defined wizard page, is there a way to capture change or focus events of the controls? I want to provide an immediate feedback on user input in some dropdowns (e.g. a message box)

Answer:
Since the scripting in innosetup is loosely based on Delphi, the controls should have some events like
```
OnEnter
```
(= control got focus) and
```
OnExit
```
(= control lost focus).  You can assign procedures to these events, something like this:
    ComboBox.OnExit := ComboBoxExit;
```
```
procedure ComboBoxExit(Sender: TObject);
begin

end;
```
```
I don't have access to Innosetup right now, so you will need to lookup the available events and parameters for the procedures.


Question:
I mean, how does Java decide which protocols are available? I run some code from inside Eclipse, and it works just fine. Then I run the same code from outside Eclipse, and I get "unknown protocol" MalformedURLException. Probably it has to do with the code base, or something? Any hints would be helpful.

Thanks!

Answer:
The work of resolving the protocol is done by the
```
URLStreamHandler
```
, which are stored in
```
URL.handlers
```
by protocol in lowercase. The handler, in turn, is created by the
```
URLStreamHandlerFactory
```
at
```
URL.factory
```
. Maybe eclipse is monkeying with that?
Some of the
URL constructors
take stream handlers and you can set the factory with
URL.setURLStreamHandlerFactory
.
Here's a web post about
developing protocol handlers
.


Question:
I've worked on a few projects managed through the use of a Gantt chart.  Some of these have has a massive number of tasks and the project manager spends all their time wrestling with MS Project instead of making good choices.

I can see the point if there are a number of separate teams working towards something (e.g. legal, IT, marketing) to manage a project overall.

Has anyone participated in a software development project that has used a Gantt chart with any success?

Answer:
A Gantt chart is only useful if it has sufficient details for a project manager to see what is the status of the project, and to have dependencies and resources properly accounted for.
You can always stick several sheets together with sticky tape.
The discipline of analyzing the project - breaking it down into phases, steps, deliverables,  determining the resource requirements is probably even more important than printing out a pretty chart.
Many of my non-trivial development projects have benefited from the sensible use of project planning tools.


Question: Should I stick with Sun's Java code conventions for PHP code?

Answer:
For PHP, i'd suggest to follow
Zends suggestions
As you might know,
Zend is the most widely used framework!


Question:
I'd like to capture the output of var_dump to a string.

The PHP documentation says;

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

What would be an example of how that might work?

print_r() isn't a valid possibility, because it's not going to give me the information that I need.

Answer:
Use output buffering:
```
```
<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
```
```


Question:
I made a class from Linq to SQL Clasees with VS 2008 SP1 Framework 3.5 SP1, in this case I extended the partial

partial void UpdateMyTable(MyTable instance){
   // Business logic
   // Validation rules, etc.
}

My problem is when I execute db.SubmitChanges(), it executes UpdateMyTable and makes the validations but it doesn't update, I get this error:

[Exception: Deliver]
   System.Data.Linq.ChangeProcessor.SendOnValidate(MetaType type, TrackedObject item, ChangeAction changeAction) +197
   System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list) +255
   System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +76
   System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +331
   System.Data.Linq.DataContext.SubmitChanges() +19

Answer:
if you provide this method, you must perform the update in the method.
http://msdn.microsoft.com/en-us/library/bb882671.aspx
If you implement the Insert, Update and Delete methods in your partial class, the LINQ to SQL runtime will call them
instead
of its own default methods when SubmitChanges is called.
Try
MiTabla.OnValidate


Question:
I've just solved another *I-though-I-was-using-this-version-of-a-library-but-apparently-my-app-server-has-already-loaded-an-older-version-of-this-library-*issue (sigh).

Does anybody know a good way to verify (or monitor) whether your application has access to all the appropriate jar-files, or loaded class-versions?

Thanks in advance!

[P.S. A very good reason to start using the OSGi module architecture in my view!]

Update: This article helped as well! It gave me insight which classes JBoss' classloader loaded by writing it to a log file.

Answer:
I don't think there is a good way to check that. And I'm not sure you want to do that. What you need to do  is get familiar with your app-server's class loading architecture, and understand how that works.
A simplified explanation of how it works is: an EJB or a web-app will first look for a class or a resource in  libraries declared in its own module (ejb-jar or war). if the class is not found there, the class loader forwards the request to the its parent class loader which is either a declared dependency (usualy an ejb) or the the application class loader which is responsible to load libraries and resources declared in the ear package. If the class or the resource is still not found the request is forwarded to the app server which will look in its own classpath.
This being said, you should remember that a Java EE module (web-app, ejb) will always load classes from a jar that is in the nearest scope. For example if you package log4j v1 in the war file, log4j v2 at ear level and you put log4j v3 in your app-server's class path, the module will use the jar in its own module. take that away and it'll use the one at ear level. take that out and it will use the one in the app-server's classpath. Things get more tricky when you have complex dependencies between modules.
Best is to put application global libraries at ear level.


Question:
I've never developed a web application that uses distributed memory.

Is it common practice to run a tool such as Microsoft Velocity on my local machine as I develop, should I run Velocity on another server as I develop, or should I just develop as normal (default session & cache) and use Velocity only after I've deployed to our development server?

We are running into a lot of memory issues in our production web application so we are researching into splitting our servers into a farm.

Answer:
I'm looking at using Velocity on a project as well. What I've done thus far is to write a common caching interface and a simple implementation that utilizes the standard ASP.NET caching system. This way I can program against that interface and later plug in the Velocity caching via a concrete implementation of the interface. You can accomplish this more easily using a dependency injection framework such as Unity or Structure Map.
As for where to use Velocity, I'd be sure to try it out in a development environment before going live. If you have a limited number of physical machines, use Virtual PC to set up some virtual servers and install the caching framework onto them.


Question: I've got a generic dictionary Dictionary<string, T> that I would like to essentially make a Clone() of ..any suggestions.

Answer:
(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)
How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.
For instance, if you don't mind the value being a shallow clone:
```
```
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
                                               entry => entry.Value);
```
```
If you've already constrained T to implement ICloneable:
```
```
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
                                               entry => (T) entry.Value.Clone());
```
```
(Those are untested, but should work.)


Question:
I have the following code:

info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents

I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at WaitForExit. Note also this code does NOT hang for smaller outputs (like 3KB).

Is it possible that the internal StandardOutput in ProcessStartInfo can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?

Answer:
The
documentation
for
```
Process.StandardOutput
```
says to read before you wait otherwise you can deadlock, snippet copied below:
```
```
// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();
```
```


Question:
I've seen both done in some code I'm maintaining, but don't know the difference. Is there one?

let me add that myCustomer is an instance of Customer

Answer:
The result of both are exactly the same in your case. It will be your custom type that derives from
```
System.Type
```
. The only real difference here is that when you want to obtain the type from an instance of your class, you use
```
GetType
```
. If you don't have an instance, but you know the type name (and just need the actual
```
System.Type
```
to inspect or compare to), you would use
```
typeof
```
.
Important difference
EDIT: Let me add that the call to
```
GetType
```
gets resolved at runtime, while
```
typeof
```
is resolved at compile time.


Question:
How do I cause the page to make the user jump to a new web page after X seconds. If possible I'd like to use HTML but a niggly feeling tells me it'll have to be Javascript.

So far I have the following but it has no time delay

<body onload="document.location='newPage.html'">

Answer:
A meta refresh is ugly but will work.  The following will go to the new url after 5 seconds:
```
```
<meta http-equiv="refresh" content="5;url=http://example.com/"/>
```
```
http://en.wikipedia.org/wiki/Meta_refresh


Question:
What's the difference between TRUNCATE and DELETE in SQL?

If your answer is platform specific, please indicate that.

Answer:
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.
General Overview
If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.
Various system-specific issues have to be considered, as detailed below.
Statement type
Delete is DML, Truncate is DDL (
What is DDL and DML?
)
Commit and Rollback
Variable by vendor
SQL*Server
Truncate can be rolled back.
PostgreSQL
Truncate can be rolled back.
Oracle
Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.
However, see Flashback below.
Space reclamation
Delete does not recover space, Truncate recovers space
Oracle
If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.
Row scope
Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.
Oracle
When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.
Object types
Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)
Data Object Identity
Oracle
Delete does not affect the data object id, but truncate assigns a new data object id
unless
there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.
Flashback (Oracle)
Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.
However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition
Use of FLASHBACK in Oracle
http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638
Privileges
Variable
Oracle
Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.
Redo/Undo
Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.
Indexes
Oracle
A truncate operation renders unusable indexes usable again. Delete does not.
Foreign Keys
A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.
Table Locking
Oracle
Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.
Triggers
DML triggers do not fire on a truncate.
Oracle
DDL triggers are available.
Remote Execution
Oracle
Truncate cannot be issued over a database link.
Identity Columns
SQL*Server
Truncate resets the sequence for IDENTITY column types, delete does not.
Result set
In most implementations, a
```
DELETE
```
statement can return to the client the rows that were deleted.
e.g. in an Oracle PL/SQL subprogram you could:
```
```
DELETE FROM employees_temp
WHERE       employee_id = 299
RETURNING   first_name,
            last_name
INTO        emp_first_name,
            emp_last_name;
```
```


Question:
I'd like to structure a Form with a TabControl but I'd like to avoid having every control on each TabPage end up being a member of the Form I'm adding the TabControl to. So far I've identified these options, please comment or suggest alternatives:

1) Write a UserControl for each TabPage

2) Leave only the Control on the main Form but turn the control variable public and cut-and-past all actual code into separate classes

3) Forgo the Form designer and do everything at runtime

4) Derive from Tabpage (not sure if this works and what the design-time implications are)

Thanks all,

Andrew

Answer:
In any complex WinForms application, you will probably run into the problem of too many controls on a form. Not that you'll run into a hard limit, but rather you'll run into a pain point -- such as you're describing.
In most scenarios, for me, your option #1 -- a user control for each tab page -- is the least painful approach. It allows you to encapsulate logical breakdowns of the controls in their own way, scoping them appropriately.
The downside to this is that you will likely end up exposing either a
ton
of properties on your user control. The way out of that problem is fairly simple, though: Use a custom class to represent the data which is "bound" to said control, and then expose a single property for the bound instance of the class.
You'll have better architecture overall, you'll be more maintainable, and as an added bonus, you won't go nuts trying to get the form to work. :)
EDIT:
I should note that you may also end up needing to expose some custom events from the user controls which represent your tab pages. Essentially, if there's a control on the tab whose event is needed by the parent form, you'll have to create an event and raise it so that the parent form knows about it. This isn't terribly difficult, but can add significant LOCs to the user controls.


Question:
if I call php's parse_ini_file("foo.ini"), in what paths does it look for foo.ini ?
the include path? the function's documentation doesn't mention it.

Answer:
I would imagine it only looks in the current working directory - See
http://uk3.php.net/manual/en/function.getcwd.php
if you want to know what that is.
You can always find a path relative to your application by basing it on $_SERVER['DOCUMENT_ROOT']


Question:
I've been doing a massive code review and one pattern I notice all over the place is this:

public bool MethodName()
{
    bool returnValue = false;
    if (expression)
    {
        // do something
        returnValue = MethodCall();
    }
    else
    {
        // do something else
        returnValue = Expression;
    }

    return returnValue;
}

This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?

I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.

Answer:
I would have used ternary, to reduce control structures...
```
```
return expression ? MethodCall() : Expression;
```
```


Question:
Is there any way to list all the files that have changed between two tags in CVS?

Every time we do a release we apply a tag to all the files in that release. I want to find all the files that changed between releases.

It would also work if I could find all files that had changed between two dates.

Answer:
I suppose this command would help:
```
```
cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 > diffs
```
```
where
```
RELEASE_1_0
```
and
```
RELEASE_1_1
```
are the names of your tags.
You can find a little more information on cvs diff command
here
plus it should be fairly simple to create a script to make report more suitbable for your needs, ex: number of files changed, created deleted etc. As far as I know the most common cvs GUI tools (wincvs and tortoise) do not provide something like this out of the box.
Hope it helps
```
;)
```


Question: I have a Console application hosting a WCF service.  I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service.  Is this possible?  How would I do this?  Could I derive a custom class from ServiceHost?

Answer:
You don't need to inherit from
```
ServiceHost
```
. There are other approaches to your problem.
You can pass an instance of the service class, instead of a type to
```
ServiceHost
```
. Thus, you can create the instance before you start the
```
ServiceHost
```
, and add your own event handlers to any events it exposes.
Here's some sample code:
```
```
MyService svc = new MyService();
svc.SomeEvent += new MyEventDelegate(this.OnSomeEvent);
ServiceHost host = new ServiceHost(svc);
host.Open();
```
```
There are some caveats when using this approach, as described in
http://msdn.microsoft.com/en-us/library/ms585487.aspx
Or you could have a well-known singleton class, that your service instances know about and explicitly call its methods when events happen.


Question:
The following test fails:

#!/usr/bin/env python
def f(*args):
    """
    >>> t = 1, -1
    >>> f(*map(lambda i: lambda: i, t))
    [1, -1]
    >>> f(*(lambda: i for i in t)) # -> [-1, -1]
    [1, -1]
    >>> f(*[lambda: i for i in t]) # -> [-1, -1]
    [1, -1]
    """
    alist = [a() for a in args]
    print(alist)

if __name__ == '__main__':
    import doctest; doctest.testmod()

In other words:

>>> t = 1, -1
>>> args = []
>>> for i in t:
...   args.append(lambda: i)
...
>>> map(lambda a: a(), args)
[-1, -1]
>>> args = []
>>> for i in t:
...   args.append((lambda i: lambda: i)(i))
...
>>> map(lambda a: a(), args)
[1, -1]
>>> args = []
>>> for i in t:
...   args.append(lambda i=i: i)
...
>>> map(lambda a: a(), args)
[1, -1]

Answer:
The lambda captures variables, not values, hence the code
```
```
lambda : i
```
```
will always return the value i is
currently
bound to in the closure.  By the time it gets called, this value has been set to -1.
To get what you want, you'll need to capture the actual binding at the time the lambda is created, by:
```
```
>>> f(*(lambda i=i: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda i=i: i for i in t]) # -> [-1, -1]
[1, -1]
```
```


Question: What is the bare minimum I need to put in web.config to get WCF working with REST? I have annotated my methods with [WebGet], but they are not getting the message.

Answer:
Ensure that you use a webHttpBinding on your endpoint (and not an httpBinding or wsHttpBinding). Here's my endpoint config...
```
```
<endpoint address="" binding="webHttpBinding" bindingConfiguration=""
      contract="WcfCore.ICustomer">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
```
```


Question:
I am using StringReplace to replace &gt and &lt by the char itself in a generated XML like this:

StringReplace(xml.Text,'&gt;','>',[rfReplaceAll]) ;
StringReplace(xml.Text,'&lt;','<',[rfReplaceAll]) ;

The thing is it takes way tooo long to replace every occurence of &gt.

Do you purpose any better idea to make it faster?

Answer:
The problem is that you are iterating the entire string size twice (one for replacing > by > and another one to replace < by <).
You should iterate with a for and simply check ahead whenever you find a & for a gt; or lt; and do the immediate replace and then skipping 3 characters ((g|l)t;). This way it can do that in proportional time to the size of the string
xml.Text
.
A simple C# example as I do not know Delphi but should do for you to get the general idea.
```
```
String s = "<xml>test</xml>";
char[] input = s.ToCharArray();
char[] res = new char[s.Length];
int j = 0;
for (int i = 0, count = input.Length; i < count; ++i)
{
    if (input[i] == '&')
    {
        if (i < count - 3)
        {
            if (input[i + 1] == 'l' || input[i + 1] == 'g')
            {
                if (input[i + 2] == 't' && input[i + 3] == ';')
                {
                    res[j++] = input[i + 1] == 'l' ? '<' : '>';
                    i += 3;
                    continue;
                }
            }
        }
    }

    res[j++] = input[i];
}
Console.WriteLine(new string(res, 0, j));
```
```
This outputs:
```
```
<xml>test</xml>
```
```


Question:
I have a C# WinForms borderless window, for which I override WndProc and handle the WM_NCHITTEST message. For an area of that form, my hit test function returns HTSYSMENU. Double-clicking that area successfully closes the form, but right-clicking it does not show the window's system menu, nor does it show up when right-clicking the window's name in the taskbar.

This form uses these styles:

this.SetStyle( ControlStyles.AllPaintingInWmPaint, true );
this.SetStyle( ControlStyles.UserPaint, true );
this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true );
this.SetStyle( ControlStyles.ResizeRedraw, true );

And has these non-default property values:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;

I've tried handling WM_NCRBUTTONDOWN and WM_NCRBUTTONUP, and send the WM_GETSYSMENU message, but it didn't work.

Answer:
I have the same properties in my application and Right click doesn't work either, so this is not
your problem
, it appears to be the way windows forms respond when they have no border.
If you set your border to the normal value, you will be able to have right click in the taskbar and such.
For right click on other controls, you'll need to set the ContextMenuStrip and provide your "menu". But I'm not sure if this works when you have it without border. I have been unable to make it work.


Question:
Is it a good idea to use while loop instead of a cursor?

What are the advantages/disadvantages of cursors?

Answer:
Some of these depends on the DBMS, but generally:
Pros:
Outperform loops when it comes to row-by-row processing
Works reasonably well with large datasets
Cons:
Don't scale as well
Use more server resources
Increases load on tempdb
Can cause leaks if used incorrectly (eg. Open without corresponding Close)


Question:
The MEF team keep saying it is about plug-in model. So, are we talking about UI plugins? How can we use this stuff in non-UI code?
I downloaded the code and the examples are all about GUI. Am I guessing it wrong?

Answer:
Ayende sums up MEF rather nicely here:
http://ayende.com/Blog/archive/2008/09/25/the-managed-extensibility-framework.aspx
Also the herding code lads had a great interview with Glenn Block, one of the MS MEF guys:
http://herdingcode.com/?p=28
http://herdingcode.com/?p=31


Question: Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap?  Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc.  Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.

Answer:
This code gets 242 countries in Sun Java 6:
```
```
String[] countryCodes = Locale.getISOCountries();
```
```
Though
the ISO website
claims there are 249
ISO 3166-1-alpha-2 code elements
, though the
javadoc
links to the same information.


Question:
Google results on this one are a bit thin, but suggest that it is not easily possible.

My specific problem is that I need to renumber the IDs in two tables that are related to each other such that table B has an "table_a_id" column in it. I can't renumber table A first because then its children in B point to the old IDs. I can't renumber table B first because then they would point to the new IDs before they were created. Now repeat for three or four tables.

I don't really want to have to fiddle around with individual relationships when I could just "start transaction; disable ref integrity; sort IDs out; re-enable ref integrity; commit transaction". Mysql and MSSQL both provide this functionality IIRC so I would be surprised if Postgres didn't.

Thanks!

Answer:
It does not seem possible. Other suggestions almost always refer to dropping the constraints and recreating them after work is done.
However, it seems you can make constraints
```
DEFERRABLE
```
, such that they are not checked until the end of a transaction. See
PostgreSQL documentation for
```
CREATE TABLE
```
(search for 'deferrable', it's in the middle of the page).


Question: I have a problem with setting the TTL on my Datagram packets.  I am calling the setTTL(...) method on the packet before sending the packet to the multicastSocket but if I capture the packet with ethereal the TTL field is always set to 0

Answer:
Basically you have to set an special system property telling the JVM to use an IPv4 stack:
```
```
-Djava.net.preferIPv4Stack=true
```
```


Question:
I'm using the document.form.submit() function for a rather large input form (hundreds of fields, it's an inventory application).  I'm calling this after the user has been idle for a certain amount of time and I would like to save any data they've typed.  When I try this the page reloads (the action is #) but any new text typed in the fields is not passed in the REQUEST, so I don't get to put it in the DB.  Is there some fundamental reason why this happens or is my code just not playing nice together (I'm using the EXTJS grid view to show the form and a library for tracking idle time)?
Thanks,
Robert

Answer:
Might the server be voiding out the input values. Say if your page on the server looks like this:
```
```
<form action="/page.cgi">
  ...
  <input name="Fieldx" value=""/>
</form>
```
```
I think it'll void out the field. Or this the server action might be setting it indirectly. In JSF, something like this.
```
```
<input name="Fieldx" value="#{bean.nullProperty}"/>
```
```
What do you have on the server and what's your browser?


Question:
I've started with ASP.NET MVC recently, reading blogs, tutorials, trying some routes, etc. Now, i've stumbled on a issue where i need some help.

Basically, i have an URL like /products.aspx?categoryid=foo&productid=bar

Most tutorials/examples propose to map this to something like: /products/category/foo/bar where "products" is the controller, "category" is the action, etc.

But i need to map it to /products/foo/bar. (without "category")

Is it possible? Am i missing something? Help will be highly appreciated. Thank you advance :)

P.S. Sorry for my bad English.

Answer:
(your English is just fine, no need to apologize!)
You can define a route like this:
```
```
routes.MapRoute("productsByCategory", "products/{category}/{productid}",
  new { controller="products", action="findByCategory" })
```
```
This will match
```
products/foo/bar
```
and call an action looking like this:
```
```
public class ProductsController : Controller
{
   ...

   public ActionResult FindByCategory(string category, string productid)
   {
          ....
   }
}
```
```
does this help?


Question: I have two functions, f and g, which call each other recursively. Unfortunately, when f calls g, it has not yet been declared, so I get an "unbound variable" error.  How can I prototype (or whatever the equivalent vocabulary is) this function in SML/NJ?

Answer:
Mutual Recursion. Use
```
and
```
instead of
```
fun
```
between the two functions.


Question:
How do I loop into all the resources in the resourcemanager?

Ie:
foreach (string resource in ResourceManager)
  //Do something with the recource.

Thanks

Answer:
Use ResourceManager.
GetResourceSet
() for a list of all resources for a given culture. The returned ResourceSet implements IEnumerable (you can use foreach).
To answer Nico's question: you can count the elements of an
```
IEnumerable
```
by casting it to the generic
```
IEnumerable<object>
```
and use the
```
Enumerable.Count<T>()
```
extension method, which is new in C# 3.5:
```
```
using System.Linq;

...

var resourceSet = resourceManager.GetResourceSet(..);
var count = resSet.Cast<object>().Count();
```
```


Question:
I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page.

Any sample code would be greatly appreciated!

Link to API: http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf

Answer:
I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simplest way to do this in .NET is using the WebClient class. Alternatively you might want to take a look at the HttpWebRequest/HttpWebResponse classes. Here is some sample code using WebClient:
```
```
using System.Net;
using System.Text;
using System;

namespace RightNowSample
{
    class Program
    {
        static void Main(string[] args)
        {
            string serviceUrl = "http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php";
            WebClient webClient = new WebClient();
            string requestXml =
@"<connector>
<function name=""ans_get"">
<parameter name=""args"" type=""pair"">
<pair name=""id"" type=""integer"">33</pair>
<pair name=""sub_tbl"" type='pair'>
<pair name=""tbl_id"" type=""integer"">164</pair>
</pair>
</parameter>
</function>
</connector>";

            string secString = "";
            string postData = string.Format("xml_doc={0}, sec_string={1}", requestXml, secString);
            byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);

            byte[] responseDataBytes = webClient.UploadData(serviceUrl, "POST", postDataBytes);
            string responseData = Encoding.UTF8.GetString(responseDataBytes);

            Console.WriteLine(responseData);
        }
    }
}
```
```
I have no access to RightNow CRM, so I could not test this, but it can serve as s tarting point for you.


Question: When creating a class library in C++, you can choose between dynamic (.dll, .so) and static (.lib, .a) libraries. What is the difference between them and when is it appropriate to use which?

Answer:
If your library is going to be shared among several executables, it often makes sense to make it dynamic to reduce the size of the executables.  Otherwise, definitely make it static.
There are several disadvantages of using a dll.  There is additional overhead for loading and unloading it.  There is also an additional dependency.  If you change the dll to make it incompatible with your executalbes, they will stop working.  On the other hand, if you change a static library, your compiled executables using the old version will not be affected.


Question:
Should it be on the development servers or a Subversion server?

I suppose this could be expanded to any client-server version control system.

Answer:
The physical repository should be on a stable system that gets regular backups.
Generally, a development server does not fit this description... it may be acceptable to put the apache server on the dev server and host the files remotely on a stable, backed-up file server (though there are a number of pitfalls with this approach) if you are unable to get additional server resources. Hosting it on the dev server may be fine if you have an aggressive backup system to protect your code...
Just keep in mind that dev servers are prone to configuration changes, being blown-away, or otherwise mucked with that could take down your repo at a critical moment.


Question: If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?

Answer:
There is a
```
WebOperationContext
```
that you can access and it has a
```
OutgoingResponse
```
property of type
```
OutgoingWebResponseContext
```
which has a
```
StatusCode
```
property that can be set.
```
```
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
```
```


Question:
I want to consume a web service over https from a java client.
What steps will i need to take in order to do this?

Answer: Really, there shouldn't much different from consuming a web service over HTTP. The big thing is that the process calling the web service will have to trust the server's SSL certificate. If the certificate was purchased from a well-known certificate-issuing authority, this usually isn't a problem. Otherwise, the client will want to either trust the root certificate, or the certificate associated with the server's fully qualified host name.


Question:
So I have a small C# app that needs to periodically check the contents of directories on multiple machines on the network.  I thought I could just read \hostname\C$ as a directory path, but with the normal Directory class there doesn't seem to be a way to authenticate against the other servers so you can access the hidden share.
I'm sure there's an easy way to do this that I've overlooked, but at the moment I'm a bit stumpted.

Answer:
From
http://bytes.com/forum/thread689145.html
:
All processes run in the context of a
logged-in user account. If you want to
open a file on another computer, your
application must be running in the
context of a user that has permissions
to open files on that machine. You can
do this with Impersonation.
The easiest way seems to be to give the current user appropriate rights on the other machines.


Question:
I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.

I couldn't have phrased it better than the person that posted the same question here.

But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the

byte[] {0x00,0xA0,0xBf}

what should I do?

I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple.

Answer:
The Hex class in commons-codec should do that for you.
http://commons.apache.org/codec/
```
```
import org.apache.commons.codec.binary.Hex;
...
byte[] decoded = Hex.decodeHex("00A0BF");
// 0x00 0xA0 0xBF
```
```


Question:
I'm working on a client site who is using Umbraco as a CMS. I need to create a custom 404 error page. I've tried doing it in the IIS config but umbraco overrides that.

Does anyone know how to create a custom 404 error page in Umbraco?
Is there a way to create a custom error page for runtime errors?

Answer:
In
```
/config/umbracoSettings.config
```
modify
```
<error404>1</error404>
```
"
1
" with the id of the page you want to show.
```
```
<errors>
   <error404>1</error404>
</errors>
```
```
Other ways to do it can be found at
Not found handlers


Question:
How can I find out which column and value is violating the constraint? The exception message isn't helpful at all:

Failed to enable constraints. One or
  more rows contain values violating
  non-null, unique, or foreign-key
  constraints.

Answer:
There is a property called RowError you can check.
See
http://dotnetdebug.net/2006/07/16/constraintexception-a-helpful-tip/
Edited to add this link showing iteration of rows to see which had errors.
http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic58812.aspx


Question:
In a servlet I do the following:

  Context context = new InitialContext();
  value = (String) context.lookup("java:comp/env/propertyName");

On an Apache Geronimo instance (WAS CE 2.1) how do i associate a value with the key propertyName?

In Websphere AS 6 i can configure these properties for JNDI lookup under the "Name Space Bindings" page in the management console, but for the life of me I can find no way to do this in community edition on the web.

Answer:
One possibility is to add the properties to your web.xml file (in the WEB-INF directory), using one or more
```
<env-entry>
```
tags. For example, something like the following:
```
```
<env-entry>
   <description>My string property</descriptor>
   <env-entry-name>propertyName</env-entry-name>
   <env-entry-type>java.lang.String</env-entry-type>
   <env-entry-value>Your string goes here</env-entry-value>
</env-entry>
```
```
Each env-entry tag declares a new environment variable that you can then access from the
```
java:comp/env
```
context.
Once you add the necessary
```
env-entry
```
's you can use code similar to what you already posted to access these values. Mind you, I don't have Geronimo installed, so I don't know if there is any additional configuration that needs to be done in order to make this work.


Question: As a developer, how do you use gdb to track down bugs within your code?  What techniques tricks do you use to make your life easier?

Answer:
In general you find something that isn't how it should be, and work backwards until you understand why.
The most obvious is the most useful:  Setting a breakpoint on a function or line number and walking through the code line by line.
Another handy tip is to have show functions for all your structures/objects even if they are never used in your program, because you can run these functions from within gdb:
```
```
gdb> p show_my_struct(struct)

My custom display of Foo:
   ...
```
```
Watchpoints can be really handy too, but may slow down your program a lot. These break the flow when the value of a variable or address changes.:
```
```
gdb> watch foo
Watchpoint4: foo
gdb>
```
```


Question:
I've got several modules containing functions, classes and templates that I keep in a directory called (hah!) 'reuse'. I know the content reasonably well, so to find a particular class or bit of code doesn't take too long, but it is slowly growing in size and I need some sensible method to store them for easy search & retrieval.

How should I do this?

A related question can be found here: full text search for source code

Answer:
Group
the sources by
area of use
(network, security, text processing, etc); best in
directories
for easier browsing.
Tag
functions by adding
keywords
into the source documentation. Use an appropriate comment markup system (like javadoc) and create some kind of indexable docs.
Search
by using some kind of full text search (grep -r, google desktop) on your sources.


Question:
I'm developing an application that is targeting the .NET 3.5 Framework. The application's setup installs the .NET 2.0 runtime on the target machine. So far I haven't had any issues with doing this, but I'm wondering what problems I'm going to have down the line. Do I need to be installing the 3.5 runtime?

I must package the .NET runtime installer into our installation (no network install). The size of the runtime installer is the issue. The .NET 2.0 runtime installer is 23MBs (manageable), the .NET 3.0 runtime installer is 50MBs (getting big) and the .NET 3.5 runtime installer is 200MBs (yikes!). What the heck is in those extra 170MBs?

Answer: This is a tough question to answer, because ultimately it depends on what .NET 3.5 features you are using.  If you are using some of the new libraries, such as LINQ, then yes, you'll need to install the 3.5 runtimes.  However, if you are just using some of the new syntatic sugars introduced in 3.5, you may not.  The reason for this is that .NET 3.5 is 100% compatible with the 2.0 CLR.


Question: I am trying to write a web service to spec and it requires a different response body depending on whether the method completes successfully or not. I have tried creating two different DataContract classes, but how can I return them and have them serialized correctly?

Answer: If you are using a xml based binding, then I believe there is no way to do that. A simple solution in that case would to just have part of the message flag if there was a failure, and store the failure information somewhere if needed. For a JSON binding you may be able to use a method that returns an object, then return two different types of objects. If I remember correctly (which is rare), that is possible because the JavaScriptSerializer class uses reflection if the object is clean of serialization attributes.


Question:
I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it!

Does anyone know what it is?

It will do something similar to:

const CRect client(0, 0, 200, 200);
const CRect window = ClientRectToWindowRect(client);
SetWindowPos(...)

Answer:
You're probably thinking of
```
AdjustWindowRectEx()
```
. Keep in mind, this is intended for use when
creating
a window - there's no guarantee that it will produce an accurate set of window dimensions for an existing window; for that, use
```
GetWindowRect()
```
.


Question:
We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity.  We need to provide that standard capability on making sure if the user forgets to click the "Save" button before navigating away or closing their browser they get a warning and can cancel (but only when there is unsaved or dirty data).

I know the basics of what I've got to do-- in fact I'm sure I've done it all before over the years (tie in to onbeforeunload, track the "dirty" state of the page, etc...) but before I embark on coding this YET AGAIN, does anyone have some suggestions for libraries already out there (free or otherwise) that will help out?

Answer:
One piece of the puzzle:
```
```
/**
 * Determines if a form is dirty by comparing the current value of each element
 * with its default value.
 *
 * @param {Form} form the form to be checked.
 * @return {Boolean} true if the form is dirty, false
 *                   otherwise.
 */
function formIsDirty(form)
{
    for (var i = 0; i < form.elements.length; i++)
    {
        var element = form.elements[i];
        var type = element.type;
        if (type == "checkbox" || type == "radio")
        {
            if (element.checked != element.defaultChecked)
            {
                return true;
            }
        }
        else if (type == "hidden" || type == "password" || type == "text" ||
                 type == "textarea")
        {
            if (element.value != element.defaultValue)
            {
                return true;
            }
        }
        else if (type == "select-one" || type == "select-multiple")
        {
            for (var j = 0; j < element.options.length; j++)
            {
                if (element.options[j].selected !=
                    element.options[j].defaultSelected)
                {
                    return true;
                }
            }
        }
    }
    return false;
}
```
```
And another
:
```
```
window.onbeforeunload = function(e)
{
    e = e || window.event;
    if (formIsDirty(document.forms["someFormOfInterest"]))
    {
        // For IE and Firefox
        if (e)
        {
            e.returnValue = "You have unsaved changes.";
        }
        // For Safari
        return "You have unsaved changes.";
    }
};
```
```
Wrap it all up, and what do you get?
```
```
var confirmExitIfModified = (function()
{
    function formIsDirty(form)
    {
        // ...as above
    }

    return function(form, message)
    {
        window.onbeforeunload = function(e)
        {
            e = e || window.event;
            if (formIsDirty(document.forms[form]))
            {
                // For IE and Firefox
                if (e)
                {
                    e.returnValue = message;
                }
                // For Safari
                return message;
            }
        };
    };
})();

confirmExitIfModified("someForm", "You have unsaved changes.");
```
```
You'll probably also want to change the registration of the
```
beforeunload
```
event handler to use
```
LIBRARY_OF_CHOICE
```
's event registration.


Question:
What is the longest string that can be created in .NET? The docs for the String class are silent on this question as far as I can see, so an authoritative answer might require some knowledge of internals. Would the maximum change on a 64-bit system?

[This is asked more for curiosity than for practical use - I don't intend to create any code that uses gigantic strings!]

Answer:
Since the
```
Length
```
property of
```
System.String
```
is an
```
Int32
```
, I would guess that that the maximum length would be 2,147,483,647 chars (max
```
Int32
```
size). If it allowed longer you couldn't check the Length since that would fail.


Question:
Which gets called first - the base constructor or "other stuff here"?

public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message, string extrainfo) : base(message)
    {
        //other stuff here
    }
}

Answer:
I'd say base
EDIT see:
http://www.c-sharpcorner.com/UploadFile/rajeshvs/ConsNDestructorsInCS11122005010300AM/ConsNDestructorsInCS.aspx
there it says:
```
```
using System;
class Base
{

public Base()
{
    Console.WriteLine("BASE 1");
}
public Base(int x)
{
    Console.WriteLine("BASE 2");
}
}

class Derived : Base
{
public Derived():base(10)
{
    Console.WriteLine("DERIVED CLASS");
}
}

class MyClient
{
public static void Main()
{
    Derived d1 = new Derived();
}
}
```
```
This program outputs
BASE2
DERIVED CLASS


Question:
Yup, long title.  I've been programming in PHP for the last 6 years or so for work and personal projects, but I've got an idea for a desktop app (which incidentally, uses a web REST api).

I'm debating on how to approach this - I've got some experience in Java, C++, Perl and Python, but have never had the chance or opportunity to write and distribute an app to others of any significance.

The app will need to communicate with a REST API (with OAuth), as well as access the file system, and possibly do some image manipulation (encoding/resizing, but this is a nice to have). I've been thinking something on .NET, but AIR is a possibility too (though I really dont want a huge runtime hanging around, this will be a system-tray type app).

I'm not looking for someone to write it, but I could use a nudge in the right direction.

Answer:
Being a Delphi programmer for years, you can do everything you want with it.
I'm starting to use C# at work. It's a great language too, but for a distributed application. the .NET framework still stops me from using it for my personnal apps.
In my point of view, Delphi is a good option. You can look at Lazarus/Free Pascal if you want a free IDE.
With this option, you build your EXE and that's it. Ship the EXE to the customer and it's working. No need for DLL/framework thing to have on the computer.
Of course, if you're using database stuff or third party DLL, you must ship the necessary stuff with it. But it's simplier than with VB with all the vbrunxx.dll, or with all .NET language.
It's my 2c... I think I'll be flamed for this! ;-)
HTH


Question:
How do I detect if my program runs in an Active Directory environment?

I'm using C# and .Net 2.0

Answer:
One way might be to query the LOGONSERVER environmental variable.  That'll give the server name of your AD controller... Which, as far as I know, will be blank (or match current workstation? Not sure) if it isn't currently logged into a domain.
Example Usage:
```
```
string ADServer = Environment.GetEnvironmentVariable("LOGONSERVER");
```
```


Question: When I try to execute a view that includes tables from different schemas an ORA-001031 Insufficient privileges is thrown.  These tables have execute permission for the schema where the view was created.  If I execute the view's SQL Statement it works.  What am I missing?

Answer:
As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as.
```
```
grant SELECT on TABLE_NAME to READ_USERNAME;
```
```


Question:
The Erlang documentation contains the documentation of modules.

Where can I find the documentation of the Erlang shell? (Which is not a module, I suppose.)

Answer:
This page in the documentation
seems to be a starting point. Especially the link in it. Check also the
first link
in it, with the shell's manpage.


Question: I'm wondering which languages support (or don't support) native multithreading, and perhaps get some details about the implementation.  Hopefully we can produce a complete overview of this specific functionality.

Answer:
Older versions of C and C++ (namely, C89, C99, C++98, and C++03) have no support at all in the core language, although libraries such as POSIX threads are available for pretty much every platform in common user today.
The newest versions of C and C++, C11 and C++11, do have built-in threading support in the language, but it's an optional feature of C11, so implementations such as single-core embedded systems can choose not to support it while supporting the rest of C11 if they desire.


Question:
It often happens that characters such as é gets transformed to Ã©, even though the collation for the MySQL DB, table and field is set to utf8_general_ci. The encoding in the Content-Type for the page is also set to UTF8.

I know about utf8_encode/decode, but I'm not quite sure about where and how to use it.

I have read the "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" article, but I need some MySQL / PHP specific pointers.

How do I ensure that user entered data containing international characters doesn't get corrupted?

Answer:
On the first look at
http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet
I think that one important thing is missing (perhaps I overlooked this one).
Depending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the client side (meaning the client side of the MySQL connection, which should be you PHP script). You can do this by manually issuing a
```
```
SET NAMES utf8
```
```
query prior to any other query you send to the MySQL server.
If your're using PDO on the PHP side you can set-up the connection to automatically issue this query on every (re)connect by using
```
```
$db=new PDO($dsn, $user, $pass);
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");
```
```
when initializing your db connection.


Question:
In Java you can do File.listFiles() and receive all of the files in a directory.  You can then easily recurse through directory trees.

Is there an analogous way to do this in Python?

Answer:
Straight from Python's Refererence Library
```
```
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
```
```


Question:
I am writing a web server in Java and I want it to support HTTP 1.1 Keep-Alive connections. But how can I tell when the client is done sending requests for a given connection? (like a double end-of-line or something).

Lets see how stackoverflow handles this very obscure question -- answers for which, on Google, are mired in technical specifications and obscure language. I want a plain-english answer for a non-C programmer :)

I see. that confirms my suspicion of having to rely on the SocketTimeoutException. But i wasn't sure if there was something i could rely on from the client that indicates it is done with the connection--which would allow me to close the connections sooner in most cases--instead of waiting for the timeout. Thanks

Answer: You close it whenever you'd like.  The header indicates that the client would prefer you to leave the connection open, but that doesn't require the server to comply.  Most servers leave it open for about 5-10 seconds, some don't pay attention to it at all.


Question:
Can you define a macro that accesses a normal variable, but in a read-only fashion (other than defining it as a call to a function)? For example, can the VALUE macro in the following code be defined in such a way that the dostuff() function causes a compile error?

struct myobj {
  int value;
}

/* This macro does not satisfy the read-only requirement */
#define VALUE(o) (o)->value

/* This macro uses a function, unfortunately */
int getvalue(struct myobj *o) { return o->value; }
#define VALUE(o) getvalue(o)

void dostuff(struct myobj *foo) {
   printf("The value of foo is %d.\n", VALUE(foo)); /* OK */
   VALUE(foo) = 1; /* We want a compile error here */
   foo->value = 1; /* This is ok. */
}

Answer:
If the variable is always numeric, this works:
```
```
#define VALUE(x) (x+0)
```
```
or in the context of your example,
```
```
#define VALUE(x) (x->value+0)
```
```


Question:
What do you think about this build tool? I'm thinking of migrating from maven2 to raven (my poms are getting bigger and bigger), but I'd like to hear some opinions first.

Thanks!

@andre:

Thank's for writing but I was actually looking for real experiences using raven. Anyway, the fact that nobody wrote is an indicator by itself (it seems few people are using it)

Answer: pom growth is a problem that everybody faces w/ maven I guess, but maven is at least maintained (2.1. just around the corner) and the raven project looks pretty dead to me. No updates this year and the mailinglist archives are also very small. It looks to me as it's too risky to switch your build process to a tool w/o a living community. Not quite the answer you wanted I guess, but my 2 cents.


Question: Is it possible to make a site with ASP.NET MVC Framework using .NET 2.0?  I am limited to using .NET 2.0 (we use VS 2008, but we have to use the 2.0 Framework) and I really want to try out the MVC Framework.

Answer:
Scott Hanselman described a way to make it work, with some caveats, in his blog:
Deploying ASP.NET MVC on ASP.NET 2.0


Question:
I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them.  Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?

So something that would yield this kind of translation table:

\r     --> \r\n
\n     --> \r\n
\n\n   --> \r\n\r\n
\n\r   --> \r\n
\r\n   --> \r\n
\r\n\n --> \r\n\r\n

Answer:
A Regex would help.. could do something roughly like this..
(\r\n|\n\n|\n\r|\r|\n) replace with \r\n
This regex produced these results from the table posted (just testing left side) so a replace should normalize.
```
```
\r   => \r
\n   => \n
\n\n => \n\n
\n\r => \n\r
\r\n => \r\n
\r\n => \r\n
\n   => \n
```
```


Question: Has anyone used C# with a Sales Logix database?

Answer:
Yes.  I have.
(Not the most interesting answer on SOB today, but that's what the question asked...)


Question:
In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">Object Name</Hyperlink></TextBlock>

But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/></TextBlock>

However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property).

Any ideas?

Answer:
It looks strange, but it works. We do it in about 20 different places in our app.
```
Hyperlink
```
implicitly constructs a
```
<Run/>
```
if you put text in its "content", but in .NET 3.5
```
<Run/>
```
won't let you bind to it, so you've got to explicitly use a
```
TextBlock
```
.
```
```
<TextBlock>
    <Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">
        <TextBlock Text="{Binding Path=Name}"/>
    </Hyperlink>
</TextBlock>
```
```
Update
: Note that as of .NET 4.0 the
Run.Text property
can now be bound:
```
```
<Run Text="{Binding Path=Name}" />
```
```


Question: I've seen a few different ways to iterate over a dictionary in C#.  Is there a standard way?

Answer:
```
```
foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}
```
```


Question:
"Dirty reads", meaning reading an object's value even though it is write-locked by another thread, are described on Terracotta's website, yet I've heard that they shouldn't be used, even if you don't care about the possibility that you might get old data when you dirty-read the locked object.

Does anyone have any experience of using dirty reads in Terracotta, and are they safe to use if you don't care about the possibility of reading an old value?

Answer:
A dirty read is a dirty read. Terracotta, being distributed/clustered, only adds the possibility to read even older values of the shared mutable state that you are accessing without proper synchronization.
You should note that, under the memory model in Java 5, you are not guaranteed to
ever
read an updated value if you don't use proper synchronization. Terracotta may decide to take advantage of this possibility. In fact, any JVM may, at their leisure, take advantage of it. Even if it might work on your machine, it may break on other machines. It may break on minor updates of the JVM, and it may break for the same version of the same JVM on a different CPU.
With that in mind, you can say that dirty reads isn't safe in any JVM... Unless you don't mind the possibility that you won't ever be able to read the updates that other threads make - an unlikely situation but it could happen.
Also, when you actually follow your link to Terracottas wiki, it says that the article has been removed and that the pattern is discouraged.


Question:
In an asp.net application, I would like to combine the use of the Webclient Software Factory (WCSF), and its associated Model View Presenter pattern (MVP), with Page Method, that is static methods on the .aspx Views marked with the [WebMethod] attribute.

However, static methods on the aspx page would seem to break the Model View Presenter pattern since an instance method is required on the page to have the context of the Presenter and Controller necessary for the View to talk to.

How would one extended asp .net's MVP pattern in WCSF to support [WebMethods] on the page, aka the View?

Answer:
I think you could come close to what you are looking for by using an ASP.Net AJAX Web Service instead of static page methods.  The web service has the advantage of not being static, and depending on how your views are implemented, (I'm not familiar with the specifics of the WCSF MVP pattern) you could potentially make the web service your "View" layer..or at least something fairly close.
I've done something similar in a project I'm working on.  I ended up needing to create a thin data-only class which got serialized to JSON by the web service to carry the data from the model to the "view", but the web service had essentially the same methods that would be exposed as events on the view.
One of the things I liked about this approach is that all the bits, including the web service, are testable.


Question:
Is it possible to find the foreach index?

in a for loop as follows:

for ($i = 0; $i < 10; ++$i) {
   echo $i . ' ';
}

$i will give you the index.

Do I have to use the for loop or is there some way to get the index in the foreach loop?

Answer:
```
```
foreach($array as $key=>$value) {
    // do stuff
}
```
```
```
$key
```
is the index of each
```
$array
```
element


Question:
I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows:

txtStart.Text = 09/19/2008 07:00:00

txtEnd.Text = 09/19/2008 05:00:00

I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page.

Answer:
Once your textbox date formats are known in advance, you can use
Matt Kruse's Date functions
in Javascript to convert the two to a timestamp, subtract and then write to the resulting text box.
Equally the
JQuery Date Input
code for
```
stringToDate
```
could be adapted for your purposes - the below takes a string in the format "YYYY-MM-DD" and converts it to a date object. The timestamp (
```
getTime()
```
) of these objects could be used for your calculations.
```
```
stringToDate: function(string) {
    var matches;
    if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
       return new Date(matches[1], matches[2] - 1, matches[3]);
    } else {
       return null;
    };
}
```
```


Question:
I want to know if my server is running Subversion 1.5.

How can I find that out?

Also would be nice to know my SVN client version number. svn help hasn't been helpful.

Note: I don't want my project's revision number, etc. This question is about the Subversion software itself.

Answer:
For an HTTP-based server there is a Python script to find the server version at:
http://svn.apache.org/repos/asf/subversion/trunk/tools/client-side/server-version.py
You can get the client version with
```
```
`svn --version`
```
```


Question: I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.

Answer:
You could query this registry value to get the SQL version directly:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90\Tools\ClientSetup\CurrentVersion
```
```
Alternatively  you can query your instance name and then use sqlcmd with your instance name that you would like:
To see your instance name:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names
```
```
Then execute this:
```
```
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
```
```
If you are using C++ you can use this code to get the registry information.


Question:
I need to see if a given process id is running, and it must work in either Java or JRuby (preferably a Ruby solution).  It can be system dependent for Linux (specifically Debian and/or Ubuntu).

I already have the PID I am looking for, just need to see if it is currently running.

UPDATE:

Thanks for all the responses everyone!  I appreciate it, however it's not QUITE what I'm looking for... I am hoping for something in a standard Ruby library (or Java, but preferably Ruby)... if no such library call exists, I will probably stick with the procfs solution I already have.

Answer:
From
my answer to this question
, I was thinking of just using procfs again, by checking if the given directory exists via File.exist? "/proc/#{pid}".  This worked in jirb:
```
irb(main):001:0> File.exist? "/proc/5555"
=> false
irb(main):002:0> File.exist? "/proc/7677"
=> true
```
However, I would still prefer to use a method that specifically exists to detect if a process is running... like Process.exist?(pid)... which unfortunately doesn't exist that I've seen.


Question:
Is there a way to detect if the user is holding down the shift key (or other modifier keys) when executing a javascript bookmarklet?

In my tests of Safari 3.1 and Firefox 3, window.event is always undefined.

Answer:
If you're looking for a way to detect the mouse position while the bookmarklet is being physically clicked, no, there is no way. Since the bookmarklet is positioned outside of any page (this area is generally called the browser "chrome" - which is confusing since there's now a browser with that name) it's not possible to detect JavaScript-related events there.
That being said, if you created this as a Firefox extension then you would have access to event information, JavaScript, and keyboard modifiers. But that doesn't appear to be what you're looking for.


Question:
I'd like the canonical way to do this.  My Google searches have come up short.  I have one ActiveRecord model that should map to a different database than the rest of the application.  I would like to store the new configurations in the database.yml file as well.

I understand that establish_connection should be called, but it's not clear where.  Here's what I got so far, and it doesn't work:

class Foo < ActiveRecord::Base
    establish_connection(('foo_' + ENV['RAILS_ENV']).intern)
end

Answer:
Heh.  I was right!  More cleanly:
```
```
class Foo < ActiveRecord::Base
    establish_connection "foo_#{ENV['RAILS_ENV']}"
end
```
```
Great post
at pragedave.pragprog.com
.


Question:
I've seen reference in some C# posted questions to a "using" clause.
Does java have the equivalent?

Answer:
Yes. Java 1.7 introduced the
try-with-resources
construct allowing you to write:
```
```
try(InputStream is1 = new FileInputStream("/tmp/foo");
    InputStream is2 =  new FileInputStream("/tmp/bar")) {
         /* do stuff with is1 and is2 */
}
```
```
... just like a
```
using
```
statement.
Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:
```
```
InputStream is1 = new FileInputStream("/tmp/foo");
try{

    InputStream is2 =  new FileInputStream("/tmp/bar");
    try{
         /* do stuff with is1 and is 2 */

    } finally {
        is2.close();
    }
} finally {
    is1.close();
}
```
```


Question: How have you tweaked the MATLAB environment to better suit your needs?  One tweak per answer.

Answer: I set the number of lines in the command window scroll buffer to the maximum (25,000).  This doesn't seem to noticeably affect performance and allows me to display a large amount of data/results.


Question: What is the difference between using the Runnable and Callable interfaces when designing a concurrent thread in Java, why would you choose one over the other?

Answer:
See explanation
here
.
The Callable interface is similar to
  Runnable, in that both are designed
  for classes whose instances are
  potentially executed by another
  thread.
A Runnable, however, does not
  return a result and cannot throw a
  checked exception.


Question:
Is there a way to check if a file has been opened by ReWrite in Delphi?

Code would go something like this:

AssignFile(textfile, 'somefile.txt');
if not textFile.IsOpen then
   Rewrite(textFile);

Answer:
You can get the filemode. (One moment, I'll create an example).
TTextRec(txt).Mode gives you the mode:
```
```
55216 = closed
55217 = open read
55218 = open write

fmClosed = $D7B0;
fmInput  = $D7B1;
fmOutput = $D7B2;
fmInOut  = $D7B3;
```
```
Search TTextRec in the system unit for more information.


Question:
Is there a way to check to see if a date/time is valid you would think these would be easy to check:

$date = '0000-00-00';
$time = '00:00:00';
$dateTime = $date . ' ' . $time;

if(strtotime($dateTime)) {
    // why is this valid?
}

what really gets me is this:

echo date('Y-m-d', strtotime($date));

results in: "1999-11-30",

huh? i went from 0000-00-00 to 1999-11-30 ???

I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?

Edit:
People are asking what i'm running:
Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux

Answer:
echo date('Y-m-d', strtotime($date));
results in: "1999-11-30"
The result of
```
strtotime
```
is 943920000 - this is the number of seconds, roughly, between the
Unix epoch
(base from which time is measured) to 1999-11-30.
There is a
documented
mysql bug
on
```
mktime(), localtime(), strtotime()
```
all returning this odd value when you try a pre-epoch time (including "0000-00-00 00:00:00"). There's some debate on the linked thread as to whether this is actually a bug:
Since the time stamp is started from 1970, I don't think it supposed to
  work in anyways.
Below is a function that I use for converting dateTimes such as the above to a timestamp for comparisons, etc, which may be of some use to you, for dates beyond "0000-00-00 00:00:00"
```
```
/**
 * Converts strings of the format "YYYY-MM-DD HH:MM:SS" into php dates
 */
function convert_date_string($date_string)
{
    list($date, $time) = explode(" ", $date_string);
    list($hours, $minutes, $seconds) = explode(":", $time);
    list($year, $month, $day) = explode("-", $date);
    return mktime($hours, $minutes, $seconds, $month, $day, $year);
}
```
```


Question:
I'm writing some server code that talks to a client process via STDIN. I'm trying to write a snippet of perl code that asynchronously receives responses from the client's STDOUT. The blocking version of the code might look like this:

sub _read_from_client
{
   my ($file_handle) = @_;
   while (my $line = <$file_handle>) {
      print STDOUT $line;
   }
   return;
}

Importantly, the snippet needs to work in Win32 platform. There are many solutions for *nix platforms that I'm not interested in. I'm using ActivePerl 5.10.

Answer:
This thread
on
Perlmonks
suggests you can make a socket nonblocking on Windows in Perl this way:
```
```
ioctl($socket, 0x8004667e, 1);
```
```
More details and resources in that thread


Question:
How does one check if a directory is already present in the PATH environment variable? Here's a start. All I've managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you'd think it would enumerate all the directories in %PATH%, but it only gets the first one.

Is there a better way of doing this? Something like FIND or FINDSTR operating on the %PATH% variable? I'd just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.

FOR /F "delims=;" %%P IN ("%PATH%") DO (
    @ECHO %%~P
)

Answer:
This may work:
```
```
echo ;%PATH%; | find /C /I ";<string>;"
```
```
It should give you 0 if the string is not found and 1 or more if it is.


Question:
My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment.  I've used a Python memory profiler (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.

What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory.  How do I get a core dump of a python process like this?  Once I have one, how do I do something useful with it?

Answer:
I don't know how to dump an entire python interpreter state and restore it. It would be useful, I'll keep my eye on this answer in case anyone else has ideas.
If you have an idea where the memory is leaking, you can add checks the refcounts of your objects. For example:
```
```
x = SomeObject()
... later ...
oldRefCount = sys.getrefcount( x )
suspiciousFunction( x )
if (oldRefCount != sys.getrefcount(x)):
    print "Possible memory leak..."
```
```
You could also check for reference counts higher than some number that is reasonable for your app. To take it further, you could modify the python interpreter to do these kinds of check by replacing the
```
Py_INCREF
```
and
```
Py_DECREF
```
macros with your own. This might be a bit dangerous in a production app, though.
Here is an essay with more info on debugging these sorts of things. It's more geared for plugin authors but most of it applies.
Debugging Reference Counts


Question:
Our resident Flex expert is out for the day and I thought this would be a good chance to test this site out. I have a dropdown with a dataProvider that is working fine:

<ep:ComboBox id="dead_reason" selectedValue="{_data.dead_reason}"
    dataProvider="{_data.staticData.dead_reason}"
    labelField="@label" width="300"/>

The ComboBox is custom but I'm not sure if that matters for the question. I need to change the combo box to radios (all in one group) but maintain the dynamic options. In other words, what is the best way to generate dynamic RadioButtons?

Answer:
Try using an <mx:Repeater>  Something like:
```
```
<mx:Repeater dataProvider="{_data.staticData.dead_reason}">
   <mx:RadioButton groupName="reasons" ...>
</mx:Repeater>
```
```


Question:
I'm pretty new to both C++ and Block Cipher encryption, and I am currently in the process of writing a decryption function for AES (16 byte seed / 16 byte blocks). All is going well, but my total data size is not always a multiple of my block size. I'm wondering what the best way to handle leftover data at the end of my data.

I'm using Crypto++ for the AES library.

The ProcessBlock() function takes an Input and Output char array. I'm assuming it is expecting them to be at least big enough as the block size.

What would be the best way to process all 16 byte blocks in a block cipher, and then also process the leftover data?

Answer:
What you want is a padding system.
Check out this CodeProject article on Crypto++
:
When a message is not a multiple of
  the cipher's block size, ECB or CBC
  mode messages must be padded. The
  method and values of padding are a
  source of problem with respect to
  interoperability between Cryptographic
  libraries and APIs. As Garth Lancaster
  points out, if you're not aware of the
  particulars of padding, use the
  StreamTransformationFilter. In this
  case, the Crypto++ filter will pad for
  you.


Question:
I installed Tomcat 6.0.18 on a windows server 2003 box and it will not start as a service.
I'm running it with jdk 1.6.0_07.

It runs when I start it with tomcat6.exe.

I got a vague error in the System Event Log on Windows.

The Apache Tomcat 6 service terminated with service-specific error 0 (0x0).

Answer:
From
gobaco.wordpress.com
Tomcat 6 couldn’t find a file called msvcr71.dll.
I just copied it over from
c:\windows\microsoft.net\framework\v1.1.4322
to
c:\windows\system32
and was able to start tomcat.
I thought this was very strange, so I wanted to post it on SO in case anyone else runs into this problem. If someone wants to post the same answer I'll accept it.


Question:
I have created a brand new project in XCode and have the following in my AppDelegate.py file:

from Foundation import *
from AppKit import *

class MyApplicationAppDelegate(NSObject):
    def applicationDidFinishLaunching_(self, sender):
        NSLog("Application did finish launching.")

        statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
        statusItem.setTitle_(u"12%")
        statusItem.setHighlightMode_(TRUE)
        statusItem.setEnabled_(TRUE)

However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default.

Answer:
I had to do this to make it work:
Open MainMenu.xib. Make sure the class of the app delegate is
```
MyApplicationAppDelegate
```
. I'm not sure if you will have to do this, but I did. It was wrong and so the app delegate never got called in the first place.
Add
```
statusItem.retain()
```
because it gets autoreleased right away.


Question:
Can anyone explain what advantages there are to using a tool like MSBuild (or NAnt) to build a collection of projects versus running DevEnv.exe from the command-line?

A colleague I had worked with in the past had explained that (at least with older versions of Visual Studio) using DevEnv.exe was much slower than the other techniques, but I haven't read any evidence of that or if that is now a moot point now that starting with 2005, Visual Studio uses MSBuild under the hood.

I know one advantage of using MSBuild allows you to build your projects without requiring Visual Studio to be installed on the build machines, but I wasn't sure if there were others.

Answer:
The prime reason for using an external build tool like NAnt or MsBuild is the ability to automate your build process and thus provide continous feedback on the status of your system. Also they can be used for loads of things besides a "pure" build and that's where you really start to get value from them, it's an extremly valuable thing to be able to build and test your application with a single command.
You can also start adding stuff like collection of metrics, packinging of release binaries and all sorts of nifty stuff like that.


Question: How do I create a file-like object (same duck type as File) with the contents of a string?

Answer:
For Python 2.x, use the
StringIO
module.  For example:
```
```
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
```
```
I use cStringIO (which is faster), but note that it doesn't
accept Unicode strings that cannot be encoded as plain ASCII strings
.  (You can switch to StringIO by changing  "from cStringIO" to "from StringIO".)
For Python 3.x, use the
```
io
```
module.
```
```
f = io.StringIO('foo')
```
```


Question:
I have a select element in a form, and I want to display something only if the dropdown is not visible.  Things I have tried:

Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't.  Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.

Change events, but these only are triggered when the select box's value changes.

Ideas?

Answer:
I don't think there's direct support.  You could also sit on the onblur of the select -- it gets called when the select loses focus.
Depending on how important it is, you could try implementing your own control or starting from one like a drop-down menu control which is similar.  Usually, unless it's critical to your application, it's not worth doing this.  If you decide to go this route, here's a discussion of someone trying to do it using dojo as a basis:
http://dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/emulating-html-select


Question:
I've got a nice little class built that acts as a cache. Each item has an expiration TimeSpan or DateTime. Each time an attempt to access an item in the cache is made, the item's expiration is checked, and if it's expired, the item is removed from the cache and nothing is returned.

That's great for objects that are accessed frequently, but if an item is put in the cache and never accessed again, it's never removed, even though it's expired.

What's a good methodology for expiring such items from the cache?

Should I have a background thread infinitely enumerating every item in the cache to check if it's expired?

Answer:
You can implement an LRU (Least Recently Used) strategy, keep your items sorted by access time, when a new item is inserted into the cache
and
the cache is full you evicted the item that is last in that list. See
Cache algorithms
at Wikipedia.
If you want to expire immediately, i would still only do that when things are accessed. I.e. when the cache object is accessed and it's time has expired refetch it.


Question:
I want to be able to explore the contents of a DB for this version of the DB. I was thinking of using the Squirrel DB client (which needs a JDBC driver).

Therefore, I'm looking for a JDBC type 4 driver for SQL SERVER 3.5.  Can somone point me to a FREE OR open source or trial ware ?

If no JDBC driver, how do MS developers explore a given .SDF file ?

Thank you,

BR,

~A

Answer:
Have you tried
SQL Server Management Studio Express
?
You can access SQL Server Compact 3.5
  databases stored on a smart device or
  on the desktop computer by using SQL
  Server Management Studio in SQL Server
  or SQL Server Management Studio
  Express (SSMSE).
http://technet.microsoft.com/en-us/library/ms172037.aspx
As for the JDBC Driver, you could take a look at
this one
, provided by Microsoft. I don't know if it works with the Compact Edition or if you already tried it, but I thought it was worth mentioning.


Question:
I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off.  I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable.  Anyone have any ideas?

Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm.

Answer:
```
```
static class EnumerableExtensions
{
    public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> sequence)
    {
        foreach(var child in sequence)
            foreach(var item in child)
                yield return item;
    }
}
```
```
Maybe like this? Or do you mean that it could potentially be infintly deep?


Question:
class Foo(models.Model):
    title = models.CharField(max_length=20)
    slug = models.SlugField()

Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.

Answer:
For pre-1.0:
```
```
slug = models.SlugField(prepopulate_from=('title',))
```
```
should work just fine
For 1.0, use
camflan's


Question:
I'm not sure if this even exists or not, so I figured I would tap the wisdom of others..

I was wondering if there are any Java libraries out there that can be used to validate a SQL query's syntax. I know that there are many deviations from common SQL spec, so it would probably only work against something like SQL:2006, but that would certainly suffice.

My goal is to use this for unit-testing purposes without needing to attempt the execution against the DB. I know it's of limited use, but it would still be useful.

Thanks!

Answer:
I don't think there are such libraries. The SQL syntax has too many derivatives.
A possible solution would be to use parts of an open source pure Java DBMS like
SmallSQL
. In this project you can create an instance of the
SQLParser
. The needed references to the connection can be removed very easily.


Question: When do you think we can expect the full release version of ASP.NET MVC?

Answer:
EDIT (16/Jul/2009)
Updating to ensure this page contains the most recent details.
ASP.NET MVC is now fully released
http://www.asp.net/mvc/
.
EDIT (28/Jan/2009)
ASP.NET MVC 1.0 RC Now Available.... final next month (
From ScottGu's Blog
)
Today’s RC is the last public release
  of ASP.NET MVC that we’ll ship prior
  to the final “1.0” release.  We expect
  to ship the final ASP.NET MVC 1.0
  release next month.
Last I heard, Q4 2008.
Scott Hanselman posted this
in his blog about 3.5 SP1
What about ASP.NET MVC?
There is likely some confusion around
  MVC as a few people expected ASP.NET
  MVC to ship in SP1. This is probably
  because MVC was included in 3.5
  "Extensions Preview." However, the
  plan was always to ship in Q4CY08.
(That date is marketing speak, I've
  just learned. I tell people what Eilon
  told me - it'll ship in a month ending
  in "-ber." Possible "March-ber" but
  also maybe "next June-ber.")
Anyway, Phil has always said that MVC
  is on its own schedule and will ship
  when its done. Possibly when Duke
  Nukem Forever ships.


Question:
I personally use var_dump, but lots of people like print_r.

What does everyone use? Pros and Cons?

Does someone have a special home brew function of their own?

Answer:
I use
```
print_r()
```
because I like the pretty array structure... but
```
var_dump
```
does give you a bit more information (like types)
```
```
$obj = (object) array(1, 2, 3);

// output of var_dump:
object(stdClass)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

// output of print_r
stdClass Object
(
  [0] => 1
  [1] => 2
  [2] => 3
)
```
```