q:
I just got burned by the Cygwin X11R7.4 update and I find the official mailing lists hostile and clunky.  So I thought I'd ask here.

If you have survived the upgrade (or at least made progress on fixing things), what steps did you take to make things work?

[A]
I ran into this same issue, I couldn't come up with an elegant solution. But the only solution I found was to either use "stitching," or to use reflection.
Stitching looks something like this.
```
```
Person existingPerson - DB.GetPerson(1);
existingPerson.BirthDate = newPerson.BirthDate;
existingPerson.JobTitle = newPerson.JobTitle;
```
```
I once read something about using a callback but I can't find it for the life of me.


q:
Good afternoon,

I have a web query in Excel 2002 going against a web page that returns a date column.  The dates are returned as DD/MM/YYYY, as I would like to show them in my spreadsheet.  My machine running Excel has its regional settings set to en-GB, and the only language set under Internet Options is UK English.

Nevertheless, the web query pulls the dates as MM/DD/YYYY, which is misinterpreted by Excel.

How can I get the Web Query to return the dates in my regional settings, MM/DD/YYYY?

[A]
Maybe you are lucky and Excel understands either the HTML
```
lang
```
attribute or
```
<meta http-equiv="content-language" content="...">
```
meta tag. To be honest - my guess is that it doesn't make a difference.
If you have control over the web site, you can try to add them and see if it makes a difference. OTOH - if you
had
control over the web page, you could change the date format.
The alternative would be to disable date recognition entirely and post-process it by hand after the query. To do this, recreate the web query and in the "New Web Query" dialog box, click the "Options..." button in the upper right. There is a "Disable date recognition" checkbox.

s: huggingface

c: devops

d: intermediate


q:
I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: os.remove("/folder_name").

What is the most effective way of removing/deleting a folder/directory that is not empty?

[A]
```
```
import shutil

shutil.rmtree('/folder_name')
```
```
Standard Library Reference: shutil.rmtree
.
By design,
```
rmtree
```
fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then use
```
```
shutil.rmtree('/folder_name', ignore_errors=True)
```
```


q: How can I create a method that has optional parameters in it in Visual Basic?

[A]
Use the
```
Optional
```
keyword and supply a default value. Optional parameters must be the last parameters defined, to avoid creating ambiguous functions.
```
```
Sub MyMethod(ByVal Param1 As String, Optional ByVal FlagArgument As Boolean = True)
    If FlagArgument Then
        'Do something special
        Console.WriteLine(Param1)
    End If

End Sub
```
```
Call it like this:
```
```
MyMethod("test1")
```
```
Or like this:
```
```
MyMethod("test2", False)
```
```


q:
I'm trying to use a break statement in a for loop, but since I'm also using strict subs in my Perl code, I'm getting an error saying:

Bareword "break" not allowed while
  "strict subs" in use at ./final.pl
  line 154.

Is there a workaround for this (besides disabling strict subs)?

My code is formatted as follows:

for my $entry (@array){
    if ($string eq "text"){
         break;
    }
}

[A]
Oh, I found it.  You use
last
instead of
break
```
```
for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}
```
```


q:
I was wondering if there was a way to bind an ArrayList (or any kind of List, for that matter) to a PreparedStatement which will eventually be used to access an Oracle database.  I found:

PreparedStatement IN clause alternatives?

And that seems similar to my issue, but this question is more specific: I'd like to bind an ArrayList to a PreparedStatement to be used in Oracle, if it is possible, how is this accomplished?

[A]
Well, judging by the answer to that one, especially the comments to my wrong answer in that question, you can't.
See
https://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html#996857
.


q: How can I prune old revisions from my development subversion repository?  I keep a subversion sandbox in which I have lots of test projects, binaries, etc.  I'd like to prune the history occasionally.

[A]
Here's the official answer:
There are special cases where you might want to destroy all evidence of a file or commit. (Perhaps somebody accidentally committed a confidential document.) This isn't so easy, because Subversion is deliberately designed to never lose information. Revisions are immutable trees which build upon one another. Removing a revision from history would cause a domino effect, creating chaos in all subsequent revisions and possibly invalidating all working copies.
The project has plans, however, to someday implement an svnadmin obliterate command which would accomplish the task of permanently deleting information. (See issue 516.)
In the meantime, your only recourse is to svnadmin dump your repository, then pipe the dumpfile through svndumpfilter (excluding the bad path) into an svnadmin load command. See chapter 5 of the Subversion book for details about this.
Found here:
http://subversion.tigris.org/faq.html#removal


q:
What is the proper way to load a ListBox in C# .NET 2.0 Winforms?

I thought I could just bind it to a DataTable. No such luck.

I thought I could bind it with a Dictionary. No luck.

Do I have to write an class called KeyValuePair, and then use List<KeyValuePair> just to be able to load this thing with objects? Maybe I am missing something obvious. I want my display text and values to be different values.

[A]
Lets assume your data type is called MyDataType. Implement ToString() on that datatype to determine the display text. e.g.:
```
```
class MyDataType
{
  public string ToString()
  {
    //return the text you want to display
  }
}
```
```
Then you can take a list consisting of your datatype and cram it into the ListBox via AddRange() as follows:
```
```
ListBox l;
List<MyDataType> myItems = new List<MyDataType>(); // populate this however you like
l.AddRange(myItems.ToArray());
```
```
Let me know if you need more help - it would help to know what datatype you are trying to display in the listbox.


q:
I have a WCF Service decorated with WebInvoke attributes and WebHttp binding for JSON enabling. The service can be accessed from JavaScript until we try to make it working cross domain. Can you please recommend how to get this to work cross domain?

We've tried to create proxy web handler but it gives "Bad Request" everytime WebHttpRequest try to access it.

[A]
For a ridiculously short value  ( Ie: values < 64 characters ), MD5 as a hash becomes ineffective due to rainbow table attacks, and as the value you're sending will be shared over the wire, all they have to do is brute force the shared secret ( and they have a known product to work with )
As such, thats not public key private key. its mererly shared secret.
Also, keep in mind this shared secret will be in your flash file you send to the user, which these days and be trivially disassembled and then your "secret" is not a secret any more.
You want a more challenge-response mechanism with proper crypto signing, where a new sign key is assigned for every game from the server, and multiple scores cannot be submitted with the same sign key. ( For extra protection ;) )
User starts game. Sign key is requested. ( the sign key is produced from another key which they cant access ).
Score is signed with sign key, and then sent
You verify the value of the sign with the key you sent them.
You discard the sign key you sent them.
However, you
still
have the problem where you have no way to prevent the actual scoring system being tampered with. Somebody smart enough could just reverse engineer your SWF object and inject new code that just sets the score to their chosen value.


q:
I want to index a computed column in my database table which uses a number of user defined functions. However I just learned that my column is non-deterministic.

Without indexing its going to be way to slow to run queries that I need.

What's the best way of tracing through user defined functions to determine whether they are deterministic?

Is there any kind of tool in SQL Server Management Studio that will tell me whether a user defined function is deterministic or do I just need to trace through all the system-defined functions I'm using to find out which are non-deterministic and find other ways to write my code without them?

[A]
Try:
```
```
SELECT  *
FROM    INFORMATION_SCHEMA.ROUTINES
WHERE   IS_DETERMINISTIC = 'NO'
        AND ROUTINE_TYPE = 'FUNCTION'
```
```
or
```
```
SELECT OBJECTPROPERTY(OBJECT_ID('schemaname.functionname'), 'IsDeterministic')
```
```
Sorry, IIRC, SQL Server 2000 did not allow non-deterministic UDFs.
Indexing a column that is non-deterministic is pretty of silly - after all if its value is not strictly dependent on parameters, it's not going to be very useful if it changes on you all willy-nilly, especially if it's used in an index to find things!


q:
I have made some changes to a site and need to re-host it as the current host is ceasing to exist.  My client has received the following from the current host:

