q:
When I Alt+Tab to my VM from my host the VM does not get keyboard input until I click inside it.  This is causing me an issue as it looks like the VM has control of the input (as the cursor is flashing away).  If while in this state, VMWare server has the focus rather then the application inside it, if you do ctrl+Z (normally for undo) it suspends the VM.

This is driving me barmey.  I have looked through all the options and preferences in VMWare Server and can't find anyway to disable this.

Anyone know how to disable this?

[A]
You could use a resource editor on
```
vmware.exe
```
to remove the keybinding for
Ctrl
+
Z
.  Obviously not for the faint of heart.


q:
Not too long ago, I had a problem which required me to set WinDbg.exe as the default post-mortem debugger.  Now that I've fixed that and am back doing normal work, it would be really nice if I could set VS to be my default post-mortem debugger.  How does one go about doing this?

Also, how do I make VS attach to an already existing session?  That is, I've got my VS project open in one window, and a command line open where I'm launching my program from.  If the program crashes, how do I get VS to figure out to attach the debugger to the active line in the project that's already open?

[A]
from the
Microsoft support page
:
```
```
1.  Start Registry Editor and locate the following Registry subkey in the HKEY_LOCAL_MACHINE subtree:

\SOFTWARE\MICROSOFT\WINDOWS NT\CURRENTVERSION\AEDEBUG
2.  Select the Debugger value.
3.  On the Edit menu, click String.

•   To use the Windows debugger, type windbg -p %ld -e %ld.
•   To use Visual C++ 4.2 or earlier, type msvc -p %ld -e %ld.
•   To use Visual C++ 5.0 or later, type msdev.exe -p %ld -e %ld.
•   To use Dr. Watson, type drwtsn32.exe -p %ld -e %ld. You can also make Dr. Watson the default debugger by running this command:drwtsn32.exe -i.
4.  Choose OK and exit Registry Editor.
```
```

s: huggingface

c: devops

d: intermediate


q:
what is the best way to put a container class or a some other class inside a class as private or a public member?

Requirements:

1.Vector< someclass> inside my class

2.Add and count of vector is needed interface

[A]
Whether a member is declared Private or Public depends entirely on your application. Could you give some more detail?
One important point to remember when declaring your member is that if you provide a "getter" to retrieve it, then you are no longer encapsulating that object. Instead, it can be good to write wrapper methods exposing only the functionality you wish to expose.
For example, with a Vector member, you might write an AddItem and Clear method, if that's all the functionality you wish to expose.


q:
I'm using the jquery library to load the content of an html file. Something like this:

$("#Main").load("login.html")

If the file (in this case 'login.html') does not exist, I would like to detect it so that I can redirect the user to an error page for example. Any ideas how I can detect if the file to load exists or not?

[A]
You can use the ajaxComplete event, whis gives you access to the xhr object which you can query the status of the request e.g a status of 404 will mean the file does not exist.
More Info in the docs
http://docs.jquery.com/Ajax/ajaxComplete#callback
Test here
http://pastebin.me/48f32a74927bb
e.g
```
```
$("#someDivId").ajaxComplete(function(request, settings){
    if (settings.status===404){
        //redirect here
    }
});
```
```


q:
We are attempting to install BizTalk Server 2006 R2 on a fresh server with x64 Windows 2008. The basic configuration is complaining that the “Default Web Site” we select for the BAM Portal installation is not validated due to “IIS is not 32-bit enabled.” Despite setting the appPool (Classic mode) 32-bit property to True, BizTalk configuration wizard is still complaining.

Has anybody successfully installed BAM Portal in 64-bit IIS 7.0?

[A]
It looks like Microsoft’s official statement is Biztalk Server 2006 R2 with Windows 2008 is “not supported”. BizTalk Server 2009 is the one that is meant to be married to Windows 2008.
UPDATE, MOFE INFO
I should additionally comment that the process of
setting up a multiple servers for a BizTalk Group
requires configuration of network COM+ and DTC access, of which Windows 2008 interface of doing so differs from Windows 2003. In fact, I haven't found how to configure MSDTC in Windows 2008 as required by BizTalk 2006. Failing to properly configure this will prevent some of the databases from being created properly in a remote SQL Server due to transactional failure.


q: I have a .net application and i published in the local location. while installing from the published location the application need to install in "c:\temp" how can i do this in clickonce method?

[A]
ClickOnce installation always installs in the predefined user folders, the ClickOnce cache.
There is no way to install a ClickOnce program somewhere else. Neither can you decide on a different location on creation of the ClickOnce package, nor can the person installing the program decide on a different location.
This is not an omission, neither an error, it is by design and it is meant to be that way.
If you want to install in a specific location, you'll need to use some other installation method.


q:
I want to split a command line like string in single string parameters. How look the regular expression for it. The problem are that the parameters can be quoted. For example like:

"param 1" param2 "param 3"

should result in:

param 1, param2, param 3

[A]
Without regard to implementation language, your regex might look something like this:
```
```
("[^"]*"|[^"]+)(\s+|$)
```
```
The first part
```
"[^"]*"
```
looks for a quoted string that doesn't contain embedded quotes, and the second part
```
[^"]+
```
looks for a sequence of non-quote characters. The
```
\s+
```
matches a separating sequence of spaces, and
```
$
```
matches the end of the string.


q:
I came across this class while reading a C# book and have some questions.

Why is this added into System.Linq namespace and not into usuall Collections namespace?

What the intention behind this class is

Why this class is not intended for direct instantiation? This is available through the ToLookup extension only, right?

[A]
Purpose of the class: a dictionary where a key can map to multiple values. Think of it as being for grouping rather than one-to-one mapping.
Only through ToLookup decision: Pass. Again, seems like a bad call to me. On the other hand, it means that the result is immutable to the outside world, which is quite nice. It's quite easy to write your own collection which supports this, of course - but it would be have been quite nice to have it in the collections "properly". My guess is that MS didn't have the time/money to go through the pretty rigorous design/test required to make it a first class collections decision.
Namespace decision: Probably related to the above. Having a version in System.Collections.Generic which you couldn't create yourself would have been a bit odd.


q:
Given a table (mytable) containing a numeric field (mynum), how would one go about writing an SQL query which summarizes the table's data based on ranges of values in that field rather than each distinct value?

For the sake of a more concrete example, let's make it intervals of 3 and just "summarize" with a count(*), such that the results tell the number of rows where mynum is 0-2.99, the number of rows where it's 3-5.99, where it's 6-8.99, etc.

[A]
The idea is to compute some function of the field that has constant value within each group you want:
```
```
select count(*), round(mynum/3.0) foo from mytable group by foo;
```
```


q: How can I unset variable? For example, PHP has an unset($var) function.

[A]
You can't. There's no notion of "unsetting" a variable. You can set it to a different value - 0, null, whatever's appropriate. Instance/static variables don't even have a concept of whether the variable is set/unset, and local variables only have "definitely assigned" or "not definitely assigned".
What is it you're trying to achieve?


q:
On occasion, my local Rails app loses its connection to MySQL. I get some error that the connection failed, but if I just refresh the page, it works fine. This has never happpened in my STAGE or PROD environments (I deploy to Ubuntu), so it has not been that big a deal.

Does this happen to anybody else?  Is there something I can do to fix it?  Is it MySQL or Ruby?

[A]
Look like the best solution to this is to install the platform specific mysql driver.
```
sudo gem install mysql
```


q:
What would you recommend to search a sql server table (varchar(max) column) for a term?

Let's say, like in ebay, if you search for "wii brand new", you get results like "Brand New Nintendo Wii Fit Game + Balance Board Bundle", "Wii Fit (Wii) BRAND NEW WII FIT GAME + BALANCE BOARD".

I think it basically searches every word and returns the ones that contains all the words, what would you recommend?

[A]
You are looking for fulltext indexing, it allows you to do more advanced querying than regular expressions or like.
Check
this
article for a quick introduction, the instructions are for SQL Server 2000, where it is a little harder to setup than in 2005 or 2008.
Relevant quote:
```
With full-text searching, you can perform many other types of search:

 * Two words near each other
 * Any word derived from a particular root (for example run, ran, or running)
 * Multiple words with distinct weightings
 * A word or phrase close to the search word or phrase
```


q:
I have a products table that contains a FK for a category, the Categories table is created in a way that each category can have a parent category, example:

Computers
    Processors
        Intel
            Pentium
            Core 2 Duo
        AMD
            Athlon

I need to make a select query that if the selected category is Processors, it will return products that is in Intel, Pentium, Core 2 Duo, Amd, etc...

I thought about creating some sort of "cache" that will store all the categories in the hierarchy for every category in the db and include the "IN" in the where clause. Is this the best solution?

[A]
I have done similar things in the past, first querying for the category ids, then querying for the products "IN" those categories. Getting the categories is the hard bit, and you have a few options:
If the level of nesting of categories is known or you can find an upper bound: Build a horrible-looking SELECT with lots of JOINs. This is fast, but ugly and you need to set a limit on the levels of the hierarchy.
If you have a relatively small number of total categories, query them all (just ids, parents), collect the ids of the ones you care about, and do a SELECT....IN for the products. This was the appropriate option for me.
Query up/down the hierarchy using a series of SELECTs. Simple, but relatively slow.
I believe recent versions of SQLServer have some support for recursive queries, but haven't used them myself.
Stored procedures can help if you don't want to do this app-side.


q:
I am creating a Visual Studio Setup project. I want to un-install another component from the system from the install of my component. The other component is installed from my own setup created using Visual Studio.

Currently when I am calling the un-install of the other component from the install action of the component I get the error code: 1618 (another MSI already running).

Could anyone suggest me an alternative way to solve this problem?

[A]
If you don't need to actually run the uninstall of the other component, you could use a Custom Action to remove files/folders you intend to replace.
Using a Custom Action will force you to do all the clean up actions the Uninstaller would do for you.
Is it that you're replacing something or are you just trying to uninstall something as a result of installing something entirely different?
MSDN Custom Action Walkthrough
I have also read a few articles from Phil Wilson that have been helpful with Custom Actions:
Phil Wilson on Custom Actions


q:
Does anyone know where I can find a library of common but difficult (out of the ordinary) SQL script examples. I am talking about those examples you cannot find in the documentation but do need very often to accomplish tasks such as finding duplicates etc.

It would be a big time saver to have something like that handy.

