Question:
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.

Answer:
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.


Question:
How do I tokenize the string:

"2+24*48/32"

Into a list:

['2', '+', '24', '*', '48', '/', '32']

Answer:
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.


Question:
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?

Answer:
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.


Question:
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.

Answer:
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.


Question: 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?

Answer:
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
)


Question:
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.

Answer:
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.


Question: 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?

Answer:
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


Question:
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?

Answer:
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...


Question: 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?

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


Question:
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?

Answer:
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.


Question:
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?

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


Question:
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.

Answer:
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


Question: 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.

Answer:
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.


Question:
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?

Answer:
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' ])
;
```
```


Question:
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.

Answer:
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


Question: 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.

Answer:
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/


Question:
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?

Answer:
```
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.


Question:
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?

Answer:
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.


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

Answer:
```
```
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.


Question:
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

Answer:
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
```
```


Question:
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'))

Answer:
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.


Question:
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)

Answer:
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.


Question:
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?

Answer:
```
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.


Question:
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.

Answer:
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.


Question:
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.

Answer:
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.


Question: 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?

Answer:
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.


Question:
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?

Answer:
Take a look at .htaccess if you're using apache:
.htaccess tutorial


Question: 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?

Answer:
```
127.0.0.1,6283
```
Add a comma between the ip and port


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

Answer:
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.


Question:
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?

Answer:
```
```
ALTER SCHEMA [NewSchema] TRANSFER [OldSchema].[Table1]
```
```


Question:
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).

Answer:
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.


Question:
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?

Answer:
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.


Question: Is that needed?

Answer: Pojos could still contain logic errors.


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

Answer:
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 }
```
```


Question: 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?

Answer:
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.


Question: 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.

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


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

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


Question:
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.

Answer:
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...).


Question:
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?

Answer:
use the field number, in this case:
```
```
order by 3
```
```


Question: 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.

Answer:
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
)


Question: 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?

Answer:
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);
```
```


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

Answer:
MSDN:
Enumerating Installed Fonts


Question:
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

Answer:
Something like this?
```
```
foreach (ParentType parentType in collectionOfRelatedObjects) {
    if (!(parentType is ISomethingable)) {
    }
}
```
```


Question: 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.

Answer:
use a regex and see if it matches!
```
```
([a-z][A-Z][0-9]\_\-)*
```
```


Question:
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?

Answer:
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. [...]


Question:
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 ;)

Answer:
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.


Question:
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

Answer:
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).


Question:
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.)

Answer:
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.


Question:
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?

Answer:
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.


Question: 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.

Answer:
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.


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

Answer:
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)


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

Answer:
Does anything on the
s3 library page
cover what you need?  There are loads of examples there.


Question: 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?

Answer:
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).


Question:
As an example in pseudocode:

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

Answer:
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.


Question:
Why doesn't this Google Chart API URL render both data sets on this XY scatter plot?

http://chart.apis.google.com/chart?cht=lxy&chd=t:10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200|0.10,0.23,0.33,0.44,0.56,0.66,0.79,0.90,0.99,1.12,1.22,1.33,1.44,1.56,1.68,1.79,1.90,2.02,2.12,2.22|0.28,0.56,0.85,1.12,1.42,1.68,1.97,2.26,2.54,2.84,3.12,3.40,3.84,4.10,4.53,4.80,5.45,6.02,6.40,6.80&chco=3072F3,ff0000,00aaaa&chls=2,4,1&chs=320x240&chds=0,201,0,7&chm=s,FF0000,0,-1,5|s,0000ff,1,-1,5|s,00aa00,2,-1,5

I've read the documentation over and over again, and I can't figure it out.

Answer:
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)


Question: 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).

Answer:
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.


Question:
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.

Answer:
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.


Question:
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.

Answer:
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;
```
```


Question:
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?

Answer:
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.


Question:
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.

Answer:
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)


Question:
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

Answer:
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.


Question:
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?

Answer:
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


Question:
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.

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


Question:
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

Answer:
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.


Question:
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.

Answer:
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?


Question:
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?

Answer:
You can specify this in your application's manifest file.
Check out
this link
and
this link
and
this link
too.


Question:
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.

Answer:
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)
.


Question:
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.

Answer:
Have you tried
```
doLayout()
```
method of
```
FormPanel
```
?


Question:
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?

Answer:
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)


Question:
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;
}