"The best thing to tell them is that, due to the fact that we are withdrawing our service completely, we would look to fully transfer the web site address across to them rather than just "point" the web address at them. If you can forward this Email to them and ask them to
confirm their "IPS tag" (they'll know what that is), I can then arrange for it to be transferred as and when they confirm it's all ready to go."

Can anyone help me out here as i'm not too sure what they mean, nor do I know what an IPS tag is? ?

[A]
an IPSTAG is a .uk only designation of the domain's registrar. basically, the webhost is asking you to transfer the domain name registration away from them to a new provider.
i would suggest you (or your client) find a new registrar, get their IPSTAG, and then send that to your old host, who will then be able to initiate the change.
once the IPSTAG has been updated (you can check WHOIS information for that), then your new registrar will be able to get the domain name (and thus the old host will have relinquished "control" of it)
here's an example from amazon.co.uk's WHOIS:
```
```
Domain name:
    amazon.co.uk

Registrant:
    Amazon Europe Holding Technologies SCS

Registrant type:
    Unknown

Registrant's address:
    65 boulevard G-D. Charlotte
    Luxembourg City
    Luxembourg
    LU-1311
    LU

Registrar:
    Amazon.com [Tag = AMAZON-COM]
```
```
the IPSTAG in this case is "AMAZON-COM"


q:
I'm making heavy use of PropertySheets in my application framework's configuration editor.  I like them a lot because it's pretty easy to work with them (once you learn how) and make the editing bulletproof.

One of the things that I'm storing in my configuration are Python scripts.  It's possible to edit a Python script in a StringCollection editor, which is what I've been using, but there's a long distance between "possible" and "useable."  I'd like to have an editor that actually supported resizeable and monospace fonts, preserved blank lines, and - hey, let's go crazy with the wishlist - did syntax coloring.

I can certainly write this if I really have to, but I'd prefer not to.

I've poked around on the Google and can't find anything like what I'm describing, so I thought I'd ask here.  Is this a solved problem?  Has anyone out there already taken a crack at building a better editor?

[A]
You would need to write your own type editor. You can think of this as a user control, in that when you write your own type editor you are providing the UI controls that appear when the property grid edits the property. As such, you can create a type editor that does anything, which means if you have a third-party editor control you can include it as part of type editor.
Some resources to get you started:
User Interface Type Editors Overview
Walkthrough: Implementing a UI Type Editor
UITypeEditor Class
How to: Implement a UI Type Editor
Rich Design Time Editing with UITypeEditors (VB.NET)
Creating Property Editors in DesignTime for VS.Net Easily (UITypeEditor Helper)
Using PropertyGrid


q:
I've used boost serialization but this doesn't appear to allow me to generate xml that conforms to a particular schema -- it seems it's purpose was to just to persist a class's state.

Platform: linux

What do you guys use to generate NOT parse xml?

So far I'm going down Foredecker's route of just generating it myself -- it's not a large document but I really shouldn't be having this much trouble finding a decent library to generate it correctly.

As for boost, the things that I would like to be able to do is set the node names, set attributes in my nodes, and get rid of all the extra crap that comes with it as I don't really care about having to put my document back into that class.

[A]
Some may declare me an XML heretic - but one effective way is to just generate it with your favorite string output tools (print, output streams, etc) - this can go to a buffer or a file.
Once saved - you really should then validate with a schema before committing it our shipping it off.
For one of our projects we have a very simple set of templates for managing begin/end tags and attributes.   These each have a stream output operator.   This makes it very easy to generate the source XML and debug.  This makes the structure of the XML generation code look very much like the XML itself.
One advantage of this is that you can generate large amounts of XML efficiently if streaming to a file.  You will pay the validation costs later (presumably at a better time for an expensive operation).
The downside of this technique is that it is essentially output only.   It is not suitable for creating then consuming XML dynamically.


q:
If I have records:

Row  Date,        LocationID, Account
1    Jan 1, 2008  1           1000
2    Jan 2, 2008  1           1000
3    Jan 3, 2008  2           1001
4    Jan 3, 2008  1           1001
5    Jan 3, 2008  3           1001
6    Jan 4, 2008  3           1002

I need to get the row (date, locatinid, account) where the row has the most recent date for each distinct locationid:

4    Jan 3, 2008  1           1001
3    Jan 3, 2008  2           1001
6    Jan 4, 2008  3           1002

[A]
Try something like:
```
```
select *
from mytable t1
where date = (select max(date) from mytable t2
              where t2.location = t1.location);
```
```


q:
I found that SQL stored procedures are very interesting and useful. I have written stored procedures but i want to write well crafted, good performance tuned and concise SPs for any sort of requirement and also would love to learn about any tricks or good practices for stored procedures. How do i move from the beginner to the advanced stage in writing stored procedures?

Update: Found from comments that my question should be more specific.
Everyone has some tricks upon their sleeves and I was expecting such tricks and practices for SPs which they use in their code which differentiates them from others and more importantly spruce up the productivity in writing and working with stored procedures.

[A]
The only trick I always try to use is: Always include an example usage in a comment near the top.  This is also useful for testing your SP.  I like to include the most common examples - then you don't even need SQL Prompt or a separate .sql file with your favorite invocation, since it's stored right there in the server (this is expecially useful if you have stored procs that look at sp_who output for blocks or whatever and take a bunch of parameters).
Something like:
```
```
/*
    Usage:
    EXEC usp_ThisProc @Param1 = 1, @Param2 = 2
*/
```
```
Then to test or run the SP, you simply highlight that section in your script and execute.


q:
How would you ensure that only one user is logged in per account at a time?

Assuming cookies are persistent.

[A]
Typically the best way is to implement a customization on the provider that checks for last login, as well as adding methods to your code to keep track of user action.
The key is that you must know at what point did the user last do something OR logout.  From there you can determine if the account is actually ready.  If you setup the tracking for these elements in code,  You can then modify the membership provider to check to ensure that the account can login.


q:
I'm looking for material on persistent data structures that can be used to implement a relational model.

Persistence in the meaning of immutable data structures.

Anyone know of some good resources, books, papers and such?

(I already have the book Purely Functional Data Structures, which is a good example of what I'm looking for.)

[A]
It is straightforward to modify the ubiquitous
B-tree
to be persistent. Simply always alloctate a new node whenever a node is modified, and return the new node to the recursive caller, who will insert it at that level by allocating a new node, etc. Ultimate the new root node is returned. No more than O(log N) nodes are allocated per operation.
This is the technique used in functional languages to implement, e.g, 2-3 trees.


q: I'm working on a idea where my a:link have one state (blue, no underline etc) with a a:hover being white. I want my visited links to have the same state as a:link and a:hover. Is this possible? supported in most common browsers?

[A]
Here's how you can style the a tags (normal and visited) and style the hover separately.
```
```
a
{
    color:#6c7492;
    font-weight:bold;
    text-decoration:none;
}
a:hover
{
    border-bottom:1px solid #6c7492;
}
```
```


q:
When I do a cvs status, I see working revision and repository revision numbers.
What is the difference between the two, or rather, what do they mean?

[A]
the
working revision
is just the revision you are currently using. the
repository revision
is the revision currently in the repository.
basically, if the
repository revision
is larger than your
working revision
, someone has committed changes to that file, and perhaps you should update your version, or you may end up with a conflict if you try to commit your own changes at a later time.


q:
In through php_info() where the WSDL cache is held (/tmp), but I don't necessarily know if it is safe to delete all files starting with WSDL.

Yes, I should be able to just delete everything from /tmp, but I don't know what else this could effect if I delete any all WSDL files.

[A]
You can safely delete the WSDL cache files. If you wish to prevent future caching, use:
```
```
ini_set("soap.wsdl_cache_enabled", 0);
```
```
or dynamically:
```
```
$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );
```
```


q: I'm setting up CruiseControl.NET and during the build I want to modify my version.txt file and have it checked in.  When I do this, CruiseControl.NET doesn't know this checkin was done by the build and so the next time it checks sources, it sees there were modifications and rebuilds again (I have IfModificationExists set in the project build).  How do I tell CruiseControl.NET to check this file in or let it know that this one is OK so it doesn't keep re-triggering builds?

[A]
I'm not using Subversion, i'm using TFS.
Version.txt contains "1.0.5.3" which is the current build number.  When someone checks out to build, they'll use 1.0.5.3 as their revision.  On the server, it will rev the build number, store it in version.txt and check it back in so that everyone's version is moved up to that level.  So it will be 1.0.5.4" for example.
I basicaly want a way to tell CCNet to checkin a file and ignore it when looking for future modifications.


q:
It seems like Groovy was forgotten in this thread so I'll just ask the same question for Groovy.

Try to limit answers to Groovy core

One feature per answer

Give an example and short description of the feature, not just a link to documentation

Label the feature using bold title as the first line

See also:

Hidden features of Python

Hidden features of Ruby

Hidden features of Perl

Hidden features of Java

[A]
Using hashes as pseudo-objects.
```
```
def x = [foo:1, bar:{-> println "Hello, world!"}]
x.foo
x.bar()
```
```
Combined with duck typing, you can go a long way with this approach.  Don't even need to whip out the "as" operator.


q:
I recently upgraded to Delphi 2009 and was disappointed to find out that I couldn't easily replace one VCL component with another. The best answer back was that GExperts could be used to do this.

Is it worthwhile to petition Embarcadero to incorporate some or all of the capabilities of GExperts right into Delphi? Which of their "Experts" do you use most and would like to see in Delphi?

Or is GExperts best left as a community Open Source addon?

[A]
My number one GExpert is Grep Search.
Close second is the Procedure List window.
Also very handy are the various keyboard shortcuts,
and the toolbar embedded in the editor - I have a few
buttons on there; like CPU-view, Project Manager and
the selection-tools as a dropdown (like sort selection).
Sometimes I use the Clipboard History window.
And even more rarely the ASCII windows.
Everything else I don't touch really.
I know the procedure-list could also be found in the structure-pane of Delphi 2009, but somehow the fact that I can press Ctrl+G to get a window with quick filtering and preview capabilities is more productive for me.
Same thing for grep - the GExperts' version is way more powerfull than the standard Delphi search function.
If these two (and maybe the clipboard history) where embedded in standard Delphi, I probably wouldn't install GExperts anymore.
But on the other hand : I do like the fact that these solutions are available as open source - this allowed me for example to add section-filtering to the grep-search, which otherwise wouldn't have been possible for me...


q:
someone has an idea how can I do that ?

thanks

[A]
If you mean "initialize a dense array of N items in a time independent of N", then it is physically impossible. A dense array has a storage space that grows linearly with the number of items, and it will take a linear amount of time to initialize this space.
You can have constant-time initialization using a sparse array. That is essentially an associative array (or hashmap, or dictionary, or table, depending on the language) which initializes items when they are first accessed.


q:
I noticed that doxygen uses the graphviz library for creating diagrams. Have you ever used graphviz for generating documentation? Is it worth learning the graphviz for documentation purposes outside the scope of doxygen? Or am I better off to sticking with a standard data modeling package like Visio?

I understand the merits of it as a graphing library, but for trying to represent more complex UML (or similar) is it still worth looking into?

[A] The graphviz is very very simple language/format for creating graphs. If the capabilities are enough for you I would recommend it (Its so easy, that I would estimate the time to learn with at most 1 hour).


q:
I'm terrible with regex, but I've had a try and a Google (and even looked in reddit's source) and I'm still stuck so here goes:

My aim is to match the following 'codes' and replace them with the HTML tags. It's just the regex I'm stuck with.

**bold text**
_italic text_
~hyperlink~

Here's my attempts at the bold one:

^\*\*([.^\*]+)\*\*$

Why this isn't working? I'm using the preg syntax.

[A]
use:
```
```
\*\*(.[^*]*)\*\*
```
```
explanation:
```
```
\*\*      // match two *'s
(.        // match any character
[^*]      // that is not a *
*)        // continuation of any character
\*\*      // match two *'s
```
```
in a character class "[ ]" "^" is only significant if it's the first character. so
```
(.*)
```
matches anything,
```
(.[^*]*)
```
is match anything until literal *
edit
: in response to comments to match asterisk within (ie
```
**bold *text**
```
), you'd have to use a non greedy match:
```
```
\*\*(.*?)\*\*
```
```
character classes are more efficient non greedy matches, but it's not possible to group within a character class (
see
"Parentheses and Backreferences...")


q:
Our application is an Xbap running in full trust. I have a function similar to this:

private void ShowPage(Page page)
{
    NavigationWindow mainWindow = Application.Current.MainWindow as NavigationWindow;
    mainWindow.Navigate(page);
}

This works great for browsing inside an existing window. I would like to open this new page in a separate window. Is there anyway to do this?

There is an overload that takes 'extraData' but I haven't been able to determine what to pass to navigate to a new window.

[A]
Apparently WPF is a little new for StackOverflow. Here is the function I came up with in case anyone else stumbles across this.
```
```
private void ShowPage(Page page)
{
    NavigationWindow popup = new NavigationWindow();
    popup.Height = 400;
    popup.Width = 600;
    popup.Show();
    popup.Navigate(page);
}
```
```
I have not tried this in partial trust, it is likely this only works in full trust.


q:
I have a text area and a function to do syntax highlighting on it. Right now it reads the entire RichTextBox. How would I get a string variable containing the current line? Below is the code i currently have.

Private Sub HighLight()
    Dim rm As System.Text.RegularExpressions.MatchCollection
    Dim m As System.Text.RegularExpressions.Match
    Dim x As Integer ''lets remember where the text courser was before we mess with it

    For Each pass In FrmColors.lb1.Items
        x = rtbMain.SelectionStart
        rm = System.Text.RegularExpressions.Regex.Matches(LCase(rtbMain.Text), LCase(pass))
        For Each m In rm
            rtbMain.Select(m.Index, m.Length)
            rtbMain.SelectionColor = Color.Blue
        Next
        rtbMain.Select(x, 0)
        rtbMain.SelectionColor = Color.Black
    Next
End Sub

[A]
Not tried it but:
```
```
rtbMain.Lines(lineNumber)
```
```
if not assign the Lines property to an array and access the array element.


q:
In a Java application (JRE 1.5.0_12) on Windows XP, I call a native method:

public native int attachImage( ... );

... which lives in a Visual C++ 6.0 .dll. It displays an application-modal window. Problem is, the application's tray icon doesn't respond to mouseclicks while this window has focus. This is an issue because when this window is displayed, users often switch to another application to select the image to attach, then want to restore this application.

[A]
What GUI package are you using?
You should be able to implement this without resorting to JNI calls.
For instance, in SWT, you can open an application modal shell like this:
```
```
Shell shell = new Shell(display,SWT.APPLICATION_MODAL);
```
```
For swing, this would be:
```
```
dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
```
```


q:
My Firefox 3.0.4 does not display non-existing images at all, or it displays the image alt as plain text (if available).

This way I would have no idea that there is supposed to be an image there.

Does anyone know if there is a way to make it work like IE/Opera? (ie. display a box even if the image file doesn't exists) - plugin or anything?

Test image:

[A]
As far as i know there is no plugin, Images should have a width and height specified like so:
```
```

or

```
```
Then firefox will reserve the appropiate space for the images.


q:
I'm looking for something like alert(), but that doesn't "pause" the script.

I want to display an alert and allow the next command, a form submit(), to continue. So the page will be changing after the alert is displayed, but it won't wait till the user has clicked OK.

Is there something like this or is it just one of those impossible things?

[A]
You could do the alert in a setTimeout (which a very short timeout) as setTimeout is asynchronous:
```
```
setTimeout("alert('hello world');", 1);
```
```
Or to do it properly you really show use a method rather than a string into your setTimeout:
```
```
setTimeout(function() { alert('hello world'); }, 1);
```
```
Otherwise you open yourself up to JavaScript injection attacks. When you pass a string it is run through the JavaScript
```
eval
```
function.


q:
We have an app that monitors a folder for file drop and need to initiate a virus scan before using any incoming files.

This needs to be a part of the Delphi app and the file must pass the Virus Scan otherwise we delete the file.

I know that there are command shell options available, however this must be a direct API call to a registered AV engine installed on the PC.

We have looked at the MSOffice AntiVirus API but that only seems to be for developers wanting to make scanning apps that are triggered by hosting apps. We need the opposite.

Any suggestions on a Virus Scanning Engine and API would be greatly appreciated.

Thanks in advance.

[A]
The procedure is described
here
, in the section entitled 'Internet Explorer 5 and Office 2000 Implementation'.
A Delphi implementation of enumerating the category is available
here
(GetRegisteredAntiviruses).  Just fill out a TMsoavinfo and call
Scan
.
Most AV programs allow you to scan a file by passing it as a single argument on the command line - I believe Windows Live Messenger uses this method.


q:
I'm using VS 2008 to create a C++ DLL (not managed) project and I need convert a char* to a long long type. Is there an easy way to do it?

Thanks in advance :)

[A]
Try
```
_atoi64.
```
This takes
```
char*
```
and returns
```
__int64
```
.


q: The concept of a coroutine sounds very interesting, but I don't know, if it makes sense in a real productive environment? What are use cases for coroutines, where the coroutine implementation is more elegant, simpler or more efficient than other methods?

[A]
True coroutines require language support.  They need to be implemented by the compiler and supported by the underlying framework.
One language-supported implementation of coroutines is the C# 2.0
```
yield return
```
keyword, which allows you to write a method that returns multiple values for looping.
The
```
yield return
```
does have limitations, however. The implementation uses a helper class to capture state, and it only supports the specific case of a coroutine as a generator (iterator).
In a more general case, an advantage of coroutines is that they make certain state-based computations easier to express and easier to understand.  For example, implementing a state machine as a set of coroutines can be more elegant than other implementations. But doing this requires language support that doesn't yet exist in C# or Java.


q: The Drupal API has drupal_get_path($type, $name) which will give the path of any particular theme or module.  What if I want the path of the current theme?

[A]
this should work (
doc
):
```
```
global $theme;
$path = drupal_get_path('theme', $theme);

// there's also a $theme_path global

global $theme_path;
```
```


q: I was wondering if anyone knew of a macro or keyboard shortcut or anything really that would automate Attaching to a Process within visual studio?

[A]
```
System.Diagnostics.Debugger.Break()
```
"If no debugger is attached, users are asked if they want to attach a debugger. If yes, the debugger is started. If a debugger is attached, the debugger is signaled with a user breakpoint event, and the debugger suspends execution of the process just as if a debugger breakpoint had been hit."
--
http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break.aspx


q:
I need to grab the height of the window and the scrolling offset in jQuery, but I haven't had any luck finding this in the jQuery docs or Google.

I'm 90% certain there's a way to access height and scrollTop for an element (presumably including the window), but I just can't find the specific reference.

[A]
```
```
$(window).height()

$(window).width()
```
```
There is also a plugin to jquery to determine element location and offsets
http://plugins.jquery.com/project/dimensions
scrolling offset = offsetHeight property of an element


q:
There are multiple ways to fill an NSTableView up with data through either bindings, delegates, or data sources.

What is the best way to go about filling up the tableview with data that is changed pretty frequently from an XML-RPC server?  I'm targeting Mac OS X 10.5 only and there are lots of examples on how to do it, but nothing very definitive.

Any opinions?

[A]
If I'm understanding correctly, it's really two separate questions. How do I fetch XML-RPC data, and how to populate a tableview?
I'm not too familiar with XML-RPC, but from doing a quick look around it seems like you can either do the parsing yourself with the NSXML* classes, or use one of several third party frameworks. I think it would be a good idea to look at the available frameworks first, even if you don't end up using one they should give you a good idea of how to go about parsing the XML data yourself if you go that route.
Once you have your data from the XML-RPC request, you'll want to store that in some sort of data structure in a controller class. You could use an array of dictionaries or basic strings, or make a custom object to represent your data, but that really depends on the complexity of what you're doing. The controller object will provide data to the table view, handle refreshing, and any other tasks you may need to do. You could make the XML-RPC request directly from the controller, or you may wish to create an additional class for this to separate the code.
Whether you use data source methods or bindings (along with an array controller) doesn't really matter, they both work fine and have their own advantages. If you're just starting with Cocoa, definitely use data source methods. Bindings requires intermediate knowledge of Objective-C and Cocoa, and will be hard to use and debug otherwise.


q: How do you access a MySQL relation using RoR?

[A]
Your question doesn't really make sense.
Rails works with ActiveRecord which handles all sorts of complex database relationships. Check the AR documentation for details.


q:
I am in the process of setting up CruiseControl.NET. The problem I am having is that I am running CC as a console application and when my build completes successfully and executes (using exec) it launches it within the CruiseControl DOS prompt. I am just using simple batch files to launch my app but having it run within the same prompt as CC is causing CC to think the build continues as long as my app runs.

Are there command line parameters to cmd.exe that will spawn another separate prompt window?

[A]
I think this works:
```
```
start cmd.exe
```
```


q:
I am getting this warning:

Use of uninitialized value in eval \"string\" at myscript.pl line 57.

When I run this code:

eval;
{
        `$client -f $confFile -i $inputFile -o $outputFile`;
};

if( $@ )
{
        # error handling here ...
}

What is causing the error?

How can I fix the underlying cause? (Or otherwise suppress the warning?)

[A]
There is a semicolon after
```
eval
```
.


q:
I am considering using Maven for a Java open source project I manage.

In the past, however,  Maven has not always had the best reputation. What are your impressions of Maven, at this time?

[A]
The JavaPosse discussed Maven quite a bit in
recent podcast #217
. The consensus was that it's very restrictive in how it allows you to structure your projects, but that its usage is growing, and that it may offer a cross-IDE standard for representing a project.
Update
—Javaposse also hosted an informative session at last spring's Java Roundup 09 entitled,
"Maven with Pain?"
I laughed (in horrified sympathy) as, toward the end of the recording, one of the participants related how a plugin update broke their build—two days before a production release.
I've steered clear of it, honestly, in large part because I find the name irritating. However, the ability to manage dependencies of third-party libraries is appealing.
Update
—for those that have an irrational disdain for my irrational opinion, let me show you what "maven" conjures up in my mind:
Yes, in my mind, Edna Mode is
the
epitome of "maven". And I don't want her in my build—too bossy!
What would be a better name? Invented words are best for their pin-point Google results. For a good impression, root them in real words with a positive connotation.


q:
I'm wondering why styling an element within a specific class, like this:

.reddish H1 { color: red }

is shown as an example of correct syntax in the CSS1 specification under Contextual selectors:

Cascading Style Sheets, level 1

but it's not shown as an example in the CSS2 spec:

Cascading Style Sheets, Level 2

At least I can't find an example of it. Has the syntax rules for this changed in CSS2, or is it simply inferred as correct syntax?

[A]
That syntax is correct, but the example may have changed for a couple of reasons.
Firstly it is not best practice to name classes by the description of what they do. In the case of
```
.reddish h1
```
, the example CSS shows that it is to be coloured red. However, if in a later design change the
```
h1
```
should in fact be blue then
```
```
.reddish h1 { color: blue; }
```
```
makes little sense. You should name your classes by their function or purpose on the page and not by what style they are supposed to represent.
Secondly, it isn't advised to use keywords for colours, as the colour you receive is down to browser interpretation. Instead, of 'red' you should use the hexcode '#ff0000' to get an accurate colour in all browsers. (red may not be the best example here, but there are some strange colour keywords out there).
While neither of these things is that bad, they both could add up to why the example had changed in the spec.


q:
Is it possible using jQuery to select all <a> links which href ends with "ABC"?

For example, if I want to find this link <a href="http://server/page.aspx?id=ABC">

[A]
```
```
$('a[href$="ABC"]')...
```
```
Selector documentation can be found at
http://docs.jquery.com/Selectors
For attributes:
```
```
= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")
```
```


q:
I am having trouble constructing a single XPath statement to return two different sets of attributes.

For example take the following XML document:

<root>
 <line name="one" alpha="a1" beta="b1"/>
 <line name="two" alpha="a2" beta="b2"/>
 <line name="three" alpha="a3" beta="b3"/>
</root>

If I use the following XPath statement:

//@alpha

It yields the following attribute set:

alpha="a1"
alpha="a2"
alpha="a3"

What statement do I use to yield the following attribute set:

alpha="a1"
alpha="a2"
alpha="a3"
beta="b1"
beta="b2"
beta="b3"

[A]
By using the
```
|
```
operator in an XPath expression you can select several paths:
```
```
//@alpha | //@beta
```
```


q:
Is it possible for me to turn on audit logging on my mysql database?

I basically want to monitor all queries for an hour, and dump the log to a file.

[A]
UPDATE: NO LONGER VALID FOR MYSQL 5.6+
Start mysql with the --log option:
```
```
mysqld --log=log_file_name
```
```
or place the following in your
```
my.cnf
```
file:
```
```
log = log_file_name
```
```
Either one will log all queries to log_file_name.
You can also log only slow queries using the
```
--log-slow-queries
```
option instead of
```
--log
```
.  By default, queries that take 10 seconds or longer are considered slow, you can change this by setting
```
long_query_time
```
to the number of seconds a query must take to execute before being logged.


q:
I have a multi-threaded application that is hanging on a call to _dl_sysinfo_int80().  According to gdb, all threads are stuck in this call.

The top of the stack trace looks like:

#0  0x002727a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1  0x004f23de in __lll_mutex_lock_wait () from /lib/tls/libpthread.so.0
#2  0x004ef00b in _L_mutex_lock_35 () from /lib/tls/libpthread.so.0
#3  0x092828ac in construction vtable for std::ostream-in-std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> > ()

Any idea what could be causing this?

[A]
int 80 is the software interrupt to make a kernel level system call.  My guess is that pthread is doing a call in to the kernel that is hanging.  There could be any number of reasons for why all of your threads would hang on a mutex like this:
- The mutex is locked by another thread that exited without releasing the lock
- The mutex is locked by one of the threads that is typing to lock it and wasn't declared recursive
- The mutex was never initialized at all
- The mutex has been corrupted by a bad pointer, stack problem, some other type of general memory corruption.


q: What's the easiest way to truncate a C++ float variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?

[A]
First it is important to know that floating point numbers are approximated.   See the link provided by @Greg Hewgill to understand why this problem is not fully solvable.
But here are a couple of solutions to the problem that will probably meet your need:
Probably the better method but less efficient:
```
```
char sz[64];
double lf = 0.600000002;
sprintf(sz, "%.4lf\n", lf); //sz contains 0.6000

double lf2 = atof(sz);

//lf == 0.600000002;
//lf2 == 0.6000

printf("%.4lf", lf2); //print 0.6000
```
```
The more efficient way, but probably less precise:
```
```
double lf = 0.600000002;
int iSigned = lf > 0? 1: -1;
unsigned int uiTemp = (lf*pow(10, 4)) * iSigned; //Note I'm using unsigned int so that I can increase the precision of the truncate
lf = (((double)uiTemp)/pow(10,4) * iSigned);
```
```


q: I want to create a right click context menu for my textboxes to provide the typical copy/paste functionality. Any ideas on how to go about this?

[A]
Looks like this is a
way to do this here
,
another example here
, and the
most recent one here
. Using these methods you should be able to show your own context menu. Once you have that you'll need access to the clipboard and there is an
example of this here
.
Good luck!


q: Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?

[A]
never used it myself, but I do follow the ipython mailing list, and there was a
thread
a couple months back.
maybe this will help
http://lists.ipython.scipy.org/pipermail/ipython-user/2008-September/005791.html
It's also a very responsive mailing list if you run into trouble.


q:
The comment to this answer got me wondering.  I've always thought that C was a proper subset of C++, that is, any valid C code is valid C++ code by extension.  Am I wrong about that?  Is it possible to write a valid C program that is not valid C++ code?

EDIT: This is really similar to, but not an exact duplicate of this question.

[A]
In general, yes C code is considered C++ code.
But C is not a proper subset in a strict sense.  There are a couple of exceptions.
Here are some valid things in C that are not valid in C++:
```
```
int *new;//<-- new is not a keyword in C
char *p = malloc(1024); //void * to char* without cast
```
```
There are more examples too, but you get the idea.
I previously wrote a more extensive answer in a similar question
here
.


q:
Having the window handle for an open application, I'm able to use the GetWindowText function to retrieve the text from the title bar of the app.  I would like to take this a step farther and retrieve the icon associated with the same app.

How might I go about doing this?  I looked through what I thought would be the relevant Win32 API sections, but nothing jumped out at me.

Any pointers would be appreciated.

Thanks in advance!

[A]
```
```
Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);
```
```
From TheSoftwareJedi
Initially this appears to be an exact duplicate of
How can I get the icon from the executable file only having an instance of it's Process in C#
but that one seems to focus largely on how to get it from within it's own self, whereas you may be asking how to get the icon using a program separate from the running process.
-Adam


