Question:
What are the pros / cons of using pthread_cond_wait or using a semaphore ?
I am waiting for a state change like this :

pthread_mutex_lock(&cam->video_lock);
while(cam->status == WAIT_DISPLAY) {
    pthread_cond_wait(&cam->video_cond, &cam->video_lock);
}
pthread_mutex_unlock(&cam->video_lock);

Using a properly initialised semaphore, I think I could do it like this :

while(cam->status == WAIT_DISPLAY) {
    sem_wait(&some_semaphore);
}

What are the pros and cons of each method ?

Answer:
In your second snippet, you're getting the lock multitude of times, never releasing it.
In general, the state you're waintin on can be completely expressed by a semaphore, then you can use just that.  A lock structure is smaller in size, and it requires less atomic operations to check/set/release.
Otherwise, if the state is complex, and different parts of the code wait on different conditions of the same variable (eg, here you want x<10; there you want y>x), use cond_wait.


Question: How to get a file's creation date or file size, for example this Hello.jpg at http://www.mywebsite.com/now/Hello.jpg(note: This URL does not exist)? The purpose of this question is to make my application re-download the files from the any website when it has detected that the website has an updated version of the files and the files in my local folder are out of date. Any ideas?

Answer:
If you use the HEAD request it will send the headers for the resource, there you can check the cache control headers which will tell you if the resource has been modified, last modification time, size (content-length) and date.
```
```
$ telnet www.google.com 80
Trying 216.239.59.103...
Connected to www.l.google.com.
Escape character is '^]'.
HEAD /intl/en_ALL/images/logo.gif HTTP/1.0

HTTP/1.0 200 OK
Content-Type: image/gif
Last-Modified: Wed, 07 Jun 2006 19:38:24 GMT
Expires: Sun, 17 Jan 2038 19:14:07 GMT
Cache-Control: public
Date: Tue, 16 Sep 2008 09:45:42 GMT
Server: gws
Content-Length: 8558
Connection: Close

Connection closed by foreign host.
```
```
Note that you'll probably have to decorate this basic and easy approach with many heuristics depending on the craziness of each webserver's admin, as each can send whatever headers they like. If they do not provide caching headers (Last-Modified, Expires, Cache-Control) nor Content-Length nor etag, you'd be stuck with redownloading it to test.


Question: How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?

Answer:
```
```
var = raw_input("Please enter something: ")
print "you entered", var
```
```
Or for Python 3:
```
```
var = input("Please enter something: ")
print("You entered: " + var)
```
```


Question:
For best performance, is it better to use a virtual IDE HDD or virtual SCSI HDD?
If, SCSI, does it matter whether you use an BusLogic or LSILogic?

Answer:
Go for the SCSI and LSILogic. IDE and BusLogic are for compatibility reasons. Like when you do physical2virtual...
There's a whitepaper from vmware showing the difference between LSILogic and BusLogic, which in my opinion is rather small:
http://www.vmware.com/pdf/ESX2_Storage_Performance.pdf
Edit after like three years:
With current ESX environments it's best to use the Paravirtual SCSI device.


Question: Is it possible to use the Asp.Net MVC framework within SharePoint sites?

Answer: I don't believe so, although you can upload standard ASPX files into SharePoint and have them operate I'm pretty sure that the URL rewritting is where it would come unstuck.


Question:
Say I have the following C++:

char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;

Is this safe according to the C++ standard? Do I need to cast back to a char* and then use delete[]? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?

Answer:
No, it's undefined behaviour - a compiler could plausibly do something different, and as the C++ FAQ entry that
thudbang
linked to says,
```
operator delete[]
```
might be overloaded to do something different to
```
operator delete
```
. You can sometimes get away with it, but it's also good practice to get into the habit of matching delete[] with new[] for the cases where you can't.


Question: I have a workbook with 20 different pivot tables. Is there any easy way to find all the pivot tables and refresh them in VBA?

Answer:
Yes.
```
```
ThisWorkbook.RefreshAll
```
```
Or, if your Excel version is old enough,
```
```
Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next
```
```


Question:
Is there a good way to exclude certain pages from using a HTTP module?

I have an application that uses a custom HTTP module to validate a session. The HTTPModule is set up like this in web config:

<system.web>
  <!-- ... -->
  <httpModules>
    <add name="SessionValidationModule"
       type="SessionValidationModule, SomeNamespace" />
  </httpModules>
</system.web>

To exclude the module from the page, I tried doing this (without success):

<location path="ToBeExcluded">
  <system.web>
    <!-- ... -->
    <httpModules>
      <remove name="SessionValidationModule" />
    </httpModules>
  </system.web>
</location>

Any thoughts?

Answer:
You could use an HTTPHandler instead of an HTTPModule.  Handlers let you specify a path when you declare them in Web.Config.
```
```
<add verb="*" path="/validate/*.aspx" type="Handler,Assembly"/>
```
```
If you must use an HTTPModule, you could just check the path of the request and if it's one to be excluded, bypass the validation.


Question:
Originally I am looking for a solution in Actionscript. The point of this question is the algorithm, which detects the exact Minute, when a clock has to switch the Daylight Saving Time.

So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock...

Answer:
There is no real algorithm for dealing with Daylight Saving Time. Basically every country can decide for themselves when -and if- DST starts and ends. The only thing we can do as developers is using some sort of table to look it up. Most computer languages integrate such a table in the language.
In Java you could use the
```
inDaylightTime
```
method of the
TimeZone
class. If you want to know the exact date and time when DST starts or ends in a certain year, I would recommend to use
Joda Time
. I can't see a clean way of finding this out using just the standard libraries.
The following program is an example: (Note that it could give unexpected results if a certain time zone does not have DST for a certain year)
```
```
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public class App {
    public static void main(String[] args) {
        DateTimeZone dtz = DateTimeZone.forID("Europe/Amsterdam");

        System.out.println(startDST(dtz, 2008));
        System.out.println(endDST(dtz, 2008));
    }

    public static DateTime startDST(DateTimeZone zone, int year) {
        return new DateTime(zone.nextTransition(new DateTime(year, 1, 1, 0, 0, 0, 0, zone).getMillis()));
    }

    public static DateTime endDST(DateTimeZone zone, int year) {
        return new DateTime(zone.previousTransition(new DateTime(year + 1, 1, 1, 0, 0, 0, 0, zone).getMillis()));
    }
}
```
```


