q:
I am trying to validate user id's matching the example:

smith.jack or smith.jack.s

In other words, any number of non-whitespace characters (except dot), followed by exactly one dot, followed by any number of non-whitespace characters (except dot), optionally followed by exactly one dot followed by any number of non-whitespace characters (except dot).  I have come up with several variations that work fine except for allowing consecutive dots!  For example, the following Regex

^([\S][^.]*[.]{1}[\S][^.]*|[\S][^.]*[.]{1}[\S][^.]*[.]{1}[\S][^.]*)$

matches "smith.jack" and "smith.jack.s" but also matches "smith..jack" "smith..jack.s" !  My gosh, it even likes a dot as a first character.  It seems like it would be so simple to code, but it isn't.  I am using .NET, btw.

Frustrating.


q:
In ColdFusion, under Request Tuning in the administrator, how do I determine what is an optimal number (or at least a good guess) for the Maximum Number of Simultaneous Template Requests?

Environment:

CF8 Standard

IIS 6

Win2k3

SQL2k5 on a separate box

[A]
The way of finding the right number of requests is load testing.  That is, measuring changes in throughput under load when you vary the request number.  Any significant change would require retesting. But I suspect most folks are going to baulk at that amount of work.
I think a good rule of thumb is about 8 threads per CPU (core).
In terms of efficiency, the lower the thread count (up to a point) the less swapping will be going on as the CPU processes your requests.  If your pages execute very quickly then a lower number of requests is optimal.
If you have longer running requests, and especially if you have requests that are waiting on third-parties (like a database) then increasing the number of working threads will improve your throughput.  That is, if your CPU is not tied up processing stuff you can afford to have more simultaneous requests working on the tasks at hand.
Although its a little bit dated, many of the principles on request tuning in Grant Straker's book on
CF Performance & Troubleshooting
would be worthwhile.

s: huggingface

c: devops

d: intermediate


q: Is it possible to set the title of a page when it's simply a loaded SWF?

[A]
I would think you would be able to do it.  You would have to access the javascript DOM.
A couple links that may steer you down the correct path..
http://homepage.ntlworld.com/kayseycarvey/document2.html
http://www.permadi.com/tutorial/flashjscommand/


q:
Is an opensource/commercial tool/framework, available for automated web app testing in Google Chrome browser on Windows XP / Vista? ( An alpha/beta Tool is also OK)

Thanks

[A]
Selenium supports Chrome pretty much out of the box because it works by injecting javascript in the web page.
http://selenium-rc.openqa.org/
Webdriver has an early version of Chrome driver.
http://code.google.com/p/webdriver/
Both are open source and works on Windows.


q:
In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working.

I has used the auto-complete plugin provided with Notepad++, which presented me with onClick.

When I changed the capital C to a small c, it did work.

So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals.

But when you change getElementById to getelementbyid, you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters.

So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't?

[A]
Javascript is
ALWAYS
case-sensitive, html is not.
It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive.  The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is.
So, you can do this:
```
```

Say Yo
 // Upper-case 'C'
```
```
or:
```
```

Say Yo
 // Lower-case 'C'
```
```
but through the DOM you must use the correct case. So this works:
```
```
getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C'
```
```
but you cannot do this:
```
```
getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C'
```
```
EDIT: CMS makes a great point that most DOM methods and properties are in
camelCase
.  The one exception that comes to mind are event handler properties and these are generally accepted to be
the wrong way to attach to events
anyway. Prefer using
```
addEventListener
```
as in:
```
```
document.getElementById('divYo').addEventListener('click', modifyText, false);
```
```


q:
I found a question here about blogs on software development, but I would like to know which blogs on software testing this community reads.

If you just have to recommend more than one blog, post each one in separate answer, so others can vote on specific blog. :)

Thanks!

Edit: I am not interested in sites that aggregate other blogs, because as @Alan said (in his answer) there are both good and not so good blogs there.

[A]
My
blog
, of course, is quite interesting - but will not be to everyone. TestingReflections is nice because it aggregates a bunch of random test blogs, but the problem is that it aggregates the bad with the good. Many of the posts that make it to the site don't have much use.
It also depends on what you're looking for - are you looking for a blog on testing philosophy, one about functional test techniques, something about writing automated tests, something all-encompassing, or something different?


q:
I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method.

For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist.  I know for  other arrays you can make the assignment like:

int[] IntArray = {1,2,3};

Is there a similar way to do this for an arraylist?  I tried the addrange method but the curly brace method doesn't implement the ICollection interface.

[A]
Array list has ctor which accepts ICollection, which is implemented by the Array class.
```
```
object[] myArray = new object[] {1,2,3,"string1","string2"};
ArrayList myArrayList = new ArrayList(myArray);
```
```


q:
For various reasons, such as cookies, SEO, and to keep things simple, I would like to make apache automatically redirect any requests for http://www.foobar.com/anything to http://foobar.com/anything. The best I could come up with is a mod_rewrite-based monstrosity, is there some easy simple way to tell it "Redirect all requests for domain ABC to XYZ"?

PS: I found this somewhat related question, but it's for IIS and does the opposite of what I want. Also it's still complex.

[A]
```
```
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]
```
```
That should do the trick.


q:
It can be either at compile time or at run-time using a config file.  Is there a more elegant way than simple (and many) if statements?

I am targeting especially sets of UI controls that comes for a particular feature.

[A]
Unless your program must squeeze out 100% performance, do it with a config file.  It will keep your code cleaner.
If one option changes many parts of code, don't write many conditionals, write one conditional that picks which class you delegate to.  For instance if a preference picks TCP versus UDP, have your conditional instantiate a TcpProvider or UdpProvider which the rest of your code uses with minimal muss or fuss.


q:
What update rate should I run my fixed-rate game logic at?

I've used 60 updates per second in the past, but that's hard because it's not an even number of updates per second (16.666666). My current games uses 100, but that seems like overkill for most things.

[A] Bear in mind that unless your code is measured down to the cycle, not each game loop will take the same number of milliseconds to complete - so 16.6666 being irrational is not an issue really as you will need to time and compensate anyway. Besides it's not 16.6666 updates per second, but the average number of milliseconds your game loop should be targeting.


q: I seem to make this mistake every time I set up a new development box. Is there a way to make sure you don't have to manually assign rights for the ASPNET user? I usually install .Net then IIS, then Visual Studio but it seems I still have to manually assign rights to the ASPNET user to get everything running correctly. Is my install order wrong?

[A]
Install IIS, then .NET.  The .NET installation will automatically register the needed things with IIS.
If you install .NET first, run this:
```
```
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i
```
```
to run the registration parts, and
```
```
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ga userA
```
```
to set up the security rights for userA


q:
I just started using the WPF WebBrowser that is included in Net 3.5 SP1.  I built my setup project (which I have been using prior to moving to 3.5 SP1) and installed it on a test machine but the WebBrowser was not available.

What must I do to be sure that the setup.exe/msi combination checks for and installs SP1?

[A]
On my way to answering my own question.  Double-clicking on the Microsoft .net Framework in the Detected dependencies one can choose the version.
Now the question is which is appropriate,
3.5.30729
or
3.5 SP1 Client
?
EDIT:
3.5.30729 works.  Any ideas of the difference between the two?
EDIT:
Double-clicking on the .net Framework above shows .NET Framework as a Launch condition.  This is where I changed the version.  (I'd add a screenshot, but I don't have one at a URL, only on my desktop.


q:
When a system has N tiers, and when using an ORM, how do you send loaded entities across the tiers ?

Do you use DTO ?

When DTO are not used and the entities are directly sent, how do you protect againt the uninitialized lazy loaded relationship errors ?

Note : this is not a "should N tiers be used ?" question. I assume that the system already has N tiers.

[A]
Well I don't know if there is a better way, but when we use Hibernate we just turn lazy loading off so that it loads everything.  It obviously costs more to do this, but I wasn't sure how to get away from the lazy loading methods that Hibernate would create.
If a Containers has sets of data that are not used often then they will not be loaded and it is up to the requesting UI Form to call it and send it for update.  (We built update classes to pass all the information together)
In the case of UI Forms that loaded lots of Containers we just make special classes and fill in what we need for them.  They are sort of read-only containers that aren't used for persistence.
There may be better ways.. but I am learning :)


q:
The title should say it all, then I can solidify 2 more ticks on the Joel test.

I've implemented build automation using a makefile and a python script already and I understand the basics and the options.

But how can I, the new guy who reads the blogs, convince my cohort of its inherent efficacy?

[A]
Ask for forgiveness, instead of permission.
Get it working in private (which it looks like you have) and then demonstrate its advantages.
One thing that always gets people is using CruiseControl's Tray utility - people love it when they can see, through their system tray, that the build succeeded. (this is assuming you're in a Windows environment, that CruiseControl will work with your existing systems, etc.)
NOTE: If asking for forgiveness instead of permission will result in instant termination, you might not want to do the above. You might also want to look for work somewhere else. Your mileage may vary.


q:
I'd like know what people think about using RAISERROR in stored procedures to pass back user messages (i.e. business related messages, not error messages) to the application.

Some of the senior developers in my firm have been using this method and catching the SqlException in our C# code to pick up the messages and display them to the user.  I am not happy with this method and would like to know how other people deal with these types of user messages from stored procs.

[A]
If it can't be checked/caught earlier it might be difficult to do anything else.
I've had to write a raiseerror in a procedure I wrote and used as a constraint on inserting/updating a table because it was the 'last stop' for the data and I had to check it there.
I think in general if you are getting errors back from the DB.. its a pain in the butt and harder to give 'nice' feedback to the user without a lot of effort, but sometimes you just don't know until you insert/update :P


q:
Recently I ran into this error in my web application:

java.lang.OutOfMemoryError: PermGen space

It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6.
Apparently this can occur after redeploying an application a few times.