q:
How do I return a constant from an sql statement?

For example how would I change the code below so "my message" would return if my (boolean expression) was true

if (my boolean expression)
 "my message"
else
 select top 1 name from people;

I am using ms sql 2000

[A]
Did you try:
```
```
select 'my message';
```
```


q:
I've been using ISAPI_Rewrite from Helicon (http://www.helicontech.com/isapi_rewrite/) on a Server 2003 box for years and have always had good luck with it.

I'm migrating all the sites on the 2003 box to a new shiny Server 2008 box.  I would prefer to not purchase a new license and I have heard that IIS 7 will have capability built in.

All the rewrites are setup in a .htaccess configuration file just like mod_rewrite for Apache.

Does anyone know if this capability ever got baked into IIS 7 and if so do you know of any good articles that explain how to get it all enabled?

Thanks.

[A]
IIS7 does have the functionality built in, as you mentioned. You can either use a custom HttpModule, as described in
Tip/Trick: Url Rewriting with ASP.NET
.
Alternatively, you could install the the
IIS7 Rewrite Module
as
described here
.


q:
I am using Python and the Twisted framework to connect to an FTP site to perform various automated tasks.  Our FTP server happens to be Pure-FTPd, if that's relevant.

When connecting and calling the list method on an FTPClient, the resulting FTPFileListProtocol's files collection does not contain any directories or file names that contain a space (' ').