Question:
We all know the various ways of testing OO systems. However, it looks like I'll be going to do a project where I'll be dealing with PLC ladder logic (don't ask :/), and I was wondering if there's a good way of testing the validity of the system.

The only way I see so far is simply constructing a huge table with all known states of the system and which output states that generates. This would do for simple 'if input A is on, turn output B on' cases. I don't think this will work for more complicated constructions though.

Answer:
The verification of "logical" systems in the IC design arena is known as "Design Verification", which is the process of ensuring that the system you design in hardware (RTL) implements the desired functionality.
Ladder logic can be transformed to one of the modern HDL's like Verilog..
transform each ladder
```
```
|---|R15|---+---|/R16|---------(R18)--------|
|           |
|---|R12|---+
```
```
to an expression like
```
```
always @(*) R18 = !R16 && ( R15 | R12);
```
```
or you could use an assign statement
```
```
assign R18 = R16 && (R15 | R12);
```
```
a latching relay
```
```
assign R18 = (set condition) || R18 && !(break condition);
```
```
Then use a free verilog simulator like
Icarus
to develop a testbench and test your system.
Make sure you're testcases give good CODE coverage of your logic!  And If your ladder editing software gives you decent naming capabilities, use them, rather than Rnn.
(Note: in Ladder Logic for PLC convention, Rnn is for internal relays, while, Xnn is an input and Ynn is an output, as can be quickly gleaned from one of the online tutorials.
Verilog will be an easier language to develop your tests and testbenches in!
It may be helpful to program in some unit delays.
Sorry, I have never looked for ladder logic to/from verilog translators..
but ladder logic in my day was only just being put into a computer for programming PLC's - most of the relay systems I used were REAL Relays, wired into the cabinets!!
Good luck.
jbd
There are a couple of ladder logic editors (with simultors) available for free..
here is one that runs on windows supposedly:
http://cq.cx/ladder.pl


Question:
How do you return 1 value per row of the max of several columns:

TableName

[Number, Date1, Date2, Date3, Cost]

I need to return something like this:

[Number, Most_Recent_Date, Cost]

Query?

Answer:
This is an old answer and broken in many way.
See
https://stackoverflow.com/a/6871572/194653
which has way more upvotes and works with sql server 2008+ and handles nulls, etc.
Original but problematic answer
:
Well, you can use the CASE statement:
```
```
SELECT
    CASE
        WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
        WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
        WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
        ELSE                                        Date1
    END AS MostRecentDate
```
```


Question:
I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like:

mvn install -Dmaven.repository=http://example.com/maven2

The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle.

Answer:
I am not sure if you can do it using the command line. You can on the other hand add repositories in the
pom.xml
as in the following example. Using this approach you do not need to change the
~/.m2/settings.xml
file.
```
```
<?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ...
    <repositories>
            <repository>
                <id>MavenCentral</id>
                <name>Maven repository</name>
                <url>http://repo1.maven.org/maven2</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>
...
            <repository>
                <id>Codehaus Snapshots</id>
                <url>http://snapshots.repository.codehaus.org/</url>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
                <releases>
                    <enabled>false</enabled>
                </releases>
            </repository>
        </repositories>

    ...

        <pluginRepositories>
            <pluginRepository>
                <id>apache.snapshots</id>
                <name>Apache Snapshot Repository</name>
                <url>
                    http://people.apache.org/repo/m2-snapshot-repository
                </url>
                <releases>
                    <enabled>false</enabled>
                </releases>
            </pluginRepository>
            <pluginRepository>
                <id>Codehaus Snapshots</id>
                <url>http://snapshots.repository.codehaus.org/</url>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
                <releases>
                    <enabled>false</enabled>
                </releases>
            </pluginRepository>
        </pluginRepositories>

    ...

    </project>
```
```


Question:
Does anyone know of a good code obsfucator for Perl? I'm being ask to look into the option of obsfucating code before releasing it to a client. I know obsfucated code can still be reverse engineered, but that's not our main concern.

Some clients are making small changes to the source code that we give them and it's giving us nightmares when something goes wrong and we have to fix it, or when we release a patch that doesn't work with what they've changed. So the intention is just to make it so that it's difficult for them to make their own changes to the code(they're not supposed to be doing that anyway).

Answer:
Please don't do that. If you don't want people to alter your Perl code then put it under an appropriate licence and enforce that licence. If people change your code when you licence says that they shouldn't do that, then it's not your problem when your updates not longer work with their installation.
See
perlfaq3's answer to "How Can I hide the source for my Perl programs?
for more details.


Question:
Maven spews out far too many lines of output to my taste (I like the Unix way: no news is good news).

I want to get rid of all [INFO] lines, but I couldn't find any mention of an argument or config settings that controls the verbosity of Maven.

Is there no LOG4J-like way to set the log level?

Answer:
You can try the
```
-q
```
switch
.
```
-q
```
,
```
--quiet
```
Quiet output - only show errors


Question:
I can make Firefox not display the ugly dotted focus outlines on links with this:

a:focus {
    outline: none;
}

But how can I do this for <button> tags as well? When I do this:

button:focus {
    outline: none;
}

the buttons still have the dotted focus outline when I click on them.

(and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots)

Answer:
There's no way to remove these dotted focus in Firefox using CSS.
If you have access to the computers where your webapplication works, go to about:config in Firefox and set
```
browser.display.focus_ring_width
```
to 0. Then Firefox won't show any dotted borders at all.
The following bug explains the topic:
https://bugzilla.mozilla.org/show_bug.cgi?id=74225


Question:
I want to compress some files (into the ZIP format) and encrypt them if possible using C#. Is there some way to do this?

Can encryption be done as a part of the compression itself?

Answer:
For compression, look at the
```
System.IO.Compression
```
namespace and for encryption look at
```
System.Security.Cryptography
```
.


Question: What is the difference, what is the official terms, are any terms obsolete in ASP.NET 3.5?

Answer:
UserControl
:  A custom control, ending in .ascx, that is composed of other web controls.  Its almost like a small version of an aspx webpage.  It consists of a UI (the ascx) and codebehind.  Cannot be reused in other projects by referencing a DLL.
WebControl
:  A control hosted on a webpage or in a UserControl.  It consists of one or more classes, working in tandem, and is hosted on an aspx page or in a UserControl.  WebControls don't have a UI "page" and must render their content directly.  They can be reused in other applications by referencing their DLLs.
RenderedControl
:  Does not exist.  May be synonymous to WebControl.  Might indicate the control is written directly to the HttpResponse rather than rendered to an aspx page.
CompositeControl
:  Inbetween UserControls and WebControls.  They code like UserControls, as they are composed of other controls.  There is not any graphical UI for control compositing, and support for UI editing of CompositeControls must be coded by the control designer.  Compositing is done in the codebehind.  CompositeControls can be reused in other projects like WebControls.


Question: Can you suggest a tool for testing accessibility and section 508/ADA compliance of a Website with MS Share Point and .Net 2.0 as the underlying platform?

Answer:
In my experience, testing Sharepoint for accessibility is not worth it. Even if you've used the Accessibility Toolkit for Sharepoint (AKS) with Sharepoint 2007, the end result is far from accessible.
The trouble is that accessibility was not, and still is not a big consideration for MS when they made Sharepoint. Everything depends on table layout, and screenreaders are given a nightmare to deal with.
There are a few online tools - some will help validate your output, others pretend to test you for accessibility (
TAW
).
The problem is that many of the guidelines under WCAG are just too arbitrary, and will never be testable by an automated tool. This may change with WCAG 2.
Anyway, wish you the best trying to make Sharepoint accessible.
EDIT:
As a side not, I can highly recommend the following tools/resources for anyone interested in accessible development:
Chris Pederick's
Web Accessibility
Toolbar
NDA's Web Accessibility IT
Guidelines


Question: Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in Foo **) in C++?

Answer:
IMO most common usage is to pass reference to pointer variable
```
```
void test(int ** var)
{
 ...
}

int *foo = ...
test(&foo);
```
```
You can create multidimensional jagged array using double pointers:
```
```
int ** array = new *int[2];
array[0] = new int[2];
array[1] = new int[3];
```
```


Question:
What's the best value for money c# code protection? Some just use obfuscation, others add win32 wrapping, some cost a fortune. So far I've come up with http://www.eziriz.com/ who's Intellilock looks promising. Any other suggestions? Any reasons why this is not a good idea?

I know its impossible to completely protect but I'd prefer the ability to protect my code so that it would require a lot of effort in order to recover it. I do hope to sell my products eventually, while also releasing some for free.

Answer:
First of all, no matter what kind of protection you'll employ,a truly dedicated cracker will, eventually, get through all of the protective barriers. It might simply not worth it employing high-level code obfuscation; rather focus that time into making a better application.
One way to look at this problem, is that people pirating your software are not your target audience; focus on paying customers instead.
With that said, Visual Studio includes the community edition of
Dotfuscator
, which is fairly decent (for it's value); I would look into that, if needed.


Question: Using the Python Documentation I found the HTML parser but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).

Answer:
Try:
```
```
import HTMLParser
```
```
In Python 3.0, the HTMLParser module has been renamed to html.parser
you can check about this
here
Python 3.0
```
```
import html.parser
```
```
Python 2.2 and above
```
```
import HTMLParser
```
```


Question: How can I find the last row that contains data in a specific column and on a specific sheet?

Answer:
```
```
Function LastRow(rng As Range) As Long
    Dim iRowN As Long
    Dim iRowI As Long
    Dim iColN As Integer
    Dim iColI As Integer
    iRowN = 0
    iColN = rng.Columns.count
    For iColI = 1 To iColN
        iRowI = rng.Columns(iColI).Offset(65536 - rng.Row, 0).End(xlUp).Row
        If iRowI > iRowN Then iRowN = iRowI
    Next
    LastRow = iRowN
End Function
```
```


Question: Why can I not see an option for copying database objects when I right click > tasks on my database?

Answer:
MS Sql Server Express doesn't come with SSIS which is what you will need to import/export objects out of your database.
You can also manually script this process. One way is to use BCP (
http://msdn.microsoft.com/en-us/library/ms162802.aspx
)


Question:
I'm currently writing a TYPO3 extension which is configured with a list of tt_content UID's.
These point to content elements of type "text" and i want to render them by my extension.

Because of TYPO3s special way of transforming the text you enter in the rich text editing when it enters the database, and again transforming it when it is rendered to the frontend, i can not just output the database contents of the bodytext field.

I want to render these texts as they would usually get rendered by TYPO3.
How do I do that?

Answer:
I had the same problem a couple of months ago. Now I must say that I am no typo3 developer, so I don't know if this is the right solution.
But I used something like this:
```
$output .= $this->pi_RTEcssText( $contentFromDb );
```
in my extension and it works.


Question:
I am using a .NET Windows Forms DataGridView and I need to edit a DataBound column (that binds on a boolean DataTable column). For this I specify the cell template like this:

DataGridViewColumn column = new DataGridViewColumn(new DataGridViewCheckBoxCell());

You see that I need a CheckBox cell template.

The problem I face is that this column is constantly readonly/disabled, as if it would be of TextBox type. It doesn't show a checkbox at all.

Any thoughts on how to work with editable checkbox columns for DataGridView?

Update: For windows forms, please.

Thanks.

Answer:
Create a TemplateField and bound the id to it, something like this:
```
```
<asp:TemplateField HeaderText="Whatever" SortExpression="fieldname" ItemStyle-HorizontalAlign="Center">
    <ItemTemplate>
        <asp:CheckBox runat="server" ID="rowCheck" key='<%# Eval("id") %>' />
    </ItemTemplate>
</asp:TemplateField>
```
```


Question:
How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.

I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it.

Answer:
See this CodeProject article for the win32 basics :
http://www.codeproject.com/KB/threads/pausep.aspx
.  This sample code makes use of the ToolHelp32 library from the SDK, so I would recommend turning this sample code into an unmanaged C++/CLI library with a simple interface like "SuspendProcess(uint processID).
Process.Start will return you a Process object, from which you can get the process id, and then pass this to your new library based on the above.
Dave


Question:
Is it possible to have one application binary build for multiple mobile devices (on BREW platform), rather than making a separate build for each device using build script with conditional compilation.

In particular is is possible to use single BREW application build for multiple screen resolutions?

Note that the goal is to have a single binary build. If it would be just to have a single codebase, than conditional compilation and smart build script would do the trick.

Answer:
Yes, it is possible, we were able to do this at my previous place of work. What's required is tricky though:
Compile for the lowest common denominator BREW version. Version 1.1 is the base for all current handsets out there.
Your code must be able to handle multiple resolutions. The methods for detecting screen width and height are accurate for all handsets in my experience.
All your resources must load on all devices. This would require making your own custom image loader to work around certain device issues. For sound, I know simple MIDI type 0 works on all but QCP should also work (no experience of it myself).
Use bitmap fonts. There are too many device issues with fonts to make it worthwhile using the system fonts.
Design your code structure as a finite state machine. I cannot emphasise this enough - do this and many, many problems never materialise.
Have workarounds for every single device issue. This is the hard part! It's possible but this rabbit hole is incredibly deep...
In the end, the more complex and advanced the application, the less likely you can go this route. Some device properties simply cannot be detected reliably at runtime (such as platform ID) and so multiple builds are then required.


Question:
I am using git on a project, that generates lots of data-files (simulation-results).
I am "forced" to version and track all those results in the same repository. (This is a hard requirement and can not be changed)

However I don't need them. We have about 50 MB for the project and 5 GB results in the repository.

Is it feasible for me to create a branch, delete all the results, check this branch out and only work on that branch?

How hard would it be (what would I have to do), to push my local changes back into the fat branch?

Is there a better solution to get rid of those 5 GB for my work?

Answer:
If you were to make a branch and delete the result files from the branch, then merging your branch back into master would also try to delete the results from master. A file delete is a change just like any other.
Perhaps you could use the git submodule support to manage your code changes as a submodule of the fat repository. In this way, the fat repository would appear to contain everything, but you could work on just the small code bits independently. This may take some fiddling around to work smoothly.


Question:
I'm trying to replace each , in the current file by a new line:

:%s/,/\n/g

But it inserts what looks like a ^@ instead of an actual newline. The file is not in DOS mode or anything.

What should I do?

If you are curious, like me, check the question Why is \r a newline for Vim? as well.

Answer:
Use
```
\r
```
instead of
```
\n
```
.
Substituting by
```
\n
```
inserts a null character into the text. To get a newline, use
```
\r
```
. When
searching
for a newline, you’d still use
```
\n
```
, however. This asymmetry is due to the fact that
```
\n
```
and
```
\r
```
do slightly different things
:
```
\n
```
matches an end of line (newline), whereas
```
\r
```
matches a carriage return. On the other hand, in substitutions
```
\n
```
inserts a null character whereas
```
\r
```
inserts a newline (more precisely, it’s treated as the input
CR
). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it).
```
xxd
```
shows a hexdump of the resulting file.
```
```
echo bar > test
(echo 'Before:'; xxd test) > output.txt
vim test '+s/b/\n/' '+s/a/\r/' +wq
(echo 'After:'; xxd test) >> output.txt
more output.txt
```
```
```
```
Before:
0000000: 6261 720a                                bar.
After:
0000000: 000a 720a                                ..r.
```
```
In other words,
```
\n
```
has inserted the byte 0x00 into the text;
```
\r
```
has inserted the byte 0x0a.


Question:
I have PHP configured so that magic quotes are on and register globals are off.

I do my best to always call htmlentities() for anything I am outputing that is derived from user input.

I also occasionally seach my database for common things used in xss attached such as...

<script

What else should I be doing and how can I make sure that the things I am trying to do are always done.

Answer:
Escaping all user input is enough for most sites. Also make sure that session IDs don't end up in the URL so they can't be stolen from the
```
Referer
```
link to another site. Additionally, if you allow your users to submit links, make sure no
```
javascript:
```
protocol links are allowed; these would execute a script as soon as the user clicks on the link.


Question:
I'm making a method combining Scrum with the OpenUP lifecycle and deliverables. I also want to keep the OpenUP disciplines apart from "Project Management".  I can "hide" it so that it's not immediately obvious in my generated method site. But when you then navigate to the "Risk List" artefact for example the PM is still seen as contributing, and if you click on the link, you get taken to the PM Discipline page.

How can I remove it completely from my method without deleting it from the OpenUP library which I'm consuming?

Answer:
I've never used EPF Composer.
I did a little bit of google searches and I understand what you are looking for can be done through Configurations (select OpenUP in your Library view) and published View definitions.
See slide 83 and 84 of this PPT document. You should be able to take it from there.
An Introduction to the Eclipse Process Framework
.
In case the link does not work, I searched for "EPF Composer" "Standard categories" on google and the document is at the bottom of the first results page.
Good luck.


Question:
I'm not sure if many people know about this text-editor?

jEdit was kinda big in 2004, but now, Notepad++ seems to have taken the lead(on Windows)
Many of the plugins haven't been updated since 2003 and the overal layout and usage is confusing...

I'm sure jEdit has many nifty features, but I'll be damned if I can find out where to find them and how to use them. Reading that manual is a fulltime job on it's own.

Answer:
I had to use during my vocational education for XML and XSLT. It had a lot of bugs and didn't work always. I couldn't get to like it, but if I had to test some XSLT I'd give it another shot. I found Notepad++ and I am more than happy with it for what I need.
To your question: Did you take a look at
jEdit's plugin list
? There are some plugins released 2008 and the latest version was released on 8th August 2008.


Question:
Given a table of votes (users vote for a choice, and must supply an email address):

votes
--
id: int
choice: int
timestamp: timestamp
ip: varchar
email: varchar

What's the best way to count "unique" votes (a user being a unique combination of email + ip) given the constraint they may only vote twice per hour?

It's possible to count the number of hours between first and last vote and determine the maximum number of allowed votes for that timeframe, but that allows users to compress all their votes into say, a single hour-long window, and still have them counted.

I realize anonymous online voting is inherently flawed, but I'm not sure how to do this with SQL. Should I be using an external script or whatever instead? (For each choice, for each email+ip pair, get a vote, calculate the next +1h timestamp, count/discard/tally votes, move on to the next hour, etc...)

Answer:
Something like
```
```
select email, ip, count(choice)
from votes
group by email, ip, datepart(hour, timestamp)
```
```
If I understand correctly


Question:
From question How to replace a character for a newline in Vim?. You have to use \r when replacing text for a newline, like this

:%s/%/\r/g

But when replacing end of lines and newlines for a character, you can do it like:

:%s/\n/%/g

What section of the manual documents these behaviors, and what's the reasoning behind them?

Answer:
```
:help NL-used-for-Nul
```
Technical detail:
```
<Nul>
```
characters in the file are stored as
```
<NL>
```
in memory. In the display
  they are shown as "
```
^@
```
".  The translation is done when reading and writing
  files.  To match a
```
<Nul>
```
with a search pattern you can just enter
CTRL-@
or
  "
CTRL-V
000".  This is probably just what you expect.  Internally the
  character is replaced with a
```
<NL>
```
in the search pattern.  What is unusual is
  that typing
CTRL-V
CTRL-J
also inserts a
```
<NL>
```
, thus also searches for a
```
<Nul>
```
in the file.  {Vi cannot handle
```
<Nul>
```
characters in the file at all}


Question:
I want to disable the selection of certain rows in a datagridview.

It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition)