What causes it and what can be done to avoid it?
How do I fix the problem?

[A]
The solution was to add these flags to JVM command line when Tomcat is started:
```
```
-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled
```
```
You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the "Java" tab, add the arguments to the "Java Options" box. Click "OK" and then restart the service.
If you get an error
the specified service does not exist as an installed service
you should run:
```
```
tomcat6w //ES//servicename
```
```
where
servicename
is the name of the server as viewed in services.msc
Source: orx's comment on
Eric's Agile Answers
.


q:
I tend to use SQLite when doing Django
development, but on a live server something more robust is
often needed (MySQL/PostgreSQL, for example).
Invariably, there are other changes to make to the Django
settings as well: different logging locations / intensities,
media paths, etc.

How do you manage all these changes to make deployment a
simple, automated process?

[A]
Update:
django-configurations
has been released which is probably a better option for most people than doing it manually.
If you would prefer to do things manually, my earlier answer still applies:
I have multiple settings files.
```
settings_local.py
```
- host-specific configuration, such as database name, file paths, etc.
```
settings_development.py
```
- configuration used for development, e.g.
```
DEBUG = True
```
.
```
settings_production.py
```
- configuration used for production, e.g.
```
SERVER_EMAIL
```
.
I tie these all together with a
```
settings.py
```
file that firstly imports
```
settings_local.py
```
, and then one of the other two.  It decides which to load by two settings inside
```
settings_local.py
```
-
```
DEVELOPMENT_HOSTS
```
and
```
PRODUCTION_HOSTS
```
.
```
settings.py
```
calls
```
platform.node()
```
to find the hostname of the machine it is running on, and then looks for that hostname in the lists, and loads the second settings file depending on which list it finds the hostname in.
That way, the only thing you really need to worry about is keeping the
```
settings_local.py
```
file up to date with the host-specific configuration, and everything else is handled automatically.
Check out an example
here
.


q:
I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output?

I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie.

Is there another way that already exist to add a cookie that will go out on the next response?

[A]
I've just looked into this in depth, and the answer seems to be no.  Specifically, there's no way to get at the response from the WARenderCanvas or anything it can access (it holds onto the WARenderingContext, which holds onto the WAHtmlStreamDocument, which holds onto the response's
stream
but not the response itself).  I think it would be reasonable to give the context access to the current response, precisely to be able to set headers on it, but you asked if there was already a way, so: no.
That said, Seaside does a lot of extra redirecting, and it doesn't seem to have much impact on the user experience, so maybe the thing to do is to stop worrying about it seeming kludgey and go with the flow of the API that's already there :)


q:
I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":

value = ""; 8.times{value  << (65 + rand(25)).chr}

but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement.  To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:

value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}

but it looks like trash.

Does anyone have a better method?

[A]
To make your first into one statement:
```
```
(0...8).collect { |n| value  << (65 + rand(25)).chr }.join()
```
```


q:
I have a class:

class MyClass:
def __init__(self, foo):
    if foo != 1:
        raise Error("foo is not equal to 1!")

and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error:

def testInsufficientArgs(self):
    foo = 0
    self.assertRaises((Error), myClass = MyClass(Error, foo))

But I get...

NameError: global name 'Error' is not defined

Why? Where should I be defining this Error object? I thought it was built-in as a default exception type, no?

[A]
'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, "The Appropriate Exception Class".
The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of error involved, such as 'OSError', 'ValueError', 'NameError', 'TypeError'.
In this case, the appropriate error is 'ValueError' (the value of foo was wrong, therefore a ValueError). I would recommend replacing 'Error' with 'ValueError' in your script.
Here is a complete version of the code you are trying to write, I'm duplicating everything because you have a weird keyword argument in your original example that you seem to be conflating with an assignment, and I'm using the 'failUnless' function name because that's the non-aliased name of the function:
```
```
class MyClass:
    def __init__(self, foo):
        if foo != 1:
            raise ValueError("foo is not equal to 1!")

import unittest
class TestFoo(unittest.TestCase):
    def testInsufficientArgs(self):
        foo = 0
        self.failUnlessRaises(ValueError, MyClass, foo)

if __name__ == '__main__':
    unittest.main()
```
```
The output is:
```
```
.
----------------------------------------------------------------------
Ran 1 test in 0.007s

OK
```
```
There is a flaw in the unit testing library 'unittest' that other unit testing frameworks fix. You'll note that it is impossible to gain access to the exception object from the calling context. If you want to fix this, you'll have to redefine that method in a subclass of UnitTest:
This is an example of it in use:
```
```
class TestFoo(unittest.TestCase):
    def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
        try:
            callableObj(*args, **kwargs)
        except excClass, excObj:
            return excObj # Actually return the exception object
        else:
            if hasattr(excClass,'__name__'): excName = excClass.__name__
            else: excName = str(excClass)
            raise self.failureException, "%s not raised" % excName

    def testInsufficientArgs(self):
        foo = 0
        excObj = self.failUnlessRaises(ValueError, MyClass, foo)
        self.failUnlessEqual(excObj[0], 'foo is not equal to 1!')
```
```
I have copied the failUnlessRaises function from unittest.py from python2.5 and modified it slightly.


q:
I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on.

Is this possible?  And if so I'd like to have it detected before the client types their first letter.

Is there a non-platform specific way to do this?

[A]
Try this, from java.awt.Toolkit, returns a boolean:
```
```
Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)
```
```


q:
Most of the MVC samples I have seen pass an instance of the view to the controller like this

public class View
{
Controller controller = new Controller(this);
}

Is there any advantage to passing a class which provides access to just the  the properties and events the controller is interested in, like this:

public class UIWrapper
{
private TextBox textBox;

public TextBox TextBox
{
get {return textBox;}
}

public UIWrapper(ref TextBox textBox)
{
this.textBox = textBox;
}

public class View
{
UIWrapper wrapper = new UIWrapper(this);
Controller controller = new Controller(wrapper)
}

[A]
This is probably not the solution you want, but just to help you with the log parsing, you can use this to get counts for each from the logs (assuming you're on a linux server) :
```
```
grep -c \.swz web_log_dir/*
grep -c \.swf web_log_dir/*
```
```


q:
Does anybody know how to apply a "where in values" type condition using LINQ-to-Entities?  I've tried the following but it doesn't work:

var values = new[] { "String1", "String2" };  // some string values

var foo = model.entitySet.Where(e => values.Contains(e.Name));

I believe this works in LINQ-to-SQL though?  Any thoughts?

[A]
Yes it does translate to SQL, it generates a standard IN statement like this:
```
```
SELECT [t0].[col1]
FROM [table] [t0]
WHERE [col1] IN ( 'Value 1', 'Value 2')
```
```


q:
I'm a little hesitant to post this, as I'm not completely sure what I'm doing. Any help would be wonderful.

I'm on a computer with a firewall/filter on it. I can download files without any difficulty. When I try to clone files from Github, though, the computer just hangs. Nothing happens. It creates a git file in the folder, but the key files don't get loaded in. For context, I'm working on a Rails app, trying to load in Restful Authentication.

Have any of you dealt with this? Any suggestions for getting the clone to work? Disabling the firewall might be an option, but if I can do something without going through that process, I'd appreciate it.

[A]
The
```
git://
```
protocol uses port 9418, so you should make sure your firewall allows outbound connections to this port.


q:
This is a follow up question to This Question.

I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used:

function exist(sFN) {
    if(self[sFN]) return true;
    return false;
}

It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?

[A]
just use
```
typeof
```
.
```
```
typeof(foobar)  // -> undefined
typeof(alert)   // -> function
```
```
You can't, however, defined a function based on typeof, because you'd need to pass an identifier which might not exist. So if you define
```
function isfun(sym) { return typeof(sym) }
```
, and then tried calling
```
isfun(inexistent)
```
, your code would throw.
The fun thing about
```
typeof
```
is that it's an operator, not a function. So you can use it to check a symbol that's not defined without throwing.
if you assume a function in the global scope (i.e., not within a closure), you can define a function to check it as follows:
```
```
function isfun(identifier) {
  return typeof(window[identifier]) == 'function';
}
```
```
Here you pass an string for the identifier, so:
```
```
isfun('alert');   // -> true
isfun('foobar');  // -> false
```
```
closure?
Here's an example of a function defined within a closure. Here, the printed value would be
```
false
```
, which is wrong.
```
```
(function closure() {
  function enclosed() {}
  print(isfun('enclosed'))
})()
```
```


q: Is there a way to get a DrawingContext (or something similar) for a WriteableBitmap?  I.e. something to allow you to call simple DrawLine/DrawRectangle/etc kinds of methods, rather than manipulate the raw pixels directly.

[A]
I'm wondering the same thing, as currently I do something like:
```
```
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
   //
   // ... draw on the drawingContext
   //
   RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Default);
   bmp.Render(drawingVisual);
   image.Source = bmp;
}
```
```
I'm trying to use the WriteableBitmap to allow multithreaded access to the pixel buffer, which is currently not allowed with neither a DrawingContext nor a RenderTargetBitmap. Maybe some sort of WritePixels routine based off of what you've retrieved from the RenderTargetBitmap would work?


q: Is there a difference between just saying throw; and throw ex; assuming ex is the exception you're catching?

[A]
```
throw ex;
```
will erase your stacktrace. Don't do this unless you mean to clear the stacktrace. Just use
```
throw;
```


q:
I wanting to show prices for my products in my online store.
I'm currently doing:

<span class="ourprice">
     <%=GetPrice().ToString("C")%>
</span>

Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00"

I think the correct HTML for an output of "£12.00" is "&pound;12.00", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00.

(The server is in the UK, with localisation is set appropriately in web.config).

Is the below an improvement, or is there a better way?

<span class="ourprice">
     <%=GetPrice().ToString("C").Replace("£","&pound;")%>
</span>

[A]
Try this, it'll use your locale set for the application:
```
```
<%=String.Format("{0:C}",GetPrice())%>
```
```


q:
In Perl, a conditional can be expressed either as

if (condition) { do something }

or as

(condition) and do { do something }

Interestingly, the second way seems to be about 10% faster. Does anyone know why?

[A]
I've deparsed it, and it really shouldn't be faster. The opcode tree for the first is
```
```
LISTOP (0x8177a18) leave [1]
    OP (0x8176590) enter
    COP (0x8177a40) nextstate
    LISTOP (0x8177b20) scope
        OP (0x81779b8) null [174]
        UNOP (0x8177c40) dofile
            SVOP (0x8177b58) const [1] PV (0x81546e4) "something"
```
```
The opcode tree for the second is
```
```
LISTOP (0x8177b28) leave [1]
    OP (0x8176598) enter
    COP (0x8177a48) nextstate
    UNOP (0x8177980) null
        LISTOP (0x8177ca0) scope
            OP (0x81779c0) null [174]
            UNOP (0x8177c48) dofile
                SVOP (0x8177b60) const [1] PV (0x81546e4) "something"
```
```
I really don't see how the latter could be faster. It does an opcode more!


q:
In C++, I can have take input like this:

cin >> a >> b >> c;

And a can be int, b can be float, and c can be whatever... How do I do the same in python?

input() and raw_input(), the way I'm using them, don't seem to be giving me the desired results.

[A]
You generally shouldn't use
```
input()
```
in production code. If you want an
```
int
```
and then a
```
float
```
, try this:
```
```
>>> line = raw_input().split()
>>> a = int(line[0])
>>> b = float(line[1])
>>> c = " ".join(line[2:])
```
```
It all depends on what exactly you're trying to accomplish, but remember that readability counts. Obscure one-liners may seem cool but in the face of maintainability, try to choose something sensible :)
(P.S.: Don't forget to check for errors with
```
try: ... except (ValueError, IndexError):
```
)


q: In a custom module for drupal 4.7 I hacked together a node object and passed it to node_save($node) to create nodes.  This hack appears to no longer work in drupal 6.  While I'm sure this hack could be fixed I'm curious if there is a standard solution to create nodes without a form.  In this case the data is pulled in from a custom feed on another website.

[A]
I don't know of a standard API for creating a node pragmatically. But this is what I've gleaned from building a module that does what you're trying to do.
Make sure the important fields are set: uid, name, type, language, title, body, filter (see
```
node_add()
```
and
```
node_form()
```
)
Pass the node through
```
node_object_prepare()
```
so other modules can add to the $node object.


q:
Does anyone know if it's possible to use regex capture within Apache's DirectoryMatch directive? I'd like to do something like the following:

<DirectoryMatch ^/home/www/(.*)>
    AuthType Basic
    AuthName $1
    AuthUserFile /etc/apache2/svn.passwd
    Require group $1 admin
</DirectoryMatch>

but so far I've had no success.

Specifically, I'm trying to create a group-based HTTP Auth for individual directories/vhosts on a server in Apache 2.0.

For example, Site A, pointing to /home/www/a will be available to all users in group admin and group a, site b at /home/www/b will be available to all users in group admin and group b, etc. I'd like to keep everything based on the directory name so I can easily script adding htpasswd users to the correct groups and automate this as much as possible, but other suggestions for solving the problem are certainly welcome.

[A]
What you are trying to do looks very similar to
per-user home directories
.  The way Apache handles these is through file system permissions and
.htaccess files
.  I don't believe there is any way to use regex capture in the enclosed directives (AuthName, etc).


q:
In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example:

void foo() throw(); // guaranteed not to throw an exception
void bar() throw(int); // may throw an exception of type int
void baz() throw(...); // may throw an exception of some unspecified type

I'm doubtful about actually using them because of the following:

The compiler doesn't really enforce exception specifiers in any rigorous way, so the benefits are not great. Ideally, you would like to get a compile error.

If a function violates an exception specifier, I think the standard behaviour is to terminate the program.

In VS.Net, it treats throw(X) as throw(...), so adherence to the standard is not strong.

Do you think exception specifiers should be used?

Please answer with "yes" or "no" and provide some reasons to justify your answer.

[A]
Generally I would not use exception specifiers.  However, in cases where if any other exception were to come from the function in question that the program would definitively be unable to
correct
, then it can be useful.  In all cases, make sure to document clearly what exceptions could be expected from that function.
Yes, the expected behavior of a non-specified exception being thrown from a function with exception specifiers is to call terminate().
I will also note that Scott Meyers addresses this subject in More Effective C++.  His Effective C++ and More Effective C++ are highly recommended books.


[A]
Regular expressions:
```
```
>>> import re
>>> splitter = re.compile(r'([+*/])')
>>> splitter.split("2+24*48/32")
```
```
You can expand the regular expression to include any other characters you want to split on.


q:
I've been looking at ways people test their apps in order decide where to do caching or apply some extra engineering effort, and so far httperf and a simple sesslog have been quite helpful.

What tools and tricks did you apply on your projects?

[A]
I use httperf for a high level view of performance.
Rails has a performance script built in, that uses the ruby-prof gem to analyse calls deep within the Rails stack. There is an awesome
Railscast
on
Request Profiling
using this technique.
NewRelic
have some seriously cool analysis tools that give near real-time data.
They just made it a "Lite" version available for free.


q:
I want to draw user interfaces for web and desktop applications.

I need something less print-oriented than omnigraffle. think pixels!

Also, need good building blocks (aka stencils). Form elements, tableviews, etc.

[A]
I very much like
Omnigraffle
, with
stencils
for UI design. More UI stencils are
also available
.
You might also check some
other
stackoverflow
questions
on this topic.


q: I want to use CSS sprites on a web site instead of separate image files, for a large collection of small icons that are all the same size. How can I concatenate (tile) them into one big image using ImageMagick?

[A]
From the page you linked,
'montage'
is the tool you want. It'll take a bunch of images and concatenate/tile them into a single output. Here's an example image I've made before using the tool:
(source:
davr.org
)


q:
Is there any centralized repository of useful Objective-C / Cocoa libraries as there is for Perl, Ruby, Python, etc.?

In building my first iPhone app, I'm finding myself implementing some very basic functions that would be just a quick "gem install" away in Ruby.

[A]
Unfortunately not :(
There are some very useful sites however.  I find one of the best is
cocoadev.com
as it contains lots of useful information about many of the more obscure classes usually including snippets of code to do some really cool things :)
Maybe we (the cocoa community) should look into building something like this!
Oh and I just remembered this site
cocoadevcentral.com
which is also very good for starting out with cocoa.


q: Do you think ASP.NET MVC will ever have a significant share of the Microsoft web development market? Or will it be more like 10-15% of the market?

[A]
I think it will be a slow start because of the webforms install base.  As unit testing and markup control starts to become
more important to more people
then I think you start to see a migration.  I doubt that it will ever reach 100% of the MS install base for a web platform but it will be a steady rise over the next years to come.  There will be the fan-boys who will say this will dominate planet sliced bread but that just isn't realistic.  With that, I'm hoping not to have to use Webforms for a long, long time.
EDIT:
Now that we are at Beta 1 we are
starting
to see the component vendors start to ship some stuff.  Looks like first up to bat is Telerik with their
ASP.NET Ajax Controls in ASP.NET MVC


q:
What are the advantages and disadvantages of the Session Façade Core J2EE Pattern?

What are the assumptions behind it?

Are these assumptions valid in a particular environment?

[A]
Session Facade is a fantastic pattern - it is really a specific version of the Business Facade pattern.  The idea is to tie up business functionality into discrete bundles - such as TransferMoney(), Withdraw(), Deposit()...  So that your UI code is accessing things in terms of business operations instead of low level data access or other details that it shouldn't have to be concerned with.
Specifically with the Session Facade - you use a Session EJB to act as the business facade - which is nice cause then you can take advantage of all the J2EE services (authentication/authorization, transactions, etc)...
Hope that helps...


q: In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?

[A]
```
```
String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");
```
```


q:
We're working on a very large .NET WinForms composite application - not CAB, but a similar home grown framework.  We're running in a Citrix and RDP environment running on Windows Server 2003.

We're starting to run into random and difficult to reproduct "Error creating window handle" error that seems to be an old fashion handle leak in our application.  We're making heavy use of 3rd Party controls (Janus GridEX, Infralution VirtualTree, and .NET Magic docking) and we do a lot of dynamic loading and rendering of content based on metadata in our database.

There's a lot of info on Google about this error, but not a lot of solid guidance about how to avoid issues in this area.

Does the stackoverflow community have any good guidance for me for building handle-friendly winforms apps?

[A]
I have tracked down a lot of issues with UIs not unloading as expected in WinForms.
Here are some general hints:
alot of the time, a control will stay in use because controls events are not properly removed (the tooltip provider caused us really large issues here) or the controls are not properly Disposed.
use 'using' blocks around all modal dialogs to ensure that they are Disposed
there are some control properties that will force the creation of the window handle before it is necessary (for example setting the ReadOnly property of a TextBox control will force the control to be realized)
use a tool like the
.Net Memory profiler
to get counts of the classes that are created.  Newer versions of this tool will also track GDI and USER objects.
try to minimize your use of Win API calls (or other DllImport calls).  If you do need to use interop, try to wrap these calls in such a way that the using/Dispose pattern will work correctly.


q:
When defining or calling functions with enough arguments to span multiple lines, I want vim to line them up. For example,

def myfunction(arg1, arg2, arg, ...
               argsN-1, argN)

The idea is for argsN-1 to have its 'a' lined up with args1.

Does anyone have a way to have this happen automatically in vim? I've seen the align plugin for lining equal signs (in assignment statements) and such, but I'm not sure if it can be made to solve this problem?