Has anyone else seen this?  Is the only solution to create a sub-class of FTPFileListProtocol and override its unknownLine method, parsing the file/directory names manually?

[A]
Firstly, if you're performing automated tasks on a retrieived FTP listing then you should probably be looking at
```
NLST
```
rather than
```
LIST
```
as noted in
RFC 959 section 4.1.3
:
```
NAME LIST (NLST)
 ...
            This command is intended to return information that
            can be used by a program to further process the
            files automatically.
```
The
Twisted documentation
for
```
LIST
```
says:
```
It can cope with most common file listing formats.
```
This make me suspicious; I do not like solutions that "cope".
```
LIST
```
was intended for human consumption not machine processing.
If your target server supports them then you should prefer
```
MLST
```
and
```
MLSD
```
as defined in
RFC 3659 section 7
:
```
7.  Listings for Machine Processing (MLST and MLSD)

   The MLST and MLSD commands are intended to standardize the file and
   directory information returned by the server-FTP process.  These
   commands differ from the LIST command in that the format of the
   replies is strictly defined although extensible.
```
However, these newer commands may not be available on your target server and I don't see  them in Twisted. Therefore
```
NLST
```
is probably your best bet.
As to the nub of your problem, there are three likely causes:
The processing of the returned results is incorrect (Twisted may be at fault, as you suggest, or perhaps elsewhere)
The server is buggy and not sending a correct (complete) response
The wrong command is being sent (unlikely with straight
```
NLST
```
/
```
LIST
```
, but some servers react differently if arguments are supplied to these commands)
You can eliminate (2) and (3) and prove that the cause is (1) by looking at what is sent over the wire. If this option is not available to you as part of the Twisted API or the Pure-FTPD server logging configuration, then you may need to break out a network sniffer such as tcpdump, snoop or WireShark (assuming you're allowed to do this in your environment). Note that you will need to trace not only the control connection (port 21) but also the data connection (since that carries the results of the
```
LIST
```
/
```
NLST
```
command). WireShark is nice since it will perform the protocol-level analysis for you.
Good luck.


q: Is there a way to find all nodes in a xml tree using cElementTree? The findall method works only for specified tags.

[A]
You can use
XPath paths
on the findall method:
The 1.2 release supports simple
  element location paths. In its
  simplest form, a location path is one
  or more tag names, separated by
  slashes (/).
You can also use an asterisk (*)
  instead of a tag name, to match all
  elements at that level. For example,
  */subtag returns all subtag grandchildren.