Thankx,

Answer:
If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected.
If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell.
Here's an example:
```
```
public class MyDataGridView : DataGridView
{
    protected override void SetSelectedRowCore(int rowIndex, bool selected)
    {
        if (selected && WantRowSelection(rowIndex))
        {
            base.SetSelectedRowCore(rowIndex, selected);
        }
     }

     protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)
     {
         if (selected && WantRowSelection(rowIndex))
         {
            base.SetSelectedRowCore(rowIndex, selected);
          }
     }

     bool WantRowSelection(int rowIndex)
     {
        //return true if you want the row to be selectable, false otherwise
     }
}
```
```
If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class.


Question:
I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up?

class MyControl : System.Web.UI.UserControl {
  // Attribute to prevent property from showing in VS Property Window?
  public bool SampleProperty { get; set; }

  // other stuff
}

Answer:
Use the following attribute ...
```
```
using System.ComponentModel;

[Browsable(false)]
public bool SampleProperty { get; set; }
```
```
In VB.net, this
will be
:
```
```
<System.ComponentModel.Browsable(False)>
```
```


Question:
I have created a namespace extension that is rooted under Desktop. The main purpose of the extension is to provide a virtual list of ZIP files that represent a list of configurable directories. When the user clicks one of the those items the contents of the related directory are zipped in place and the resulting ZIP file is stored in a cache folder.

All this works well aside a minor issue. If we go to Windows Explorer, open the extension and double click an item the opened file is the one from the cache. [CORRECT]

If on the other hand we open it by an Open Dialog the opened file is one from a Temporary Internet files directory. [INCORRECT]

What do I have to change for the Open Dialog (when used for example trough notepad.exe) to open the file from the cache folder and not from Temporary Internet files. I have tried to send allways the qualified file name in IShellFolder::GetDisplayNameOf but without any luck.

Answer:
What would be wrong with doing something like the following:
Defining a 'Maintainer' interface with the addListener(Listener, Enum) method.
Create a DefaultMaintainer class (as above) which implements Maintainer.
Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer.
other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :)


Question:
The win32.perl.org web site provides references to several Perl distributions for MS Windows.

For a long time I have been using ActivePerl from
ActiveState but recently I switched to
Strawberry Perl.

IMHO The only advantage that Active Perl still has over Strawberry Perl is the fact that it comes with Perl Tk which means its easy to install
Devel::ptkdb the graphical debugger. Other than that, I think Strawberry Perl has all the advantages.

Answer:
Strawberry Perl
is just getting better and better.  One problem I've repeatedly had with ActiveState is that my modules sometimes fail to install because I need an upgrade to a core module, but they won't allow that.  Thus, everybody who
doesn't
use Windows can use my code, but they can't do that with ActiveState's Perl.
ActiveState also has a very dodgy build system which often fails to report exactly why a module failed to build.  I got so tired of emailing and asking for this information that I eventually gave up.  I want my code to run on Windows, but if ActiveState doesn't provide me with that information and doesn't give me any option for upgrading core modules, I just can't use it.  Some of my modules have NO build failures on any operating system -- except those with ActiveState Perl.  Support Strawberry Perl and just don't worry about ActiveState.
If ActiveState has fixed their build system and their 'no upgrade to core modules' policy, it's worth revisiting.