[A]
I believe you have to issue the command:
```
```
:set cino=(0
```
```
This is when using cindent of course.
edit: I missed "set"


q:
When {0} is used to initialize an object, what does it mean? I can't find any references to {0} anywhere, and because of the curly braces Google searches are not helpful.

Example code:

SHELLEXECUTEINFO sexi = {0}; // what does this do?
sexi.cbSize = sizeof(SHELLEXECUTEINFO);
sexi.hwnd = NULL;
sexi.fMask = SEE_MASK_NOCLOSEPROCESS;
sexi.lpFile = lpFile.c_str();
sexi.lpParameters = args;
sexi.nShow = nShow;

if(ShellExecuteEx(&sexi))
{
    DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE);
    if(wait == WAIT_OBJECT_0)
        GetExitCodeProcess(sexi.hProcess, &returnCode);
}

Without it, the above code will crash on runtime.

[A]
What's happening here is called
aggregate
initialization.  Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec:
An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions.
Now, using
```
{0}
```
to initialize an aggregate like this is basically a trick to
```
0
```
the entire thing.  This is because when using aggregate initialization
you don't have to specify all the members
and the spec requires that all unspecified members be default initialized, which means set to
```
0
```
for simple types.
Here is the relevant quote from the spec:
If there are fewer initializers in the list than there are members in the
  aggregate, then each member not
  explicitly initialized shall be
  default-initialized.
  Example:
```
```
struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };
```
```
initializes
```
ss.a
```
with
```
1
```
,
```
ss.b
```
with
```
"asdf"
```
, and
```
ss.c
```
with the value of an
  expression of the form
```
int()
```
, that is,
```
0
```
.
You can find the complete spec on this topic
here


q: At what length of text and/or length of audio snippet does a piece of commercially distributable software pass the threshold of fair use and violate the included work's copyright?  Does attribution absolve the developer from infringement?  An example would be a quote from a novel used on a start-up screen.

[A]
Unfortunately, there is no cut and dried answer.  Determining what is fair use involves a very subjective and fact-dependent
four point test
.  You're never really going to know for sure if a borderline use is permissible or not unless you end up in court and a judge decides.
The four factors are:
the purpose and character of the use, including whether such use is of a commercial nature or is for nonprofit educational purposes;
the nature of the copyrighted work;
the amount and substantiality of the portion used in relation to the copyrighted work as a whole; and
the effect of the use upon the potential market for or value of the copyrighted work.
Each of these has a specific legal meaning based on previous precedents (which may or may not correspond to what most people would think of as the plain language meaning).  If you're doing anything that could get you sued, talk to a lawyer.
Software is even more complicated, since not all code is copyrightable to begin with.


q:
What I'd like to know is if there is a nice way to queue jQuery functions to execute after a set amount of time. This wouldn't pause the execution of other functions, just the ones following in the chain. Perhaps an example of what I'd envisage it would look like would illustrate:

$('#alert')
    .show()
    .wait(5000)    // <-- this bit
    .hide()
;

I know that it's possible by using timeouts, but it seems like that's a messy way to do it, especially compared to the above example (if it were real).

So, is something like this already built-in to jQuery, and if not, what is the best way to emulate it?

[A]
You can't do that, and you probably don't want to.  While it certainly looks pretty, there is no mechanism in Javascript that will allow you do to that without just looping in "wait" until the time has passed.  You could certainly do that but you risk seriously degrading the browser performance and if your timeout is longer than a handful of seconds browsers will show a warning to the user that your javascript seems to be stuck.
The correct way to do this is with timeouts:
```
```
var el = $('#alert');
el.show()
setTimeout(function() { el.hide() }, 5000);
```
```
Your other option would be to extend jquery to essentially add an effect for actions you want to delay:
```
```
jQuery.fn.extend({
    delayedHide: function(time) {
        var self = this;
        setTimeout(function() { self.hide(); }, time);
    }
});

$('#alert')
    .show()
    .delayedHide(5000)
;
```
```
You could also extend jquery with a method similar to setTimeout:
```
```
jQuery.fn.extend({
    delayThis: function(fn, time, args) {
        var self = this;
        setTimeout(function() { jQuery.fn[fn].apply(self, args); }, time);
    }
});

$('#alert')
    .show()
    .delayThis('hide', 5000)
;
```
```
or to call with args pass arguments in an array:
```
```
$('#alert')
    .show()
    .delayThis('css', 5000, [ 'display', 'none' ])
;
```
```


q:
I am getting an 403 access forbidden when attempting to open a page under a vhost where the document root is sitting on a different drive than where apache is sitting. I installed using the apachefriends release. This is my httpd-vhosts.conf file:

NameVirtualHost 127.0.0.1

<VirtualHost 127.0.0.1>
  ServerName foo.localhost
  DocumentRoot "C:/xampp/htdocs/foo/public"
</VirtualHost>

<VirtualHost 127.0.0.1>
  ServerName bar.localhost
  DocumentRoot "F:/bar/public"
</VirtualHost>

When opening bar.localhost in my browser, Apache is giving me 403 Access Forbidden. I tried setting lots of different access rights, even full rights to everyone, but nothing I tried helped.

Edit: Thanks! For future reference, add 'Options indexes' within to show directory indexes.

[A]
Somewhere, you need to tell Apache that people are allowed to see contents of this directory.
```
```
<Directory "F:/bar/public">
    Order Allow,Deny
    Allow from All
    # Any other directory-specific stuff
</Directory>
```
```
More info


q: How do you implement autocomplete on ASP.Net Gridview? Can anyone point me where to go to achieve this? I'm willing to use non-.Net ajax controls if that what it takes.

[A]
The AJAX Control Toolkit provides an
autocomplete
but requires a web service to work.  You could always write your own asmx if there isn't one you can use.
Otherwise, there are all sorts of JS and jQuery examples:
http://www.javascript-examples.com/autocomplete-demo/


q:
Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following:

var people = from p in Person
             where p.age < 18
             select p

var otherPeople = from p in people
                  where p.firstName equals "Daniel"
                  select p

Assuming that Person is an ADO entity which defines the age and firstName fields, what would this do from a database standpoint?  Specifically, would the people query be run to produce an in-memory structure, which would then be queried by the otherPeople query?  Or would the construction of otherPeople merely pull the data regarding the query from people and then produce a new database-peered query?  So, if I iterated over both of these queries, how many SQL statements would be executed?

[A]
```
people
```
and
```
otherPeople
```
contain objects of type
```
IQueryable<Person>
```
.
If you iterate over both, separatly, it will run two queries.
If you only iterate over
```
otherPeople
```
, it will run the expected query, with two where clauses.
If you do
```
.ToList()
```
on
```
people
```
and use the returned
```
List<Person>
```
in the second query instead of people, it becomes LINQ-to-Objects and no SQL is executed.
This behavior is referred to as deferred execution. Meaning no query is done until it is needed. Before execution they are just expression trees that get manipulated to formulate the final query.


q:
What is the difference in C# between Convert.ToDecimal(string) and Decimal.Parse(string)?

In what scenarios would you use one over the other?

What impact does it have on performance?

What other factors should I be taking into consideration when choosing between the two?

[A]
From
bytes.com
:
The Convert class is designed to
  convert a wide range of Types, so you
  can convert more types to Decimal than
  you can with Decimal.Parse, which can
  only deal with String. On the other
  hand Decimal.Parse allows you to
  specify a NumberStyle.
Decimal and decimal are aliases and
  are equal.
For Convert.ToDecimal(string),
  Decimal.Parse is called internally.
Morten Wennevik [C# MVP]
Since Decimal.Parse is called internally by Convert.ToDecimal, if you have
extreme
performance requirements you might want to stick to Decimal.Parse, it will save a stack frame.


q: How do I call an external command within Python as if I'd typed it in a shell or command prompt?

[A]
```
```
import os
os.system("your command")
```
```
Note that this is dangerous, since the command isn't cleaned. I leave it up to you to google for the relevant documentation on the 'os' and 'sys' modules. There are a bunch of functions (exec* and spawn*) that will do similar things.


q:
Using Windows Server 2003 in a multi-user environment (via Remote Desktop, using it as an application server), how to mount a (preferably encrypted) volume in a way, that won't show up on any other user's desktop?

Tried, and failed approaches:

tweaking user rights -display of mounted volume can not be changed.

Bestcrypt / truecrypt. Both of them displays the volume for a local administrator

[A]
There's a key in the Registry that's used to hide mapped drives.
If you want to stop any combination of drives appearing in My Computer
Add the Binary Value of 'NoDrives' in the registry at
"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer"
Here is the table of all the values (Note that you can add up values to hide multiple drives, also the value is binary type but must be entered in hexadecimal, so if you add up a few drives, get ready for a little hex math. )  :
```
```
A 1 00 00 00
B 2 00 00 00
C 4 00 00 00
D 8 00 00 00
E 16 00 00 00
F 32 00 00 00
G 64 00 00 00
H 128 00 00 00
I 00 1 00 00
J 00 2 00 00
K 00 4 00 00
L 00 8 00 00
M 00 16 00 00
N 00 32 00 00
O 00 64 00 00
P 00 128 00 00
Q 00 00 1 00
R 00 00 2 00
S 00 00 4 00
T 00 00 8 00
U 00 00 16 00
V 00 00 32 00
W 00 00 64 00
X 00 00 128 00
Y 00 00 00 1
Z 00 00 00 2
```
```


q:
I’m trying to run this SQL using get external.

It works, but when I try to rename the sub-queries or anything for that matter it remove it.

I tried as, as and the name in '', as then the name in "",
 and the same with space. What is the right way to do that?

Relevant SQL:

SELECT list_name, app_name,
    (SELECT fname  + ' ' + lname
     FROM dbo.d_agent_define map
     WHERE map.agent_id = tac.agent_id) as agent_login,
   input, CONVERT(varchar,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))