An empty tag (//) is used to search on
  all levels of the tree, beneath the
  current level. The empty tag must
  always be followed by a tag name or an
  asterisk.
```
```
etree.findall('.//*')
```
```


q: What Inversion of Control Container framework would you recommend to a beginner in this area?

[A]
I have done some evaluation of the
Spring.NET port
.  It offers AOP, config-file setup of the container, and other cool stuff.  I think their site is well organized and the docs are well written.


q:
I have a custom NSTableView subclass which is bound to a data source (an NSArray) which updates asynchronously. When items are added to the array, rows are automatically added to the tableview. Awesome!

My question is this: How can I detect that this magic has happened so that I can perform some other tasks related to the display of my custom tableview? Is there a method that I can override in my subclass which will be called when the tableview is updated?

[A]
You don't need to subclass NSTableView to change its height based on the number of rows. In your controller, just monitor the data array using KVO and adjust the frame size of the tableview's scrollview (you can find it using
```
enclosingScrollView
```
) when rows are added or removed. I've used this technique before and it's worked well. You can use the tableview's
```
rowHeight
```
and
```
intercellSpacing
```
methods to calculate the height of the frame.


q:
I've been contacted to see about updating an old legacy web application that was built using ASP and Access. The server is running Windows 2000 Advanced Server and I believe IIS 5.0 (I am trying to get confirmation on that, but the company isn't technical so I highly doubt Apache is running on the server).

What languages would be viable for updating this web app on the above platform? I've never touched classic ASP much less done any web development work against Windows 2000/IIS 5. There are no plans on updating the server to anything new due to budget concerns.

I'm leaning at the moment to moving to an SQLite-based database (customer isn't too keen on installing MySQL at the moment but I'm still in planning stages and this is a relatively low-traffic website) but what language would I pair with that? Does ASP.NET work well under IIS 5? Does PHP perform worth anything under this kind of setup?

[A]
If the company is concerned with cost, I would be very conservative making changes.  Concentrate on why they want to update- do they want to add new functionality?  What are their mid-to-long term plans for the site?  Are they having trouble maintaining the site?  Going to a custom .NET solution may only complicate things further unless they are willing to make some ongoing investment in development.
If it's a relatively simple site, they may want to consider a platform like DotNetNuke.  There are hosts out there that sell ready-to-configure sites that can do quite a lot with a minimum of configuration.  That combined with a profressionally developed DotNetNuke UI template (TemplateMonster.com offers them) may be a good solution.
If they do want to go with a custom solution, ASP.NET runs fine on IIS 5.0.  I believe you can run the .NET Framework up to at least 2.0, not sure about 3.0 or 3.5.  Language won't make a difference to functionality, so C# or VB.NET are fine, all things being equal.


q:
<?php
class foo
{
    //this class is always etended, and has some other methods that do utility work
    //and are never overrided
    public function init()
    {
        //what do to here to call bar->doSomething or baz->doSomething
        //depending on what class is actually instantiated?
    }

    function doSomething()
    {
        //intentionaly no functionality here
    }

}

class bar extends foo
{
    function doSomething()
    {
        echo "bar";
    }
}

class baz extends foo
{
    function doSomething()
    {
        echo "baz";
    }
}
?>

[A]
```
```
public function init() {
    $this->doSomething();
}

$obj = new bar();
$obj->doSomething(); // prints "bar"

$obj2 = new baz();
$obj->doSomething(); // prints "baz"
```
```


q:
I assume 100 bytes is too small and can slow down larger file transfers with all of the writes, but something like 1MB seems like it may be too much.  Does anyone have any suggestions for an optimal chunk of bytes per write for sending data over a network?

To elaborate a bit more, I'm implementing something that sends data over a network connection and show the progress of that data being sent.  I've noticed if I send large files at about 100 bytes each write, it is extremely slow but the progress bar works out very nicely. However, if I send at say 1M per write, it is much faster, but the progress bar doesn't work as nicely due to the larger chunks being sent.

[A]
If you can, just let the IP stack handle it; most OSes have a lot of optimization already built in. Vista, for example, will dynamically alter various parameters to maximize throughput; second-guessing the algorithm is unlikely to be beneficial.
This is especially true in higher-order languages, far from the actual wire, like C#; there are enough layers between you and actual TCP/IP packets that I would expect your code to have relatively little impact on throughput.
At worst, test various message sizes in various situations for yourself; few solutions are one-size-fits-all.


q: The Python datetime.isocalendar() method returns a tuple (ISO_year, ISO_week_number, ISO_weekday) for the given datetime object.  Is there a corresponding inverse function?  If not, is there an easy way to compute a date given a year, week number and day of the week?

[A]
EDIT: ignore this, the edge cases are a pain. Go with Ben's solution.
Ok, on closer inspection I noticed that
```
strptime
```
has
```
%W
```
and
```
%w
```
parameters, so the following works:
```
```
def fromisocalendar(y,w,d):
   return datetime.strptime( "%04dW%02d-%d"%(y,w-1,d), "%YW%W-%w")
```
```
A couple of gotchas: The ISO week number starts at
```
1
```
, while
```
%W
```
starts at
```
0
```
.  The ISO week day starts at
```
1
```
(Monday), which is the same as
```
%w
```
, so Sunday would probably have to be
```
0
```
, not
```
7
```
...


q:
I am given a responsibility in my project to develop a Equipment tracking tool with following requirements

New Equipment can be added by admin to a particular user

Once equipment is assigned to a person he will a request to accept the request so he will be responsible

User can transfer his equipment to other users.

At the same time Admin should be sent a mail or message whenever there is a change in status.

It should be deployed locally on a PC( So it is not actually a web app) that is connected to network which can be accessed by everyone

I thought I can use Django for this( I am new to it ), but I do not know much about deployment on a local PC , How can I do this, or is there any better Idea for this?

[A]
It still sounds like you want a web app, you just won't be deploying it on a traditional web server.  One thing to note, client versions of Windows (XP, Vista) will limit you to 10 incoming connections per computer.
You'll want to follow these
instructions on how to install Django
.  If you haven't installed python yet, I'll recommend that you
install version 2.5
, since that will include sqlite, an embedded database that makes it
very easy
to get started developing with Django.  Django includes its own development web server, which you will come across naturally as you
go through the tutorial
.
Start by installing and then jump right into the tutorial.  Your deployment options will be much easier to understand once you're comfortable with developing in Django.


q:
I am looking to use Java to get the MD5 checksum of a file.  I was really surprised but I haven't been able to find anything that shows how to get the MD5 checksum of a file.

How is it done?

[A]
There's an example at
Real's Java-How-to
using the
MessageDigest
class.
Check that page for examples using CRC32 and SHA-1 as well.
```
```
import java.io.*;
import java.security.MessageDigest;

public class MD5Checksum {

   public static byte[] createChecksum(String filename) throws Exception {
       InputStream fis =  new FileInputStream(filename);

       byte[] buffer = new byte[1024];
       MessageDigest complete = MessageDigest.getInstance("MD5");
       int numRead;

       do {
           numRead = fis.read(buffer);
           if (numRead > 0) {
               complete.update(buffer, 0, numRead);
           }
       } while (numRead != -1);

       fis.close();
       return complete.digest();
   }

   // see this How-to for a faster way to convert
   // a byte array to a HEX string
   public static String getMD5Checksum(String filename) throws Exception {
       byte[] b = createChecksum(filename);
       String result = "";

       for (int i=0; i < b.length; i++) {
           result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
       }
       return result;
   }

   public static void main(String args[]) {
       try {
           System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));
           // output :
           //  0bb2827c5eacf570b6064e24e0e6653b
           // ref :
           //  http://www.apache.org/dist/
           //          tomcat/tomcat-5/v5.5.17/bin
           //              /apache-tomcat-5.5.17.exe.MD5
           //  0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe
       }
       catch (Exception e) {
           e.printStackTrace();
       }
   }
}
```
```


q:
Ok, I have one JavaScript that creates rows in a table like this:

  function AddRow(text,rowID) {
    var tbl = document.getElementById('tblNotePanel');
    var row = tbl.insertRow(tbl.rows.length);

    var cell = row.insertCell();
    var textNode = document.createTextNode(text);
    cell.id = rowID;
    cell.style.backgroundColor = "gold";

    cell.onclick = clickTest;

    cell.appendChild(textNode);
  }

In the above function, I set the cell's onclick function to call another JavaScript function called clickTest.  My question is when I assign the onclick event to call clickTest, how do I set parameter information to be sent when the clickTest method is called on the cell's onclick event?  Or, how do I access the cell's ID in the clickTest function?

Thanks,
Jeff

[A]
In the clickTest function you should have access to a the
```
this
```
variable.  Try this inside of
```
clickTest
```
function:
```
```
alert(this.id);
```
```
This will refer to the DOM element that fired the event.
Basically, there isn't really a way to pass parameters to an event handler function.  The reason for that is that the browser is executing the function based on an event and you are not actually calling the function.
You can use closures which allow you to access local variables (to the closure) when you assign the event handler function.  That would look like this:
```
```
cell.onclick = function() { alert(this.id); alert(cell.id); };
```
```
Were
```
cell.id
```
is the locally scoped variable that is still considered in scope when the event handler is executed.


q:
What is a security sandbox violation, and how do I override it? I'm making a project in FlashDevelop, and today, it will not load external files, even though it had been previously. It gives the following output:

************* Security Sandbox Violation *********   Connection to
  file:///C|/Documents%20and%20Settings/Kevin.PC885314341208/Desktop/Import%20.txt/StockData/1.txt
  halted - not permitted from
  file:///C|/Documents%20and%20Settings/Kevin.PC885314341208/Desktop/Import%20.txt/import.swf

I hope this isn't a serious problem.

Thanks for any help.

[A]
You're loading a local file, something that's not permitted. However, as you're developing this you can of course allow this.
Add your project folder to the trusted locations:
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html
Edit: I might add that if you run it with networking disabled it will work (this is for development purposes). This happens for example when you run it from the Flash IDE, which would explain why it may have worked before?