Question:
I have just found a static nested interface in our code-base.

class Foo {
    public static interface Bar {
        /* snip */
    }
    /* snip */
}

I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:

What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?

Answer:
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with
```
Foo.Bar
```
, like so:
```
```
public class Baz implements Foo.Bar {
   ...
}
```
```
In most ways, this isn't different from a static inner class.


Question:
I have an ASP.Net 2.0 application in which the Session_Start event is not firing in my Global.asax file. Can anyone tell why this is happening and how I can get it working?

The application worked fine on my Windows XP development machine, but stopped working when deployed to the server (Win Server 2003/IIS 6/ASP.Net 2.0).

I'm not sure if this is relevant, but the server also hosts a SharePoint installation (WSS 3.0) which I know does change some settings at the default web site level.

Answer: Are you sure the website in IIS is set to use ASP.NET 2.0 rather than 1.1?


Question: Is there an api to bring the vista side bar to the front (Win+Space) programatically and to do the reverse (send it to the back ground).

Answer:
Probably using SetWindowPos you can change it to be placed the top / bottom of the z-order or even as the top-most window. You would need to find the handle to the sidebar using FindWindow or an application like WinSpy.
But after that something like.
Sets the window on top, but not top most.
```
```
SetWindowPos(sidebarHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE);
```
```
Sets the window at the bottom.
```
```
SetWindowPos(sidebarHandle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE);
```
```
This is my best guess on achieving what you asked, hopefully it helps.


Question:
I've been using OpenGL for years, but after trying to use D3D for the first time, I wasted a significant amount of time trying figure out how to make my scene lights stay fixed in the world rather than fixed on my objects.

In OpenGL light positions get transformed just like everything else with the MODELVIEW matrix, so to get lights fixed in space, you set up your MODELVIEW the way you want for the lights, and call glLightPosition then set it up for your geometry and make geometry calls.   In D3D that doesn't help.

(Comment -- I eventually figured out the answer to this one, but I couldn't find anything helpful on the web or in the MSDN.  It would have saved me a few hours of head scratching if I could have found this answer then.)

Answer:
The answer I discovered eventually was that while OpenGL only has its one amalgamated
```
MODELVIEW
```
matrix, in D3D the "world" and "view" transforms are kept separate, and placing lights seems to be the major reason for this.  So the answer is you use
```
D3DTS_VIEW
```
to set up matrices that should apply to your lights, and
```
D3DTS_WORLD
```
to set up matrices that apply to the placement of your geometry in the world.
So actually the D3D system kinda makes more sense than the OpenGL way.  It allows you to specify your light positions whenever and wherever the heck you feel like it once and for all, without having to constantly reposition them so that they get transformed by your  current "view" transform.  OpenGL has to work that way because it simply doesn't know what you think your "view" is vs your "model".  It's all just a modelview to GL.
(Comment - apologies if I'm not supposed to answer my own questions here, but this was a real question that I had a few weeks ago and thought it was worth posting here to help others making the shift from OpenGL to D3D.  Basic overviews of the D3D lighting and rendering pipeline seem hard to come by.)


Question: How effective is merging when folders and projects have been renamed in your solution?

Answer:
In my experience TFS can track renames, as long as you do all the renaming within the SourceControlExplorer (TFS).
The problems tend to occur when you have other people making changes to the original files while someone else is doing massive renames/moves, while someone else is editing the renamed version.
Where possible I would say that if you are doing large scale renaming and moving it is worth informing team mates, and if possible get them to hold off making changes until you've checked yours in.
As with all branch/merge issues the problem is greatly reduced by checking in and merging little and often.


Question:
in our application we have a Java applet running inside a .NET browser control. It is a know issue from Sun that running an applet this way may crash the control.

Has anyone come across the same problem and solved it?

Atm we are running the applet in a Webbrowser but we need to run it in a browser control.

Thx for any help.

Answer:
If you wrote the applet and have source, then you could try to migrate the Java Applet to a J# Browser control and stuff that in your .net application.
```
```
Here is a link - http://msdn.microsoft.com/en-us/library/aa290083(VS.71).aspx
```
```


Question:
In Delphi, I want to be able to create an private object that's associated with a class, and access it from all instances of that class.  In Java, I'd use:

public class MyObject {
    private static final MySharedObject mySharedObjectInstance = new MySharedObject();
}

Or, if MySharedObject needed more complicated initialization, in Java I could instantiate and initialize it in a static initializer block.

(You might have guessed...  I know my Java but I'm rather new to Delphi...)

Anyway, I don't want to instantiate a new MySharedObject each time I create an instance of MyObject, but I do want a MySharedObject to be accessible from each instance of MyObject.  (It's actually logging that has spurred me to try to figure this out - I'm using Log4D and I want to store a TLogLogger as a class variable for each class that has logging functionality.)

What's the neatest way to do something like this in Delphi?

Answer:
Before version 7, Delphi didn't have static variables, you'd have to use a global variable.
To make it as private as possible, put it in the
```
implementation
```
section of your unit.


Question:
I have to read data from some files and insert the data into different tables in a database. Is Unix shell script powerful enough to do the job?

Is it easy to do the job in shell script or should I go about doing this in Java?

Answer:
Can't test it right now, but something like:
```
```
echo "INSERT INTO foo (b,a,r) VALUES (1,2,3);" |
    mysql -u user -psecret -h host database
```
```
in a shell script should work. Don't know about getting Data out of it though


Question:
The problem: I have a class which contains a template method execute which calls another method _execute. Subclasses are supposed to overwrite _execute to implement some specific functionality. This functionality should be documented in the docstring of _execute.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use execute, so he won't see the correct docstring if he uses help(execute).

Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of execute is automatically replaced with that of _execute. Any ideas how this might be done?

I was thinking of metaclasses to do this, to make this completely transparent to the user.

Answer:
Well the doc-string is stored in
```
__doc__
```
so it wouldn't be too hard to re-assign it based on the doc-string of
```
_execute
```
after the fact.
Basically:
```
```
```
class MyClass(object):
    def execute(self):
        '''original doc-string'''
        self._execute()

class SubClass(MyClass):
    def _execute(self):
        '''sub-class doc-string'''
        pass

    # re-assign doc-string of execute
    def execute(self,*args,**kw):
        return MyClass.execute(*args,**kw)
    execute.__doc__=_execute.__doc__
```
Execute has to be re-declared to that the doc string gets attached to the version of execute for the
```
SubClass
```
and not for
```
MyClass
```
(which would otherwise interfere with other sub-classes).
That's not a very tidy way of doing it, but from the POV of the user of a library it should give the desired result.  You could then wrap this up in a meta-class to make it easier for people who are sub-classing.


Question: Does anyone know if the Infragistics UltraGrid control provides functionality similar to that of DataGridView.HitTestInfo?

Answer:
There's a
```
.MousePosition
```
property which returns
```
System.Drawing.Point
```
and "Gets the position of the mouse cursor in screen coordinates" but I'm using an older version of their UltraWinGrid (2003).
They have a
free trial download
, so you could see if they've added it to their latest and greatest  :o)


Question: Anyone know uf there's a dll/runner anywhere that returns TAP output from an NUnit test suite?

Answer: Seems unlikely to me, since there is an impedance mismatch. TAP has no concept for what NUnit calls a test, and what TAP calls a test usually corresponds to an NUnit assertion, but not precisely. So I’m not sure how the thing you’re looking for would work at all. (But maybe a heuristic could work well enough.)


Question:
I'm using an Xml field in my Sql Server database table. I'm trying to search a word using the XQuery contains method but it seems to search only in case sensitive mode. The lower method isn't implemented on Sql Server XQuery implementation also.
¿Is there a simple solution to this problem?

Answer:
First
link from google points to MSDN page:
contains Function (XQuery)
In order to get case-insensitive
  comparisons, the
upper-case
or
  lower-case functions can be used.


Question:
I'm missing the boat on something here, kids.  This keeps rearing its head and I don't know what's going on with it, so I hope my homeys here can help.

When working in Silverlight, when I create bindings in my c# code, they never hold up when the application is running.  The declarative bindings from my xaml seem ok, but I'm doing something wrong when I create my bindings in C#.  I'm hoping that there is something blindingly obvious I'm missing.  Here's a typical binding that gets crushed:

TextBlock tb = new TextBlock();
Binding b = new Binding("FontSize");
b.Source = this;
tb.SetBinding(TextBlock.FontSizeProperty, b);

Answer:
I've just tried the exact code you just posted and it worked fine, with some changes. I believe the problem is the element you are using for the SetBinding call is not the textblock you want to bind. It should be:
```
```
TextBlock tb = new TextBlock();
Binding b = new Binding("FontSize");
b.Source = this;
tb.SetBinding(TextBlock.FontSizeProperty, b);
```
```
Make sure you also have a FontSize public property of type double on "this". If "this" is a user control, I would recommend renaming the property so you don't hide the inherited member.


Question:
I am using <input type="file" id="fileUpload" runat="server"> to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions).

Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).

Answer:
Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-back.
I think you may be able to do it on the client using JavaScript.  Personally, I use a third party component called
radUpload by Telerik
.  It has a good client-side and server-side API, and it provides a progress bar for big file uploads.
I'm sure there are open source solutions available, too.


Question:
I find I can do more with NHibernate, and even Castle than with the Linq to Entities, or linq to SQL.

Am I crazy?

Answer:
No you're not crazy. nHibernate is a full OR Mapper, Linq to SQL and Linq to Entities don't implement everything you'd expect from an OR mapper and targeted at a slightly different group of developers.
But don't let that put you off linq though. Linq is still a pretty good idea.. Try Linq to nHibernate :-)


Question:
Given the following example, why do I have to explicitly use the statement b->A::DoSomething() rather than just b->DoSomething()?

Shouldn't the compiler's overload resolution figure out which method I'm talking about?

I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)