FROM dbo.maps_report_list list
JOIN dbo.report_tac_agent tac ON (tac.list_id = list.list_id)
WHERE input = 'SYS_ERR'
   AND app_name = 'CHARLOTT'
   AND convert(VARCHAR,DATEADD(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
   AND list_name LIKE 'NRBAD%'
ORDER BY agent_login,CONVERT(VARCHAR,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))

[A]
You could get rid of your
```
dbo.d_agent_define
```
subquery and just add in a join to the agent define table.
Would this code work?
```
```
select list_name, app_name,
map.fname + ' ' + map.lname as agent_login,
input,
convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) as tac_seconds
from dbo.maps_report_list list
join dbo.report_tac_agent tac
on (tac.list_id = list.list_id)
join dbo.d_agent_define map
on (map.agent_id = tac.agent_id)
where input = 'SYS_ERR'
and app_name = 'CHARLOTT'
and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
and list_name LIKE 'NRBAD%'
order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))
```
```
Note that I named your dateadd column because it did not have a name.  I also tried to keep your convention of how you do a join.  There are a few things that I would do different with this query to make it more readable, but I only focused on getting rid of the subquery problem.
I did not do this, but I would recommend that you qualify all of your columns with the table from which you are getting them.


q:
I'm designing a language. First, I want to decide what code to generate. The language will have lexical closures and prototype based inheritance similar to javascript. But I'm not a fan of gc and try to avoid as much as possible. So the question: Is there an elegant way to implement closures without resorting to allocate the stack frame on the heap and leave it to garbage collector?

My first thoughts:

Use reference counting and garbage collect the cycles (I don't really like this)

Use spaghetti stack (looks very inefficient)

Limit forming of closures to some contexts such a way that, I can get away with a return address stack and a locals' stack.

I won't use a high level language or follow any call conventions, so I can smash the stack as much as I like.

(Edit: I know reference counting is a form of garbage collection but I am using gc in its more common meaning)

[A]
This would be a better question if you can explain what you're trying to avoid by not using GC. As I'm sure you're aware, most languages that provide lexical closures allocate them on the heap and allow them to retain references to variable bindings in the activation record that created them.
The only alternative to that approach that I'm aware of is what
```
gcc
```
uses for nested functions: create a trampoline for the function and allocate it on the stack. But as the gcc manual says:
If you try to call the nested function through its address after the containing function has exited, all hell will break loose. If you try to call it after a containing scope level has exited, and if it refers to some of the variables that are no longer in scope, you may be lucky, but it's not wise to take the risk. If, however, the nested function does not refer to anything that has gone out of scope, you should be safe.
Short version is, you have three main choices:
allocate closures on the stack, and don't allow their use after their containing function exits.
allocate closures on the heap, and use garbage collection of some kind.
do original research, maybe starting from the region stuff that ML, Cyclone, etc. have.


q:
I frequently use git stash and git stash pop to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but git stash pop appears to remove all references to the associated commit.

I know that if I use git stash then .git/refs/stash contains the reference of the commit used to create the stash. And .git/logs/refs/stash contains the whole stash. But those references are gone after git stash pop. I know that the commit is still in my repository somewhere, but I don't know what it was.

Is there an easy way to recover yesterday's stash commit reference?

[A]
```
git fsck --unreachable | grep commit
```
should show the sha1, although the list it returns might be quite large.
```
git show <sha1>
```
will show if it is the commit you want.
```
git cherry-pick -m 1 <sha1>
```
will merge the commit onto the current branch.


q:
quick question: my customer has a situation where he has his database with a varchar field and the corresponding jdbc code is storing/retrieving a boolean.

I guess that the boolean values false and true are going to be translated to "0" and "1" but I would like to have a confirmation of this (I can't find the precise behavior specification online, maybe it depends on each driver, Oracle in this case).

I know I could experiment by myself, but I want to have a try at stackoverflow.com!

Thanks for your answer,

Eric.

[A]
Unfortunately,
```
BOOLEAN
```
semantics are highly database-specific.  I'm
guessing
that the Oracle driver is going to translate boolean values to a
```
VARCHAR
```
field into "
```
true
```
" and "
```
false
```
", rather than
```
0
```
and
```
1
```
, but you should verify this yourself.


q:
Assume I have an "images" folder directory under the root of my application.  How can I, from within a .css file, reference an image in this directory using an ASP.NET app relative path.

Example:

When in development, the path of ~/Images/Test.gif might resolve to /MyApp/Images/Test.gif while, in production, it might resolve to /Images/Test.gif (depending on the virtual directory for the application).  I, obviously, want to avoid having to modify the .css file between environments.

I know you can use Page.ResolveClientUrl to inject a url into a control's Style collection dynamically at render time.  I would like to avoid doing this.

[A]
In case you didn't know you could do this...
If you give a relative path to a resource in a CSS it's relative to the CSS file, not file including the CSS.
```
```
background-image: url(../images/test.gif);
```
```
So this might work for you.


q: I have Visual Studio web test attached nicely to a data source, but I need to be able to iterate over each entry in the data source. How should I do this?

[A]
This
article
seems to Discuss something quite like what you're talking about.
Good luck.
Ola
EDIT:
From the linked article, your DataSource is exposed to your test via an attribute.
```
```
[DataSource("System.Data.SqlClient",
    "Data Source=VSTS;Initial Catalog=ContactManagerWebTest;
    Integrated Security=True", "ValidContactInfo",
    DataAccessMethod.Sequential), TestMethod()]
```
```
There are several other DataSources you can link to, for example CSV, or even Parameters of a Test Case in TFS. Be sure to include the
```
DataAccessMethod.Sequential
```
. If there are multiple rows in the table indicated by the
```
DataSourceAttribute
```
, then each test run will have
```
TestContext.DataRow
```
pointing to the current row/iteration for the test.


q:
For reasons I won't go into, I wish to ban an entire company from accessing my web site. Checking the remote hostname in php using gethostbyaddr() works, but this slows down the page load too much. Large organizations (eg. hp.com or microsoft.com) often have blocks of IP addresses. Is there anyway I get the full list, or am I stuck with the slow reverse-DNS lookup? If so, can I speed it up?

Edit: Okay, now I know I can use the .htaccess file to ban a range. Now, how can I figure out what that range should be for a given organization?

[A]
Take a look at .htaccess if you're using apache:
.htaccess tutorial


q: I am trying to connect to a Microsoft SQL 2005 server which is not on port 1433.  How do I indicate a different port number when connecting to the server using SQL Management Studio?

[A]
```
127.0.0.1,6283
```
Add a comma between the ip and port


q: You do AssignProcessToJobObject and it fails with "access denied" but only when you are running in the debugger. Why is this?

[A]
This one puzzled me for for about 30 minutes.
First off, you probably need a UAC manifest embedded in your app (
as suggested here
). Something like this:
```
```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <!-- Identify the application security requirements. -->
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
      <security>
        <requestedPrivileges>
          <requestedExecutionLevel
            level="asInvoker"
            uiAccess="false"/>
        </requestedPrivileges>
      </security>
    </trustInfo>
  </assembly>
```
```
Secondly (and this is the bit I got stuck on), when you are running your app under the debugger, it creates your process in a job object. Which your child process needs to be able to breakaway from before you can assign it to your job. So (duh), you need to specify
```
CREATE_BREAKAWAY_FROM_JOB
```
in the flags for
```
CreateProcess
```
).
If you weren't running under the debugger, or your parent process were in the job, this wouldn't have happened.


q:
I have a table that got into the "db_owner" schema, and I need it in the "dbo" schema.

Is there a script or command to run to switch it over?

[A]
```
```
ALTER SCHEMA [NewSchema] TRANSFER [OldSchema].[Table1]
```
```


q:
I have added some code which compiles cleanly and have just received this Windows error:

---------------------------
(MonTel Administrator) 2.12.7: MtAdmin.exe - Application Error
---------------------------
The exception Privileged instruction.

 (0xc0000096) occurred in the application at location 0x00486752.

I am about to go on a bug hunt, and I am expecting it to be something silly that I have done which just happens to produce this message. The code compiles cleanly with no errors or warnings. The size of the EXE file has grown to 1,454,132 bytes and includes links to ODCS.lib, but it is otherwise pure C to the Win32 API, with DEBUG on (running on a P4 on Windows 2000).

[A]
I saw this with Visual c++ 6.0 in the year 2000.
The debug C++ library had calls to physical I/O instructions in it, in an exception handler.
If I remember correctly, it was dumping status to an I/O port that used to be for DMA base registers, which I assume someone at Microsoft was using for a debugger card.
Look for some error condition that might be latent causing diagnostics code to run.
I was debugging, backtracked and read the dissassembly. It was an exception while processing
```
std::string
```
, maybe indexing off the end.


q:
I'm looking for the best way to take a simple input:

echo -n "Enter a string here: "
read -e STRING

and clean it up by removing non-alphanumeric characters, lower(case), and replacing spaces with underscores.

Does order matter? Is tr the best / only way to go about this?

[A]
After a bit of looking around it seems
```
tr
```
is indeed the simplest way:
```
```
export CLEANSTRING="`echo -n "${STRING}" | tr -cd '[:alnum:] [:space:]' | tr '[:space:]' '-'  | tr '[:upper:]' '[:lower:]'`"
```
```
Occam's razor
, I suppose.


q: Is that needed?

[A] Pojos could still contain logic errors.


q: I would like to pass an argument(s) to a method being defined using define_method, how would I do that?

[A]
The block that you pass to define_method can include some parameters.  That's how your defined method accepts arguments.  When you define a method you're really just nicknaming the block and keeping a reference to it in the class.  The parameters come with the block.  So:
```
```
define_method(:say_hi) { |other| puts "Hi, " + other }
```
```


q: When you create a new content type in Drupal using the Content Creation Kit, you automatically get Title and Body fields in the generated form. Is there a way to remove them?

[A]
To remove the body edit the type, expand "Submission form settings" and put in blank for body field label.  For title you can rename it to another text field.  If you really have no need for any text fields you can create a custom module, say called foo, and create function foo_form_alter() which replaces $form['title'] with a
#value
when $form['type']['#value'] is your node type.


q: I am trying to find the virtual file that contains the current users id. I was told that I could find it in the proc directory, but not quite sure which file.

[A]
I'm not sure that can be found in
```
/proc
```
. You could try using the
```
getuid()
```
function or the
```
$USER
```
environment variable.


q: How can I get hierarchy recordset in ms access through select statement?


q:
When I start my process from Visual Studio, it is always created inside a job object. I would like to know how to turn this behaviour off. Any ideas?

I expect that it is created in a job object to be debugged. I want to place my program in a different job object.

It's not the hosting process. I'm talking about a Job Object. This is an unmanaged C++ application.

[A]
I'm not aware of any ways to control this aspect of processes spawned for debugging by VS.NET. But there's a workaround, which is applicable to any situation in which VS.NET can't or doesn't start your process in the exact way you want:
Start your process (possibly using a wrapper EXE that runs as part of the post-build event), then attach to the newly started process using Tools/Attach to Process. If you break into the debugger as part of your startup code, this won't even be required (and you can also debug startup issues...).


q:
I am using mssql and am having trouble using a subquery. The real query is quite complicated, but it has the same structure as this:

select
  customerName,
  customerId,
  (
    select count(*)
    from Purchases
    where Purchases.customerId=customerData.customerId
  ) as numberTransactions
from customerData

And what I want to do is order the table by the number of transactions, but when I use

order by numberTransactions

It tells me there is no such field. Is it possible to do this? Should I be using some sort of special keyword, such as this, or self?

[A]
use the field number, in this case:
```
```
order by 3
```
```


q: What are the best Java example sites? I'm looking for places that you go when you have a specific question and you want a little Java code snippet to solve it with.

[A]
I like
DZone Snippets
from
It is a public source code repository.
You can build up your personal collection of code snippets, and categorize them with tags / keywords.
(just add
another suggestion
)


q: We are creating a Real-Time Process in VxWorks 6.x, and we would like to limit the amount of memory which can be allocated to the heap.  How do we do this?

[A]
When creating a RTP via rtpSpawn(), you can specify an environment variable which controls how the heap behaves.
There are 3 environment variables:
```
HEAP_INITIAL_SIZE - How much heap to allocate initially (defaults to 64K)
HEAP_MAX_SIZE     - Maximum heap to allocate (defaults to no limit)
HEAP_INCR_SIZE    - memory increment when adding to RTP heap (defaults to 1 virtual page)

The following code shows how to use the environment variables:
```
char * envp[] = {"HEAP_INITIAL_SIZE=0x20000", "HEAP_MAX_SIZE=0x100000", NULL);
   rtpSpawn ("myrtp.vxe", NULL, envp, 100, 0x10000, 0, 0);
```
```


q: Specifically in .NET, but I'm leaving it open.

[A]
MSDN:
Enumerating Installed Fonts


q:
Maybe the need to do this is a 'design smell' but thinking about another question, I was wondering what the cleanest way to implement the inverse of this:

foreach(ISomethingable somethingableClass in collectionOfRelatedObjects)
{
  somethingableClass.DoSomething();
}

i.e. How to get/iterate through all the objects that don't implement a particular interface?

Presumably you'd need to start by upcasting to the highest level:

foreach(ParentType parentType in collectionOfRelatedObjects)
{
  // TODO: iterate through everything which *doesn't* implement ISomethingable
}

Answer by solving the TODO: in the cleanest/simplest and/or most efficient way

[A]
Something like this?
```
```
foreach (ParentType parentType in collectionOfRelatedObjects) {
    if (!(parentType is ISomethingable)) {
    }
}
```
```


q: I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.


q:
I want to download a lot of urls in a script but I do not want to save the ones that lead to HTTP errors.

As far as I can tell from the man pages, neither curl or wget provide such functionality.
Does anyone know about another downloader who does?

[A]
I think the
```
-f
```
option to
```
curl
```
does what you want:
```
-f
```
,
```
--fail
```
(HTTP) Fail silently (no output at all) on server errors. This is mostly done to  better
            enable  scripts  etc  to  better deal with failed attempts. In normal cases when an HTTP
            server fails to deliver a document, it returns an HTML document stating so (which  often
            also  describes  why  and  more).  This  flag will prevent curl from outputting that and
            return error 22. [...]
However, if the response was actually a 301 or 302 redirect, that still gets saved, even if its destination would result in an error:
```
```
$ curl -fO http://google.com/aoeu
$ cat aoeu
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE>

301 Moved

The document has moved
here.

```
```
To follow the redirect to its dead end, also give the
```
-L
```
option:
```
-L
```
,
```
--location
```
(HTTP/HTTPS)  If  the  server  reports  that the requested page has moved to a different
                location (indicated with a Location: header and a 3XX response code), this  option  will
                make  curl redo the request on the new place. [...]


q:
If you were to mandate a minimum percentage code-coverage for unit tests, perhaps even as a requirement for committing to a repository, what would it be?

Please explain how you arrived at your answer (since if all you did was pick a number, then I could have done that all by myself ;)

[A]
85% would be a good starting place for checkin criteria.
I'd probably chose a variety of higher bars for shipping criteria - depending on the criticality of the subsystems/components being tested.


q:
I'm trying to create a deployment tool that will install software based on the hardware found on a system. I'd like the tool to be able to determine if the optical drive is a writer (to determine if burning software sould be installed) or can read DVDs (to determine if a player should be installed). I tried uing the following code

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_CDROMDrive")
For Each objItem in colItems
    Wscript.Echo "MediaType: " & objItem.MediaType
Next

but it always respons with CD-ROM

[A]
You can use WMI to enumerate what Windows knows about a drive; get the
```
Win32_DiskDrive
```
instance from which you should be able to grab the the
```
Win32_PhysicalMedia
```
information for the physical media the drive uses; the
MediaType
property to get what media it uses (CD, CDRW, DVD, DVDRW, etc, etc).


q:
I'm using a table to design the layout of my web page. I want the table to fill the page even if it doesn't contain much content. Here's the CSS I'm using:

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#container {
    min-height: 100%;
    width: 100%;
}