EDIT: Thanks everyone, I think this is turning into a great quick reference. The more descriptive the more effective it would be, so please if you see your way open - please edit and add some descriptions of what one could find. Many thanks to those that have already done so!

[A]
Here are a few that I find very useful:
SQL Server Best Practices
- Microsoft SQL Server White Papers and Best Practices
vyaskn
- A mixture of articles From DBA to Developer
Backup, Integrity Check and Index
Optimization
SQLServerCentral Scripts
- Scripts for most most DBA tasks and more
Script Repository: SQL Server 2005
- TechNet Script Center
Scripts and Tools for Performance Tuning and Troubleshooting SQL Server 2005
SQL Server Query Processing Team
- Hardcore advice from the MS SQL optimisation team
Common Solutions for T-SQL Problems
Davide Mauri's Index Scripts


q:
I only just recently discovered that Visual C++ 2008 (and perhaps earlier versions as well?) supports for each syntax on stl lists et al to facilitate iteration.
For example:

list<Object> myList;

for each (Object o in myList)
{
  o.foo();
}

I was very happy to discover it, but I'm concerned about portability for the dreaded day when someone decides I need to be able to compile my code in say, gcc or some other compiler. Is this syntax widely supported and can I use it without worrying about portability issues?

[A]
For each is not standard C or C++ syntax. If you want to be able to compile this code in gcc or g++, you will need to create an iterator and use a standard for loop.
QuantumPete
[edit]
This seems to be a new feature introduced into MS Visual C++, so this is definitely not portable. Ref:
http://msdn.microsoft.com/en-us/library/xey702bw%28VS.80%29.aspx
[/edit]


q:
I am dealing with MySQL tables that are essentially results of raytracing simulations on a simulated office room with a single venetian blind. I usually need to retrieve the simulation's result for a unique combination of time and blind's settings. So I end up doing a lot of

SELECT result FROM results WHERE timestamp='2005-05-05 12:30:25' \
         AND opening=40 AND slatangle=60

This looks suspiciously optimizable, since this query should never ever return more than one row. Does it make sense to define an index on the three columns that uniquely identify each row? Or are there other techniques I can use?

[A]
The answer is most definately a yes. If you define a unique index on timestamp, opening and slatangle MySQL should be able to find your row with very few disc seeks.
You might experiment with creating an index on timestamp, opening, slateangle and result. MySQL may be able to fetch your data from the index without touching the datafile at all.
The MySQL Manual has a
section about optimzing queries
.


q:
I want to create a bundle from an arbitrary bundle identifier

e.g. com.apple.iokit.IOStorageFamily

It's not an unreasonable thing to do as bundle IDs are supposed

to be unique, however the obvious code does not work:

NSString* bID = @"com.apple.iokit.IOStorageFamily";
NSBundle* bundle = [NSBundle bundleWithIdentifier:bID];

This code only works for bundles you've already loaded

(hello, chicken and egg problem), and in fact, you have

to know a little more than you'd like about the the identifier

before you can do anything. For the above style of ID

I grep out the final component and tranform it into

/System/Library/Extensions/IOStorageFamily.kext

which I then load by path.

Is this the state of the art or is there a more general way?

[A]
Use this
```
```
NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.TextEdit"];
```
```


q:
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion?

class MyClass(object):
    def my_function():
        """This docstring works!"""
        return True
    my_list = []
    """This docstring does not work!"""

[A]
To my knowledge, it is not possible to assign docstrings to module data members.
PEP 224
suggests this feature, but the PEP was rejected.
I suggest you document the data members of a module in the module's docstring:
```
```
# module.py:
"""About the module.

module.data: contains the word "spam"

"""

data = "spam"
```
```


q:
I am developing a CMS where the clients will need to upload files larger than 2mb - up to 10mb at least. I have changed the details in the php.ini file and I cannot see anywhere else that the problem might be. Any help?

Cheers

[A]
As long as you have restarted your web service (ie apache) then the changes  should take  effect, however if you are developing for anyone other then yourself then instead of changing the php.ini I would add this to the upload script:
```
```
ini_set('upload_max_filesize', '10M');
```
```
as some people may not be able to modify php.ini this will change it just for the page it is on.


q:
I'm a new user of Matlab, can you please help:

I have the following code in an .M file:

function f = divrat(w, C)
S=sqrt(diag(diag(C)));
s=diag(S);
f=sqrt(w'*C*w)/(w'*s);

I have stored this file (divrat.M) in the normal Matlab path, and therefore I'm assuming that Matlab will read the function when it's starting and that this function therefore should be available to use.

However, when I type

>> divrat(w, C)

I get the following error

??? Undefined function or method 'divrat' for input arguments of type 'double'.

What is the error message telling me to do, I can't see any error in the code or the function call?

[A]
The error code indicates the function definition cannot be found. Make sure you're calling the function from the same workspace as the
```
divrat.m
```
file is stored. And make sure
```
divrat
```
function is not a subfunction, it should be first function declaration in the file. You can also try to call the function from the same
```
divrat.m
```
file in order to see if the problem is with workspace selection or the function.
By the way, why didn't you simply say
```
```
s = sqrt(diag(C));
```
```
Wouldn't it be the same?


q:
I'm using libcurl in a Win32 C++ application.

I have the curllib.vcproj project added to my solution and set my other projects to depend on it.

How do I build it with SSL support enabled?