class A
{
  public:
    int DoSomething() {return 0;};
};

class B : public A
{
  public:
    int DoSomething(int x) {return 1;};
};

int main()
{
  B* b = new B();
  b->A::DoSomething();    //Why this?
  //b->DoSomething();    //Why not this? (Gives compiler error.)
  delete b;
  return 0;
}

Answer:
The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done
afterwards
. In your case this means that the compiler sees
```
B::DoSomething
```
. It then tries to match the argument list, which fails.
One solution would be to pull down the overload from
```
A
```
into
```
B
```
's scope:
```
```
class B : public A {
public:
    using A::DoSomething;
    // …
}
```
```


Question:
What are some important practices to follow when creating a .NET assembly that is going to be embedded to SQL Server 2005?

I am brand new to this, and I've found that there are significant method attributes like:

[SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "letter nchar(1)")]

I'm also looking for common pitfalls to avoid, etc.

Answer:
Some that I remember:
Keep its usage to a minimum, only use it when T-SQL proved too complex.
Avoid pointers/cursors at all costs because a for loop is so easily abusable in CLR context.
Only use the SQL-Server native data types unless totally necessary.
Can't remember where I've found the information, but those are some that I do remember.
Basically, only use it when declarative T-SQL is too complex or is impossible to do (such as registry editing etc.).


Question: I want to create cursor rsrc files on the Mac from png files. The application that uses the cursors requires it to be in a .rsrc format and I cannot change that. Does anybody know of any way I can create the cursor .rsrc files from png images.

Answer:
Its been a long time since I've thought about MacOS resource forks. Are you using the classic MacOS (i.e. before MacOS X)?
As I recall,
ResEdit
was the application most often used to manipulate the resource fork of a classic Mac application. I know it can edit cursor resources, but I don't recall if it can read PNG files. You may need to convert the files to GIF.
ResEdit is a Classic MacOS application. MacOS X prior to 10.5 could run Classic apps in emulation, but in 10.5 this support has been removed. You'd need to find a system either running the classic MacOS directly, or running 10.4 with Classic installed.


Question: I would like to have a Guile script, which implements functions, which output test result messages according to the TAP protocol.

Answer:
The following script, to be named guiletap.scm, implements the frequently-needed functions for using the TAP protocol when running tests.
```
; Define functions for running Guile-written tests under the TAP protocol.
; Copyright © 2008 by Omer Zak
; Released under the GNU LGPL 2.1 or (at your option) any later version.
;;;
;;; To invoke it:
;;; (use-modules (guiletap))
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-module (guiletap))
(export plan)
(export ok)
(export bail_out)
(export diag)
(export is_ok)

(use-modules (ice-9 format))

; n is the number of tests.
(define plan
  (lambda (n) (display (format "1..~d~%" n))))

; n -        test number
; testdesc - test descriptor
; res -      result which is #f at failure, other at success.
(define ok
  (lambda (n testdesc res)
    (if (not res)(display "not "))
    (display (format "ok ~d - ~a~%" n testdesc))))

; testdesc - test descriptor
(define bail_out
  (lambda (testdesc)
    (display (format "Bail out! - ~a~%" testdesc))))

; diagmsg - diagnostic message
(define diag
  (lambda (diagmsg)
    (display (format "# ~a~%" diagmsg))))

; n -        test number
; testdesc - test descriptor
; expres -   expected test result
; actres -   actual test result
(define is_ok
  (lambda (n testdesc expres actres)
    (ok n testdesc (equal? expres actres))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; !!! TODO:
; !!! To be implemented also:
; plan_no_plan
; plan_skip_all [REASON]
;
; is RESULT EXPECTED [NAME]
; isnt RESULT EXPECTED [NAME]
; like RESULT PATTERN [NAME]
; unlike RESULT PATTERN [NAME]
; pass [NAME]
; fail [NAME]
;
; skip CONDITION [REASON] [NB_TESTS=1]
; Specify TODO mode by setting $TODO:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; End of guiletap.scm
```


Question:
I'm trying to modify my GreaseMonkey script from firing on window.onload to window.DOMContentLoaded, but this event never fires.

I'm using FireFox 2.0.0.16 / GreaseMonkey 0.8.20080609

This is the full script that I'm trying to modify, changing:

window.addEventListener ("load", doStuff, false);

to

window.addEventListener ("DOMContentLoaded", doStuff, false);

Answer:
So I googled
greasemonkey dom ready
and the
first result
seemed to say that the greasemonkey script is actually running at "DOM ready" so you just need to remove the onload call and run the script straight away.
I removed the
```
window.addEventListener ("load", function() {
```
and
```
}, false);
```
wrapping and it worked perfectly. It's
much
more responsive this way, the page appears straight away with your script applied to it and all the unseen questions highlighted, no flicker at all. And there was much rejoicing.... yea.


Question:
Let me use the following example to explain my question:

public string ExampleFunction(string Variable) {
    return something;
}

string WhatIsMyName = "Hello World";
string Hello = ExampleFunction(WhatIsMyName);

When I pass the variable WhatIsMyName to the ExampleFunction, I want to be able to get a string of the original variable's name. Perhaps something like:

Variable.OriginalName.ToString() // == "WhatIsMyName"

Is there any way to do this?

Answer:
No.
I don't think so.
The variable name that you use is for your convenience and readability. The compiler doesn't need it & just chucks it out if I'm not mistaken.
If it helps, you could define a new class called
```
NamedParameter
```
with attributes
```
Name
```
and
```
Param
```
. You then pass this object around as parameters.


Question:
Using C++ (and Qt), I need to process a big amount of 3D coordinates.

Specifically, when I receive a 3D coordinate (made of 3 doubles), I need to check in a list if this coordinate has already been processed.
If not, then I process it and add it to the list (or container).

The amount of coordinates can become very big, so I need to store the processed coordinates in a container which will ensure that checking if a 3D coordinate is already contained in the container is fast.

I was thinking of using a map of a map of a map, storing the x coordinate, then the y coordinate then the z coordinate, but this makes it quite tedious to use, so I'm actually hoping there is a much better way to do it that I cannot think of.

Answer:
Well, it depends on what's most important... if a tripple map is too tedious to use, then is implementing other data structures not worth the effort?
If you want to get around the uglyness of the tripple map solution, just wrap it up in another container class with an access function with three parameter, and hide all the messing around with maps internally in that.
If you're more worried about the runtime performance of this thing, storing the coordinates in an
Octree
might be a good idea.
Also worth mentioning is that doing these sorts of things with floats or doubles you should be very careful about precision -- if (0, 0, 0.01) the same coordinate as (0, 0, 0.01000001)? If it is, you'll need to look at the comparison functions you use, regardless of the data structure. That also depends on the source of your coordinates I guess.


Question:
How can I construct a MSBuild ItemGroup to exclude .svn directories and all files within (recursively). I've got:

<ItemGroup>
     <LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*" Exclude=".svn" />
</ItemGroup>

At the moment, but this does not exclude anything!

Answer:
Thanks for your help, managed to sort it as follows:
```
```
<ItemGroup>
     <LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*"
                   Exclude="$(LibrariesReleaseDir)\**\.svn\**" />
</ItemGroup>
```
```
Turns out the pattern matching basically runs on files, so you have to exclude everything BELOW the
```
.svn
```
directories (
```
.svn\\**
```
) for MSBuild to exclude the
```
.svn
```
directory itself.


Question:
We have hundreds of websites which were developed in asp, .net and java and we are paying lot of money for an external agency to do a penetration testing for our sites to check for security loopholes.
Are there any (good) software (paid or free) to do this?

or.. are there any technical articles which can help me develop this tool?

Answer: I've heard good things about SpiDynamics WebInspect as far as paid solutions go, as well as Nikto (for a free solution) and other open source tools. Nessus is an excellent tool for infrastructure in case you need to check that layer as well. You can pick up a live cd with several tools on it called Nubuntu (Auditor, Helix, or any other security based distribution works too) and then Google up some tutorials for the specific tool. Always, always make sure to scan from the local network though. You run the risk of having yourself blocked by the data center if you scan a box from the WAN without authorization. Lesson learned the hard way. ;)


Question:
How do I find out which sound files the user has configured in the control panel?

Example: I want to play the sound for "Device connected".

Which API can be used to query the control panel sound settings?

I see that there are some custom entries made by third party programs in the control panel dialog, so there has to be a way for these programs to communicate with the global sound settings.

Edit: Thank you. I did not know that PlaySound also just played appropriate sound file when specifying the name of the registry entry.

To play the "Device Conntected" sound:

::PlaySound( TEXT("DeviceConnect"), NULL, SND_ALIAS|SND_ASYNC );

Answer:
```
PlaySound
```
is the API.
Also see
Play System Sounds
.


Question:
I have a query that is dynamically built after looking up a field list and table name.  I execute this dynamic query inside a stored proc.  The query is built without a where clause when the two proc parameters are zero, and built with a where clause when not.