And I place something like this in the page code:

<table id="container">
<tr>
<td>
...

This works for Opera 9, but not for Firefox 2 or Internet Explorer 7. Is there a simple way to make this solution work for all popular browsers?

(Adding id="container" to td doesn't help.)

[A]
Just use the
```
height
```
property instead of the
```
min-height
```
property when setting
```
#container
```
. Once the data gets too big, the table will automatically grow.


q:
I'm using the following html to load dojo from Google's hosting.

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("dojo", "1.1.1");</script>
<script type="text/javascript">
dojo.require("dojox.gfx");
...

This errors out on the requre line with an error like dojox.gfx is undefined. Is there a way to make this work, or does Google not support the dojox extensions?

Alternatively, is there another common host I can use for standard dojo releases?

[A]
I believe that google becomes the namespace for your imported libraries. Try:
```
google.dojo.require
```
.
Oh! And as pointed out below, don't forget to use google.setOnLoadCallback instead of calling your function directly.


q: On my current project, we've been using Struts 1 for the last few years, and ... ahem ... Struts is showing its age. We're slowly migrating our front-end code to an Ajax client that consumes XML from the servers. I'm wondering if any of you have migrated a legacy Struts application to a different framework, and what challenges you faced in doing so.

[A]
Sure. Moving from Struts to an AJAX framework is a very liberating experience. (Though we used JSON rather than XML. Much easier to parse.) However, you need to be aware that it's effectively a full rewrite of your application.
Instead of the classic Database/JSP/Actions scheme for MVC, you'll find yourself moving to a Servlet/Javascript scheme whereby the model is represented by HTTP GET requests, actions are represented by POST/PUT/DELETE requests, and the view is rendered on the fly by the web browser. This leads to interesting challenges in each area:
Server Side
- On the server side you will need to develop a standard for exposing data to the client. The simplest and easiest method is to adopt a
REST
methodology that best matches your data's hierarchy. This is fairly simple to implement with servlets, but Sun also has developed a
Java 1.6 scheme
using attributes that looks pretty cool.
Another aspect of the server side is to choose a transmission protocol. I know you mentioned XML already, but you might want to reconsider. XML parsers vary greatly between browsers. One browser might make the document root the first child, another one might add a special content object, and they all parse whitespace differently. Even worse, the normalize() function doesn't seem to be correctly implemented by the major browsers. Which means that XML parsing is liable to be full of hacks.
JSON
is much easier to parse and more consistent in its results. Javascript and Actionscript (Flash) can both translate JSON directly to objects. This makes accessing the data a simple matter of x.y or x[y]. There are also plenty of APIs to handle JSON in every language imaginable. Because it's so easy to parse, it's almost supported BETTER than XML!
Client Side
- The first issue you're going to run into is the fact that no one understands how to write Javascript. ESPECIALLY those who think they do. If you have any books on Javascript, throw them out the window NOW. There are practically no good books on the language as they all follow the same "hacking" pattern without really diving into what they are doing.
From the lowest level, your team is going to need remedial training on Javascript development. Start with the
Javascript Client Guide
. It's the
de facto
source of information on the language. The next stop is
Douglas Crockford's videos
on Javascript. I don't agree with everything he has to say, but he's one of the few experts on the language.
Once you've got that down, consider what frameworks, if any, you want to use. Generally speaking, I dislike stuff like Prototype and Mootools. They tend to take a simple problem and make it worse. None the less, you can feel free to evaluate these tools and decide if they'll work for you.
If you absolutely feel that you cannot live without a framework because your team is too inexperienced, then
GWT
might fit the bill. GWT allows you to quickly write DHTML web apps in Java code, then compile them to Javascript. The PROBLEM is that you're giving up massive amounts of flexibility by doing this. The Javascript language is far more powerful than GWT exposes. However, GWT does let Java developers get up to speed faster. So pick your battles.
Those are the key areas I can think of. I can say that you'll heave a sigh of relief once you get struts out of your application. It can be a bit of a beast. Especially if you've had inexperienced developers working on your Struts model. :-)
Any questions?
Edit 1:
I forgot to add that your team should study the
W3C specs
religiously. These are the APIs available to you in modern browsers. If you catch anyone using the DOM 0 APIs (e.g. document.forms['myform'].blah.value instead of document.getElementById("blah").value) force them to transcribe the entire DOM 1 specification until they understand it top to bottom.
Edit 2:
Another key issue to consider is how to document your fancy new AJAX application. REST style interfaces lend themselves well to being documented in a Wiki. What I did was a had a top level page that listed each of the services and a description. By clicking on the service path, you would be taken to a document with detailed information on each of the sub-paths. In theory, this scheme can document as deep as you need the tree to go.
If you go with JSON, you will need to develop a scheme to document the objects. I just listed out the possible properties in the Wiki as documentation. That works well for simple object trees, but can get complex with larger, more sophisticated objects. You can consider supplementing with something like IDL or WebIDL in that case. (Can't be much worse than XML DTDs and Schemas. ;-))
The DHTML code is a bit more classical in its documentation. You can use a tool like
JSDoc
to create JavaDoc-style documentation. There's just one caveat. Javascript code does not lend itself well to being documented in-code. If for no other reason that the fact that it bloats the download. However, you may find yourself regularly writing code that operates as a cohesive object, but is not coded behind the scenes as such an object. Thus the best solution is to create JSDoc skeleton files that represent and document the Javascript objects.
If you're using GWT, documentation should be a no-brainer.


q: Can I store a database connection in the Session object?

[A]
It is generally not recommended to do so, a connection string in the Application variable, with a nice helper function/class is a much preferred method.
Here
is some reference.
(Dead link removed because it now leads to a phishy site)


q: Anyone got a working example of using ruby to post to a presigned URL on s3

[A]
Does anything on the
s3 library page
cover what you need?  There are loads of examples there.


q: What is the difference between different optimization levels in GCC?  Assuming I don't care to have any debug hooks, why wouldn't I just use the highest level of optimization available to me?  does a higher level of optimization necessarily (i.e. provably) generate a faster program?

[A]
Generally optimization levels higher than
```
-O2
```
(just
```
-O3
```
for gcc but other compilers have higher ones) include optimizations that can increase the size of your code.  This includes things like loop unrolling, lots of inlining, padding for alignment regardless of size, etc.  Other compilers offer vectorization and inter-procedural optimization at levels higher than
```
-O3
```
, as well as certain optimizations that can improve speed a lot at the cost of correctness (e.g., using faster, less accurate math routines).  Check the docs before you use these things.
As for performance, it's a tradeoff.  In general, compiler designers try to tune these things so that they don't decrease the performance of your code, so
```
-O3
```
will usually help (at least in my experience) but your mileage may vary.  It's not always the case that really aggressive size-altering optimizations will improve performance (e.g. really aggressive inlining can get you cache pollution).


q:
As an example in pseudocode:

if ((a mod 2) == 0)
{
    isEven = true;
}
else
{
    isEven = false;
}

[A]
Here is the representation of your pseudo-code in minimal Java code;
```
```
boolean isEven = a % 2 == 0;
```
```
I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.


[A]
I think it actually does render both data sets, but you can only se one of them because there's only one scale on the y axis. (In other words, 0.10 is too small to show.)
And, you should really be using percentages. 100 is the highest accepted value:
Where chart data string consists of positive floating point numbers from zero (0.0) to one hundred (100.0)


q: How to create new PCL file similar to existing MS doc. I have MS doc template and replacing it with actual data. I need to achieve same for PCL format (Create PCL file as template and replacing it with actual value from database and send it to fax).

[A]
install a new printer
when asked for a port, create a new port of type "Local Port"
as name of the port, enter some file name, e.g.
```
c:\temp\print.pcl
```
select some PCL-compatible printer, e.g. HP LaserJet 4, or whatever your fax is comptaible with
When you print to this printer, Windows will write the output to that file.
Many programs allow you to redirect printing to a file; in this case, you'd be able to select a different file name for each print job.


q:
I have some experience making multiplayer turn-based games using sockets, but I've never attempted a realtime action game. What kind of extra issues would I have to deal with? Do I need to keep a history of player actions in case lagged players do something in the past? Do I really need to use UDP packets or will TCP suffice? What else?

I haven't really decided what to make, but for the purpose of this question you can consider a 10-player 2D game with X Y movement.

[A]
There are a few factors involved in setting up multiplayer
The protocol, it's important that you decide whether you want TCP or UDP.  UDP has less overhead but isn't guaranteed delivery.  Conversely TCP is more trustworthy.  Each game will have their preferred protocol.  UDP for instance will work for a first person shooter but may not be suited for an RTS where information needs to be consistent
Firewall/Connection.  Making sure your multiplayer game doesn't have to make 2000 outbound connections and uses a standard port so portforwarding is easy.  Interfacing it with windows firewall will probably be an added bonus.
Bandwidth.  This is important, how much data are you intending to push through a network connection?  I guess this will come down to play testing and recording throughput.  If you're requiring upwards of 200kb/s for each client you may want to rethink a few things.
Server Load.  This is also important, how much processing is required by a server for a normal game?  Do you need some super 8 core server with 16gb of RAM to run it?  Are there ways of reducing it?
I guess there are heaps more, but really you want a game that is comfortable to play over the network and over a variety of connections.


q:
How can I cast long to HWND (C++ visual studio 8)?

Long lWindowHandler;
HWND oHwnd = (HWND)lWindowHandler;

But I got the following warning:

warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size

Thanks.

[A]
As long as you're sure that the LONG you have is really an HWND, then it's as simple as:
```
```
HWND hWnd = (HWND)(LONG_PTR)lParam;
```
```


q:
I find it much more difficult to manage your session in a desktop application, because you cannot take advantage of such a clear bondary like HttpContext.
So how do you manage your session lifetime to take advantage of lazy loading but without having one session open for the entire application?

[A]
I think it boils down to the design of your objects. Because lazy-loading can be enforced in the per-object level, you can take advantage of that fact when you think about session management.
For example, I have a bunch of objects which are data-rich and lazy loaded, and I have a grid/summary view, and a details view for them. In the grid-summary view, I do not use the lazy-loaded version of the object. I use a surrogate object to present that data, and that surrogate object is not lazy loaded.
On the other hand, once a user selects that record for viewing/editing, and you enter a multi-paged details view of the object, that's when we apply lazy-loading to the specific object. Data is now lazy loaded depending on which details are viewed only on demand. That way, the scope of my session being open for lazy loading only lasts as long as the details view is being used.


q:
NHibernate is not really a good fit for our environment due to all the dependencies. (Castle, log4net etc.)

Is there a good lightweight alternative?

Support for simple file based databases such as Access/SQLite/VistaDB is essential.

Ideally, something contained in a single assembly that only references .NET assemblies. If it only requires .NET framework 2.0 or 3.0 that is a bonus.

[A]
Generally speaking, for your database backend to work with .net you need an ADO.Net provider for it.
For MS Access (Jet), the Provider is shipped with .net.
For SQLite, there is a selfcontained ADO.Net Provider.
As for the data access layer lib, if you want some abstraction over ADO.Net:
MS
Data Access Application Block
, a part of
ms enterprise library
.
iBatis.Net
(Was
retired
by the Apache Foundation in 2010)
MyBatis.net
ADOTemplate
from the Spring Framework.net
All those work well starting with framework 2.0 and up.
Basically,
you
choose (and there is a lot of choices)


q:
How to center text over an image in a table cell using javascript, css, and/or html?

I have an HTML table containing images - all the same size - and I want to center a text label over each image. The text in the labels may vary in size. Horizontal centering is not difficult, but vertical centering is.

ADDENDUM: i did end up having to use javascript to center the text reliably using a fixed-size div with absolute positioning; i just could not get it to work any other way

[A]
you could try putting the images in the background.
```
```

            Here is my text

```
```
You'll just need to set the height and width on the cell and that should be it.


q:
I am developing an application using vb.net. For performing some tasks the application needs administrator privileges in the machine. How to ask for the privileges during the execution of the program?

What is the general method of switching user accounts for executing an application? In other words, is there some way for an application to run under an arbitrary user account?

[A]
There are several articles on the Internet about developing elevated processes in Vista, but essentially elevation requests involve decorating .NET assemblies and WIN32 executables with elevation status in the application manifest file (may be embedded or side-by-side).
There is an excellent blog post about your question which provides the code you'll probably need:
.NET Wrapper for COM Elevation


q:
Is it possible to get a thread dump of a Java Web Start application? And if so, how?

It would be nice if there were a simple solution, which would enable a non-developer (customer) to create a thread dump. Alternatively, is it possible to create a thread dump programmatically?

In the Java Web Start Console I can get a list of threads by pressing 't' but stacktraces are not included.

If answers require certain java versions, please say so.

[A]
Try
```
```
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
```
```
Then you can iterate over the collection to show the top x stack elements you're interested in.


q:
I have tree control object created using CTreeCtrl MFC class. The tree control needs to support rename.
When I left click on any of item in Tree the TVN_SELCHANGED event is called from which I can get the selected item of the tree as below :
  HTREEITEM h = m_moveListTree.GetSelectedItem();
  CString s = m_moveListTree.GetItemText(h);

However when I rightclick on any item in tree I do not get any TVN_SELCHANGED event and hence my selected item still remains the same from left click event. This is causing following problem :
1)User leftclicks on item A
2)user right clicks on item B and says rename
3)Since the selected item is still A the rename is applying for item A.