[A]
Well, since this post failed badly, I had to dig into the matter myself.
Also check out the other answers and comments for additional info regarding other versions etc.
EDIT: Since I posted this Q there seems to be ready-built binaries made available from the curl homepage. Check out
James' answer
.
So here goes:
-
Preprocessor
The following two symbols need to be fed to the preprocessor to enable SSL for libcurl:
```
```
USE_SSLEAY
USE_OPENSSL
```
```
(libcurl uses OpenSSL for SSL support)
Alternatively the symbols can be added directly to a file called setup.h in libcurl, but I'm not too happy about modifying code in 3rd party distributions unless I really have to.
Rebuilding the libcurl library, I now got some errors about OpenSSL include files not being found. Naturally, since I haven't set up the OpenSSL distribution properly yet.
Compiling OpenSSL binaries
I downloaded the OpenSSL 0.9.8 source distribution and unpacked it.
In the root of the source distribution there's a file called INSTALL.W32 which describes how to compile the OpenSSL binaries. The build chain requires perl, so I installed the latest version of ActivePerl.
I had some trouble with the build, which might not be applicable to all systems, but I'll go through it here in case somebody experiences the same.
According to INSTALL.W32:
Run the following commandline tasks with current directory set to the source distribution root:
```
```
1> perl Configure VC-WIN32 --prefix=c:/some/openssl/dir
```
```
(Where "c:/some/openssl/dir" should be replaced by the dir where OpenSSL should be installed. Don't use spaces in this path. The compilation further ahead will fail in that case)
```
```
2> ms\do_ms
```
```
For me this step was unsuccessful at first, since I lacked the environment variables OSVERSION and TARGETCPU. I set these to
5.1.2600
and
x86
respectively. You may get complaint about OSVERSION being "insane", but look closer, this error is for WinCE and doesn't affect the Win32 setup. To get hold of your OS version, run the 'ver' command from a command prompt or run winver.exe.
```
```
3> nmake -f ms\nt.mak (for static library)
```
```
or
```
```
3> nmake -f ms\ntdll.mak (for DLL)
```
```
The source now compiles. Took approx 5 minutes on my laptop.
When compilation is completed, the libs or binaries have been placed in:
distroot/out32
- for static library build
or
distroot/out32dll
- for DLL build
Building and linking
Now, back to visual studio and point out the libs and include path for headers. The include files are located in
distroot/inc32/openssl
.
Remember to add
libeay32.lib
and
ssleay32.lib
as linker input.
Rebuild the libcurl project.
Error!
Well at least for me with this version of OpenSSL.
it complained about a struct typedef in one of the OpenSSL headers. I couldn't find any info on this. After an hour of googling I broke my own principle and commented out the typedef from the OpenSSL header, and luckily libcurl wasn't using that symbol so it built fine.
Update: As pointed out by Jason, this issue seems to have dissapeared as of version 1.0.0a.
Now, for confirming that SSL support is enabled for libcurl, run the following code:
```
```
curl_version_info_data * vinfo = curl_version_info( CURLVERSION_NOW );
if( vinfo->features & CURL_VERSION_SSL )
    // SSL support enabled
else
    // No SSL
```
```
Simple as that.


q: Someone asked me how familiar I am with VC++ and how familiar I am with C++.  What is the difference?

[A]
C++ is the actual language, VC++ is Microsoft's Visual C++, an IDE for C++ development.
From
stason.org
:
C++ is the programming language, Visual C++ is Microsoft's implementation of it.
When people talk about learning Visual C++, it usually has more to do with learning how to use the programming environment, and how to use the Microsoft Foundation Classes (MFCs) for Windows rather than any language issues. Visual C++ can and will compile straight C and C++.


q:
What's the best/easiest to integrate templating system for PHP, and what are the benefits of using one?

I currently don't use one at all, and am thinking that it might help to seperate content from presentation a little more.

[A]
Smarty
I've found it to be fast, easy to use, and easy to install (even in a shared-hosting environment).  It also doesn't require that you use validating XHTML which is handy sometimes (although I think the template engines that
do
require valid XHTML are probably faster.)
It's really nice to have your content in one place and code somewhere else.
Plus you're not limited to just HTML.  I've used Smarty to generate
XML
and even
SQL
.


q:
I'm just starting up a new ATL/WTL project and I was wondering if the global _Module variable is still required?

Back a few years when I started working with WTL it was required (at least for ATL 3.0) that you define a global variable such as:

CAppModule _Module;

To get ATL to work correctly. But recently I've read somewhere that this may not be required anymore (yet the wizard generated code still uses it). Also I did a search through the Visual C++ include directories and it only picked up _Module in a few places - most notably the ATL COM registry stuff.

So do I still need to define a global variable to use ATL these days?

[A]
In the sample projects of the latest WTL version, this is still used.
In stdafx.h:
```
```
extern CAppModule _Module;
```
```
In implementation files:
```
```
CAppModule _Module;
```
```


q:
What are the guidelines for when to create a new exception type instead of using one of the built-in exceptions in .Net?

The problem that got me thinking is this. I have a WCF service, which is a basic input-output service. If the service is unable to create an output, because the input is invalid, I want to throw an exception, but which one?

Right now I'm just throwing system.Exception, but this doesn't feel right to me, I don't know why, it just feels wrong.
One thing that bugs me, if I test it with a unit test and I expect the system.Exception to be thrown. The exception could as well be thrown by the framework or other code and not by the code I excepted to throw. The test would then pass, as I get the expected exception, but it should have failed.

What do you recommend?

[A]
Avoid throwing
```
System.Exception
```
or
```
System.ApplicationException
```
yourself, as they are too general.
For WCF services there are Fault Contracts - a generic exception that you can tell subscibers to handle.
Flag the interface with:
```
```
[FaultContract( typeof( LogInFault ) )]
void LogIn( string userName, string password, bool auditLogin );
```
```
Then if there is an exception you can throw this specific fault:
```
```
throw new FaultException<LogInFault>( new LogInFault(), "message" );
```
```
Use the
```
[DataContract]
```
serialisation on your fault - this saves you from having to handle all the serialisation stuff exceptions normally require.


q:
I am using the jQuery library to implement drag and drop.

How do I get at the element that is being dragged when it is dropped?

I want to get the id of the image inside the div. The following element is dragged:

<div class="block">
    <asp:Image ID="Image9" AlternateText="10/12/2008 - Retina" Width=81 Height=84 ImageUrl="~/uploads/ImageModifier/retina.jpg" runat=server />
</div>

I have the standard dropped function from their example:

$(".drop").droppable({
                 accept: ".block",
                 activeClass: 'droppable-active',
                 hoverClass: 'droppable-hover',
                 drop: function(ev, ui) { }
});

I have tried various ui.id etc. which doesn't seem to work.

[A]
Is it not the ui.draggable?
If you go here (in Firefox and assuming you have firebug) and look in the firebug console youll see I am doing a console.dir of the ui.draggable object which is the div being dragged
http://jsbin.com/ixizi
Therefore the code you need in the drop function is
```
```
drop: function(ev, ui) {
                 //to get the id
                 //ui.draggable.attr('id') or ui.draggable.get(0).id or ui.draggable[0].id
                 console.dir(ui.draggable)
       }
```
```


q:
What is the best way to determine how many window handles an application is using?  Is there a tool or a WMI performance counter that I could use?

I would like to run up an app and watch a counter of some sort and see that the number of window handles is increasing.

for (int i=0; i < 1000; i++)
{
    System.Threading.Thread.Sleep(1000);
    RichTextBox rt = new RichTextBox();
    rt.Text = "hi";
    this.Controls.Add(rt);
}

I am running the above code and watching the "Handle Count" counter on the process, and it does not seem to be increasing.  Is there something I am looking at incorrectly?

[A]
Perfmon, which comes with your computer can do it.  You can also add a column to your task manager processes tab (Handle Count).
Instructions for Perfmon
Add a counter (click the +)
Choose Process under Performance object
Choose Handle Count under the counter list
Choose your process from the instance list
Click Add, click Close
To get the graph in range, you have to right-click it in the list, choose properties, and then choose the right scale (.1 or .01 would probably be right)
Edit (in response to added information): I think you just proved that creating RichTextBoxes doesn't result in Handles being allocated. I don't think it really needs one until you are editing the control and it might be smart enough to do that, since allocating too many resources for a control that isn't active would make it hard to have a lot of controls on a form (think about Excel, for example).


q:
I have inherited a load of VB6 code which has tons of individual OCX files, each of which contain a single control.  I have two questions:

Firstly, Is it possible to refactor them so that I can have a single OCX file with all the OCX's in it?

Secondly, if it is possible, how do I do this?

TIA

[A]
Yes this is possible.
You can do this by selecting
Project->Add User Control
from within an existing ActiveX User Control project. From here you can choose to add a new control to the project or add an existing user control.
Also, it can certainly make sense to group related controls together into a single project, as long as you group controls according to some kind of logic. For example, the Forms 2.0 library groups "commonly-used" controls together (Textbox, Checkbox, Combobox, Label, etc.) into a single library.


q:
As a follow up to an earlier question that attracted a whole zero answers, I'm wondering about the possibilities of allowing a web server (apache) to write to its own document root (Linux), in order to dynamically create meta-redirect files.

Of course, this sounds incredibly dangerous, and I'm wary of going the whole hog and granting the web-server user full write-access to its own docroot. Is there a more appropriate way of achieving this?

[A]
What's usually done is to allow writes only to subdirectories, hopefully located in a noexec mounted partition.
That said, it seems to me that you should just create a set of
RewriteMap
directives to do your dynamic redirection, there's no need to write files in the document root to accomplish that.
I answered similarly in the
other question
, just for completeness.


q:
I'm working with embedded C for the first time. Although my C is rusty, I can read the code but I don't really have a grasp on why certain lines are the way the are. For example, I want to know if a variable is true or false and send it back to another application. Rather than setting the variable to 1 or 0, the original implementor chose 0xFF.

Is he trying to set it to an address space? or else why set a boolean variable to be 255?

[A]
```
0xFF
```
sets all the bits in a char.
The original implementer probably decided that the standard
```
0
```
and
```
1
```
wasn't good enough and decided that if all bits
off
is
false
then all bits
on
is
true
.
That works because in C any value other than 0 is true.
Though this will set all bytes in a char, it will also work for any other variable type, since any one bit being set in a variable makes it true.


q:
I want to do some checking in a writer accessor. My first idea was returning a boolean.

class MyClass
  def var=(var)
    @var = var
    # some checking
    return true
  end
end

m = MyClass.new
retval = (m.var = 'foo')

=> "foo"

Can I set a return value in a writer accessor? If yes, how can I get this value?

[A]
I would use set_var(var) instead of what you are trying to do, an attribute writer is assumed to just work. What you are trying to do is nonstandard and non-obvious to the next poor person to use your code. (It may just be yourself) I would throw an exception if bad input is sent or something rather exceptional happens.
You want this behavior
```
```
Correct
>>temp = object.var = 7
=> 7

Wrong
>>temp = object.var = 7
=> false
```
```
The = operator should always return the value that was passed to it. Ruby uses implicit returns which is uncommon in programming languages. Double check the returns when you use
```
method=()
```
.


q:
I'd like to use Rich Text Editing in place on forms in order to let admins change instructions.   What are the best options for doing this?

[To be more clear - the admins are non-technical but may want to control some formatting without using markup or with as little markup as possible.  What I'd like is for them to be able to edit inline all AJAXy with an RTE featuring some formatting controls and then submit and be able to see what the instructions will look like to the end user without changing pages.

With Regards to plugins specifically, what I'd like to know is which Rich Test Editing plugins are the best for use in Rails.  Easiest to implement, clearest API, easiest to use inline, etc... ]

[A]
I'm not sure if I fully understand the question, but if you just ask about which editor to use, there are many options and none of them is a matter of Rails - you can use any of them just by adding a little piece of javascript into your markup. Nice and up to date overview can be found here:
http://bulletproofbox.com/web-based-rich-text-editors-compared/
.


q:
echo "<td><a href='delete.php?id=$row[id]&&category=$a' onclick='return confirm(\'are you sure you wish to delete this record\');'>delete</a></td>";

Above is the code I am trying to use. Every time it does nothing and I cannot see how I can use 'proper' JavaScript methods. What is the reason?

[A]
```
```
echo "delete	";
```
```
Use Firefox's HTML syntax highlighting to your advantage. :-)


q:
I am importing the CreateICeeFileGen() function from the unmanaged DLL mscorpe.dll in a C# application, in order to  generate a PE file. This function returns a pointer to an C++ object defined here, is there any way I can access fields from this class via C# or do I need to write an unmanaged wrapper DLL?

The code I'm using currently is as follows:-

[DllImport(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorpe.dll", EntryPoint = "CreateICeeFileGen")]
static extern void CreateICeeFileGen(out IntPtr iceeFileGenPointer);
...
IntPtr filePtr;
CreateICeeFileGen(out filePtr);

N.B.: I know you can do similar things with .net libraries but I need to use unmanaged libraries for my purposes.

[A]
You need a wrapper library to be able to use the class from C#.
The best bet would be to create the wrapper using C++/CLI, which can directly call the unmanaged function and expose the details with a managed class.  This will eliminate the need to use P/Invoke for anything.
(Well, technically if you know the class layout you could mess around with pointer arithmetic to access the fields, but this would be very fragile and messy, and trying to call virtual functions in this way would be extremely ugly).


q:
Looking for a c# library that interfaces to multiple merchant gateways.
Should at minimum be able to handle PayPal and authorize.

[A]
Considering that working with the gateways themselves is extremely simple, Adding support to your application for each one shouldn't be difficult.
That said, here is one that claims to have the support you want:
http://www.componentsource.com/products/ibiz-e-payment-integrator-net/index.html
Note that Payflow link and payflow pro were purchased by PayPal from verisign.


q:
I want to create a new row in my database on a table that has a couple of foreign key relationships and I haven't been able to get a handle on what order and what calls need to be made. This is what I have so far:

db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.CustomerReference.Attach( ( from c in db.Customer where c.Id == custId select c ).First() );
db.SaveChanges();

The code is failing on the second line there, saying:

Attach is not a valid operation when
  the source object associated with this
  related end is in an added, deleted,
  or detached state. Objects loaded
  using the NoTracking merge option are
  always detached.

Any ideas?

[A]
(Thanks John for the grammar fixes)
So I figured it out. This is what you have to do:
```
```
db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.Customer = (from c in db.Customer where c.Id == custId select c).First();
db.SaveChanges();
```
```
I hope that helps people.


q: Anyone know a simple method to swap the background color of a webpage using JavaScript?

[A]
Modify the JavaScript property
```
document.body.style.background
```
.
For example:
```
```
function changeBackground(color) {
   document.body.style.background = color;
}

window.addEventListener("load",function() { changeBackground('red') });
```
```
Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.


q:
I have a bunch of XML that has lines that look like this

<_char font_name="/ITC Stone Serif Std Bold" italic="true" />

but sometimes look like this

<_char font_size="88175" italic="true" font_name="/ITC Stone Serif Std Bold" />

Here's what I need to do

Replace italic="true" with italic="false for every line that contains ITC Stone Serif Std Bold, regardless of whether it comes before OR after the italic part.

Can this be done with a single regex?

I'm not looking for a real-time solution.  I just have a ton of XML files that have this "mistake" in them and I'm trying to do a global search-and-replace with PowerGrep which would require a single regex.  If scripting's the only way to do it, then so be it.

[A]
Well, in general, using RE for XML parsing isn't a great idea.  But if you really wanted, the easiest way would be to just do it in two lines:
```
```
if (/ITC Stone Serif Std Bold/) {
   s/italic="true"/italic="false"/g;
}
```
```


q: I have an excel file which has more than 65536 rows. However, I can see only first 65536 of them. Is it possible to see all of them in Excel 2007?

[A]
According to
this MSDN entry
, the limit is 1 million rows.  You could be running in compatibility mode, which would limit you to the old standard of 65k.  Does your excel say compatibility mode in the title?  If so, you can save the file as a new style file under the "save as" menu, or change your default to always use the 2007 file standard.


q:
I am trying to open a report in Crystal Report 11 Designer (product version 11.5.8.826), but it seems to freeze up. This report use to work fine, but today the client could not load the report.

I also tried to open the report on another developer's workstation, with the same result.

Has this happened to anyone else?

[A]
Are you sure all servers referenced in the report are still online? If you've changed database connections on the report, I've seen Crystal store a reference to the old one even when there are no active usages. If the old server is offline, Crystal still tries to connect to it when loading and will hang for a long time. We had a report that used to load in seconds start taking minutes right after an old test server was powered down. Powered it back up, it loaded instantly again, even though all the connections to it were seeming removed. We wound up totally rebuilding the report from scratch.
I found it using Sysinternals TDIMon, it showed connection attempts and timeouts coming from Crystal.


q:
I am putting together a SVN demonstration using a WinXP Virtual PC image, and am unable to see my host machine from within the VPC guest OS.

This demo will be performed while disconnected from our LAN, so I installed the Microsoft Loopback adapter on my laptop.  In the TCP/IP settings I manually set the IP address to 192.168.3.1 to avoid conflicts with our internal network.  In the VPC image settings I set the Network Type to Microsoft Loopback Adapter and set the IP address to 192.168.3.2.

I cannot ping my host machine from the guest OS and vice versa.  I've followed through several different how-to pages on this subject but still cannot determine why this isn't working.  What am I missing here?

[A]
So your host machine's loopback is set to 192.168.3.1 (subnet 255.255.255.0, gateway 192.168.3.1) and your VM's network adapter is set to 192.168.3.2 (subnet 255.255.255.0, gateway 192.168.3.1)?  They should be able to see each other, there's not much else to this setup.
I'd shake things up:
Install the VM additions, maybe the network driver that comes with the guest OS isn't cutting it.
Try a different subnet, maybe 192.168.22.1.
Disable your host machine's other network adapters for a bit, maybe packets are getting routed elsewhere.


q:
I'm currently experiencing an intermediate problem with some inherited client side javascript. Every so often the users' experience a browser hang with the cursor becoming an egg timer and then the browser failing to respond.

I'm having real difficulty in determining where the issue is arising from. Short of disabling large chunks of javascript at a time is there any way to detect a hang in internet explorer and then examine the stack trace to determine the last few functions called in order to localise the problem?

Any help with this would be really appreciated.

[A]
Update
: You can use
Web Development Helper
or
IE Dev Toolbar
to trace your Javascript calls.
Fiddler
is also a powerful web debugging proxy.
If you want to eliminate the IE part of the problem, disable all unnecessary addons loaded in Internet Explorer first. I had a big problem with skype addons.
If you want to do low level monitoring, you have to use tools like Process Explorer and Process Monitor. They have functionalities to show the stack trace, your trace of files and registries being accessed etc from your IE.
For javascript profiling, you can use a tool like
firebug
.


q:
I start a .Net server side program on my local workstation, but soon it throws a security exception. I searched the web for answers, but no quick fix was found / worked. I just want to run my program. How do I get rid of the exception? I fully trust the program, because its mine.

Edit: Oh, yes, I do run the program from a mapped folder that is mapped to my own local drive for the sake of clarity of folder structures. Thanks for the answers, I try tomorrow to run it directly from my drive.

Edit: When I use directly my drive, it works.

[A]
.NET 3.5 SP1 has better support for running applications on the local intranet.
If you can't target 3.5 SP1, you can map the share you're running the application from to a local drive and
use CasPol to set that mapped drive to a fully trusted location.


q: I have 2 columns in a Grid.  When I click a button, I want the first column to animate to the left from it's current position to 0.  So, in effect, it collapses and I'm left with just viewing a single column.

[A]
Shouldn't be too hard.  You'd need to create an EventTrigger that has a BeginStoryboard that targets the grid and uses a DoubleAnimation to shrink the column width.
The example here has a similar setup.
The EventTrigger would go on the button and the DoubleAnimation's
StoryBoard.Target
would point to the ColumnDefinition you wish to shrink.
Okay, so that doesn't work so well.  You can't shrink the column directly, but you CAN set the shrinking column to fill (width="*"), set the width of the Grid and the non-shrinking column, and then shrink the entire grid.  This does work.  The below example works:
```
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      WindowTitle="Opacity Animation Example"
      Background="White">
   <StackPanel Margin="20">
      <Grid Name="MyGrid" Width="200" HorizontalAlignment="Left">
         <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
         </Grid.RowDefinitions>
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="100"/>
         </Grid.ColumnDefinitions>
         <Rectangle HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    Grid.Column="0" Fill="Red"/>
         <Rectangle HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    Grid.Column="1" Fill="Blue"/>
      </Grid>

      <Button Name="hideButton">
         <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
               <BeginStoryboard>
                  <Storyboard>
                     <DoubleAnimation
                         Storyboard.TargetName="MyGrid"
                         Storyboard.TargetProperty="(Grid.Width)"
                         From="200" To="100"
                         Duration="0:0:2"
                         AutoReverse="True"  />
                  </Storyboard>
               </BeginStoryboard>
            </EventTrigger>
         </Button.Triggers>
      </Button>
   </StackPanel>
</Page>
```
```


q:
OK, so instead of writing a whole bunch of access control specs, and duplicating them across many of my spec files, I'm looking to create a custom matcher. So instead of this:

describe "access control" do
  it "should prevent access by non-logged-in users"
  it "should prevent access by normal users"
  it "should prevent access by editor users"
  it "should prevent access by admin users"
  it "should allow access by super admin users"
end

I want do something like this:

lambda do
  get :index
end.should have_access_control(:allowed => [:super_admin], :disallowed => [:admin, :editor, :user])

Are there any examples or suggestions of how I can go about doing something like this?

[A]
OK,
I have found a method of achieving this
, though it doesn't use a custom matcher. Include the following code in your spec_helper.rb:
```
```
def access_control (code, options={})
  options = {:allow => [], :disallow => []}.merge(options)

  options[:allow].each do |user|
    it "#{code} should allow #{user.to_s}" do
      login_as(user)
      eval code
      response.should_not redirect_to(login_path)
    end
  end

  options[:disallow].each do |user|
    it "#{code} should disallow #{user.to_s}" do
      login_as(user)
      eval code
      response.should redirect_to(login_path)
    end
  end
end
```
```
And call it as follows:
```
```
access_control("get :index", {:allow => [:super_admin], :disallow => [:quentin, :admin]})
```
```
You can then use it to build up a complete list of methods that should be restricted, and the users to which they are restricted to.


q:
How do I uninstall a .NET Windows Service if the service files do not exist anymore?

I installed a .NET Windows Service using InstallUtil. I have since deleted the files but forgot to run

 InstallUtil /u

first, so the service is still listed in the Services MMC.

Do I have to go into the registry? Or is there a better way?

[A]
From the command prompt, use the Windows "sc.exe" utility.  You will run something like this:
```
```
sc delete <service-name>
```
```
If the service name has one or more spaces, surround the name in double quotes (h/t @geoffc):
```
```
sc delete "<service-name>"
```
```


q:
A curious thing happens in Java when you use an abstract class to implement an interface: some of the interface's methods can be completely missing (i.e. neither an abstract declaration or an actual implementation is present), but the compiler does not complain.

For example, given the interface:

public interface IAnything {
  void m1();
  void m2();
  void m3();
}

the following abstract class gets merrily compiled without a warning or an error:

public abstract class AbstractThing implements IAnything {
  public void m1() {}
  public void m3() {}
}

Can you explain why?

[A]
That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate.  The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.
Following your example code, try making a subclass of
```
AbstractThing
```
without implementing the
```
m2
```
method and see what errors the compiler gives you.  It will force you to implement this method.


q: Ideally, something cross-platform.

[A]
The CPAN is probably the best way to go.  Take a look at
Term::Screen:Uni
:
```
```
require Term::Screen::Uni;
my $scr = new Term::Screen::Uni;

$scr->clrscr()
```
```


q:
I'm trying to write a Windows cmd script to perform several tasks in series.
However, it always stops after the first command in the script.

The command it stops after is a maven build (not sure if that's relevant).

How do I make it carry on and run each task in turn please?

Installing any software or configuring the registry etc is completely out of the question - it has to work on a vanilla Windows XP installation I'm afraid.

Ideally I'd like the script to abort if any of the commands failed, but that's a "nice to have", not essential.

Thanks.

[A]
When you call another .bat file, I think you need "call" in front of the call:
```
```
call otherCommand.bat
```
```


q:
For example:

javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

[A]
This comes up in Java 5 and later if you're using collections without type specifiers (e.g.,
```
Arraylist()
```
instead of
```
ArrayList<String>()
```
).  It means that the compiler can't check that you're using the collection in a type-safe way, using
generics
.
To get rid of the warning, you need to be specific about what type of objects you're storing in the collection.  So, instead of
```
```
List myList = new ArrayList();
```
```
use
```
```
List<String> myList = new ArrayList<String>();
```
```
In Java 7 you can shorten generic instantiation by using
Type Inference
.
```
```
List<String> myList = new ArrayList<>();
```
```


q:
Are there any tools to assist with the internationalization of Strings within JSP files?

Most IDEs (for example, NetBeans) offer such a feature for Java code. However, in the case of NetBeans, no such feature exists for JSP files.

With gettext, for example, there is are various tools out there that assist with extracting text Strings from code. Something similar for JSP would be great!

[A]
I found this as a
workaround solution
to this problem. Its far from ideal, but allows you to search all Strings with an IDE. Paraphrashing the solution:
JSPs compile to servlets, so find the corresponding servlet class for each JSP on your file system. In the case of Tomcat this would be the 'work' directory.
Import the associated servlet .java file into the IDE, and then use the IDE's regular internationalization tool:
Externalize strings...
(Eclipse) /
Internationalization wizard
(NetBeans).


q:
How do I go about doing this with jQuery?

Basically the structure:

<form id="myForm">
  <iframe>
    <!-- Normal HTML headers omitted -->
    <input type=radio name="myRadio" value=1>First
    <input type=radio name="myRadio" value=2>Second
    <input type=radio name="myRadio" value=3>Third
  </iframe>
  <input type=button value="Submit" />
</form>

I tried various examples from the net such as

$("input[@type=radio][@checked]");

But failed. Even with jQuery form plugin's .fieldValue() failed.

[A]
Try
```
$('#myForm iframe').contents().find('input[name=myradio]').val()
```
I'll assume that the iframe contents have already been loaded and are accessible e.g same domain.


q:
Is there a way to tell the debugger to stop just before returning, on whichever statement exits from the method, be it return, exception, or fall out the bottom? I am inspired by the fact that the Java editor shows me all the places that my method can exit - it highlights them when you click on the return type of the method declaration, (Mark Occurrences enabled).

[eclipse 3.4]

[A]
Good question. Off the top of my head, I'd do this:
```
```
public void method(Object stuff) {
    try {
        /* normal code */
    } finally {
        int x = 0;
    }
}
```
```
You can set the breakpoint on the x = 0 line, and it will ALWAYS be executed no matter where you return. Even with an exception being thrown, it will be run.
The catch to this is scope. Unless you define variables outside of the try block, you won't be able to see their values where you get to the finally block since they will have exited scope.
Having to just place 5 breakpoints (one for each return statement, whatever) may work best.
I hope there is a better way, I'd love to know it.


q:
I've got a spreadsheet with plenty of graphs in it and one sheet with loads of data feeding those graphs.

I've plotted the data on each graph using

=Sheet1!$C5:$C$3000

This basically just plots the values in C5 to C3000 on a graph.

Regularly though I just want to look at a subset of the data i.e. I might just want to look at the first 1000 rows for example. Currently to do this I have to modify the formula in each of my graphs which takes time.

Would you know a way to simplify this? Ideally if I could just have a cell on single sheet that it reads in the row number from and plots all the graphs from C5 to C 'row number' would be best.

Any help would be much appreciated.

[A]
You can set the range for a chart dynamically in Excel. You can use something like the following VBA code to do it:
```
```
Private Sub Worksheet_Change(ByVal Target as Range)
    Select Case Target
    Case Cells(14, 2)
        Sheet1.ChartObjects(1).Chart.SetSourceData Range("$C5:$C$" & Cells(14,2))
    ...
    End Select
End Sub
```
```
In this case, the cell containing the number of the last row to include is B14 (remember row first when referring to the Cells object). You could also use a variable instead of the Cells reference if you wanted to do this entirely in code. (This works in both 2007 and 2003.) You can assign this procedure to a button and click it to refresh your chart once you update the cell containing the last row.
However, this may not be precisely what you want to do ... I am not aware of a way to use a formula directly within a chart to specify source data.
Edit:
And as PConroy points out in a comment, you could put this code in the Change event for that worksheet, so that neither a button nor a key combination is necessary to run the code. You can also add code so that it updates each chart only when the matching cell is edited.
I've updated the example above to reflect this.


q:
Can anyone suggest a tutorial or sample code that implements a nested set (or similar ordered tree structure) with associated Javascript that facilitates drag and drop? I'm looking for both the display code (view) as well as the AJAX backend controller which writes the tree to the database on change.

I want it to represent a multi-layer menu where the ordering and depth of items is important.

[A]
Something like this you really don't wanna be slapping a jquery plugin for. If you can't find anything out there it's time to make yourself an espresso and dive right into the code yourself :)
Use other -- more mature -- code out there as a sample point, but write it yourself and it will really suit your project the best. Looking for front-end and back-end code together is real tough too... unless you want something from a blog post that might be titled something like "30 jquery plugins to AJAXify your website" and you want crap PHP code. (In this case it appears that you want RoR)
This might not be of much assistance to you, but it's what I would do.
I'm particularly anti-jquery-plugins anyway... even if it does the job you want. A lot of that code is bloat. Plus I tend not to trust other people :)


q:
I'd like to show a div that has a background-color with the height and width set to 100% but no content. Is it possible to do that without putting a &nbsp; inside?

Edit: Thanks to Mark Biek for pointing out that empty div with width and height styles shows how I'd expect. My div is in a table cell, where it does not show.

<table style="width:100%">
<tr>
<th>Header</th>
<td><div id="foo"></div></td>
</tr>
</table>

[A]
This seems to work in Firefox, Safari, IE6, & IE7.
```
```

```
```


q:
Greetings!

I am trying to check directory write-permissions from within a Windows MFC/ATL program using C++. My first guess is to use the C-standard _access function, e.g.:

if (_access("C:\mydir", 2) == -1)
   // Directory is not writable.

But apparently on Windows 2000 and XP, _access can't determine directory permissions. (i.e. the Security tab in the Properties dialog when you right-click on a directory in Explorer) So, is there an elegant way to determine a directory's write-permissions in Windows 2000/XP using any of the Windows C++ libraries? If so, how?

Thanks

Evan

[A]
Use sec api.
You can ask on Adv. Win32 api newsgroup :
news://194.177.96.26/comp.os.ms-windows.programmer.win32
where it has often been discussed (C/C++ code)


q:
Does anyone know a good resource to concisely explain the different types of lists available in C# and when their usage is appropriate?

For example, List, Hashtable, Dictionaries etc.

I'm never quite sure when I should be using what.

[A]
If you start at the
MSDN doco for System.Collections
, you can drill down into the individual collection types for more details about those "lists" and how to use them. For example, the doco for
```
Hashtable
```
says, "Represents a collection of key/value pairs that are organized based on the hash code of the key."
There's also a nice discussion of System.Collections.Generic in
Understanding Generics
.


q: How to find out size of session in ASP.NET from web application?

[A]
I think you can find that information by adding
Trace="true"
to the page directive of a aspx page. Then when the page loads you can see a large number of details regarding the page request, including session information i think.
You can also enable tracing in your entire application by adding a line to your web.config file. Something like:
```
```
<trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime"
 localOnly="true"/>
```
```


q:
We recently switched our Windows software packages from RPM (cygwin) to MSI (wix). Having a native packaging is a much welcome change and we intend to stick with it. However, MSI feels overly complicated for what it does and doesn't seem to provide some basic abilities. But I'm probably mistaken.

Is there a way to list all installed MSI from the command line ?

[A]
Mabybe
this
is a good starting point for you example VB Script from MSDN:
```
```
strComputer = "."

Set objWMIService = GetObject("winmgmts:" & _
    "{impersonationLevel=impersonate}!\\" & _
    strComputer & _
    "\root\cimv2")

Set colSoftware = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_Product")

If colSoftware.Count > 0 Then

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objTextFile = objFSO.CreateTextFile( _
        "c:\SoftwareList.txt", True)

    For Each objSoftware in colSoftware
        objTextFile.WriteLine objSoftware.Caption & vbtab & _
        objSoftware.Version
    Next

    objTextFile.Close

Else
    WScript.Echo "Cannot retrieve software from this computer."

End If
```
```


q:
I have a server written in Java that runs as a Windows service (thanks to Install4J).  I want this service to be able to download the latest version of the JAR file it runs from, and start running the new code.  The stitch is that I don't want the Windows service to fully exit.

Ideally, I would accomplish this by a unix-style exec() call to stop the current version and run the new one.  How can I best accomplish this?

[A]
As far as I know, there is no way to do this in Java.
I suppose you could work around it by using the Java
```
Runtime.exec
```
or
```
ProcessBuilder
```
's start() command (which start new processes) then letting the current one end... the docs state
The subprocess is not killed when
  there are no more references to the
  Process object, but rather the
  subprocess continues executing
  asynchronously.
I'm assuming the same is true if the parent finishes and is garbage collected.
The catch is Runtime.exec's process will no longer have valid in, out, and err streams.


q:
Inside a service, what is the best way to determine a special folder path (e.g., "My Documents") for a specific user? SHGetFolderPath allows you to pass in a token, so I am assuming there is some way to impersonate the user whose folder you are interested in.

Is there a way to do this based just on a username? If not, what is the minimum amount of information you need for the user account? I would rather not have to require the user's password.

(Here is a related question.)

[A]
This information is stored in the registry in the key "HKEY_USERS\S-1-5-21-616815238-485949776-2992451252-3228\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders".
The "S-1-5-21-616815238-485949776-2992451252-3218" is the GUID of the user. You need to get this GUID to find the corresponding key and read it.
In
this
example they use SHGetFolderPath function you mention and there is a list with all special folders which might be helpful.
NOTE:
Microsoft discourages to use the registry key, since it is still there just for backward compatibility


q:
Which is faster?  someCondition has the same probability of being true as it has of being false.

Insertion:

arrayList = Array("apple", "pear","grape")
if someCondition then
    ' insert "banana" element
end if

Deletion:

arrayList = Array("apple","banana","pear","grape")
if not someCondition then
    ' remove "banana" element
end if

It looks like it depends purely on the implementation of Insert and Remove.  So which, in general, is faster?  I'm leaning toward insertion because I've read that one can use CopyMemory to insert without looping.  Is this the same for deletion?  Does anyone have an example?

Edit:
This is VB6, not VB.NET.
For display reasons, I have to use insert rather than append.

[A]
I've found an example showing that one can delete without looping as well.  It looks simpler than the code to insert.
```
```
Public Sub RemoveArrayElement_Str(AryVar() As String, ByVal _
    RemoveWhich As Long)
    '// The size of the array elements
    '// In the case of string arrays, they are
    '// simply 32 bit pointers to BSTR's.
    Dim byteLen As Byte

    '// String pointers are 4 bytes
    byteLen = 4

    '// The copymemory operation is not necessary unless
    '// we are working with an array element that is not
    '// at the end of the array
    If RemoveWhich < UBound(AryVar) Then
        '// Copy the block of string pointers starting at
        ' the position after the
        '// removed item back one spot.
        CopyMemory ByVal VarPtr(AryVar(RemoveWhich)), ByVal _
            VarPtr(AryVar(RemoveWhich + 1)), (byteLen) * _
            (UBound(AryVar) - RemoveWhich)
    End If

    '// If we are removing the last array element
    '// just deinitialize the array
    '// otherwise chop the array down by one.
    If UBound(AryVar) = LBound(AryVar) Then
        Erase AryVar
    Else
        ReDim Preserve AryVar(UBound(AryVar) - 1)
    End If
End Sub
```
```
http://www.vb-helper.com/howto_delete_from_array.html


q:
I have a postgres table. I need to delete some data from it. I was going to create a temporary table, copy the data in, recreate the indexes and the delete the rows I need. I can't delete data from the original table, because this original table is the source of data. In one case I need to get some results that depends on deleting X, in another case, I'll need to delete Y. So I need all the original data to always be around and available.

However it seems a bit silly to recreate the table and copy it again and recreate the indexes. Is there anyway in postgres to tell it "I want a complete separate copy of this table, including structure, data and indexes"?

Unfortunately PostgreSQL does not have a "CREATE TABLE .. LIKE X INCLUDING INDEXES'

[A]
Create a new table using a select to grab the data you want.  Then swap the old table with the new one.
```
```
create table mynewone as select * from myoldone where ...
mess (re-create) with indexes after the table swap.
```
```


q:
<html>
    <head>
        <style type="text/css">
            div {
                border:1px solid #000;
                min-width: 50%;
            }
        </style>
    </head>
    <body>
        <div>This is some text. </div>
    </body>
</html>

I believe the div should be 50 percent of the page, unless, for some reason, the text inside the div makes it larger. However, the border around the div stretches across the entire page width. This occurs in both IE and Firefox.

Suggestions?

[A]
If you provide
```
absolute
```
positioning to the element, it will be
```
50%
```
in Firefox.  However, IE doesn't like the
```
min-width
```
or
```
min-height
```
attributes, so you will have to define width as
```
50%
```
also for it to work in IE.


q:
I'm trying to verify if a schema matches the objects I'm initializing.

Is there a way to get the TableName of a class other than simply reflecting the class name?

I am using some class with explicit TableNames

Edit: using Joe's solution I added the case where you don't specify the table name, it could probably use a constraint

public string find_table_name(object obj)
{
        object[] attribs = obj.GetType().GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);

        if (attribs != null)
        {
            ActiveRecordAttribute attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];
            if (attrib.Table != null)
                return attrib.Table;
            return obj.GetType().Name;
        }
    return null;
}

[A]
If you have something like the following:
```
```
[ActiveRecord(Table = "NewsMaster")]
public class Article
{
    [PrimaryKey(Generator = PrimaryKeyType.Identity)]
    public int NewsId { get; set; }

    [Property(Column = "NewsHeadline")]
    public string Headline { get; set; }

    [Property(Column = "EffectiveStartDate")]
    public DateTime StartDate { get; set; }

    [Property(Column = "EffectiveEndDate")]
    public DateTime EndDate { get; set; }

    [Property]
    public string NewsBlurb { get; set; }
}
```
```
This will get you the table name:
```
```
[Test]
    public void Can_get_table_name()
    {
        var attribs = typeof(Article).GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);

        if (attribs != null)
        {
            var attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];
            Assert.AreEqual("NewsMaster", attrib.Table);
        }
    }
```
```


q:
I'm curious to know how people are using table aliases.  The other developers where I work always use table aliases, and always use the alias of a, b, c, etc.

Here's an example:

SELECT a.TripNum, b.SegmentNum, b.StopNum, b.ArrivalTime
FROM Trip a, Segment b
WHERE a.TripNum = b.TripNum

I disagree with them, and think table aliases should be use more sparingly.

I think they should be used when including the same table twice in a query, or when the table name is very long and using a shorter name in the query will make the query easier to read.

I also think the alias should be a descriptive name rather than just a letter.  In the above example, if I felt I needed to use 1 letter table alias I would use t for the Trip table and s for the segment table.

[A]
I feel that you should use them as often as possible but I do agree that t & s represent the entities better than a & b.
This boils down to, like everything else, preferences.  I like that you can depend on your stored procedures following the same conventions when each developer uses the alias in the same manner.
Go convince your coworkers to get on the same page as you or this is all worthless.  The alternative is you could have a table Zebra as first table and alias it as a.  That would just be cute.


q: How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?

[A]
```
```
#include <cstdio>
#include <cstdlib>
#include <string>

void strrev(char *str)
{
        if( str == NULL )
                return;

        char *end_ptr = &str[strlen(str) - 1];
        char temp;
        while( end_ptr > str )
        {
                temp = *str;
                *str++ = *end_ptr;
                *end_ptr-- = temp;
        }
}

int main(int argc, char *argv[])
{
        char buffer[32];

        strcpy(buffer, "testing");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "a");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "abc");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "");
        strrev(buffer);
        printf("%s\n", buffer);

        strrev(NULL);

        return 0;
}
```
```
This code produces this output:
```
```
gnitset
a
cba
```
```


q:
int main()
{
    HandPhone A,B;
    A>>B;//overloading operator>> to simulate sending sms to another handphone(object)
    return 0;
}

How should I declare the istream operator to simulate sending sms to another handphone(object)?

[A]
std::istream
is a class, not an operator.  The << and >> operators can be defined for any two types:
```
```
class A;
class B;

A operator << (A& a, const B& b)    // a << b;  sends b to a.
{
   a.sendMessage(b);
   return a;
}
```
```


q:
I'm trying to install the .Net framework version 2.0 on embedded Windows XP SP2 (aka XPE).

I'm using the XPE specific version of the installer from Microsoft:

http://www.microsoft.com/downloads/details.aspx?familyid=c4837dad-5719-4b63-8752-cb0a65802329&displaylang=en

When the installation starts it fails with the following error:

QFE Installer -- Error
Cannot connect to the database - please check the database

How can I get .Net 2.0 installed on SPE?

[A]
Okay, so you're running the installer that is updating your XPE development environment, right?  Or are you attempting to run that on a device before you seal it?
You need to run that installer on the workstation that has the XPE dev environment (and database) installed.  The installer is looking for a specific database on a specific instance of Sql Server, so if you have (or somebody else has) changed it, you'll need to read up on how to specify the connection string to use with the installer.
In addition, it's probably trying to connect using your windows account credentials.  Make sure you are able to log on to Sql Server, open the DB with the component definitions, and add records to it.  Alternatively, if you can specify the connection string you can set a Sql login username and password to use.
Profiler is a great tool for troubleshooting the two issues described above.
Once you have the components installed, you'll have to add them to your image, check your dependencies and then build it.
If you're trying to just install .NET 2.0 on a machine directly (before you reseal it), you will need the packages for Windows Installer on the machine first.  There might be some other dependencies; I haven't done it in a long time so I can't remember.
The best way to troubleshoot dependencies on an XPE installation is to put ProcessMonitor from Sysinternals on it.  As you run the installer, you'll see where it attempts to find stuff and fails.  Take that information back to your XPE IDE and search your components for those files.  You then have to add the packages containing those files to your image and try again.  Its an arduous process sometimes..,.


q:
How can I make my window not have a title bar but appear in the task bar with some descriptive text?
If you set the Form's .Text property then .net gives it a title bar, which I don't want.

        this.ControlBox = false;
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.ShowInTaskbar = true;
        this.Text = "My title for task bar";

I've found a partial solution, to override CreateParams:

    protected override System.Windows.Forms.CreateParams CreateParams
    {
        get
        {
            System.Windows.Forms.CreateParams cp = base.CreateParams;
            cp.Style &= ~0x00C00000; // WS_CAPTION
            return cp;
        }
    }

However this causes my window to be resized as if they have a title bar, ie it's taller than it should be.  Is there any good solution to this?

[A]
Just set the border style to None.
```
```
this.FormBorderStyle = FormBorderStyle.None;
```
```


q:
I have a checkstyle suppression filter setup (e.g. ignore magic numbers in unit test code).

The suppression xml file resides in the same folder as the checkstyle xml file. However, where this file actually is varies:
on my windows dev box it is in d:\dev\shared\checkstyle\config
on the Linux CI server it will be in /root/repo/shared/checkstyle/config
on another developers box it could be anywhere (they check out their svn repo to).

The only "consistent" thing is that the suppression file is always in the same folder as the checkstyle xml file.
I cannot work out how to ensure that this file is always consistently picked up. Also I don't know why checkstyle does not support embedded suppression within the checkstyle xml file.

any help?

[A]
I had this same problem with the Checkstyle suppression configuration when I was going back and forth between Linux and Windows. Here's how I solved it in my Ant-based build system:
Basically, I inject the proper, platform-specific directory value into the main Checkstyle configuration file by configuring a Checkstyle properties file with an Ant build script.
My main Checkstyle configuration file has a
```
SuppressionFilter
```
module declaration as shown below. The value of the
```
checkstyle-suppressions-file
```
property comes from a Checkstyle properties file:
```
```
<module name="SuppressionFilter">
    <property name="file" value="${checkstyle-suppressions-file}"/>
</module>
```
```
The Checkstyle properties file is not static, it is generated by an Ant build script from a properties file template called
```
template-checkstyle.properties
```
. Here's what the template looks like for the suppressions file property:
```
```
checkstyle-suppressions-file=@SCM_DIR@/checkstyle_suppressions.xml
```
```
My Ant build script copies this file to a file named
```
checkstyle.properties
```
. The copy has the special token replaced with the proper value of the directory in which the suppressions file is found:
```
```
<copy file="${scm.dir}/template-checkstyle.properties" tofile="${scm.dir}/checkstyle.properties">
    <filterset>
        <filter token="SCM_DIR" value="${scm.dir.unix}"/>
    </filterset>
</copy>
```
```
Now, where does the value of
```
scm.dir.unix
```
come from? Well, it's
derived
from a property of my build, read on. You'll need to specify such a value with the directory values that you mentioned.
Note that there is one slightly non-obvious issue concerning the way in which you specify this directory. I say that the
```
scm.dir.unix
```
value is derived from a build property because I observed that the main Checkstyle configuration file cannot contain backslashes, i.e. Windows path separator characters, in the value of the
```
file
```
property of the
```
SuppressionFilter
```
module. For example, specifying something like
```
C:\foo\bar\baz
```
leads to a Checkstyle error message saying that
```
C:foobarbaz
```
cannot be found. I work around this by "converting" the
```
scm.dir
```
directory build property to a "unix" format with Ant's
```
pathconvert
```
task:
```
```
<pathconvert targetos="unix" property="scm.dir.unix">
    <path location="${scm.dir}"/>
</pathconvert>
```
```
Then I call the
```
checkstyle
```
Ant task like this:
```
```
<checkstyle config="${scm.dir}/checkstyle_checks.xml"
            properties="${scm.dir}/checkstyle.properties">
    <!-- details elided -->
</checkstyle>
```
```
The call to the
```
checkstyle
```
task injects the key/value pairs contained in the
```
checkstyle.properties
```
file into the main Checkstyle configuration.
If you like, you can see the full scripts
here
Hope this helps


q: I’m using the gcc in MinGW that comes with Strawberry Perl, on Windows XP. I’d like to have ddd (the Data Display Debugger) as well but apparently on Windows the simplest way to get ddd is by running Cygwin. So what's the bare minimum of Cygwin I can install to get ddd up and running? I'd prefer if I could run ddd natively on Win32 but that doesn't seem to be an option.

[A]
If you're going for minimalism, you might want a smaller X server than
cygwin-x11
(though it's what I use, and I'm quite fond of it).
Starwin X-Win32
is actively maintained (though it costs $$ beyond the trial period), and avoids the overhead of installing Cygwin proper; there are other, zero-cost minimal X servers for win32 available, but I don't have linkage immediately available.
As the documentation at
x.cygwin.com
indicates, the
```
xorg-x11-base
```
package is the bare minimum needed.


q:
Can anyone provide and example of downloading a PDF file using Watin?  I tried the SaveAsDialogHandler but I couldn't figure it out.  Perhaps a MemoryStream could be used?

Thanks,

--jb

[A]
This code will do the trick. The UsedialogOnce class can be found in the WatiN.UnitTests code and will be part of the WatiN 1.3 release (which will probably be released tonigh 14 october).
FileDownloadHandler fileDownloadHandler = new FileDownloadHandler(file.FullName);
using (new UseDialogOnce(ie.DialogWatcher, fileDownloadHandler))
{
    ie.Button("exportPdfButtonId").ClickNoWait();
```
```
fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(30);
fileDownloadHandler.WaitUntilDownloadCompleted(200);
```
```
}
HTH,
Jeroen van Menen
Lead developer WatiN


q:
We've all seen in-browser rich text editors, which allow you to edit colored/styled text in a WYSIWYG manner. But what about code editors, which automatically highlight code based on language rules as you type? Think Eclipse in a textarea (but without the refactoring support).

Do such things exist? I imagine scaling would be a problem - larger files would be difficult  to edit efficiently.

[A]
The
editArea
javascript library does a pretty good job. It's used by the
OpenCMS
content management system as it's in-place JSP and JavaScript editor. The colorization gets a bit confused when the file is > 2000 lines or so.
The feature list from their page is:
Easy to integrate, only one script include and one function call
Tab support (allow to write well formated source code)
Search and replace (with regexp)
Customizable real-time syntax highlighting (currently: PHP, CSS, Javascript, Python, HTML, XML, VB, C, CPP, SQL, Pascal, Basic, Brainf*ck)
Auto-indenting new lines
Line numbering
Multilanguage support (currently: Croatian, Danish, English, French, German, Italian, Japanese, Polish, Portuguese)
Full screen mode
Can work in the same environment than "protype" and "mootools"'s like libraries.


q:
I'm using the following code, using the SharpZipLib library, to add files to a .zip file, but each file is being stored with its full path.  I need to only store the file, in the 'root' of the .zip file.

string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
     zipFile.BeginUpdate();
     foreach (string file in files)
     {
          zipFile.Add(file);
     }
     zipFile.CommitUpdate();
}

I can't find anything about an option for this in the supplied documentation.  As this is a very popular library, I hope someone reading this may know something.

[A]
How about using
System.IO.Path.GetFileName()
combined with the entryName parameter of ZipFile.Add()?
```
```
string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
     zipFile.BeginUpdate();
     foreach (string file in files)
     {
          zipFile.Add(file, System.IO.Path.GetFileName(file));
     }
     zipFile.CommitUpdate();
}
```
```


q:
I'm learning how to make a firefox extension.
I have created a xul and overlay file that makes a sidebar in my browser. I'm trying to put buttons in my sidebar that load different pages within the main browser window. I'm not sure how to access the main browser window and load a new url within it. I have here a simple button and script to show you what I have so far. Any light on this subject would be greatly appreciated!

<script type="application/x-javascript">
    function loadURL(url) {

            // I know this part is wrong. How do I load url into main browser??
    window.content.open(url)
    }
</script>

<button
     id="identifier"
     class="dialog"
     label="Yahoo"
     image="images/image.jpg"
     oncommand="loadURL("http://www.yahoo.com);"/>

[A]
You should be able to access active tab window context in the following way:
```
function loadURL(url) {
    content.wrappedJSObject.location = url;
}
```


q:
We're working with a fixed transaction log size on our databases, and I'd like to put together an application to monitor the log sizes so we can see when things are getting too tight and we need to grow the fixed trn log.

Is there any TSQL command that I can run which will tell me the current size of the transaction log, and the fixed limit of the transaction log?

[A]
A quick google search revealed this:
```
```
DBCC SQLPERF ( LOGSPACE )
```
```
Why aren't you using autogrowth on the transaction log?  It seems like this would be a more reliable solution.


q:
in Config.groovy I see this:

// set per-environment serverURL stem for creating absolute links
environments {
    production {
        grails.serverURL = "http://www.changeme.com"
    }
}

what is the correct way to access that at runtime?

[A]
here it is:
```
```
import org.codehaus.groovy.grails.commons.ConfigurationHolder
println ConfigurationHolder.config.grails.serverURL
```
```
alternatively, in controllers and tags, apparently this will work:
```
```
grailsApplication.config.grails.serverURL
```
```
I needed it in BootStrap, so option 1 was what I needed.


q: Is there code in VBA I can wrap a function with that will let me know the time it took to run, so that I can compare the different running times of functions?

[A]
Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is
```
QueryPerformanceCounter
```
. Google it for more info. Try pushing the following into a class, call it
```
CTimer
```
say, then you can make an instance somewhere global and just call
```
.StartCounter
```
and
```
.TimeElapsed
```
```
```
Option Explicit

Private Type LARGE_INTEGER
    lowpart As Long
    highpart As Long
End Type

Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long

Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double

Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#

Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
    Low = LI.lowpart
    If Low < 0 Then
        Low = Low + TWO_32
    End If
    LI2Double = LI.highpart * TWO_32 + Low
End Function

Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
    QueryPerformanceFrequency PerfFrequency
    m_crFrequency = LI2Double(PerfFrequency)
End Sub

Public Sub StartCounter()
    QueryPerformanceCounter m_CounterStart
End Sub

Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
    QueryPerformanceCounter m_CounterEnd
    crStart = LI2Double(m_CounterStart)
    crStop = LI2Double(m_CounterEnd)
    TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property
```
```


q:
I'm planning on doing my next project in c# rather than c++ (using SlimDX).

All of directX uses floats, however System.Math uses doubles. This means constantly converting between floats and doubles.

So ideally I'd like to write all the code using floats, since I'm not getting any added precision converting to floats from doubles all the time anyways...

However Ive been unable to find a set of maths functions for .net that uses floats. I could of course write my own library in c#, but id rather use an existing library which has been optimised etc...

[A]
XNA provides several math constants (including 3D specialists, like PI/2 etc.) and some advanced math functions with float precision (though not the trigonometric functions). While that is most likely not an option for you, since XNA is not as slim as SlimDX, it certainly means that System.Math is either actually missing something, or the performance hit is not that big. In my experience, you don't actually calculate that much for yourself, because most of that is handled either by the geometry classes (Matrix, Quaternion, Vector) or the GPU itself.
From that point of view, I'd have a look into SlimDX, what they are providing. Seems like the typical things like matrices, vectors, quaternions (and even 16 bit floats) are already there. If you're missing some constants with float precisions, just create them yourself (don't have the cast to be done every time, just at startup).


q: How do I generate a random number between 0 and n?

[A]
Well, I figured it out. Apparently there is a builtin (?) function called rand:
```
```
rand(n + 1)
```
```
If someone answers with a more detailed answer, I'll mark that as the correct answer.


q:
Is there any way to access the file object used by a CSV writer/reader object after it has been instantiated?  I openned up the csv module, and it appears it's contest are builtin.  I also tried setting the file object as a property but I get the following error:

AttributeError: '_csv.writer' object has no attribute 'fileobj'

[A]
```
csv.writer
```
is a "builtin" function.  That is, it is written in compiled C code rather than Python.  So its internal variables can't be accessed from Python code.
That being said, I'm not sure
why
you would need to inspect the csv.writer object to find out the file object.  That object is specified when creating the object:
```
```
w = csv.writer(fileobj, dialect, ...)
```
```
So if you need to access that object later, just save it in another variable.


q:
I'm developing a system that needs to execute Intersystems Cache Terminal Scripts.

When I run a routine inside the regular Caché terminal or a telnet terminal, Cache executes the routine until the end with no problems. But when I try to run the same routine, but this time calling the routine within a Caché terminal Script, Caché disconnects the session after a while. There is no mention at all in the documentation of a "timeout" setting or anything realted to the "" messages i'm getting.

The script is run just like this:

Cterm.exe /console=cn_iptcp:192.168.2.13[23] c:\test.s

1) Does anybody know what may be causing Interystems Caché to disconnected the session in the middle of the run (the session isn't idle either. It regularly outputs status messages to the console)?

2) Any ideas of how to solve it?

Thanks,

Luís Fernando

[A]
Is there a chance it's not a timeout, but some other problem?  Possibly a runtime error that's not being trapped/logged?
The main difference between running from the interactive console and as a script is that when you run interactively you're in Programmer Mode, but in the script you're in User Mode.  I can't think of any reason off-hand why that would matter, but possibly your code is sensitive to that.
Here's something to try:  Write a very simple script that does nothing except write out a character every now and then.  Maybe something like this:
F I=1:1:360 H 10 W "."  ;Write a dot every 10 seconds for 1 hour
If that gets the timeout too then you know it's the terminal, not your code.


q: What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

[A]
The
Clone()
method returns a new array (a shallow copy) object containing all the elements in the original array.  The
CopyTo()
method copies the elements into another existing array.  Both perform a shallow copy.  A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array.  A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.
So the difference are :
```
```
1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.
```
```
Edit:
Remove the wrong example.


q:
How do I determine if the currency symbol is supposed to be on the left or right of a number using CFLocale / CFNumberFormatter in a Mac Carbon project?

I need to interface with a spreadsheet application which requires me to pass a number, currency symbol, currency symbol location and padding instead of a CStringRef created with CFNumberFormatter.

CFLocaleRef currentLocale = CFLocaleCopyCurrent();
CFTypeRef currencySymbol = CFLocaleGetValue (currentLocale, kCFLocaleCurrencySymbol);

provides me with the currency symbol as a string. But I'm lost on how to determine the position of the currency symbol...

[A]
As a workaround, I have started to create a string representing a currency value and determining the position of the currency symbol by searching the string, but this sure looks fishy to me.
```
```
CFNumberFormatterRef numberFormatter = CFNumberFormatterCreate(kCFAllocatorDefault, CFLocaleCopyCurrent(), kCFNumberFormatterCurrencyStyle);
    double someNumber = 0;
    CFStringRef asString = CFNumberFormatterCreateStringWithValue(kCFAllocatorDefault, numberFormatter, kCFNumberDoubleType, &someNumber);
```
```
...
Feel free to hit me with a rolled-up newspaper and tell me the real answer...


q:
In .NET (at least in the 2008 version, and maybe in 2005 as well), changing the BackColor property of a DateTimePicker has absolutely no affect on the appearance. How do I change the background color of the text area, not of the drop-down calendar?

Edit: I was talking about Windows forms, not ASP.

[A]
According to
MSDN
:
Setting the
```
BackColor
```
has no effect on
  the appearance of the
```
DateTimePicker
```
.
You need to write a custom control that extends
```
DateTimePicker
```
. Override the
```
BackColor
```
property and the
```
WndProc
```
method.
Whenever you change the
```
BackColor
```
, don't forget to call the
```
myDTPicker.Invalidate()
```
method. This will force the control to redrawn using the new color specified.
```
```
const int WM_ERASEBKGND = 0x14;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if(m.Msg == WM_ERASEBKGND)
    {
        using(var g = Graphics.FromHdc(m.WParam))
        {
            using(var b = new SolidBrush(_backColor))
            {
                g.FillRectangle(b, ClientRectangle);
            }
        }
        return;
    }

    base.WndProc(ref m);
}
```
```


q:
I have a third-party editor that basically comprises a textbox and a button (the DevExpress ButtonEdit control). I want to make a particular keystroke (Alt + Down) emulate clicking the button. In order to avoid writing this over and over, I want to make a generic KeyUp event handler that will raise the ButtonClick event. Unfortunately, there doesn't seem to be a method in the control that raises the ButtonClick event, so...

How do I raise the event from an external function via reflection?

[A]
From
Raising an event via reflection
, although I think the answer in
VB.NET
, that is, two posts ahead of this one will provide you with the generic approach (for example, I'd look to the VB.NET one for inspiration on referencing a type not in the same class):
```
```
public event EventHandler<EventArgs> MyEventToBeFired;

    public void FireEvent(Guid instanceId, string handler)
    {

        // Note: this is being fired from a method with in the same
        //       class that defined the event (that is, "this").

        EventArgs e = new EventArgs(instanceId);

        MulticastDelegate eventDelagate =
              (MulticastDelegate)this.GetType().GetField(handler,
               System.Reflection.BindingFlags.Instance |
               System.Reflection.BindingFlags.NonPublic).GetValue(this);

        Delegate[] delegates = eventDelagate.GetInvocationList();

        foreach (Delegate dlg in delegates)
        {
            dlg.Method.Invoke(dlg.Target, new object[] { this, e });
        }
    }

    FireEvent(new Guid(),  "MyEventToBeFired");
```
```


q: I am interacting with an Oracle DB using SQL over an ODBC connection.  Is there an SQL command I can use to get the MAC address of the server, or something that uniquely identifies the server hardware or software installation.  This is so I can be sure (or at least fairly sure) that I'm talking to the same database all the time.

[A]
I don't know if you could get the mac address at all. But there are several informations which may help you at the v$instance view.
```
```
SELECT * FROM v$instance;
```
```


q:
I've used a tool from Aspose (Aspose.PDF.kit) to generate a JPG thumbnail on the fly of a PDF for a .NET application.  This works great,  but what kind of other alternatives are there?  Codeproject.com has this tutorial, but it requires you to have the full version of Acrobat.

Is there an open source alternative that's geared for ASP.NET?

[A]
I absolutely despise working with PDF documents.  But when I absolutely have to, I have been using
iTextSharp
.  It has quite a bit of functionality,
the API is fairly well documented
, and it is theoretically free.  Though to use it effectively it helps if you get the book that they push on their website.  I'm not certain if you can easily make thumbnails with it, but it has worked for me in generating and manipulating PDFs on every project I've worked on so far.


q:
I have apache web server installed as frontend and I have j2ee SAP Netweaver Application Server installed in Intranet server. How can I configure apache to forward requests and response to/from j2ee app server.
for example, external apache server's ip is 9.20.1.1:80.
internal sap server's address is 192.168.0.1/sap/bc/gui/sap/its/webgui?sap_client=200
I want access to my sap app server for example 9.20.1.1/sapserver/sap/bc/gui/sap/its/webgui?sap_client=200

[A]
Assuming you have mod_proxy enabled, add to you're sites-available:
```
```
ProxyRequests Off
   <Location "/sapserver">
        ProxyPass http://192.168.0.1
        ProxyPassReverse http://192.168.0.1
   </Location>
```
```
Be careful though as this does expose your internal site to the entire internet.


q:
Is there any real practical difference between "java -server" and "java -client"?

All I can find on Sun's site is a vague

"-server starts slower but should run faster".

What are the real differences?  (Using JDK 1.6.0_07 currently.)

[A] I've not noticed any difference in startup time between the 2, but clocked a very minimal improvement in application performance with "-server" (Solaris server, everyone using SunRays to run the app).  That was under 1.5.


q:
Recently I've been thinking about finite state machines (FSMs), and how I would implement them in software (programming language doesn't matter).

My understanding is that deterministic state machines are in widespread use (parses/lexers, compilers and so on), but what's the matter with non-deterministic state machines?

I know that is possible to convert all non-deterministic state machines to deterministic ones (even programmatically). That's not my point. I also imagine that non-deterministic state machines are much more complicated to implement.

Anyway, does it make any sense to implement a non-deterministic state machine? Are there any special applications I don't know about?
What could be the reasons to do that? Maybe optimized and specialized non-deterministic state machines are faster?

[A]
Most regular expression engines use
non
-deterministic automata since they offer much greater flexibility. DFAs are much more restricted. Have a look at some implementations and you'll see this. Microsoft even underlines this fact in their documentation of the .NET
Regex
class:
The .NET Framework regular expression engine is a backtracking regular expression matcher that incorporates a traditional Nondeterministic Finite Automaton (NFA) engine such as that used by Perl, Python, Emacs, and Tcl.
Matching behavior
(first paragraph) – this article also offers a rationale for the employment of an NFA rather than the more efficient DFA.


q:
I typically use URL rewriting to pass content IDs to my website, so this

 Foo.1.aspx

rewrites to

 Foo.aspx?id=1

For a specific application I need to pass in multiple IDs to a single page, so I've rewritten things to accept this:

 Foo.1,2,3,4,5.aspx

This works fine in Cassini (the built-in ad hoc web server for Visual Studio) but gives me "Internet Explorer cannot display the webpage" when I try it on a live server running IIS. Is this an IIS limitation? Should I just use dashes or underscores instead of commas?

[A]
The right way to
accept
multiple ids is like this:
```
```
Foo.aspx?id=1;id=2;id=3;id=4;id=5
```
```
Note that's just what the target is.  When re-writing urls, you can set your own rules to a certain extent for what you want the source to look like.
I had to learn this on StackOverflow, too.  See this question:
Split out ints from string


q:
In asp.net, you can retrieve MULTIPLE datatables from a single call to the database.  Can you do the same thing in php?

Example:

$sql ="select * from t1; select * from t2;";
$result = SomeQueryFunc($sql);
print_r($result[0]); // dump results for t1
print_r($result[1]); // dump results for t2

Can you do something like this?

[A]
This should be possible with newer MySQL and the mysqli (improved) php extension.
I'm not sure if any DB abstraction layers support this.
See relevant
MySQL docs
and
PHP docs
.


q:
I'm working on a solution that contains multiple projects targeting Windows Mobile 5 and standard Windows applications.

Lately when opening up a form in designer the common UI controls (textbox, button, label, etc etc...) have vanished leaving only the controls defined within the project.

Resetting the toolbox has no effect.  A google search suggested deleting the toolbox temp files in the Local Settings\Application Data\Microsoft\VisualStudio\9.0, however this was only successful in bringing back the default controls for Windows Mobile 5.  The WinForms controls are still mysteriously missing.

Also, if I right-click and Select All on the toolbox, all of the WinForms controls do in fact come up, however they're all grayed out.

Has anyone else experienced this?

[A]
I've noticed this exact same thing for regular WinForms as well. I can't speak to mobile applications but in regular winforms this has a tendency to happen.
I believe it's actually a bug in Visual Studio.
There are some things you can do (again, for WinForms. I'm not sure about mobile) with adding attributes to your control. Such as:
```
```
[ToolboxBitmap(typeof(MyControl), "MyControlBitmap")]
```
```
There are some other useful related things on this site:
http://en.csharp-online.net/Design-Time_Integration-Attributes


q: I have a site that is using x509 client certificates (2 way SSL) to authenticate users and an LDAP directory that contains authorization information. I would like to use one of the certificate attributes to query the directory ( SSL_CLIENT_S_DN_CN to be exact ).  I see how to use mod_ssl to use the user's client certificates for authentication and I see how to use mod_auth_ldap and the like to use the username from basic or form based authentication to query the LDAP store for authorization. What I haven't seen a good example for is how to use an attribute of the user's client certificate in place of the username to query the LDAP. Any ideas?

[A]
this might help:
settingcerts
+
mod_authnz_ldap
(authldapurl)