When I execute the proc with
    SET FMTONLY ON
    exec [cpExportRecordType_ListByExportAgentID] null, null
It returns no column information.  I have just now replaced building the query without a where clause to just executing the same query directly, and now I get column information.  I would love to know what causes this, anyone?

Answer:
Perhaps it is related to the fact that the passed parameters are NULL,
check how your query is build perhaps it behaves in different way then expected when you pass NULL.
Does you proc returns expected results when you call:
    SET FMTONLY OFF exec [cpExportRecordType_ListByExportAgentID] null, null
?
Other possibility:
I understand that you build your query dynamically by getting results from calling another queries to get the column names.
Perhaps the query that would normally give you the column names returns no data but only column information (SET FMTONLY ON) so you do not have data to build you dynamic query.


Question:
I'm a Java-developer toying with Ruby, and loving it. I have understood that because of Ruby's metaprogramming facilities my unit-tests become much cleaner and I don't need nasty mocking frameworks. I have a class which needs the File class's services and in my test I don't want to touch my real filesystem. In Java I would use some virtual file system for easier "seams" to pass fake-objects in but in Ruby that's obviously overkill. What I come up seems already really nice compared to the Java-world. In my class under test I have an optional constructor parameter:

def initialize(file_class=File)

When I need to open files within my class, I can then do this:

@file_class.open(filename)

And the call goes to either the real File-class, or in case of my unit-test, it goes to a fake-class which doesn't touch the filesystem. I know there must be a better way to do this with metaprogramming?

Answer:
Mocha (
http://mocha.rubyforge.org/
) is a very good mocking library for ruby.  Depending on what you're actually wanting to test (i.e. if you want to just fake out the File.new call to avoid the file system dependency or if you want to verify that the correct arguments are passed into File.new) you could do something like this:
```
```
require 'mocha'

mock_file_obj = mock("My Mock File") do
  stubs(:some_instance_method).returns("foo")
end

File.stubs(:new).with(is_a(String)).returns(mock_file_obj)
```
```


Question:
I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE.

What are the steps to create such an executable?

Answer:
Single Assembly Deployment of Managed and Unmanaged Code
Sunday, February 4, 2007
.NET developers love XCOPY deployment. And they love single assembly components. At least I always feel kinda uneasy, if I have to use some component and need remember a list of files to also include with the main assembly of that component. So when I recently had to develop a managed code component and had to augment it with some unmanaged code from a C DLL (thx to Marcus Heege for helping me with this!), I thought about how to make it easier to deploy the two DLLs. If this were just two assemblies I could have used ILmerge to pack them up in just one file. But this doesn´t work for mixed code components with managed as well as unmanaged DLLs.
So here´s what I came up with for a solution:
I include whatever DLLs I want to deploy with my component´s main assembly as embedded resources.
Then I set up a class constructor to extract those DLLs like below. The class ctor is called just once within each AppDomain so it´s a neglible overhead, I think.
```
```
namespace MyLib
{
    public class MyClass
    {
        static MyClass()
        {
            ResourceExtractor.ExtractResourceToFile("MyLib.ManagedService.dll", "managedservice.dll");
            ResourceExtractor.ExtractResourceToFile("MyLib.UnmanagedService.dll", "unmanagedservice.dll");
        }

        ...
```
```
In this example I included two DLLs as resources, one being an unmanaged code DLL, and one being a managed code DLL (just for demonstration purposes), to show, how this technique works for both kinds of code.
The code to extract the DLLs into files of their own is simple:
```
```
public static class ResourceExtractor
{
    public static void ExtractResourceToFile(string resourceName, string filename)
    {
        if (!System.IO.File.Exists(filename))
            using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
                {
                    byte[] b = new byte[s.Length];
                    s.Read(b, 0, b.Length);
                    fs.Write(b, 0, b.Length);
                }
    }
}
```
```
Working with a managed code assembly like this is the same as usual - almost. You reference it (here: ManagedService.dll) in your component´s main project (here: MyLib), but set the Copy Local property to false. Additionally you link in the assembly as an Existing Item and set the Build Action to Embedded Resource.
For the unmanaged code (here: UnmanagedService.dll) you just link in the DLL as an Existing Item and set the Build Action to Embedded Resource. To access its functions use the DllImport attribute as usual, e.g.
```
```
[DllImport("unmanagedservice.dll")] public extern static int Add(int a, int b);
```
```
That´s it! As soon as you create the first instance of the class with the static ctor the embedded DLLs get extracted into files of their own and are ready to use as if you deployed them as separate files. As long as you have write permissions for the execution directory this should work fine for you. At least for prototypical code I think this way of single assembly deployment is quite convenient.
Enjoy!
http://weblogs.asp.net/ralfw/archive/2007/02/04/single-assembly-deployment-of-managed-and-unmanaged-code.aspx


Question: Can anyone provide a good explanation of the volatile keyword in C#? Which problems does it solve and which it doesn't? In which cases will it save me the use of locking?

Answer:
The CLR likes to optimize instructions, so when you access a field in code it might not always access the current value of the field (it might be from the stack, etc). Marking a field as
```
volatile
```
ensures that the current value of the field is accessed by the instruction. This is useful when the value can be modified (in a non-locking scenario) by a concurrent thread in your program or some other code running in the operating system.
You obviously lose some optimization, but it does keep the code more simple.


Question: I'd like to add the HttpOnly flag to JSF/richfaces cookies, especially the session cookie, to up the level of security on my web app. Any ideas?

Answer:
Something like:
```
```
response.setHeader("Set-Cookie", "yourcookiename=yourcookievalue; HTTPOnly");
```
```
might work in a Java environment. I am not aware of a JSF-specific way to achieve this... sorry
This seems to be not an easy task in Java.


Question:
here is what a I'm doing:

object ReturnMatch(System.Type type)
{
    foreach(object obj in myObjects)
    {
        if (obj == type)
        {
            return obj;
        }
    }
}

However, if obj is a subclass of type, it will not match. But I would like the function to return the same way as if I was using the operator is.

I tried the following, but it won't compile:

if (obj is type) // won't compile in C# 2.0

The best solution I came up with was:

if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))

Isn't there a way to use operator is to make the code cleaner?

Answer:
Perhaps
```
```
type.IsAssignableFrom(obj.GetType())
```
```


Question:
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed:

result = re.match("a_regex_of_pure_awesomeness", "a string containing the awesomeness")
# result is None`

After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:

regex = ".*(a_regex_of_pure_awesomeness)"

into

regex = "a_regex_of_pure_awesomeness"

Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.

Answer:
Are you using the
```
re.match()
```
or
```
re.search()
```
method? My understanding is that
```
re.match()
```
assumes a "
```
^
```
" at the beginning of your expression and will only search at the beginning of the text, while
```
re.search()
```
acts more like the Perl regular expressions and will only match the beginning of the text if you include a "
```
^
```
" at the beginning of your expression. Hope that helps.


Question:
Is it possible in a large GWT project, load some portion of JavaScript lazy, on the fly?
   Like overlays.

PS: Iframes is not a solution.

Answer:
I think this is what you are looking for.
```
```
<body onload="onloadHandler();">
<script type="text/javascript">
function onloadHandler() {
    if (document.createElement && document.getElementsByTagName) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = './test.js';
        var heads = document.getElementsByTagName('head');
        if (heads && heads[0]) {
            heads[0].appendChild(script);
        }
    }
}
function iAmReady(theName) {
   if ('undefined' != typeof window[theName]) {
       window[theName]();
   }
}
function test() {
   // stuff to do when test.js loads
}
</script>
```
```
-- test.js
```
```
iAmReady('test');
```
```
Tested and working in Firefox 2, Safari 3.1.2 for Windows, IE 6 and Opera 9.52. I assume up-level versions of those should work as well.
Note that the loading is asynchronous. If you attempt to use a function or variable in the loaded file immediately after calling
```
appendChild()
```
it will most likely fail, that is why I have included a call-back in the loaded script file that forces an initialization function to run when the script is done loading.
You could also just call an internal function at the bottom of the loaded script to do something once it has loaded.


Question:
What does the volatile keyword do? In C++ what problem does it solve?

In my case, I have never knowingly needed it.

Answer:
```
volatile
```
is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the
```
volatile
```
keyword to ensure that such accesses aren't optimised away by the compiler.


Question:
I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid.

Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.

Answer:
```
volatile
```
is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the
```
volatile
```
keyword to ensure that such accesses aren't optimised away by the compiler.


Question: What's the best and/or fastest method of doing multijoin queries in Django using the ORM and QuerySet API?

Answer:
If you are trying to join across tables linked by ForeignKeys or ManyToManyField relationships then you can use the double underscore syntax. For example if you have the following models:
```
```
class Foo(models.Model):
    name = models.CharField(max_length=255)

class FizzBuzz(models.Model):
    bleh = models.CharField(max_length=255)

class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    fizzbuzz = models.ForeignKey(FizzBuzz)
```
```
You can do something like:
```
```
Fizzbuzz.objects.filter(bar__foo__name = "Adrian")
```
```


Question:
Can you use CMFCVisualManager with a dialog based application to change the applications appearance? If so how is it done?

The idea is to change the shape, colour etc. of controls such as push buttons using the MFC Feature Pack released with MSVC 2008.

Answer:
No, can't be done, at least not if you're talking about the Feature Pack version. Version 10 of the BCGSoft libraries do have this functionality, see for example:
http://www.bcgsoft.com/bcgcontrolbarpro-versions.htm
and
http://www.bcgsoft.com/images/SkinnedBuiltInDlgs.jpg
. The MFC feature pack is more or less the previous version of the BCGSoft libraries, MS bought a license from them.