Please help in solving problem.

-Praveen

[A]
I created my own MFC like home grown C++ GUI library on top of the Win32 API and looking at my code, this is how it handles that situation:
```
```
LRESULT xTreeCtrl::onRightClick(NMHDR *)
{
  xPoint pt;

  //-- get the cursor at the time the mesage was posted
  DWORD dwPos = ::GetMessagePos();

  pt.x = GET_X_LPARAM(dwPos);
  pt.y = GET_Y_LPARAM (dwPos);

  //-- now convert to window co-ordinates
  pt.toWindow(this);

  //-- check for a hit
  HTREEITEM hItem = this->hitTest(pt);

  //-- select any item that was hit
  if ((int)hItem != -1) this->select(hItem);

  //-- leave the rest to default processing
  return 0;
}
```
```
I suspect if you do something similar in the MFC right click or right button down events that will fix the problem.
NOTE: The onRightClick code above is nothing more than the handler for the
WM_NOTIFY
,
NM_RCLICK
message.


q:
How do I create a resource that I can reference and use in various parts of my program easily?

My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time.

[A]
Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.
How to create a resource:
In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.
Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.
Click the "Resources" tab.
The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.
Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.
At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.
How to use a resource:
Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.
There is a static class called
```
Properties.Resources
```
that gives you access to all your resources, so my code ended up being as simple as:
```
```
paused = !paused;
if (paused)
    notifyIcon.Icon = Properties.Resources.RedIcon;