Answer:
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.


Question: 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.

Answer:
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.


Question:
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.

Answer:
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!


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

Answer:
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.


Question: 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?

Answer:
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);
}
```
```


Question: There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!

Answer:
The translate behavior is another of CakePHP's very useful but poorly documented features. I've implemented it a couple of times with reasonable success in multi-lingual websites along the following lines.
Firstly, the translate behavior will only internationalize the database content of your site. If you've any more static content, you'll want to look at Cake's
```
__('string')
```
wrapper function and
```
gettext
```
(there's some useful information about this
here
)
Assuming there's Contents that we want to translate with the following db table:
```
```
CREATE TABLE `contents` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `title` varchar(255) default NULL,
    `body` text,
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
```
```
The content.php model then has:
```
```
var $actsAs = array('Translate' => array('title'   => 'titleTranslation',
                     'body'    => 'bodyTranslation'
                     ));
```
```
in its definition. You then need to add the i18n table to the database thusly:
```
```
CREATE TABLE `i18n` (
  `id` int(10) NOT NULL auto_increment,
  `locale` varchar(6) NOT NULL,
  `model` varchar(255) NOT NULL,
  `foreign_key` int(10) NOT NULL,
  `field` varchar(255) NOT NULL,
  `content` mediumtext,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
```
```
Then when you're saving the data to the database in your controller, set the locale to the language you want (this example would be for Polish):
```
```
$this->Content->locale = 'pol';
$result = $this->Content->save($this->data);
```
```
This will create entries in the i18n table for the title and body fields for the pol locale. Finds will find based on the current locale set in the user's browser, returning an array like:
```
```
[Content]
  [id]
  [titleTranslation]
  [bodyTranslation]
```
```
We use the excellent
p28n component
to implement a language switching solution that works pretty well with the gettext and translate behaviours.
It's not a perfect system - as it creates HABTM relationships on the fly, it can cause some issues with other relationships you may have created manually, but if you're careful, it can work well.


Question:
Emacs Lisp has replace-string but has no replace-char. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with:

(replace-string (make-string 1 ?\x53979) "'")

I think it would be better with replace-char.

What is the best way to do this?

Answer:
which would certainly be better with replace-char. Any way to improve my code?
Is it actually slow to the point where it matters? My elisp is usually ridiculously inefficient and I never notice. (I only use it for editor tools though, YMMV if you're building the next MS live search with it.)
Also, reading the docs:
```
```
This function is usually the wrong thing to use in a Lisp program.
What you probably want is a loop like this:
  (while (search-forward "’" nil t)
    (replace-match "'" nil t))
```
```
This answer is probably GPL licensed now.


Question:
I have an IList that contains items ( parent first ), they need to be added to a Diagram Document in the reverse order so that the parent is added last, drawn on top so that it is the first thing to be selected by the user.

What's the best way to do it? Something better/more elegant than what I am doing currently
which I post below..

Answer:
NewItems is my List here... This is a bit clunky though.
```
```
for(int iLooper = obEvtArgs.NewItems.Count-1; iLooper >= 0; iLooper--)
            {
                GoViewBoy.Document.Add(CreateNodeFor(obEvtArgs.NewItems[iLooper] as IMySpecificObject, obNextPos));
            }
```
```


Question:
I am fairly comfortable with standalone Java app development, but will soon be working on a project using a Java EE application server.

Does anyone know of a straightforward how-to tutorial to getting a hello-world type application working in an application server? I'm (perhaps naievly) assuming that the overall approach is similar between different frameworks, so I'm more interested in finding out the approach rather than getting bogged down in differences between the different frameworks.

If you are not aware of a good guide, then could you post bullet-point type steps to getting a hello-world running?, i.e.

Download XX

Write some code to do YY

Change file ZZ

Other steps...

Note: Just because I have a windows machine at home, I would prefer to run if this could be run on windows, but in the interest of a better answer, linux/mac based implementations are welcome.

Answer:
The JavaEE (they dropped the 2) space is pretty big. A good tutorial to start is
the one from Sun
. For a simple hello world application, the web container only would suffice. A well known servlet jsp container is tomcat. See
here
for installation instructions. Try installing it with eclipse and create a web project. This will generate some files for you that you can look at and edit. Also starting and stopping the application server is simpler.


Question:
In Emacs, C-x o takes me to the next window.

What keyboard macro takes me to the previous window in Emacs?

Answer:
That'd be
C-- C-x o
In other words,
C-x o
with an argument of -1. You can specify how many windows to move by inserting a numeric argument between
C-u
and the command, as in
C-u 2 C-x o
. (
C--
is a shortcut for
C-u - 1
)


Question: How do I get my C# program to sleep (pause execution) for 50 milliseconds?

Answer:
```
```
System.Threading.Thread.Sleep(50);
```
```
Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")
Just remove the
```
;
```
to make it work for VB.net as well.


Question:
How to match a single quote in sed if the expression is enclosed in single quotes:

sed -e '...'

For example need to match this text:

'foo'

Answer:
You can either use:
```
```
"texta'textb" (APOSTROPHE inside QUOTATION MARKs)
```
```
or
```
```
'texta'\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE)
```
```
I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash.
In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.


Question: How do I create an optional parameter in a mysql stored procedure?

Answer:
According to
this bug
, there is currently no way to create optional parameters.


Question: Are XMLSockets available in Flash Lite, and if yes in which versions, and are there differences between the regular and the lite objects?

Answer:
I don't know enough to tell you the exact difference(s) between XML sockets in Flash and Flash Lite, but they are definitely supported in Flash Lite versions 2.1 and later.  See the
Flash Mobile Blog
for an example.


Question: What things have to be done before I can honestly tell myself my web application is accessible by anyone? Or even better, convince Joe Clark. I don't have any video or audio to worry about, so I know I won't need transcripts. What else do I have to check?

Answer:
Your question is very vague, but in short, you need to ensure that your site meets one of the three levels (A, AA, or AAA) of the
Web Content Accessibility Guidelines
.
FWIW, in my experience, if you are providing anything other than a purely static HTML site, aim for AA. Trying to follow the WCAG guidelines stringently to triple-A standard for a dynamic website is the road to hair loss IMO. This may change with WCAG 2.0.
Good luck!
EDIT:
@Blowdart suggests running your site through online checkers. This is fine so long as you realise that many of the WCAG guidelines (especially towards the higher end) are so arbitrary, they can only be validated with a human eye.
Do not trust the output of these online checkers and blindly stick a AAA badge on your site. If you are called on it, you may be in trouble.
+1 Blowdart for suggesting HTML and CSS validation, and Chris Pederick's add-on is
great
!


Question:
this is my first question to stackoverflow so here it goes...

I use cruise control for my continuous integration scheme, i want to use obfuscation in order to add another protection layer to my assemblies. The thing is that i don't know how to go about it since i couldn't find articles describing about this. Suggestions that include other CI tools such as NAnt are also accepted.

Commercial tools are also an option so don't hesitate to include them in your answer. The applications that i am building and want to obfuscate are mostly written in Compact Framework 2.0, Dot Net 2.0-3.5.

At the moment cruise control checks for changes in the repository, then based on the script for the specific solution downloads and builds the project by using devenv, after the setup project has been run it copies the setup file into a different folder and thats more or less it. So i need obfuscate somewhere in this process..

Answer:
Nice to hear someone is using CruiseControl.NET. That is a nice tool. You can use a command line tool for obfuscation as RemoteSoft .NET Obfuscator and integrate a call to the tool in the build script. See example on how to execute a file below from CruiseControl.NET wiki.
http://www.remotesoft.com/salamander/obfuscator.html
```
```
<exec>
    <executable>make</executable>
    <baseDirectory>D:\dev\MyProject</baseDirectory>
    <buildArgs>all</buildArgs>
    <buildTimeoutSeconds>10</buildTimeoutSeconds>
    <successExitCodes>0,1,3,5</successExitCodes>
    <environment>
        <variable>
            <name>MyVar1</name>
            <value>Var1Value</value>
        </variable>
        <variable name="MyVar2" value="Var2Value"/>
        ...
    </environment>
</exec>
```
```


Question: I need to write code in python language for comparing the text of document using fingerprint techniques. I do not know to take fingerprint of a document or to generate fingerprint of a document. I'm asking if anyone knows the method or has source code for generating fingerprints of documents which is stored in bits form.

Answer:
Nice to hear someone is using CruiseControl.NET. That is a nice tool. You can use a command line tool for obfuscation as RemoteSoft .NET Obfuscator and integrate a call to the tool in the build script. See example on how to execute a file below from CruiseControl.NET wiki.
http://www.remotesoft.com/salamander/obfuscator.html
```
```
<exec>
    <executable>make</executable>
    <baseDirectory>D:\dev\MyProject</baseDirectory>
    <buildArgs>all</buildArgs>
    <buildTimeoutSeconds>10</buildTimeoutSeconds>
    <successExitCodes>0,1,3,5</successExitCodes>
    <environment>
        <variable>
            <name>MyVar1</name>
            <value>Var1Value</value>
        </variable>
        <variable name="MyVar2" value="Var2Value"/>
        ...
    </environment>
</exec>
```
```


Question:
I'm trying to draw a polygon using c# and directx

All I get is an ordered list of points from a file and I need to draw the flat polygon in a 3d world.

I can load the points and draw a convex shape using a trianglefan and drawuserprimitives.

This obviously leads to incorrect results when the polygon is very concave (which it may be).

I can't imagine I'm the only person to grapple with this problem (tho I'm a gfx/directx neophyte - my background is in gui\windows application development).

Can anyone point me towards a simple to follow resource\tutorial\algorithm which may assist me?

Answer:
Direct3D can only draw triangles (well, it can draw lines and points as well, but that's besides the point). So if you want to draw any shape that is more complex than a triangle, you have to draw a bunch of touching triangles that equal to that shape.
In your case, it's a concave polygon triangulation problem. Given a bunch of vertices, you can keep them as is, you just need to compute the "index buffer" (in simplest case, three indices per triangle that say which vertices the triangle uses). Then draw that by putting into vertex/index buffers or using DrawUserPrimitives.
Some algorithms for triangulating simple (convex or concave, but without self-intersections or holes) polygons are at
VTerrain site
.
I have used Ratcliff's code in the past; very simple and works well. VTerrain has a dead link to it; the code can be found
here
. It's C++, but porting that over to C# should be straightforward.
Oh, and don't use triangle fans. They are of very limited use, inefficient and are going away soon (e.g. Direct3D 10 does not support them anymore). Just use triangle lists.


Question: I'm a little confused about how the standard library will behave now that Python (from 3.0) is unicode-based. Will modules such as CGI and urllib use unicode strings or will they use the new 'bytes' type and just provide encoded data?

Answer:
Logically a lot of things like MIME-encoded mail messages, URLs, XML documents, and so on should be returned as
```
bytes
```
not strings. This could cause some consternation as the libraries start to be nailed down for Python 3 and people discover that they have to be more aware of the
```
bytes
```
/
```
string
```
conversions than they were for
```
str
```
/
```
unicode
```
...


Question:
I've been wanting to program for the Plan 9 operating system for a while. I'd really like to play around with a web app there. Of course, the only language I know for Plan 9 is C, and that doesn't seem ideal for web development. I also understand that it doesn't run apache or mysql either.

What is the best way to start coding web apps on Plan 9?

Answer:
Check out Kenji Arisawa's
Pegasus
(
paper
) webserver for Plan 9.
Plan 9 may have a reputation for being C-only, but several langauges, including Scheme, Ruby, Python, and Perl have been ported. Check out the
Contrib Index
for the code.
Finally, start reading the Plan 9
white papers
so that you can understand its philosophy. If you want to do net-related things, the file protocol
9p
is essential.


Question: mysql_real_escape_string and addslashes are both used to escape data before the database query, so what's the difference? (This question is not about parametrized queries/PDO/mysqli)

Answer:
It seems that
```
mysql_real_escape_string
```
is binary-safe - the documentation states:
If binary data is to be inserted, this function must be used.
I think it's probably safer to always use
```
mysql_real_escape_string
```
than addslashes.


Question:
Part of the install for an app I am responsible for, compiles some C code libraries. This is done in a console using GNU Make.

So, as part of the install, a console window pops open, you see the make file output wiz by as it compiles and links, when finished the console window closes and the installer continues.

All good, unless there is a compilation error. Then the make file bugs out and the console window closes before you have a chance to figure out what is happening.

So, what I'd like to happen is have the console window pause with a 'press a key to continue' type functionality, if there is an error from the makefile so that the console stays open. Otherwise, just exit as normal and close the console.

I can't work out how to do this in a GNU Makefile or from a batch file that could run the Make.

Answer:
this should do the trick:
```
```
if not ERRORLEVEL 0 pause
```
```
type
```
help if
```
in DOS for more info on errorlevel usage.


Question:
Any free alternative to Robohelp?  Prefer open source

Need some sort of online help authoring tool for an open source project.

Answer:
Are you trying to make just CHM or other output formats too?
Take a look at DocBook. You can make (from one source file) pdf, html and chm - and some others, too. I've used it in the past but it's not very easy or convenient to use. If you only want to output chm (and need to use a free solution), see if you can get away with using the htmlhelp workshop (
http://www.microsoft.com/downloads/details.aspx?familyid=00535334-c8a6-452f-9aa0-d597d16580cc&displaylang=en
).


Question:
SslStream is supposed to negotiate the cipher type, key length, hash algorithm, etc. with its peer SSL stack. When using it in my code, I find that the negotiation always defaults to RC4 & MD5. I would like to use 3DES or AES for some added security.

Looking around the web I find only a few references to this problem and no solutions; one poster is claiming this actually makes sense, since the lowest common denominator between the two stacks is secure while has the added benefit of being faster/using less CPU resources. While this may be technically correct, my particular trade-off between complexity and cost lies elsewhere (I prefer to use AES with a long key).

If anyone can help I'd appreciate it.

Answer:
It should be using the most secure set of algorithms that were in both lists. I find it hard to believe that it isn't, because SslStream is wrapping the SChannel SSPI, and if that were broken then Internet Explorer, IIS and everything else on Windows would be broken too.
It could be that you have an outdated version of SChannel.dll/Secur32.dll. What OS and Internet Explorer version do you have installed?
It is possible to
disable protocols in SCHANNEL
. Could you check that this hasn't been done?


Question:
Is there a easy way to do this? Or do I have to parse the file and do some search/replacing on my own?

The ideal would be something like:

var myXML: XML = ???; // ... load xml data into the XML object

myXML.someAttribute = newValue;

Answer:
Attributes are accessible in AS3 using the
```
@
```
prefix.
For example:
```
```
var myXML:XML = <test name="something"></test>;
trace(myXML.@name);
myXML.@name = "new";
trace(myXML.@name);
```
```
Output:
```
```
something
new
```
```


Question:
When I use quick documentaion lookup (Ctrl+Q) on j2ee classes or annotations in IDEA I only get an empty javadoc. It only contains the basics like class name.

How do I add the javadoc to the libs IDEA provides itself?

Answer:
You can attach javadoc to any library you have configure in your module or project. Just access the project structure windows
```
(File -> Project Structure)
```
, then select "modules" and select the module that has the dependency you want to configure.
Then select the "Dependencies" tab, select the dependency that's missing the javadoc and click "Edit". In the window that just showed up you see two buttons "Add" and "Specify Javadoc URL". If you have the javadoc in a jar file select the first one, if you want to point to a web site that contains the javadoc select the latest.
That's it.


Question:
How can brackets be escaped in using string.Format?

For example:

String val = "1,2,3"
String.Format(" foo {{0}}", val);

This example doesn't throw an exception, but it outputs the string foo {0}.

Is there a way to escape the brackets?

Answer:
For you to output
```
foo {1, 2, 3}
```
you have to do something like:
```
```
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
```
```
To output a
```
{
```
you use
```
{{
```
and to output a
```
}
```
you use
```
}}
```
.
Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)
Escaping brackets: String interpolation $("")
. It is new feature in C# 6.0.
```
```
var inVal = "1, 2, 3";
var outVal = $" foo {{{inVal}}}";
// The output will be:  foo {1, 2, 3}
```
```


Question:
From a shell script, how do I check if a directory contains files?

Something similar to this

if [ -e /some/dir/* ]; then echo "huzzah"; fi;

but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).

Answer:
Try:
```
```
if [ ! -z `ls /some/dir/*` ]; then echo "huzzah"; fi
```
```


Question:
By default data extracted by the GROUP BY clause is ordered as ascending.
How to change it to descending.

Answer:
Add
```
DESC
```
to the
```
GROUP BY
```
clause, e.g. :
```
```
GROUP BY myDate DESC
```
```


Question: I would like to know where can I find the code which eclipse uses to display the forms in the plugin.xml file. In particular I am looking for the form layout used in the extension tab in the plugin.xml

Answer:
Add
```
DESC
```
to the
```
GROUP BY
```
clause, e.g. :
```
```
GROUP BY myDate DESC
```
```


Question: I keep running into this problem when debugging JSP pages in OpenNMS. The Jetty wiki talks about keepGenerated (http://docs.codehaus.org/display/JETTY/KeepGenerated) in webdefault.xml but it seems unclear how this works in embedded setups.

Answer:
It is dumped already.
for example if you have a file called
```
index.jsp
```
, a file will be created called
```
index_jsp.java
```
Just search for something like that in the work directory.


Question:
I have a memory buffer corresponding to my screen resolution (1280x800 at 24-bits-per-pixel) that contains my screen contents at 24bpp. I want to convert this to 8-bpp (ie. Halftone color palette in Windows).
I currently do this:
1. Use CreateDIBSection to allocate a new 1280x800 24-bpp buffer and access it as a DC, as well as a plain memory buffer
2. Use memcpy to copy from my original buffer to this new buffer from step 1
3. Use BitBlt to let GDI perform the color conversion

I want to avoid the extra memcpy of step 2. To do this, I can think of two approaches:

a. Wrap my original mem buf in a DC to perform BitBlt directly from it

b. Write my own 24-bpp to 8-bpp color conversion. I can't find any info on how Windows implements this halftone color conversion. Besides even if I find out, I won't be using the accelerated features of GDI that BitBlt has access to.

So how do I do either (a) or (b)?

thanks!

Answer:
OK, to address the two parts of the problem.
the following code shows how to get at the pixels inside of a bitmap, change them and put them back into the bitmap.  You could always generate a dummy bitmap of the correct size and format, open it up, copy over your data and you then have a bitmap object with your data:
```
```
private void LockUnlockBitsExample(PaintEventArgs e)
{

   // Create a new bitmap.
   Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");

   // Lock the bitmap's bits.
   Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
   System.Drawing.Imaging.BitmapData bmpData =
         bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
         bmp.PixelFormat);

   // Get the address of the first line.
   IntPtr ptr = bmpData.Scan0;

   // Declare an array to hold the bytes of the bitmap.
   int bytes  = bmpData.Stride * bmp.Height;
   byte[] rgbValues = new byte[bytes];

   // Copy the RGB values into the array.
   System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

   // Set every third value to 255. A 24bpp bitmap will look red.
   for (int counter = 2; counter < rgbValues.Length; counter += 3)
       rgbValues[counter] = 255;

   // Copy the RGB values back to the bitmap
   System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);

   // Unlock the bits.
   bmp.UnlockBits(bmpData);

   // Draw the modified image.
   e.Graphics.DrawImage(bmp, 0, 150);
}
```
```
To convert the contents to 8bpp you'll want to use the System.Drawing.Imaging.ColorMatrix class.  I don't have at hand the correct matrix values for half-tone, but this example grayscales and adjustment of the values should give you an idea of the effect:
```
```
Graphics g = e.Graphics;
Bitmap bmp = new Bitmap("sample.jpg");
g.FillRectangle(Brushes.White, this.ClientRectangle);

// Create a color matrix
// The value 0.6 in row 4, column 4 specifies the alpha value
float[][] matrixItems = {
                            new float[] {1, 0, 0, 0, 0},
                            new float[] {0, 1, 0, 0, 0},
                            new float[] {0, 0, 1, 0, 0},
                            new float[] {0, 0, 0, 0.6f, 0},
                            new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(matrixItems);

// Create an ImageAttributes object and set its color matrix
ImageAttributes imageAtt = new ImageAttributes();
imageAtt.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

// Now draw the semitransparent bitmap image.
g.DrawImage(bmp, this.ClientRectangle, 0.0f, 0.0f, bmp.Width, bmp.Height,
            GraphicsUnit.Pixel, imageAtt);

imageAtt.Dispose();
```
```
I shall try and update later with the matrix values for half-tone, it's likely to be lots 0.5 or 0.333 values in there!


Question:
Suppose I have a simple XHTML document that uses a custom namespace for attributes:

<html xmlns="..." xmlns:custom="http://www.example.com/ns">
    ...
    <div class="foo" custom:attr="bla"/>
    ...
</html>

How do I match each element that has a certain custom attribute using jQuery? Using

$("div[custom:attr]")

does not work. (Tried with Firefox only, so far.)

Answer:
You should use
```
$('div').attr('custom:attr')
```
.


Question:
I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find crti.o. This is not one of my object files, it seems to be related to libc but I can't understand why it would need this crti.o, wouldn't it use a library file, e.g. libc.a?

I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it?

crti.o is on one of the 'libraries' search path, but should it look for .o file on the library path?

Is the search path the same for gcc and ld?

Answer:
```
crti.o
```
is the bootstrap library, generally quite small. It's usually statically linked into your binary. It should be found in
```
/usr/lib
```
.
If you're running a binary distribution they tend to put all the developer stuff into -dev packages (e.g. libc6-dev) as it's not needed to run compiled programs, just to build them.
You're not cross-compiling are you?
If you're cross-compiling it's usually a problem with gcc's search path not matching where your crti.o is. It should have been built when the toolchain was. The first thing to check is
```
gcc -print-search-dirs
```
and see if crti.o is in any of those paths.
The linking is actually done by ld but it has its paths passed down to it by gcc. Probably the quickest way to find out what's going on is compile a helloworld.c program and strace it to see what is getting passed to ld and see what's going on.
```
```
strace -v -o log -f -e trace=open,fork,execve gcc hello.c -o test
```
```
Open the log file and search for crti.o, as you can see my non-cross compiler:
```
```
10616 execve("/usr/bin/ld", ["/usr/bin/ld", "--eh-frame-hdr", "-m", "elf_x86_64", "--hash-style=both", "-dynamic-linker", "/lib64/ld-linux-x86-64.so.2", "-o"
, "test", "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "-L/usr/lib/gcc/x86_64-linux-g
nu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/lib/../lib", "-L/usr/lib/../lib", "-L/usr/lib/gcc/x86_64-linux-gnu
/"..., "/tmp/cc4rFJWD.o", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "-lc", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "/usr/lib/gcc/x86_
64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."...],  "COLLECT_GCC=gcc", "COLLECT_GCC_OPTIONS=\'-o\' \'test\' "..., "COMPILER_PATH=/usr/lib/gcc/x86_6"..., "LIBRARY_PATH=/usr/lib/gcc/x86_64"..., "CO
LLECT_NO_DEMANGLE="]) = 0
10616 open("/etc/ld.so.cache", O_RDONLY) = 3
10616 open("/usr/lib/libbfd-2.18.0.20080103.so", O_RDONLY) = 3
10616 open("/lib/libc.so.6", O_RDONLY)  = 3
10616 open("test", O_RDWR|O_CREAT|O_TRUNC, 0666) = 3
10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crt1.o", O_RDONLY) = 4
10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crti.o", O_RDONLY) = 5
10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/crtbegin.o", O_RDONLY) = 6
10616 open("/tmp/cc4rFJWD.o", O_RDONLY) = 7
```
```
If you see a bunch of attempts to
```
open(...crti.o) = -1 ENOENT
```
,
```
ld
```
is getting confused and you want to see where the path it's opening came from...


Question:
In static languages like Java you need interfaces because
otherwise the type system just won't let you do certain things.
But in dynamic languages like PHP and Python you just take
advantage of duck-typing.

PHP supports interfaces.
Ruby and Python don't have them.
So you can clearly live happily without them.

I've been mostly doing my work in PHP and have never really
made use of the ability to define interfaces. When I need a
set of classes to implement certain common interface, then
I just describe it in documentation.

So, what do you think? Aren't you better off without using
interfaces in dynamic languages at all?

Answer:
Well, first of all, it's right that Ruby does not have Interface as is, but they have mixin, wich takes somehow the best of both interfaces and abstract classes from other languages.
The main goal of interface is to ensure that your object SHALL implement ALL the methods present in the interface itself.
Of course, interface are never mandatory, even in Java you could imagine to work only with classes and using reflection to call methods when you don't know wich kind of object you're manipulating, but it is error prone and should be discouraged in many ways.


Question: I'm trying to match elements with a name that is 'container1$container2$chkChecked', using a regex of '.+\$chkChecked', but I'm not getting the matches I expect when the element name is as described.  What am I doing wrong?

Answer:
try
```
```
string.match( /[$]chkChecked$/ )
```
```
alternatively, you could try
```
```
string.match( /[^a-zA-Z0-9]chkChecked/ )
```
```
( Also, make sure your using
```
//
```
around your regex, otherwise you might be matching using string literals. Not obvious tho without a larger code snippet )