Question:
I have a non-.Net executable file that is included in my .net assembly as an embedded resource.  Is there a way to run this executable that does not involve writing it out to disk and launching it?

This is .Net 2.0.

Answer:
You can load a .NET assembly from a byte array using an overload of
Assembly.Load
.
However, there are implications for the security model that need to be considered which make things more complex.  See the discussion
here
, and also this
thread
.
If your embedded executable is not .NET then I think you will have to write it out to disk  first.


Question:
I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, not a source code file -- but embed that file in the executable file like a resource.

(This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if it were for Windows.)

Is there any simple way to do it, or will it effectively require me to write my own resource system for Linux? (Easily possible, but it would take a lot longer.)

Answer:
Use macros. Technically that file would be
source code
file but it wouldn't look like this.
Example:
```
```
//queries.incl - SQL queries
Q(SELECT * FROM Users)
Q(INSERT [a] INTO Accounts)

//source.cpp
#define Q(query) #query,
char * queries[] = {
#include "queries.incl"
};
#undef Q
```
```
Later on you could do all sorts of other processing on that file by the same file, say you'd want to have array and a hash map of them, you could redefine Q to do another job and be done with it.


Question:
Has anyone written an 'UnFormat' routine for Delphi?

What I'm imagining is the inverse of SysUtils.Format and looks something like this

UnFormat('a number %n and another %n',[float1, float2]);

So you could unpack a string into a series of variables using format strings.

I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me.

Answer:
This is called scanf in C, I've made a Delphi look-a-like for this :
```
```
function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer;
var
  InputOffset: Integer;
  FormatOffset: Integer;
  InputChar: Char;
  FormatChar: Char;

  function _GetInputChar: Char;
  begin
    if InputOffset <= Length(Input) then
    begin
      Result := Input[InputOffset];
      Inc(InputOffset);
    end
    else
      Result := #0;
  end;

  function _PeekFormatChar: Char;
  begin
    if FormatOffset <= Length(Format) then
      Result := Format[FormatOffset]
    else
      Result := #0;
  end;

  function _GetFormatChar: Char;
  begin
    Result := _PeekFormatChar;
    if Result <> #0 then
      Inc(FormatOffset);
  end;

  function _ScanInputString(const Arg: Pointer = nil): string;
  var
    EndChar: Char;
  begin
    Result := '';
    EndChar := _PeekFormatChar;
    InputChar := _GetInputChar;
    while (InputChar > ' ')
      and (InputChar <> EndChar) do
    begin
      Result := Result + InputChar;
      InputChar := _GetInputChar;
    end;

    if InputChar <> #0 then
      Dec(InputOffset);

    if Assigned(Arg) then
      PString(Arg)^ := Result;
  end;

  function _ScanInputInteger(const Arg: Pointer): Boolean;
  var
    Value: string;
  begin
    Value := _ScanInputString;
    Result := TryStrToInt(Value, {out} PInteger(Arg)^);
  end;

  procedure _Raise;
  begin
    raise EConvertError.CreateFmt('Unknown ScanFormat character : "%s"!', [FormatChar]);
  end;

begin
  Result := 0;
  InputOffset := 1;
  FormatOffset := 1;
  FormatChar := _GetFormatChar;
  while FormatChar <> #0 do
  begin
    if FormatChar <> '%' then
    begin
      InputChar := _GetInputChar;
      if (InputChar = #0)
      or (FormatChar <> InputChar) then
        Exit;
    end
    else
    begin
      FormatChar := _GetFormatChar;
      case FormatChar of
        '%':
          if _GetInputChar <> '%' then
            Exit;
        's':
          begin
            _ScanInputString(Args[Result]);
            Inc(Result);
          end;
        'd', 'u':
          begin
            if not _ScanInputInteger(Args[Result]) then
              Exit;

            Inc(Result);
          end;
      else
        _Raise;
      end;
    end;

    FormatChar := _GetFormatChar;
  end;
end;
```
```


Question:
I have a svn repository, R, that depends on a library, l, in another repository.

The goal is that when someone checks out R, they also check out l. We want l to still be in its own repository so that l can be updated without dependence on R.

I don't know much about external svn links, but I believe that when depending on a svn-based library one can link to it externally, 'ext'.

If l is in a git repository, can I do something similar? I'd like to preserve the goal stated above.

Answer:
I suggest using a script wrapper for svn co.
```
```
#!/bin/sh
svn co path://server/R svn-R
git clone path://server/l git-l
```
```
Or similar.


Question: Is there an easy way to capitalize the first letter of a string and lower the rest of it?  Is there a built in method or do I need to make my own?

Answer:
```
TextInfo.ToTitleCase()
```
capitalizes the first character in each token of a string.
If there is no need to maintain Acronym Uppercasing, then you should include
```
ToLower()
```
.
```
```
string s = "JOHN DOE";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
// Produces "John Doe"
```
```
If CurrentCulture is unavailable, use:
```
```
string s = "JOHN DOE";
s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());
```
```
See the
MSDN Link
for a detailed description.


Question:
Imagine this directory structure:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py

I'm coding mod1, and I need to import something from mod2. How should I do it?

I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package".

I googled around but found only "sys.path manipulation" hacks. Isn't there a clean way?

Edit: all my __init__.py's are currently empty

Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (sub1, subX, etc.).

Edit3: The behaviour I'm looking for is the same as described in PEP 366 (thanks John B)

Answer:
Everyone seems to want to tell you what you should be doing rather than just answering the question.
The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.
From
PEP 328
:
Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
In Python 2.6, they're adding the ability to reference modules relative to the main module.
PEP 366
describes the change.
Update
: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.


Question: How can I redirect the response to an IFrame?

Answer: . . . not totally sure what your trying to do, but you normally control the source of an iframe through javascript


Question: Are there any programs or IDEs that support refactoring for Ruby or RoR?

Answer: I believe net-beans and eclipse both support some refactoring within their 'ruby-mode' - also the emacs code browser (ECB)  and the various ruby support tools (e.g. rinari) for emacs have some support.


Question: I have been researching asynchronous messaging, and I like the way it elegantly deals with some problems within certain domains and how it makes domain concepts more explicit. But is it a viable pattern for general domain-driven development (at least in the service/application/controller layer), or is the design overhead such that it should be restricted to SOA-based scenarios, like remote services and distributed processing?

Answer:
Great question :). The main problem with asynchronous messaging is that when folks use procedural or object oriented languages, working in an asynchronous or event based manner is often quite tricky and complex and hard for the programmer to read & understand. Business logic is often way simpler if its built in a kinda synchronous manner - invoking methods and getting results immediately etc :).
My rule of thumb is generally to try use simpler synchronous programming models at the micro level for business logic; then use asynchrony and SEDA at the macro level.
For example submitting a purchase order might just write a message to a message queue; but the processing of the purchase order might require 10 different steps all being asynchronous and parallel in a high performance distributed system with many concurrent processes & threads processing individual steps in parallel. So the macro level wiring is based on a SEDA kind of approach - but at the micro level the code for the individual 10 steps could be written mostly in a synchronous programming style.


Question: If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called?

Answer:
A Lambda expression can contain complex statements, so you can do the following:
```
```
Func<IEnumerator, object> f = ie => { ie.MoveNext(); return ie.Current; };
```
```


Question:
Using Django's built in models, how would one create a triple-join between three models.

For example:

Users, Roles, and Events are the models.

Users have many Roles, and Roles many Users.  (ManyToMany)

Events have many Users, and Users many Events. (ManyToMany)

But for any given Event, any User may have only one Role.

How can this be represented in the model?

Answer:
I'd recommend just creating an entirely separate model for this.
```
```
class Assignment(Model):
    user = ForeignKey(User)
    role = ForeignKey(Role)
    event = ForeignKey(Event)
```
```
This lets you do all the usual model stuff, such as
```
```
user.assignment_set.filter(role__name="Chaperon")
role.assignment_set.filter(event__name="Silly Walkathon")
```
```
The only thing left is to enforce your one-role-per-user-per-event restriction.  You can do this in the Assignment class by either overriding the save method (
http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods
) or using signals (
http://docs.djangoproject.com/en/dev/topics/signals/
)


Question:
I am trying to program a small server+client in Javascript on Firefox, using XPCOM.

To get the HTTP message in Javascript, I am using the nsIScriptableInputStream interface.
This f**ing component through the read() method randomly cut the message and I cannot make it reliable.

Is anybody know a solution to get reliably the information? (I already tried a binary stream, same failure.)

J.

Answer:
If you control the protocol (that is, both the client and server) I would highly recommend using Javascript/JSON for your server-to-client messages.  The client can open a stream either via dynamically adding a <script> tag to the DOM.  The server can then send a stream of Javascript commands like:
```
```
receiveMsg({type:"text", content:"this is my message"});
```
```
Then the client just needs to define a receiveMsg function. This allows you to rely on fast browser code to parse the message and determine where the end of each message is, at which point it will call your handler for you.
Even if you're working with an existing HTTP protocol and can't use JSON, is there some reason you can't use XMLHttpRequest?  I would expect it to be more stable than some poorly documented Firefox-specific XPCOM interface.
--Chouser


Question:
This is from an example accompanying the agsXMPP .Net assembly.  I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message.  I guess what I'm looking for is an understanding of why delegate(0) accomplishes this, in the kind of simple terms I can understand.

xmpp.OnLogin += delegate(object o) {
    xmpp.Send(new Message(new Jid(JID_RECEIVER),
    MessageType.chat,
    "Hello, how are you?"));
};