q:
I`ve read that columns that are chosen for indices should discriminate well among the rows, i.e. index columns should not contain a large number of rows with the same value. This would suggest that booleans or an enum such as gender would be a bad choice for an index.

But say I want to find users by gender and in my particular database, only 2% of the users are female, then in that case it seems like the gender column would be a useful index when getting the female users, but not when getting all the male users.

So would it generally be a good idea to put an index on such a column?

[A] This is a case where I would let the server statistics inform me of when to create the index.  Unless you know that this query is going to predominate or that running such a query would not meet your performance goals a priori, then creating the index prematurely may just cost you performance rather than increase it.  Also, you may want to think about how you would actually use the query.  In this case, my guess would be that you'd typically be doing some sort of aggregation based on this column rather than simply selecting the users who meet the criteria.  In that event, you'll be doing the table scan anyway and the index won't buy you anything.


q: Does MySQL index foreign key columns automatically?

[A]
Yes, see
InnoDB and FOREIGN KEY Constraints
.


q:
Is there a way I can export my Silverlight DataGrid data to excel or csv?

I searched the web but can't find any examples!

Thanks a lot

[A]
I don't think Silverlight offers a way to download files.  You can add a button to your app that calls a URL- i.e.
http://www.mysite.com/generateexcelfile.aspx
.  Include as Querystring values the parameters used to generate the data being displayed in your Silverlight app, run your query and use your favorite Excel file generation component to generate the file on the fly.  Redirect to it and it will download to the users' system.


q:
What is the best way to integrate an external script into the Zend Framework? Let me explain because I may be asking this the wrong way. I have a script that downloads and parses an XML file. This script, which runs as a daily cron job, needs to dump its data into the database.

I am using Zend Framework for the site which uses this script and it seems to me that it would be best to use my subclassed model of Zend_Db_Abstract to do the adding and updating of the database. How does one go about doing this? Does my script go in the library next to the Zend Components (i.e. library/Mine/Xmlparse.php) and thus have access to the various ZF components? Do I simply need to include the correct model files and the Zend DB component in the file itself? What is the best way to handle this sort of integration?

[A]
I just came across something that may be germane to this question.
This IBM developerWorks article.
The author recommends simply creating a scripts folder in the ZF hierarchy and the using it as one normally would within ZF (though he does set the ini path and call autoload). Is it that simple? Does simply being in the hierarchy of the framework and including the path and autoloader grant your script access to all of the goodies?


q:
Was wandering if anyone uses ASP .NET membership? If you do, tell me what you think about it.

If you don't use it, Are you planning to use it on future projects? If not, why?

RWendi

[A]
Yes. Have used it quite a lot, and it will save you a lot of work.
There are some pain points like changing usernames, and administrative reset of passwords, that clients will often ask for, and you will have to hack your way around them.
The role provider is also pretty handy, and there are a lot of prebuilt controls that work with it, although recently hit a bug between role manager and aspnet ajax that has been a PITA.
The model is generally very good, even if you have shop around for some different providers that suit your needs.
Overall, it's not perfect, but if you can live with it and work around it's issues, it will save you heaps of code.
For some situations, it is maybe using a chainsaw when a butter knife would do, but it's there, it works, and there are plenty of other people using it.
Its one kind of hammer, for the price, is ok, but there is no golden hammer.


q:
I'm looking to get some help on using the cycle library for jQuery. I'm in the beginner demos, and I got the absolute first one completed. This is the second one on the page.

<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery.cycle.all.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {

    $('.pics').cycle({
        fx:      'scrollDown',
        speed:    300,
        timeout:  2000
    });
</script>

My CSS is identical to the one on the page, that's why I put .pics in the quotes.

[A]
I will take a guess that this is just not working for you.
You need to balance your braces and parentheses.
Please
help others to help you by saying what the actual problem is next time.
Try this:
```
```
$(document).ready(function() {
    $('.pics').cycle({
        fx: 'scrollDown',
        speed: 300,
        timeout: 2000
    });
});
```
```


q:
How long do you normally test an update for Zend Framework before pushing it out into a productions project.  We can break this question up into minor updates 1.6.0 -> 1.6.1 or maybe a major update 1.6.2 -> 1.7.0.  Obviously you don't release it if it add bugs to your code.

Also, as with most other server software updates normally people have a window of time they like to wait and watch the community before even attempting an update on a development environment.  How long do you even wait to start the process?

[A]
It seems like the best method would be to have a comprehensive set of tests that exercised all the functionality in your application.  With a good method for testing it seems like you could push it into production pretty quickly.
Another simple thing you can do to help you make your decision would be to simply do a diff against the repository to see what changes where applied to any modules that you use.  If there where no changes, then upgrading shouldn't make any difference.  If something underwent a major re-write, you would probably want to investigate a lot deeper.


q: How do I compare two images & recognize the pattern in an image irrespective of its size and pattern size, and using .Net C#?  Also, which algorithms are used for doing so from Image Processing?

[A]
See
Scale-invariant feature transform
,
template matching
, and
Hough transform
. A quick and inaccurate guess may be to make a histogram of color and compare it. If the image is complicated enough, you might be able to distinguish between several sets of images.
To make the matter simple, assume we have three buckets for R, G, and B. A completely white image would have (100%, 100%, 100%) for (R, G, B). A completely red image would have (100%, 0%, 0%). A complicated image might have something like (23%, 53%, 34%). If you take the distance between the points in that (R, G, B) space, you can compare which one is "closer".


q: In VB.NET, which is better to use: function overloading or default parameters?

[A]
if the parameters are optional (i.e. the overloads are a subset of the parameters that the full procedure signature accepts) then default or optional parameters would make more sense.
If the overload is allowing a different type for the parameter or is a semantically different parameter that will be interpreted differently by the routine then overloads would make more sense.


q:
Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?

Note: I am rewriting an existing system that is painfully slow.


q: One of the appropriate uses for sqlite3 is "in-memory databases".  This sounds like a really useful tool for my C++ applications.  Does anyone have an example of how this is done in C or C++?  I'm specifically looking for a canonical way to slurp several flat-files into an in-memory database, then do some joins.

[A]
Just open the file :memory: and that should do it (at least it does in PHP).
You mention that you want to read in several flat files and do joins on them. If it's possible to store the flat files as SQLite databases, you can work directly with both by attaching one to the other:
```
```
ATTACH foo.db AS foo
```
```
Then refer to the tables in foo like so:
```
```
SELECT * FROM foo.users
```
```
This way you can do your joins without the need for creating an in-memory database.


q:
I'm looking for some sample code that will sort the list items in an HTML list by alphabetical order.  Can anyone help?

Here is a sample list for people to work with:

<ul class="alphaList">
    <li>apples</li>
    <li>cats</li>
    <li>bears</li>
</ul>

[A]
```
```
var items = $('.alphaList > li').get();
items.sort(function(a,b){
  var keyA = $(a).text();
  var keyB = $(b).text();

  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
});
var ul = $('.alphaList');
$.each(items, function(i, li){
  ul.append(li); /* This removes li from the old spot and moves it */
});
```
```


q:
I need to do a join with a table/result-set/whatever that has the integers n to m inclusive. Is there a trivial way to get that without just building the table?

(BTW what would that type of construct be called, a "Meta query"?)

m-n is bounded to something reasonable ( < 1000's)

[A]
There is no sequence number generator (
CREATE SEQUENCE
) in MySQL. Closest thing is
```
AUTO_INCREMENT
```
, which can help you construct the table.


q:
I am writing a text editor which has an option to display a bullet in place of any invisible Unicode character.  Unfortunately there appears to be no easy way to determine whether a Unicode character is invisible.

I need to find a text file containing every Unicode character in order that I can look through for invisible characters.  Would anyone know where I can find such a file?

EDIT: I am writing this app in Cocoa for Mac OS X.

[A]
Its an impossible task, Unicode supports even Klingon, so it's not going to work. However most text editors use the standard ANSI invisible characters. And if your Unicode library is good, it will support finding equivalent characters and/or categories, you can use these two features to do it as well as any editor out there
Edit:
Yes I was being silly about Klingon support, but that doesn't make it not true... of course Klingon is not supported by the Consortium, however there is a movement for Klingon in the Unicode's "Private Use Area" defined for Klingon alphabet (U+F8D0 - U+F8FF).
Link here
for those interested :)
Note:
Wonder what editor Klingon programmers use...


q: How do I check if a field (textbox) is empty or filled only with white spaces (spaces/enters/tabs etc.), using javascript RegExp?

[A]
```
```
if (myField.value.match(/\S/)) {
  // field is not empty
}
// or
if (/\S/.test(myField.value)) {
  // field is not empty
}
```
```
Explanation, since other people seem to have some
crazy
different ideas:
```
\s
```
will match a space, tab or new line.
```
\S
```
will match anything but a space, tab or new line.
If your string has a single character which is not a space, tab or new line, then it's not empty.
Therefore you just need to search for one character:
```
\S
```


q:
I have this piece of code in my PHP code:

while ($row = mysqli_fetch_assoc($result))
{
    extract($row);
    echo "<tr>";
    echo "<td bgcolor='#FFFFFF'><input id='bookArray[]' name='bookArray[]' type='checkbox' value='$book_id' />$book_id</td>";
    echo "<td bgcolor='#FFFFFF'>$threat_name</td>";
    echo "</tr>";
}

In HTML page, I want to use jQuery serialize() method to sent array of selected books in bookArray[]. In my JavaScript,

var selectedbooks = $("book_form").serialize();
alert (selectedbooks);

In the alert message box, i did not get any value (empty string).

Previously when i am using Prototype, it worked nicely.

[A]
You may need to change your PHP as @Tomalak suggests, but you will also need to change your javascript.  To reference a named element use the #name selector:
```
```
var selectedbooks = $('form#book_form').serialize();;
```
```


q:
i have two servers a main site and a static server.
i want to get a file's content from ajax in runtime, which is stored in static server.
obviously cross domain problem will occur.

so what i am trying to do is storing that ajax .js in the static server, so that calling the local file wont be a problem.

but after i include that js file from static, still that problem remains...

Any solutions?!

[A]
Are you sure the path to
```
info.xml
```
is correct?  That gets me sometimes when I am including a file from a subdirectory.


q:
Ok, I know this is a strange question, but there is a "standard" (fan-wise at least) Unicode support for the Klingon alphabet, and since code can be written in Unicode with no problem, that means it is possible to write Kode with Klingon tokens( vars, function names, etc...).

For the record I've written C++ in Japanese and it works, so K++ in Klingon should work too. But I don't know of any text editor with support for Klingon. Any suggestions?

[A]
Not likely, especially when you consider rule 9 of the
KLINGON GUIDE To Writing Perfect Code
“Indentation?! I will show you how to indent when I indent your skull!”
and number 7 does not bode well for any editor:
“Klingon function calls do not have ‘parameters.’ They have ‘arguments’ . . . and they ALWAYS WIN THEM!”
```
[
```
Seriously, this is an interesting
Unicode editor problem
```
]
```
After all, ITunes has a license agreement in Klingon!
And you need the right keyboard, off course \o/
Now... may be you can try to "Google it" ;-)


q:
Simple question:

Can a swing frame be completely modal ( block all others windows ) ?

I tried the following, but I can still click on other apps windows ( like this browser )

JDialog myDialog  = ....
myDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

Plase paste some code if this is possible.

[A]
I don't know about global modal, but here's an idea.
Take the screenshot of the desktop.
Go full screen.
Pop up your dialog.
Since the desktop is fake screenshot, you can ignore any attempt to click into it.
Full screen sample
:
```
```
private void toggleFullScreenWindow() {
  GraphicsEnvironment graphicsEnvironment
    = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice graphicsDevice
    = graphicsEnvironment.getDefaultScreenDevice();
  if(graphicsDevice.getFullScreenWindow()==null) {
    dialog.dispose(); //destroy the native resources
    dialog.setUndecorated(true);
    dialog.setVisible(true); //rebuilding the native resources
    graphicsDevice.setFullScreenWindow(dialog);
  }else{
    graphicsDevice.setFullScreenWindow(null);
    dialog.dispose();
    dialog.setUndecorated(false);
    dialog.setVisible(true);
    dialog.repaint();
  }
  requestFocusInWindow();
}
```
```
FYI:
Full-Screen Exclusive Mode API
.


q: Unfortunately I don't have access to a *nix box at work or at home.  The only way I can play with Haskell is on windows.  Anyone here using Haskell on Windows? What's your setup?

[A]
GHC
is a state-of-the-art, open source, compiler and interactive environment for the functional language Haskell.
There is a
Windows installer for GHC
, but it for Version 6.4.2 .
A Windows
```
.exe
```
(not an
```
.msi
```
installer) for version 6.10.1 is at
http://www.haskell.org/ghc/dist/6.10.1/
It is not clear when the current (GHC 6.10.1) version will offer a Windows installer.


q:
Assuming the following class stub:

public class Foo<T> {
  private Class<T> type;

  public Foo<T> () {}
}

Can I store the generic type T into the field type in the constructor, without changing the constructor's signature to "public Foo<T> (Class<T> type)"?

If yes, how? If no, why?

"type = T" doesn't seem to work.

[A]
Does
```
```
type = T.getClass();
```
```
work?


q:
I am trying to create a custom subclass of NSScroller. I have created the class, and set it as the vertical scroller on an NSScrollView in IB. When I run my project, the drawRect: method is called for my subclass, so I know that it is properly connected.

Now, How do I change the width of my fancy new NSScroller? No matter what I do to its bounds and frame, it always wants to draw in a rectangle 15 pixels wide (the size of the default NSScroller).

[A]
In your NSScroller subclass, you have to override scrollerWidth:
```
```
+(CGFloat)scrollerWidth
{
    return 30.0;
}
```
```
This is the value that NSScrollView uses to define the frame for your component when it sets it up.


q:
The performance of a Direct3D application seems to be significantly better in full screen mode compared to windowed mode. What are the technical reasons behind this?

I guess it has something to do with the fact that a full screen application can gain exclusive control for the display. But why the application cannot gain exclusive control for part of the screen (i.e. window) and have the same performance benefits?

[A]
There's
a bit
on MSDN that says full screen mode uses buffer flipping, if set up correctly, as opposed to blitting. It makes sense.
Of course you can (and in a way, do) give exclusive control for part of the screen to an application, but what happens to the rest of the screen? You still have to blit, do occlusion checking, etc. on the rest of the windows, and I think that's what causes the performance hit.


q:
i'm using vs installer to build a setup package for my vb6 app.
and the problem is i can see that under the project explorer there's a list of dependencies attached to my exe file.

alt text http://img505.imageshack.us/img505/9696/croppercapture259lr8.png

and under the file system on target machine treeview, i can actually store the dll/ocx on a folder or in the windows system folder itself[the left window].

alt text http://img101.imageshack.us/img101/9224/croppercapture251qm1.png

so what i don't understand is .. is there actually a difference?
if i just set the dependencies and didn't add the dll or ocx to the folder or win sys folder, does the dll automatically get copied over too?

[A]
It is not guaranteed that all those dlls will be present on the system that the software is being installed on. So they need to be included in your installer. From there you have two choices.
You can install them in your windows system folders or in your application folder. The difference is that if you install them in your application folder you can set things up on XP and Vista so that the different version of the software with different version of the components can be fired up and run side by side. Installing them into the system folder will break any older version that depend on older version of the components.
Installing in the application folder rarely doesn't work if a component depends on other components that can't be updated. When this occurs it is usually with with Microsoft libraries. They have gotten better over the years on this issue.
You can read more about the issues involving side by side execution
here
Finally the dependencies need to be in your installer so that they are registered in the Windows Registry. Unlike most .NET assemblies any ActiveX/COM application needs to have the component registered in order to use it even if you are using CreateObject and Variant types to access it.
I will admit the whole process is idiosyncratic and is one of the sources for the stories about DLL Hell.  Start with the MSDN article, use wikipedia, and of course ask further questions here.


q: Is there any free IDE for Pl/SQL development

[A]
I personally like
http://www.allroundautomations.nl/plsqldev.html
Quite usefull for PL/SQL and Oracle in general. But not free.


q:
We often send emails in HTML for clients (Dont like it but not my choice)

Does anyone have any info or a link on support for the dynscrc attribute or img in email clients?

[A]
My solution here would be to have a screenshot (perhaps with a 'click to watch' overlay) of your movie that links to a non-mail page that has a player in it.
Dealing with html email, in my experience, isn't so much about having standards as it is learning to compromise.  Web client and (the increasingly rare) desktop clients have differing behaviors that make website browser compliance seem like preschool by comparison.


q: With which version(s) of VS2008/VSTS can I work with .dbproj files?

[A]
You can definitely use
Team Edition for Database Professionals
.  The bad news is that it seems you
can only use this
or of course the superset version
Team Suite
but that would set you back a lot for a team.
It would be nice if the whole team could edit these files without having to fork out for these expensive extra licenses.  On the plus side the dbproj projects can be
built using Team Build


q:
Does using delegates slow down my programs?

I've been avoiding them because I really have no clue if they make my programs any slower.  I know if I cause a (catch) exception, that uses quite a bit of CPU power but I don't know about Delegates and Events and what .NET does to them.

[A]
Delegates are very, very fast. Not quite as fast as direct method calls, but not far off. The chances of them becoming a bottleneck are miniscule.
(Likewise exceptions, when used properly,
rarely actually cause a performance issue
.)
Would using delegates make your code simpler, more readable, and more robust? If so, use them. Measure your performance carefully, and keep an eye on it. Move away from readability for the sake of performance only when the data is clear.
I'm sure there are some graphs around showing the speed of delegates vs interfaces vs non-virtual method calls etc - I don't know where they are, but you could always run tests yourself if you're really worried.


q: Is it possible to use CPython to develop Adobe Flash based applications?

[A]
I guess it would be possible to compile the python interpreter to flash bytecode using this
http://labs.adobe.com/downloads/alchemy.html
and then use it to run python programs. But apart from that the answer is no.


q:
What is JDBC and where can I start learning about?

I know it's a way to access databases with Java, but what problems does it solve? Is it an ORM (or does it try to be)? Does it abstract away differences between databases, at the syntax level? What does it do? and what does it not do?

[A]
No, JDBC isn't an ORM. It's the
Java Database Connectivity
API and basically it provides a database-agnostic access layer with a provider model (so that new database drivers can be added easily). Vendors can add more functionality for specific database features if they wish, but developers can ignore those features if they wish to work with multiple databases.
There's no mapping involved - just modeling for connections (and pools), prepared statements, stored procedures, result sets etc.


q:
I want to let the user draw on an image in a browser. In other words, I need both bitmapped graphics and drawing capabilities, whether vector or bitmapped.

Canvas looks good, but is not supported by IE, and though there is ExCanvas, I wonder if ExCanvas is stable enough for consistent use in IE6 through 8.

Or best of all, is there an open-source image/drawing library that supports all this out of the box? I found two dozen or so Web-based image editors or drawing tools, but none support the requirements. (And I'd like to avoid Flash/Flex/Silverlight/JavaFX.)

[A] Even though you said you'd like to avoid it I'd suggest Flash. You could easily use Flash 6 or 7 and these have a > 90% adoption rate. I'd be surprised if you could get that level of support with JavaScript. Flash is truly write once run anywhere, which will cut down on your development time.


q:
I receive some arguments into a stored procedure. These arguments are NVARCHAR's.

I have a problem, when I need to cast some of these values to FLOATS, because they are being received as e.g.

@VALUE1 NVARCHAR(100)

DECLARE @ChangedValue
SET @ChangedValue = CAST(@Value1 AS FLOAT)

E.g. @Value1 = "0,001"

Gives me a problem, as it expects "0.001"

I can't change the format of the input, but can I somehow change it on the SQL-server side? By changing all "," to "." instead?

Best regards, Kenn

[A]
You could use
```
@VALUE1 = REPLACE(@VALUE1, ',', '.')
```
This does seem a horrible thing to do though!


q:
I am pulling data out of an old-school ActiveX in the form of arrays of doubles. I don't initially know the final number of samples I will actually retrieve.

What is the most efficient way to concatenate these arrays together in C# as I pull them  out of the system?

[A]
You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a
```
List<T>
```
which can grow as it needs to.
Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.
See
Eric Lippert's blog post on arrays
for more detail and insight than I could realistically provide :)


q:
Is there a way to detect whether IIS is enabled or not?

I know how to check if it is INSTALLED, but I need to know if it's installed but not enabled.

Also, can this be done natively via InstallShield?  Checking this via .NET would be acceptable as we can write custom actions, but if there is an IS call then that would be ideal.

Any hints/tips are appreciated, thanks


q:
Did you ever use SQL Server auditing features on a production db?

How did that impact on performances, and are there differences you noticed between different versions of SQL Server.

Also how we need to enable the audit features.

[A]
I'm afraid there's no such a thing as "audit feature". Instead you need to build it yourself depending on what kind of requirements you have. There are many ways to do this, for example
A trigger fires every time data in audited tables change. An example here:
http://web.archive.org/web/20071006100909/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-audit-changes-to-sql-server-data.html
using your ORM, with NHIbernate
ideas here:
Data Auditing in NHibernate and SqlServer


q:
Forgive me for probably using the wrong term for this "application mode".

Our application has a problem during start in that it doesn't show a task bar icon until the main window is up, even though there are loading progress windows, logon-windows, etc. on screen before that.

We change the code to fix this, but unfortunately this fix, when running the app through citrix, now shows two icons, one with just the icon and no text.

Is there a way for me to detect that the application is running through citrix? I don't know the right term for this, but only the app window is brought to the users desktop, not the whole remote desktop.

If it matters, the app is written in Delphi.

[A]
Not sure exactly how to do this in delphi, but if you can call out to the user32.dll, and call the function:
```
```
if (GetSystemMetrics(SM_REMOTESESSION) != 0)
{
   // We are in a remote session
}
```
```
This should tell you if you are running in a Citrix or Terminal Services environment.
SM_REMOTESESSION is defined as:
```
```
#define SM_REMOTESESSION        0x1000
```
```
More info on the GetSystemMetrics api here:
Link to msdn
Edit
The following page describes how to do exactly the above in delphi. What works for Terminal Services should also work for Citrix:
Is your Delphi Application Running under Terminal Services as a Remote Session


q:
I'm writing this question in the spirit of answering your own questions, since I found a solution to the problem, but if anyone has a better solution I would gladly listen to it.

In the application I am currently working on I am subclassing the ListView control to add some functionality of which some interacts with the ListView SelectedIndices and SelectedItems properties.

The problem is that when I try to unit test my subclass, the SelectedIndices and SelectedItems properties does not update when I add items to the selection. I tried both

item.Selected = true

and

listView.SelectedIndices.Add(...)

But SelectedIndices or SelectedItems simply does not appear to be affected. The unit tests for the other parts of the functionality works fine.

How can I unit test the selection dependent parts of my ListView subclass?

[A]
The problem seems to be that the SelectedIndices and SelectedItems does not update properly if the ListView has not been drawn, as is stated in this comment from the MSDN documentation of the
ListViewItem.Selected property
:
The Selected property cannot be trusted if your ListView has never been drawn (for example, it's in a TabControl, in a tab that has not been selected yet). In that case, the SelectedItems and SelectedIndices of the parent ListView are not correctly updated and will still be empty.
One solution to this problem is to create a simple dummy form class in your test, add the ListView to the form and simply show the form. After that the SelectedIndices and SelectedItems properties work as expected.
Something like this:
```
```
[Test]
    public void CanGetSelectedItems()
    {
        // simple test to make sure that the SelectedIndices
        // property is updated
        using (var f = new DummyForm(listView))
        {
            f.Show();

            listView.SelectedIndices.Add(0);
            Assert.AreEqual(1, listView.SelectedIndices.Count);
        }
    }

    private class DummyForm : Form
    {
        public DummyForm(ListView listView)
        {
            // Minimize and make it not appear in taskbar to
            // avoid flicker etc when running the tests
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
            this.Controls.Add(listView);
        }
    }
```
```


q:
I wish to set a usererror string before leaving a function, depending on the return code and variable in the function.

I currently have:

Dim RetVal as RetType

try
...
if ... then
    RetVal = RetType.FailedParse
    end try
endif
...

finally
    select case RetVal
        case ...
            UserStr = ...
    end select
end try

return RetVal

Is it possible to use return RetType.FailedParse, then access this in the finally block?

[A]
The only real way of doing this in C# would be to declare a variable at the start of the method to hold the value - i.e.
```
```
SomeType result = default(SomeType); // for "definite assignment"
try {
   // ...
   return result;
}
finally {
    // inspect "result"
}
```
```
In VB, you
might
be able to access the result directly - since IIRC it kinda works like the above (with the method name as "result") anyway. Caveat: I'm
really
not a VB person...


q: Is it good practice to have a unit test that specifies how long a certain function takes to return a value. I'm unit testing a curl function and want to specify that it needs to time out after 5 seconds. Is this in line with the way unit tests work?

[A]
I don't think, that this is a test of the contract of the method. That's why I would say no, it's not an unit-test. But it sound like some sort of system-test.
Another point that disqualifies your example as unit-test is the fact, that it needs long time (5 seconds) to execute. Typically you should be able to execute the complete suite of unit-tests every time you do a change. You cannot wait long time.
That's why I think your test should be in another set of tests, than the unit-tests. It should be executed in your daily builds/continuous integration but not before every checkin from every programmer.


q:
I am wondering what is best practice when it comes to dependencies and how releases should be done. In my case I have a library that relies on log4net and I am wondering if I should distribute log4net.dll (set the log4net reference to copy local) along with the release?

Could I simply state that log4net should be installed in the GAC?


q:
We have a number of very old data entry forms that were made in Access that link to our SQL Server database. Each form may have any number of sub-forms.

We'd like to move away from using these access frontends but don't have the time to create a new app or web app to replace every form that we've got.

Is there another option that would link to SQL Server and allow visual design of the form and automatic linkage to the database?

Or if that's too much of an ask, can you think of a way to make hand-coding the forms easier?

[A]
From experience, I don't think you will find any product, tool or technology any easier than Access for creating forms with a DB behind them.
Do you have a copy of
Access Developer's Handbook
?   In the past, I found this a valuable resource for implementing best practices in quite complex projects with Access as a front-end to SQL Server.
If you want to move to web forms, I would take a look at
IronSpeed Designer


q:
MS SQL has a convenient workaround for concatenating a column value from multiple rows into one value:

SELECT col1
 FROM table1
 WHERE col2 = 'x'
 ORDER by col3
 FOR XML path('')

and that returns a nice recordset:

XML_F52E2B61-18A1-11d1-B105-00805F49916B
----------------------------------------
<col1>Foo</col1><col1>Bar</col1>

only the column name in the returned recordset is rather nasty!

The column name seems to include random elements (or a GUID), and hence I am reluctant to use it in my application (different instances or different servers might have another GUID).  Unfortunately I cannot use * to select the value, and due to the restrictions in the existing application I cannot iterate through returned columns, either...

Is there a way to force the column name in the returned recordset to something more sensible?

[A]
That should do:
```
```
select(
SELECT col1
 FROM table1
 WHERE col2 = 'x'
 ORDER by col3
 FOR XML path('')
) as myName
```
```
Not pretty but should give the result that you need


q:
I was wondering if there was a way to tell if an instance of Oracle on a system has a database installed or not?

This is for an installation script, and I need to verify that there is an actual database in place before proceeding with the loading of my own tablespace onto that database. Has anyone tackled this problem before?

Cheers

[A]
You could use
```
tnsping
```
to check whether the database listener is active, that would be a good indication. Other than that, why not just simply do a test connection? If it's part of an installer process, you could prompt the user to enter the appropriate connection credentials if you don't know what they'll be in advance.


q:
The web service endpoint usually is defined in an early stage of a project. Since it follows the "contract first" principle, it shouldn't be changed after communicated to client systems.

Therefore, it is vital to label the web service in a good way.

How would you label web services?

e.g.

http://my.domain.com/businessProcess/services/concreteServiceName

Other ideas?

See this question as a poll... Feel free to vote for the best idea.

[A]
We decide on names by talking to the developers, business guys, and support guys. We formed a committee called the "interface control committee", and we approach it kind of like you described in the question. We want service names to be descriptive, reflect the processes they support, and fit the needs of the technical and business stakeholders.
When we have ICC meetings, we also talk about schemas and how they should be developed. The business guys are key in this as well since they know what data they want to expose and why.
KA


q:
I have following situation:
I have loged user, standard authentication with DB table

$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('users');
$authAdapter->setIdentityColumn('user_name');
$authAdapter->setCredentialColumn('password');

When user edits his profile, I save it into Db, but I need to update also storage (using standard Zend_Auth_Storage_Session). Is there any easy way how to do it? Many thanks.

[A]
I have done it like this, it works, but I don't know if there is not some better way,how to do it
```
```
$user_data = User::getUser($user_id)->toArray();
unset($user_data['password']);

$std_user = new stdClass();

foreach ($user_data as $key => $value)
{
   $std_user->$key = $value;
}

$auth = Zend_Auth::getInstance();
$auth->getStorage()->write($std_user);
```
```


q:
We are currently creating an InfoPath 2007 form is deployed in SharePoint 2007. In the form we populate the repeating tables with more than 60 records. However, when we're submitting the form, an error message appears. Does the number of records in the repeating table affects the submitting of the form? Also provide some workaround to resolve the issue.

Thanks in advance.


q:
I'm trying to programmatically reject a call on a BlackBerry, with Java + JDE.
I'm intercepting the callIncoming event, and in there I need to do something to reject a call from a specific number.

Does anyone know how to do that?

[A]
I couldn't find an API for directly rejecting the call in progress. However, you could explore a hack where you inject a keypress of the Hangup/Disconnect button (see
```
EventInjector
```
).
As to determining the phone number, you could use
```
Phone.getCall(callId).getDisplayPhoneNumber()
```
or
```
Phone.getActiveCall().getDisplayPhoneNumber()
```
.


q:
I have a loader.exe with Main() that loads the 'UI' in WPF, the thing is that I want only one instance of the loader.exe, how can I achieve it?

Is there a way a user clicks loader.exe it should check if an existing loader.exe is running and does nothing.

currently I have

loader.exe

with

main()
....
..
Load UI
...

the loader has no idea what its loading etc so I can't do many things with the loader project...

Any help n code is highly appreciated

Thanks in advance.

[A]
Have a look at:
http://yogesh.jagotagroup.com/blog/post/2008/07/03/Ways-of-making-a-WPF-application-Single-Instance.aspx
Also, you might find a more detailed answer in the following post here on StackOverflow:
What is the correct way to create a single-instance application?