else
    notifyIcon.Icon = Properties.Resources.GreenIcon;
```
```
Done! Finished! Everything is simple when you know how, isn't it?


q:
I am working on a small application in VB.NET. The program needs administrator privilege for doing some tasks. Is there a way to ask for administrator privileges during the execution if the program?

What is the general way of changing the user account under which the application is running?

[A]
You can specify this in your application's manifest file.
Check out
this link
and
this link
and
this link
too.


q:
GNU/Linux text console, X11 not involved, indeed not even
installed. Keyboard is US layout, keymap US default. Kernel
version 2.20.x or later.

An application written in C is getting keyboard input in
translation mode, i.e. XLATE or UNICODE. When a key is
pressed, the application receives the corresponding
keystring. As an example, you press F1, the application
reads "\033[[A".

Before the kernel sends the keystring to the application, it
must know which key is pressed, i.e. it must know its
scancode. In the F1 example above, the scancode for the key
pressed is 59 or 0x3b.

That's to say even when the keyboard is in translation mode,
the scancodes are held somewhere in memory. How can the
application access them without switching the keyboard to
RAW or MEDIUMRAW mode? A code snippet would help.

[A]
Sure, the code you want to look at is in kbd-1.12.tar.bz2, which is the source bundle for the 'kbd' package. The 'kbd' package provides tools such as 'dumpkeys', 'showkeys' and 'loadkeys', which are useful for looking at the current keyboard mapping, checking what keys emit what scancodes, and loading a new mapping.
You will have to communicate with the kernel via ioctls, and it's quite complicated, so I recommend reading the source of that package to see how it's done.
Here's a link to the tarball:
kbd-1.12.tar.bz2 (618K)
.


q:
i've created a Form Panel, and i'm rendering couple of Combo Boxes in the panel with a store which is populated via an response handler.
the problem if i want to render the panel again it renders the combo boxes without the store, though i'm re-constructing the panel.
i tried to debug to figure out the cause and surprisingly though for combo box the Store is null on calling - comboBox.setStore(store) it checks for the property (isRendered) and finds it to be true and hence doesn't add the store but just keep the existing store which is still null.

i've seen this problem in another scenaio where i had created a collapsible field set containing the Combobox, On minimize and maximize of the fieldset the store vanishes for the same reasons.

can someone please help me here, i'm completely struck here i tried various option but nothing works.

[A]
Have you tried
```
doLayout()
```
method of
```
FormPanel
```
?


q:
How do I get a list of the active IP-addresses, MAC-addresses and NetBIOS names on the LAN?

I'd like to get NetBIOS name, IP and MAC addresses for every host on the LAN, preferably not having to walk to every single PC and take note of the stuff myself.

How to do that with Windows Script Host/PowerShell/whatever?

[A]
If you're using DHCP then the server will give you a list of all that information.
This website has a good tutorial on using powershell to get networking information
http://www.powershellpro.com/powershell-tutorial-introduction/powershell-scripting-with-wmi/
If you neet to get quick list of computer names you can use "net view".  Also have a look at nbmac although I'm unsure of it's working status under XP.  Another option could be to use nbtstat -a  (once you've used net view to list workstations)


q:
I want to make an entity that has an autogenerated primary key, but also a unique compound key made up of two other fields. How do I do this in JPA?

I want to do this because the primary key should be used as foreign key in another table and making it compound would not be good.

In the following snippet, I need the command and model to be unique. pk is of course the primary key.

@Entity
@Table(name = "dm_action_plan")
public class ActionPlan {
    @Id
    private int pk;
    @Column(name = "command", nullable = false)
    private String command;
    @Column(name = "model", nullable = false)
    String model;
}

[A]
You can use
```
@UniqueConstraint
```
something like this :
```
```
@Entity
@Table(name = "dm_action_plan",
       uniqueConstraints={ @UniqueConstraint(columnNames= "command","model") } )
public class ActionPlan {
    @Id
    private int pk;

    @Column(name = "command", nullable = false)
    private String command;

    @Column(name = "model", nullable = false)
    String model;
}
```
```
This will allow your JPA implementation to generate the DDL for the unique constraint.


q: Is there a way to control the Fujitsu Softune debugger with an other application(e.g. Eclipse)? I think about sending the command mentioned in the documentation of Softune and parse the output, but also other approaches are welcome.

[A]
What do you mean by controlling the Fujitsu Softune debugger?
If what you want to do is to start a debugging session with your freshly-compiled .abs file, you can do the following.
In the Eclipse environment add a button or shortcut to call the make utility to make a
```
debug:
```
. Your makefile would have an entry like:
```
```
debug: $(make_vars)
# start debugger
make -f$(make_vars) -f$(make_dir)/$(cfg) cfg="$(cfg)"   debug_session
```
```
In the make entry for
```
debug_session
```
you put something like:
```
```
echo UPDATING SOFTUNE-3 PROJECT FOR  DEBUGGING;\
$(subst \,/,$(DIR_SOFTUNE_WORKBENCH))/bin/Fs907s.exe softune/E7x_proj.wsp    2>/dev/null;
```
```
I hope this was useful.


q:
I'm looking for someone reasonably cheap but better than the majority of budget hosts out there. I'm currently with brinkster.net and I've become increasingly annoyed at the their immense unreliability and low available resources.

Fasthosts business plan is close, but has no mysql, only has ASP.NET 2.0 and is maybe slightly more expensive than I was hoping for.

[A]
I have had great luck with
Viux.com
- their customer service is top-notch and they were quick to implement asp.net 3.5. I moved all my sites (5) to Viux now and couldn't be happier. Very reliable and I can't say enough about their super fast and friendly service! MySQL comes free with all of their plans and MSSQL is $2/month.
I have tried quite a few hosts, and these guys are my favorite. If you decide on another, just make sure it is not M6.net, their customer service was just horrendous!


q: Could somebody please name a few.  I could given time, but this is for somebody else, and I'd also like some community input.

[A]
Depends on your programming language.
On .net, the built-in support for .net 3.5 is obvious, although this is mainly project templates. However, SP1 adds .net Client Framework support, which is not possible within VS2005 to my knowledge.
This also means support for WPF with a XAML Designer, although most people still prefer Expression Blend for WPF Interfaces.
Apparantly, there is now a JavaScript Debugger, even though it's a
bit broken
as it seems (not sure if SP1 fixes this)
In short: For .net 3.5, it's almost a must-have if you are a professional developer, but that is just my opinion.


q: I'm writing the memory manager for an application, as part of a team of twenty-odd coders.  We're running out of memory quota and we need to be able to see what's going on, since we only appear to be using about 700Mb. I need to be able to report where it's all going - fragmentation etc.  Any ideas?

[A]
You can use existing memory debugging tools for this, I found Memory Validator
1
quite useful, it is able to track both API level (heap, new...) and OS level (Virtual Memory) allocations and show virtual memory maps.
The other option which I also found very usefull is to be able to dump a map of the whole virtual space based on VirtualQuery function. My code for this looks like this:
```
```
void PrintVMMap()
{
  size_t start = 0;
  // TODO: make portable - not compatible with /3GB, 64b OS or 64b app
  size_t end = 1U<<31; // map 32b user space only - kernel space not accessible
  SYSTEM_INFO si;
  GetSystemInfo(&si);
  size_t pageSize = si.dwPageSize;
  size_t longestFreeApp = 0;

  int index=0;
  for (size_t addr = start; addr<end; )
  {
    MEMORY_BASIC_INFORMATION buffer;
    SIZE_T retSize = VirtualQuery((void *)addr,&buffer,sizeof(buffer));
    if (retSize==sizeof(buffer) && buffer.RegionSize>0)
    {
      // dump information about this region
      printf(.... some buffer information here ....);
      // track longest feee region - usefull fragmentation indicator
      if (buffer.State&MEM_FREE)
      {
        if (buffer.RegionSize>longestFreeApp) longestFreeApp = buffer.RegionSize;
      }
      addr += buffer.RegionSize;
      index+= buffer.RegionSize/pageSize;
    }
    else
    {
      // always proceed
      addr += pageSize;
      index++;
    }
  }
  printf("Longest free VM region: %d",longestFreeApp);
}
```
```