Answer: That is creating an anonymous function.  This feature was introduced in C# 2.0


Question:
I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.

I have an array (in Ruby) that I need to sort by multiple conditions.  I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions.  However, in this case I need the first condition to sort ascending and the second to sort descending.  For example:

ordered_list = [[1, 2], [1, 1], [2, 1]]

Any suggestions?

Edit:  Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here).  So for a simple example it's more like:

ordered_list = [[1, "b"], [1, "a"], [2, "a"]]

Answer:
How about:
```
```
ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
ordered_list.sort! do |a,b|
  [a[0],b[1]] <=> [b[0], a[1]]
end
```
```


Question:
I need to run a stored procedure from a C# application.

I use the following code to do so:

Process sqlcmdCall = new Process();
sqlcmdCall.StartInfo.FileName = "sqlcmd.exe";
sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\""
sqlcmdCall.Start();
sqlcmdCall.WaitForExit();

From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).

How can I customize these return codes?

H.

Answer:
If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the command line.  Look at
```
SqlConnection
```
and
```
SqlCommand
```
in the
```
System.Data.SqlClient
```
namespace.
Once you are calling the stored procedure via
```
SqlCommand
```
you will be able to catch an exception raised by the stored procedure as well we reading the return value of the procedure if you need to.


Question:
I'm working with a fairly simple database, from a Java application.  We're trying to insert about 200k of text at a time, using the standard JDBC mysql adapter.  We intermittently get a com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column error.

The column type is longtext, and database collation is UTF-8.  The error shows up using both MyISAM and InnoDB table engines.  Max packet size has been set ot 1 GB on both client and server sides, so that shouldn't be causing a problem, either.

Answer:
Well you can make it ignore the error by doing an INSERT IGNORE which will just truncate the data and insert it anyway. (from
http://dev.mysql.com/doc/refman/5.0/en/insert.html
)
If you use the IGNORE keyword, errors
  that occur while executing the INSERT
  statement are treated as warnings
  instead. For example, without IGNORE,
  a row that duplicates an existing
  UNIQUE index or PRIMARY KEY value in
  the table causes a duplicate-key error
  and the statement is aborted. With
  IGNORE, the row still is not inserted,
  but no error is issued. Data
  conversions that would trigger errors
  abort the statement if IGNORE is not
  specified. With IGNORE, invalid values
  are adjusted to the closest values and
  inserted; warnings are produced but
  the statement does not abort.


Question:
For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.

This is a readonly textbox used only for display.  It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check  for overflow (if so, how to tell if the text fits?)

Not having any luck with various combinations of WordWrap and Scrollbars settings.  I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.

@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.

@André Neves, good point, and I would go that way if it was user-editable.  I agree that consistency is the cardinal rule for UI intuitiveness.

Answer:
I also made some experiments, and found that the vertical bar will always show if you enable it, and the horizontal bar always shows as long as it's enabled and
```
WordWrap == false
```
.
I think you're not going to get exactly what you want here. However, I believe that users would like better Windows' default behavior than the one you're trying to force. If I were using your app, I probably would be bothered if my textbox real-estate suddenly shrinked just because it needs to accomodate an unexpected scrollbar because I gave it too much text!
Perhaps it would be a good idea just to let your application follow Windows' look and feel.


Question:
I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array new thus:

STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];

Later on however the memory is freed using a delete call:

delete pStruct;

Will this mix of array new[] and non-array delete cause a memory leak or would it depend on the compiler?  Would I be better off changing this code to use malloc and free instead?

Answer:
Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c++ you should not use them since they won't handle (de)constructors.
Also your code will call the deconstructor, but not the constructor. For some structs this may cause a memory leak (if the constructor allocated further memory, eg for a string)
Better would be to do it correctly, as this will also correctly call any constructors and deconstructors
```
```
STRUCT* pStruct = new STRUCT;
...
delete pStruct;
```
```


Question: Are there any utilities or browser plugins that let you easily switch the version of the Flash player that is being used?

Answer:
Found the following:
http://www.google.be/search?q=firefox%20switch%20flash%20version
http://www.sephiroth.it/weblog/archives/2006/10/flash_switcher_for_firefox.php
(seems nice)
http://www.communitymx.com/content/article.cfm?page=2&cid=6FBA7
(seems nicely integrated as well)
https://addons.mozilla.org/nl/firefox/addon/5044
(from mozilla.org, must be good :p)


Question:
I want to use a specific foreign language font for a Blackberry application.  How is such a font created and loaded onto the Blackberry device?

For example: ਪੰਜਾਬੀ

Answer:
A quick google search shows that the same thing has been asked at
blackberry forums
.
The solution they came up with is a class for loading the font from a
fnt file
.
There are
programs available
to import and edit fnt files.


Question: I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.

Answer: Well, the really oversimplified version is that a lambda is just shorthand for an anonymous function.  A delegate can do a lot more than just anonymous functions: things like events, asynchronous calls, and multiple method chains.


Question: If a user saves the password on the login form, ff3 is putting the saved password in the change password dialoge on the profile page, even though its not the same input name as the login. how can I prevent this?

Answer:
Try using autocomplete="off" as an attribute of the text box. I've used it in the past to stop credit card details being stored by the browser but i dont know if it works with passwords. e.g.
```
print("<input type="text" name="cc" autocomplete="off" />");
```


Question:
Looking for a way to read the unique ID / serial# of a USB thumb drive;
please note that

- I am looking for the value of the manufacturer, not the one Windows allocates for it.

- I need to support multiple OS (Windows, Unix, Mac), thus needs to be a Java solution

The idea is to be able to distinguish between different USB thumb drives.

Answer:
I've never tried using it (it's been on my todo list for a good few months now), but there is the "marge" project on java.net:
http://marge.java.net/
This should let you connect to bluetooth devices (although I don't think it is 100% feature complete, there is demo code on there), and then the ClientDevice class has a "getBluetoothAddress" method which I
believe
should be unique to that device
http://marge.java.net/javadoc/v06/marge-core/net/java/dev/marge/entity/ClientDevice.html
As I say though, I've never tried it...


Question: What is the difference between Introspection and Reflection in .NET

Answer:
They're two parts of the same whole.
Introspection refers to the ability of a class to look 'inside' itself and see, for example, what parameters a method takes, what the names of its members are, etc.
Reflection is the specific name for how .NET implements introspection.  Other languages may call it something different (C++ calls its limited introspection RTTI, for run-time type information).


Question:
Is there an easy way to convert a string from csv format into a string[] or list?

I can guarantee that there are no commas in the data.

Answer:
```
```
CsvString.split(',');
```
```


Question:
Does a caching-nameserver usually cache the negative DNS response SERVFAIL?

EDIT:
To clarify the question, I can see the caching nameserver caching negative responses NXDOMAIN, NODATA. But it does not do this for SERVFAIL responses. Is this intentional?

Answer: One of the timeout fields in the SOA is a "negative timeout". It is usually set to a short time, such as 30 or 60 seconds. So, yes, but for a shorter time than a "positive" response.


Question: What's the most efficient way to convert the output of this function from a varbinary() to a a varchar()?

Answer:
How about this:
```
```
master.sys.fn_varbintohexstr(@binvalue)
```
```


Question: We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true?

Answer:
No, it isn't true, you can encode XML to any Writer in Java using something similar to:
```
```
char[] ch;
AttributesImpl atts = new AttributesImpl();
Writer writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();

// SAX2.0 ContentHandler
TransformerHandler transformerHandler = tf.newTransformerHandler();

Transformer serializer = transformerHandler.getTransformer();

serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "nodes.dtd");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");

transformerHandler.setResult(streamResult);

transformerHandler.startDocument();

atts.clear();
// atts.addAttribute("", "", "xmlns", "CDATA", "http://www.example.com/nodes");
// atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
// atts.addAttribute("", "", "xsi:schemaLocation", "CDATA", "/nodes.xsd");
transformerHandler.startElement("", "", "node_list", atts);

// displayName element
if (displayName != null) {
    transformerHandler.startElement("", "", "display_name", null);
    ch = displayName.toCharArray();
    transformerHandler.characters(ch, 0, ch.length);
    transformerHandler.endElement("", "", "display_name");
}

// nodes element
transformerHandler.startElement("", "", "nodes", null);

atts.clear();
atts.addAttribute("", "", "node_type", "CDATA", "sometype");
transformerHandler.startElement("", "", "node", atts);

ch = node.getValue().toCharArray();
transformerHandler.startElement("", "", "value", null);
transformerHandler.characters(ch, 0, ch.length);
transformerHandler.endElement("", "", "value");

transformerHandler.endElement("", "", "node");

transformerHandler.endElement("", "", "nodes");

transformerHandler.endElement("", "", "node_list");

transformerHandler.endDocument();

String xml = writer.toString();
```
```


Question:
When I'm initializing a dialog, I'd like to select one of the radio buttons on the form.  I don't see a way to associate a Control variable using the Class Wizard, like you would typically do with CButtons, CComboBoxes, etc...

Further, it doesn't like a CRadioButton class even exists.

How can I select one of the several radio buttons?

Answer:
Radio buttons and check buttons are just buttons.  Use a
```
CButton
```
control and use
```
GetCheck
```
/
```
SetCheck
```
.


Question:
I am getting some errors thrown in my code when I open a Windows Forms form in Visual Studio's designer. I would like to branch in my code and perform a different initialization if the form is being opened by designer than if it is being run for real.

How can I determine at run-time if the code is being executed as part of designer opening the form?

Answer:
```
```
System.Diagnostics.Debugger.IsAttached
```
```