Question:
I'm trying to compile/link a very old piece of software on a linux system and I can't for some reason link with a shared library that's installed on my system.

I get the following error from the linker:

/usr/bin/ld: cannot find -lXaw

However, the lib itself is installed. If I run

ldconfig -v | grep libXaw

I get (among other things) this hit:

libXaw.so.7 -> libXaw7.so.7.0.0

The library and the links to it are in /usr/lib btw. So nothing special.

So the library is there and ldconfig finds it. What could ld cause ld from not finding the library during link-time? As you may have already guessed I'm quite new to the shared library stuff.

Any ideas?

Answer: The linker may be looking, literally, for "libXaw.so".  Is that in /usr/lib?  If not, you could try adding it as another soft link from libXaw7.so.7.0.0.


Question:
What are best resources/tutorials for starting up with SQLAlchemy?
Maybe some simple step by step stuff like creating a simple table and using it and going up from there.

Answer:
Personally, I'd buy
this book
and cram it into the noggin over the course of a week or so.
I've tried tackling SQLAlchemy on the job without learning the details first. I had a hard time with it, because I found the online documentation to be sparse and cryptic ("
read the source for more info...
"). SA also provides several levels of abstraction at which you can work and I wasn't confident that I was ever working at the correct level.


Question:
I was wondering if there was any difference in the way the following code was compiled into assembly. I've heard that switch-case is more efficient than if else, but in this example I am not quite sure if that would be the case.

if(x==1){
...
}else if(x==2){
...
}else{
...
}

and

switch(x){
 case 1:
 ...
 break;

 case 2:
 ...
 break;

 default:
 ...
}

Answer:
In
this
specific case, the
```
switch
```
can be turned into a jump table. The
```
if
```
statement (if you write your
```
=
```
as
```
==
```
:-P) could still do the same thing if the compiler could tell that
```
x
```
isn't changing between the
```
if
```
clauses (which is usually the case, unless
```
x
```
is
```
volatile
```
or something).


Question: What are the main differences between XHTML and HTML? Which one is better in your opinion, and why? Do most browsers support both?

Answer:
The Extensible Hypertext Markup Language, or XHTML, is a markup language that has the same depth of expression as HTML, but also conforms to XML syntax.
XHTML is "the modern version of HTML 4".
More info :
wikipedia
and
W3C


Question:
What are the basic differences between a semaphore & spin-lock?

When would we use a semaphore over a spin-lock?

Answer:
very simply, a semaphore is a "yielding" synchronisation object, a spinlock is a 'busywait' one. (there's a little more to semaphores in that they synchronise several threads, unlike a mutex or guard or monitor or critical section that protects a code region from a single thread)
You'd use a semaphore in more circumstances, but use a spinlock where you are going to lock for a very short time - there is a cost to locking especially if you lock a lot. In such cases it can be more efficient to spinlock for a little while waiting for the protected resource to become unlocked. Obviously there is a performance hit if you spin for too long.
typically if you spin for longer than a thread quantum, then you should use a semaphore.


Question: When uninstalling my application, I'd like to configure the Wix setup to remove all the files that were added after the original installation. It seems like the uninstaller removes only the directories and files that were originally installed from the MSI file and it leaves everything else that was added later in the application folder. In another words, I'd like to purge the directory when uninstalling. How do I do that?

Answer:
Use
RemoveFile element
with On="
uninstall
". Here's an example:
```
```
<Directory Id="CommonAppDataFolder" Name="CommonAppDataFolder">
  <Directory Id="MyAppFolder" Name="My">
    <Component Id="MyAppFolder" Guid="*">
      <CreateFolder />
      <RemoveFile Id="PurgeAppFolder" Name="*.*" On="uninstall" />
    </Component>
  </Directory>
</Directory>
```
```
Update
It didn't work 100%. It removed the files, however none of the additional directories -
  the ones created after the installation - were removed. Any thoughts on that?  – pribeiro
Unfortunately Windows Installer doesn't support deleting directories with subdirectories. In this case you have to resort to custom action. Or, if you know what subfolders are, create a bunch of RemoveFolder and RemoveFile elements.


Question: How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?

Answer:
This is easiest with a library like jQuery:
```
```
<input type="button" onClick="javascript:test_byid();" value="id='second'" />

<script>
function test_byid()
{
    $("#second").toggleClass("highlight");
}
</script>
```
```


Question:
For example, how to avoid writing the 'func_name' twice?

#ifndef TEST_FUN
#  define TEST_FUN func_name
#  define TEST_FUN_NAME "func_name"
#endif

I'd like to follow the Single Point of Truth rule.

Version of C preprocessor:

$ cpp --version
cpp (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14)

Answer:
```
#define TEST_FUN_NAME #FUNC_NAME
```
see
here


Question: which library better for faster java application swt or swing?

Answer:
According to wikipedia there is no clear winner (although you can edit that if you want). Inevitably, you can write benchmarks which will show either much faster that the other. Swing has more freedom to optimise on the Java side of things. SWT can allow more optimisations to occur within the windowing system.
Probably the bigger impact on performance is going to come from how your application behaves. Concentrate on getting your code clean (and do a little profiling when necessary).


Question: I'd like to generate unique random numbers between 0 and 1000 that never repeat (i.e. 6 doesn't show up twice), but that doesn't resort to something like an O(N) search of previous values to do it. Is this possible?

Answer:
You can do this:
Create a list, 0..1000.
Shuffle the list. (See
Fisher-Yates shuffle
for a good way to do this.)
Return numbers in order from the shuffled list.
So this doesn't require a search of old values each time, but it still requires O(N) for the initial shuffle. But as Nils pointed out in comments, this is amortised O(1).


Question:
I need to create a 'slider' for a client's site. The slider should allow people to select how many items they want of x item, and show what the price will be based on that. The weird(ish) part is that the ratio of the price increase will go down as the amount of items goes up:

1 item: $100

2 items: +90 = $190

3 items: + 80 = $270

4 items: + 70 = $340

5 items: + 60 = $400

6 items: + 50 = $450

7 items: + 50 = $500

And all increases from then on are +50. This probably seems like an overly simplistic question, but does anyone know how I could go about doing this? I have almost no experience with JavaScript :(

Answer:
Check out Yahoo! UI. they have a slider widget:
http://developer.yahoo.com/yui/slider/
The following example should get you started:
http://developer.yahoo.com/yui/examples/slider/slider-ticks.html
.
All JavaScript frameworks (
jQuery
,
MooTools
) seem to offer a slider. The YUI will give you a lot of control and a loader so you don't have to host the script on your server. Beware that YUI does not make implementation as painless as with the two other i mentioned.
Here is a MooTools example:
```
```
// First example of http://demos.mootools.net/Slider

```
```
And the JavaScript:
```
```
var el = $('myslider'); // The slider graphic
new Slider(el, el.getElement('.knob'), {
    steps: 7,   // There are 7 choices
    range: [1, 7],  // Minimum value is 1, maximum is 7
    onChange: function(value){
        // Calculation of the value goes here
    }
});
```
```


Question:
I have a PHP script that initialises an image gallery. It loops through all images, checks if they are thumbnailed and watermarks them.

My shared hosting account only lets me have 30 seconds of execution per script, as set in the php.ini settings. I can't change that.

What can I do to get round this? Currently I refresh the page after every 5 images, this prevents the script timing out, but the browser recognises that the script won't complete and gives an error. That's ok, but it's not really user friendly.

Any suggestions?

Answer:
three ideas:
you could offload this to a script that runs on the server (PHP CLI perhaps?) and have your current script check the progress (still running! check back later!).
if javascript is ok in your environment, perhaps you could make ajax calls to handle this as well. the first solution allows the user to keep wandering around the site though, not sure if that's an important consideration in your case.
you could get the PHP script to just do a certain batch (say 10 images at a time), then refresh the page with a progress report and go for 10 more, instead of an arbitrary time based refresh.


Question: How can I access a public static member of a Java class from ColdFusion?

Answer:
You run the createObject but don't call the "init" before running the static method. For example:
```
```
<cfset systemObject = createObject("java", "java.lang.System") />
<cfoutput>#systemObject.currentTimeMillis()#</cfoutput>
```
```
In this case "currentTimeMillis()" is a static method of the System class.


Question:
I listen to the podcast java posse,  on this there is often discussion about components (note components are not (clearly) objects).  They lament the fact that Java does not have components, and contrast with .NET that does.  Components apparently makes developing applications (not just GUI apps) easier.

I can figure from the discussion certain qualities that a component has,  its something to-do with decoupling (substituting one component for another is just a matter of plumbing).  It has something to-do with properties, it definitely has something to-do with events and delegates.

So to the questions:

./ can anyone explain to me what a component is. (and why java beans are not components).

./ can anyone explain how they help development.

./ can anyone explain why java does not have them if they are so useful.

Answer:
Software Engineering Radio has an episode on exactly this topic:
http://se-radio.net/podcast/2008-02/episode-87-software-components
The general idea is that a software component can describe what its own dependencies and services are, in the form of metadata. I don't know why you might have heard that Java does not have components, since you can certainly imagine an architecture in Java where components do describe themselves through metadata. I suppose it's just that the Java platform definition by itself doesn't really have a component architecture.
Update: Indeed, one need not imagine such an architecture because as others pointed out, Java Beans or Servlets could certainly be considered component-based architectures.


Question:
I know I can get the public static members of a class by doing something like:

obj.getClass().getFields()

but this doesn't get me the enums.  I'd like to be able to get them from the Class object returned by the getClass method.  Any ideas?

Answer:
(Turned into a community wiki as it looks like there's scope for a fair amount of expansion, e.g. to include tackline's comments. No sense in me just transcribing comments when everyone could be expanding it.)
Do you mean enums nested within a top-level class? If so, use
```
Class.getDeclaredClasses()
```
and iterate through the results seeing if any of the nested classes are enums. The simplest way of testing each nested class is to use
```
Class.isEnum()
```
; if you want to iterate through the values within the enum then
```
Class.getEnumConstants()
```
is the way to go.


Question:
On a site of mine in which a textarea is used for submission, I have code that can appear something along the lines of the following:

<textarea><p>text</p></textarea>

When validating (XHTML 1.0 Transitional), this error arises,

line 88 column 50 - Error: document type does not allow element "p" here

If this is not a valid method, then what is expected?  I could do a workaround with an onload JavaScript event, but that seems needless.  Regardless this doesn't affect the output, but I'd rather my site validate.

Answer:
is there a reason you're trying to put a
```
<p>
```
within
```
<textarea>
```
? as you found out it's not valid. if it's for display purposes (ie, showing code) it should be translated:
```
```
<textarea>
text
</textarea>
```
```
beyond validation issues, allowing arbitrary tags (which are not properly encoded as above) to display can be a huge security issue. it's paramount to make sure any user supplied input has been properly sanitized before it is displayed.


Question:
Does anybody know of a good media framework for Flex?

I'd like to be able to create apps that can play not only those formats that the Flex framework provides support for, but other formats as well (like wav, wma, ogg and other...).

EDIT 13.10.2008.: It was recently pointed out to me in the answers section that I should perhaps rephrase the question, so here goes: What I'm really looking for is a way to play various media formats in a Flex/Air app. Onekidney posted a nice answer about Ogg/Vorbis. Does anybody know of a way to play other media formats? Never mind about the portability to different platforms now. Portability would be nice, but if I can't get it, I can live without it :-).

Thanks for the answers!

Answer:
is there a reason you're trying to put a
```
<p>
```
within
```
<textarea>
```
? as you found out it's not valid. if it's for display purposes (ie, showing code) it should be translated:
```
```
<textarea>
text
</textarea>
```
```
beyond validation issues, allowing arbitrary tags (which are not properly encoded as above) to display can be a huge security issue. it's paramount to make sure any user supplied input has been properly sanitized before it is displayed.


Question:
I chmod'ed the directory to 777, same with the directory contents. Still, I get a "permission denied" error. Does PHP throw this error if apache is not the group/owner, regardless of the file permissions? Here's the call that's failing:

rename('/correct/path/to/dir/1', '/correct/path/to/dir/2');

Answer:
Try running the following script:
```
```
print_r(posix_getpwuid(getmyuid()));
print_r(pathinfo($YOUR_PATH));
```
```
And see what that returns.


Question: I just forgot the password. Can anyone help me how to get back the password.

Answer:
There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).
Start the SQL service again and use the new created login (recovery in my example)
Go via the security panel to the properties and change the password of the SA account.
Now write down the new SA password.


Question: Is it possible to use a CHECK constraint to prevent any date that falls on a Sunday?  I don't want to use a trigger.

Answer:
Not sure about the actual constraint, but you can use the function:
```
```
TO_CHAR(sysdate, 'D');
```
```
to get the day of the week as an integer, then do a small check on it


Question:
Is it possible to assign a custom ID to a HTTP session through Servlet API?

I know that session handling from any application server, Tomcat for example, it's enough good to generate unique IDs. But I have custom unique session IDs based on information per user and time, so it won't be repeated.

And I looked at every documentation about session handling but nowhere I find what I need.

It's a requirement for a project, so if it's not possible, I need to know the reasons (or it's only not available through API?).

Answer:
Um...if you have the code to generate a unique ID, you can just do this:
```
```
/**
 * The String key of the user id attribute.
 */
public static final String USER_ID_KEY = "userIdKey";

// Set the user attribute (createUniqueUserId's parameters and return type are up to you)
httpSession.setAttribute(USER_ID_KEY, createUniqueUserId());

// Retrieve the user attribute later
httpSession.getAttribute(USER_ID_KEY);
```
```
The HttpSession interface also provides a getId() method, which is documented
here
(copying the documentation for reference):
public java.lang.String getId()
Returns a string containing the unique
identifier assigned to this session.
The identifier is assigned by the
servlet container and is
implementation dependent.
Returns: a
string specifying the identifier
assigned to this session


Question:
I have a component which writes/generates javascript from a server side renderer. This component can be used in multiple times in a same page. However, once the page is loaded I have to collect all the variables or JSO written by this multiple components in the page. How can I do this so that I will have a collection of all the variables or JSO?
For e.g. If this component (lets say   ) is used twice in the page then it emits two javascript block on client/browser -
     var arr1 = new Array['First', 'Second'] and
     var arr2 = new Array['Third', 'Fourth'].

In order to make a final rendering I have to combine these two arrays.

Answer:
You will need to be a little more specific about your problem, maybe with an example page but here are some thoughts.
If you have a server-side component that writes JavaScript during page generation, I would generate a function call each time, something like:
```
```
Component_appendArray(['First', 'Second']);
...
Component_appendArray(['Third', 'Fourth']);
```
```
then ensure that you have your function
```
Component_appendArray()
```
defined before these calls:
```
```
var globalArray = [];
function Component_appendArray(array)
{
     globalArray = globalArray.concat(array);
}
```
```
At the end,
```
globalArray
```
should contain:
```
```
['First', 'Second', 'Third', 'Fourth']
```
```
Hope this helps.


Question:
I'm trying to learn about catamorphisms and I've read the Wikipedia article and the first couple posts in the series of the topic for F# on the Inside F# blog.

I understand that it's a generalization of folds (i.e., mapping a structure of many values to one value, including a list of values to another list). And I gather that the fold-list and fold-tree is a canonical example.

Can this be shown to be done in C#, using LINQ's Aggregate operator or some other higher-order method?

Answer:
I've been doing more reading, including a Micorosft Research paper on
functional programming with catamorphisms ("bananas")
, and it seems that
catamorphism
just refers to any function that takes a list and typically breaks it down to a single value (
```
IEnumerable<A> => B
```
), like
```
Max()
```
,
```
Min()
```
, and in the general case,
```
Aggregate()
```
, would all be a catamorphisms for lists.
I was previously under the impression that it refefred to a way of creating a function that can generalize different folds, so that it can fold a tree
and
a list. There may actually still be such a thing, some kind of
functor
or
arrow
maybe but right now that's beyond my level of understanding.


Question:
I'm working on a project in C and it requires memalign(). Really, posix_memalign() would do as well, but darwin/OSX lacks both of them.

What is a good solution to shoehorn-in memalign?  I don't understand the licensing for posix-C code if I were to rip off memalign.c and put it in my project- I don't want any viral-type licensing LGPL-ing my whole project.

Answer:
Mac OS X appears to be
16-byte mem aligned.
Quote from the website:
I had a hard time finding a definitive
  statement on MacOS X memory alignment
  so I did my own tests. On 10.4/intel,
  both stack and heap memory is 16 byte
  aligned. So people porting software
  can stop looking for memalign() and
  posix_memalign(). It’s not needed.


Question: If the amount of data stored within a given field of a database is unknown, and could be very large, should I store it in an external file rather than within a field in the database?

Answer:
That's why BLOB or Memo field types were designed.  They are very good at storing variable length / large objects.
That being said, I would still store certain large objects using the file system instead of using a database.  If the objects were very large (multi-MB each) I would consider just placing them on the file system and storing a pointer (filename) in the database.


Question: I see that the SML/NJ includes a queue structure. I can't figure out how to use it. How do I use the additional libraries provided by SML/NJ?

Answer:
I don't have a complete answer for you but I could point you in the right direction. You should look up using the compilation manager (CM) which is built in to SML/NJ. You can think of it as Make for SML.
To use a library from the SML/NJ library you then add smlnj-lib.cm to the CM description file of your application. Then you can use the declarations such as Queue from that library.
The smlnj website has some documentation about the
compilation manager
.
Hope this at least points you in the right direction.


Question:
I know of many utilities that can tell me the bitrate of an MP3 file, but I've never seen one that can tell me whether or not the MP3 file is VBR (variable bit rate - the bit rate fluctuates within the file) or a CBR (constant bit rate - the bit rate stays the same within the file). My guess is that most programs aren't interested in finding this out since it involves analyzing the file somewhat to see if the bitrate changes, which takes away from speed.

So, in lieu of finding a utility, I'd like to write one - so how could I programmatically determine whether or not an MP3 file is VBR or CBR? I have about 15,000 files to go through to find this out for, so I need to automate the process.

Answer:
Check this
MP3Header Class
, it has a method that tells you if the mp3 file is VBR, and all the mp3 header information...
```
```
...
boolVBitRate = LoadVBRHeader(bytVBitRate);
...
```
```


Question:
In c#, I have a handle to a window ( an IntPtr ), I want to change the background color of that window.  How can I do this?

I can get the GDI graphics object for that handle like so:

Graphics graphics = Graphics.FromHwnd(theHandle);

So I should somehow be able to change the background color from this?

I also want to ensure the background color remains even after the window moves,resizes,repaints etc.

Answer:
Create a control class with the Control.FromHandle method and then set the property.
Something like...
```
Control someControl = Control.FromHandle(myHandle);
    someControl.BackColor = SystemColors.Black;
```


Question:
Should I be using this method of throwing errors:

if (isset($this->dbfields[$var])) {
    return $this->dbfields[$var];
} else {
    throw new FieldNotFoundException($var);
}

or this style:

try {
    return $this->dbfields[$var];
} catch (Exception $e) {
    throw new FieldNotFoundException($var);
}

...or something else altogether?

quick explanation of the code: $this->dbfields is an array. isset() checks if a variable is set, in this case, whether the array element exists.

Answer:
The second example is bad.  You're taking a lot of overhead to catch an exception when, as you demonstrate, it's just as easy to prevent the exception in the first place.  Plus you also assume you know why that exception was thrown - if there was some other exception, like say an out of memory or something, you're reporting it as a "field not found" even if it wasn't.
Keep in mind that
```
try
```
/
```
catch
```
in languages like C++ and Java are very expensive because of all the state they have to save and restore. Python, on the other hand, has very cheap exceptions and they positively encourage you to use a
```
try
```
/
```
except
```
for simple validation. But even so, catching everything and pretending it's one type of exception is still bad.


Question:
The Wikipedia article on Effect system is currently just a short stub and I've been wondering for a while as to what is an effect system.

Are there any languages that have an effect system in addition to a type system?

What would a possible (hypothetical) notation in a mainstream language, that you're familiar, with look like with effects?

Answer:
(This is not an authoritative answer; just trying to trawl my memory.)
In a sense, any time you code a 'state monad' in a language, you're using the type system as a potential effect system.  So "State" or "IO" in Haskell capture this notion (IO captures a whole lot of other effects as well).  I vaguely remember reading papers about various languages that use advanced type systems including things like "dependent types" to control finer-grained management of effects, so that for instance the type/effect system could capture information about which memory locations would be modified in a given data type.  This is useful, as it provides ways to make two functions that modify mutually exclusive bits of state be allowed to "commute" (monads don't typically commute, and different monads don't always compose well with one another, which often makes it hard to type (read: assign a static type to) 'reasonable' programs)...
An analogy at a
very
hand-wavy level is how Java has checked exceptions.  You express extra information in the type system about certain effects (you can think of an exception as an 'effect' for the purpose of the analogy), but these 'effects' typically leak out all over your program and don't compose well in practice (you end up with a million 'throws' clauses or else resort to lots of unchecked runtime exception types).
I think a lot of research is being done in this area, both for research-y and mainstream-y languages, as the ability to annotate functions with effect information can unlock the compiler's ability to do a number of optimizations, can impact concurrency, and can do great things for various program analyses and tooling.  I don't personally have high hopes for it any time soon, though, as I think lots of smart people have been working on it for a long time and there's still very little to show for it.


Question:
I have a table with two fields of interest for this particular exercise: a CHAR(3) ID and a DATETIME.  The ID identifies the submitter of the data - several thousand rows.  The DATETIME is not necessarily unique, either.  (The primary keys are other fields of the table.)

Data for this table is submitted every six months.  In December, we receive July-December data from each submitter, and in June we receive July-June data.  My task is to write a script that identifies people who have only submitted half their data, or only submitted January-June data in June.

...Does anyone have a solution?

Answer:
From your description, I wouldn't worry about the efficiency of the query since apparently it only needs to run twice a year!
There are a few ways to do this, which one is 'best' depends on the data that you have. The datediff (on max/min date values) you suggested should work, another option is to just count records for each submitted within each date range, e.g.
```
```
select * from (
    select T.submitterId,
        (select count(*)
        from TABLE T1
        where T1.datefield between [july] and [december]
        and T1.submitterId = T.submitterId
        group by T1.submitterId) as JDCount,
        (select count(*)
        from TABLE T2
        where T2.datefield between [december] and [june]
        and T2.submitterId = T.submitterId
        group by T2.submitterId) as DJCount
    from TABLE T) X
where X.JDCount <= 0 OR X.DJCount <= 0
```
```
Caveat: untested query off the top of my head; your mileage may vary.


Question:
From a jsp is thrown a NullPointerException for example using  <% null.toString(); %>

This exception is not handled by the HandlerExceptionResolver, but thrown to the web container(tomcat) and converted into a code 500 error.

How can I configure spring to get that error in my HandlerExceptionResolver ?

Details:

Spring can be configured to handle exceptions thrown inside Controllers, but not exceptions thrown by view.

Of course i can resolve the NullPointerException, but i want to design a solution that will gracefully resolve any possible problem on the web application in order to display a user friendly message to the user.

Answer:
I have not worked with this particular bit of the spring framework, but the docs say
"Interface to be implemented by objects than can resolve exceptions thrown during handler mapping or execution, in the typical case to error views. Implementors are typically registered as beans in the application context.
Error views are analogous to the error page JSPs, but can be used with any kind of exception including any checked exception, with potentially fine-granular mappings for specific handlers."
so I'd imagine that given that NullPointer extends RuntimeException the framework isn't designed to catch it. Is there a reason the exception(s) can't be handled in the controller directly?


Question:
I have a text file in the root of my web app http://localhost/foo.txt and I'd like to load it into a variable in javascript.. in groovy I would do this:

def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;

How can I get a similar result in javascript?

Answer:
XMLHttpRequest, i.e. AJAX, without the XML.
The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:
```
```
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
  alert(client.responseText);
}
client.send();
```
```
Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.
One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.


Question:
I have a WordPress installation with an .htaccess file that looks like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

I tried installing a fresh copy of WordPress into a subdirectory for a separate blog and am getting 404 errors within the root WordPress when I try to view it. I'm assuming this is because of the .htaccess file.

How do I change it so that I can view the subfolder?

Answer:
Edit#2
: ok i think i figured this out, but it's pretty messy.
modify your base wordpress install's .htaccess file to look like this:
```
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_URI} !^/blog2/.*
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
```
now, load a new copy of wordpress into "blog2/", and copy your
```
wp-config.php
```
file over to it. edit the "/blog2/wp-config.php" file and change the
```
$table_prefix
```
to something different than your first blog. (this will install both wordpresses into the same database).
once you've done that, you should be able to go to:
```
```
http://yourdomain.com/blog2/
```
```
and finish up the installation without issue. the initial problem was that the new copy of wordpress kept trying to use the first copy's
```
wp-config.php
```
file. moving it over manually fixed that all up.
because i'm insane, i tested this with two fresh copies, wrote a few test articles, and was able to navigate around without issue, so it should work :)


Question:
Is there a way to use THE LOOP in Wordpress to load pages instead of posts?

I would like to be able to query a set of child pages, and then use THE LOOP function calls on it - things like the_permalink() and the_title().

Is there a way to do this? I didn't see anything in query_posts() documentation.

Answer:
Yes, that's possible. You can create a new WP_Query object. Do something like this:
```
```
query_posts(array('showposts' => <number_of_pages_to_show>, 'post_parent' => <ID of the parent page>, 'post_type' => 'page'));

while (have_posts()) { the_post();
    /* Do whatever you want to do for every page... */
}

wp_reset_query();  // Restore global post data
```
```
Addition
: There are a lot of other parameters that can be used with query_posts. Some, but unfortunately not all, are listed here:
http://codex.wordpress.org/Template_Tags/query_posts
. At least
```
post_parent
```
and more important
```
post_type
```
are not listed there. I dug through the sources of
```
./wp-include/query.php
```
to find out about these.


Question:
I'm looking for a container that keeps all its items in order.  I looked at SortedList, but that requires a separate key, and does not allow duplicate keys.  I could also just use an unsorted container and explicitly sort it after each insert.

Usage:

Occasional insert

Frequent traversal in order

Ideally not working with keys separate from the actual object, using a compare function to sort.

Stable sorting for equivalent objects is desired, but not required.

Random access is not required.

I realize I can just build myself a balanced tree structure, I was just wondering if the framework already contains such a beast.

Answer:
If the key is also an attribute of the object, you might try the
```
System.Collections.ObjectModel.KeyedCollection<TKey, TItem>
```
.  It's an abstract class, but if your key is just a property of the item then it's real simple to derive from.


Question:
What's the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string "text" from the string "ignore everything except this (text)" in the most efficient manner possible.

So far, the best I've come up with is this:

$fullString = "ignore everything except this (text)";
$start = strpos('(', $fullString);
$end = strlen($fullString) - strpos(')', $fullString);

$shortString = substr($fullString, $start, $end);

Is there a better way to do this? I know in general using regex tends to be less efficient, but unless I can reduce the number of function calls, perhaps this would be the best approach? Thoughts?

Answer:
i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it)
```
```
$text = 'ignore everything except this (text)';
preg_match('#\((.*?)\)#', $text, $match);
print $match[1];
```
```


Question: There's something I want to customize in the System.Web.Script.Services.ScriptHandlerFactory and other .NET stuff inside an internal class.  Unfortunately, it's an internal class.  What options do I have when trying to customize a method in this class?

Answer:
You might find
this recent article
enlightening.  Basically, it says that you can't override anything marked
```
internal
```
, and the source is about as authoritative as it gets.  Best you can hope for is an extension method.


Question:
I need to do a query that search for a text with 'Nome % teste \  / ' as prefix. I'm doing the query using:

where "name" ILIKE 'Nome a% teste \ /%' ESCAPE 'a' (using a as escape character).

There is a row that match this, but this query returns nothing. Removing the slash ('Nome % teste \'), it works. But I don't see why the slash is a problem, since the default escape is a backslash and I've changed it to 'a' in this test.

There is something that I'm missing? (I've consulted TFM)

Answer:
Have you tried just using the backslash to escape it like this:
```
```
where "name" ILIKE 'Nome \% teste \\\/';
```
```


Question: I have a form that has multiple fields, and for testing purposes is there a way I could print out the values entered in all the fields, without having to individually print each value.

Answer:
You should be able to do a
```
var_dump($_REQUEST);
```
http://us2.php.net/manual/en/reserved.variables.request.php
http://us2.php.net/manual/en/function.var-dump.php


Question:
I'm working on a system that includes a large number of reports, generated using JasperReports. One of the newer features is that you can define styles for reports.

From the available docs I believe there is some way to have an external file defining styles to use, and you can reference that in your jasper reports. This allows a single style to be used by multiple reports.

I can't find any concrete information on whether this is an actual feature, and if it is, how to use it. Does anyone know if it is possible to have external styles for jasper reports, and if so, how to do it?

Answer:
Use
JasperReport templates
. A JasperReports template is one that ends in
```
.jrtx
```
, and may look similar to this (
```
styles.jrtx
```
):
```
```
<?xml version="1.0"?>
<!DOCTYPE jasperTemplate
  PUBLIC "-//JasperReports//DTD Template//EN"
  "http://jasperreports.sourceforge.net/dtds/jaspertemplate.dtd">

<jasperTemplate>
    <style name="Report Title" isDefault="false" hAlign="Center" fontSize="24" isBold="true"/>
    <style name="Heading 1" isDefault="false" fontSize="18" isBold="true"/>
    <style name="Heading 2" isDefault="false" fontSize="14" isBold="true"/>
</jasperTemplate>
```
```
and then in your
```
.jrxml
```
file, include it as a template:
```
```
...
<template><![CDATA["styles.jrtx"]]></template>
...
```
```
iReport also understands this, so your styles are imported and shown in iReport correctly (though I did notice sometimes it wouldn't pick them up an a reload or recompile was necessary).


Question:
All right, say I have this:

<select id='list'>
    <option value='1'>Option A</option>
    <option value='2'>Option B</option>
    <option value='3'>Option C</option>
</select>

What would the selector look like if I wanted to get "Option B" when I have the value '2'?

Please note that this is not asking how to get the selected text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:

$("#list[value='2']").text();

But it is not working.

Answer:
It's looking for an element with id
```
list
```
which has a property
```
value
```
equal to
```
2
```
.
What you want is the
```
option
```
child of the
```
list
```
:
```
```
$("#list option[value='2']").text()
```
```


Question:
I need to match something in the form

<a href="pic/5" id="piclink"><img src="thumb/5" /></a>

to find the number, in this case 5, using JavaScript. I have no idea how to use regexes, so I was wondering if anyone here could help out.

Answer:
Nevermind, I solved it with a simple
```
```
''.match(/[0-9]/);
```
```


Question: I need to extract only the 2nd level part of the domain from request.servervariables("HTTP_HOST") what is the best way to do this?

Answer:
```
```
If Len(strHostDomain) > 0 Then
    aryDomain = Split(strHostDomain,".")

    If uBound(aryDomain) >= 1 Then
        str2ndLevel = aryDomain(uBound(aryDomain)-1)
        strTopLevel = aryDomain(uBound(aryDomain))
        strDomainOnly = str2ndLevel & "." & strTopLevel
    End If
End If
```
```
works for what I need but it doesn't handle .co.uk or other domains that have two parts expected for the top level.


Question:
I've inherited a piece of code with a snippet which empties the database as follows:

dbmopen (%db,"file.db",0666);
foreach $key (keys %db) {
  delete $db{$key};
}
dbmclose (%db);

This is usually okay but sometimes the database grows very large before this cleanup code is called and it's usually when a user wants to do something important.

Is there a better way of doing this?

Answer:
Actually, a workmate has pointed me to a solution.  You can apparently do:
```
```
dbmopen (%db,"file.db",0666);
%db = ();
dbmclose (%db);
```
```
which clears out the hash before closing the database.


Question: I've been working with the Joomla framework and I have noticed that they use a convention to designate private or protected methods (they put an underscore "_" in front of the method name), but they do not explicitly declare any methods public, private, or protected.  Why is this?  Does it have to do with portability?  Are the public, private, or protected keywords not available in older versions of PHP?

Answer:
public, private and protected are PHP5 keywords. unfortunately, PHP4 still has a very high install base (especially amongst shared hosting services).
here's a
pretty pic
showing july usage rates (text in french).
spoiler
: php4 still has over a 35% usage rate sadly.


Question:
I've seen some horrific code written in Perl, but I can't make head nor tail of this one:

select((select(s),$|=1)[0])

It's in some networking code that we use to communicate with a server and I assume it's something to do with buffering (since it sets $|).

But I can't figure out why there's multiple select calls or the array reference. Can anyone help me out?

Answer:
It's a nasty little idiom for setting autoflush on a filehandle other than STDOUT.
```
select()
```
takes the supplied filehandle and (basically) replaces STDOUT with it, and it returns the old filehandle when it's done.
So
```
(select($s),$|=1)
```
redirects the filehandle (remember
```
select
```
returns the old one), and sets autoflush (
```
$| = 1
```
). It does this in a list (
```
(...)[0]
```
) and returns the first value (which is the result of the
```
select
```
call - the original STDOUT), and then passes
that
back into another
```
select
```
to reinstate the original STDOUT filehandle. Phew.
But now you understand it (well, maybe ;)), do this instead:
```
```
use IO::Handle;
$fh->autoflush;
```
```


Question:
I need to be able to send encrypted data between a Ruby client and a Python server (and vice versa) and have been having trouble with the ruby-aes gem/library. The library is very easy to use but we've been having trouble passing data between it and the pyCrypto AES library for Python. These libraries seem to be fine when they're the only one being used, but they don't seem to play well across language boundaries. Any ideas?

Edit: We're doing the communication over SOAP and have also tried converting the binary data to base64 to no avail. Also, it's more that the encryption/decryption is almost but not exactly the same between the two (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)

Answer:
Kind of depends on how you are transferring the encrypted data. It is possible that you are writing a file in one language and then trying to read it in from the other. Python (especially on Windows) requires that you specify binary mode for binary files. So in Python, assuming you want to decrypt there, you should open the file like this:
```
```
f = open('/path/to/file', 'rb')
```
```
The "b" indicates binary. And if you are writing the encrypted data to file from Python:
```
```
f = open('/path/to/file', 'wb')
f.write(encrypted_data)
```
```


Question:
I'm trying to implement search result highlighting for pdfs in a web app. I have the original pdfs, and small png versions that are used in search results. Essentially I'm looking for an api like:

pdf_document.find_offsets('somestring')
# => { top: 501, left: 100, bottom: 520, right: 150 }, { ... another box ... }, ...

I know it's possible to get this information out of a pdf because Apple's Preview.app implements this.

Need something that runs on Linux and ideally is open source. I'm aware you can do this with acrobat on windows.

Answer:
I think you can do this using the Adobe Acrobat SDK, a Linux version of which can be
downloaded for free from Adobe
. You can use this to
extract text from PDFs
and then work out offsets. The PDF can then be highlighted by using the
Acrobat XML highlighting file
. This is used to specify which words in which positions are to be highlighted and is fed to acrobat as follows:
http://example.com/a.pdf#xml=http://example.com/highlightfile.xml


Question:
Some ways to iterate through the characters of a string in Java are:

Using StringTokenizer?

Converting the String to a char[] and iterating over that.

What is the easiest/best/most correct way to iterate?

Answer:
I use a for loop to iterate the string and use
```
charAt()
```
to get each character to examine it.  Since the String is implemented with an array, the
```
charAt()
```
method is a constant time operation.
```
```
String s = "...stuff...";

for (int i = 0; i < s.length(); i++){
    char c = s.charAt(i);
    //Process char
}
```
```
That's what I would do.  It seems the easiest to me.
As far as correctness goes, I don't believe that exists here.  It is all based on your personal style.


Question:
I am looking for a way to add a drop down list in WPF to a menu. This used to be really easy in winforms and so I am expecting you experts to know just now to do it in WPF. Thanks.

Sorry if this is a bad question, it is late and I don't want to think.

Answer:
It is very easy to add any UIElement to any control, You can just add Combobox to a Menu control and create menu as bellow.
```
```
<Menu>
    <MenuItem Header="File">
        <MenuItem Header="Open"/>
        <MenuItem Header="Close"/>
        <Separator/>
        <ComboBox Width="85" Height="21.96" />
    </MenuItem>
</Menu>
```
```


Question:
In Python, you can do this:

print "Hi!  I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30})

What's the closest, simplest Ruby idiom to replicate this behavior?  (No monkeypatching the String class, please.)

One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:

template = "Hi!  I'm %(name)s, and I'm %(age)d years old."
def greet(template,name,age):
    print template % ({"name":name,"age":age})

This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use.  Ruby's "Hi!  I'm #{name}" convention is cursorily similar, but the immediate evaluation makes it less versatile.

Answer:
In a double-quoted string in Ruby, you can insert the result of a Ruby expression like this:
```
```
puts "Hi!  I'm #{name}, and I'm #{age} years old."
```
```
Just put an expression inside the curly braces. (It could also be something more complex like #{age + 5}, or #{name + ' ' + last_name}, or a function call.)


Question:
I'm looking for a subversion web client ala SVN::Web but with a very specific feature I've always thought would be quite useful.

What I want is the ability to find which revision was responsible for a certain line (or lines) in a text file.  A way to do this via the web would be fantastic.

Anybody know of such a tool?

Answer:
I thought that SVN had the 'blame' function that could do something similar to that. I am taking a stab in the dark though.  Hold on while I take a quick look through the interwebs.
You bet.  Check
this
out.  (I use subclipse btw)
This implies that most web SVN interfaces will have this feature because it is not anything really special.


Question: I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button

Answer:
Here's some self-contained HTML/JS that does the trick:
```
```
<html>
  <head>
    <script type="text/javascript">
      function mkclr(cntl,clr) {
        document.getElementById(cntl).style.backgroundColor = clr;
      };
    </script>
  </head>
  <body>
    <form>
      <input type="textbox" id="tb1"></input>
      <input type="submit" value="Go"
        onClick="javascript:mkclr('tb1','red');">
      </input>
    </form>
  </body>
</html>
```
```


Question: JavaScript doesn't seem to have a native trim() method. How can I trim white spaces at the start and end of a string with JavaScript?

Answer:
according to
this page
the best all-around approach is
```
```
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
```
```
Of course if you are using jQuery , it will provide you with an optimized trim method.


Question:
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and pywin32 or wxPython?

Essentially, I need a function that called will return True iff current OS is Vista:

>>> isWindowsVista()
True

Answer:
The simplest solution I found is this one:
```
```
import sys

def isWindowsVista():
    '''Return True iff current OS is Windows Vista.'''
    if sys.platform != "win32":
        return False
    import win32api
    VER_NT_WORKSTATION = 1
    version = win32api.GetVersionEx(1)
    if not version or len(version) < 9:
        return False
    return ((version[0] == 6) and
            (version[1] == 0) and
            (version[8] == VER_NT_WORKSTATION))
```
```


Question:
I'm writing some code for a class constructor which loops through all the properties of the class and calls a generic static method which populates my class with data from an external API. So I've got this as an example class:

public class MyClass{
  public string Property1 { get; set; }
  public int Property2 { get; set; }
  public bool Property3 { get; set; }

  public static T DoStuff<T>(string name){
    // get the data for the property from the external API
    // or if there's a problem return 'default(T)'
  }
}

Now in my constructor I want something like this:

public MyClass(){
  var properties = this.GetType().GetProperties();
  foreach(PropertyInfo p in properties){
    p.SetValue(this, DoStuff(p.Name), new object[0]);
  }
}

So the above constructor will thrown an error because I'm not supplying the generic type.

So how do I pass in the type of the property in?

Answer:
Do you want to call DoStuff<T> with T = the type of each property? In which case, "as is" you would need to use reflection and MakeGenericMethod - i.e.
```
```
var properties = this.GetType().GetProperties();
foreach (PropertyInfo p in properties)
{
    object value = typeof(MyClass)
    .GetMethod("DoStuff")
    .MakeGenericMethod(p.PropertyType)
    .Invoke(null, new object[] { p.Name });
    p.SetValue(this, value, null);
}
```
```
However, this isn't very pretty. In reality I wonder if it wouldn't be better just to have:
```
```
static object DoStuff(string name, Type propertyType);
... and then
object value = DoStuff(p.Name, p.PropertyType);
```
```
What does the generics give you in this example? Note that value-types will still get boxed etc during the reflection call - and even then boxing
isn't as bad as you might think
.
Finally, in many scenarios, TypeDescriptor.GetProperties() is more appropriate than Type.GetProperties() - allows for flexible object models etc.


Question:
I was trying the following example, but with external URLs:
Using WebViews

The example shows how to load an HTML file from assets folder (file:// url) and display it in a WebView.

But when I try it with external URLs (like http://google.com), I am always getting a "Website Not Available" error. Android's built-in browser is able to access all external URLs.

I suspect that it has something to do with permissions, but wasn't able to confirm it.

Answer:
I found out the answer myself.
The permission name is android.permission.INTERNET.
Adding following line to the AndroidManifest.xml (nested directly in  tag) did the trick:
```
```
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
```
```
The file can also be edited graphically in Eclipse plugin through permissions tab.


Question:
I have an application that I have to run as Administrator.

One small part of that application is to start other applications with Process.Start

The started applications will also be run as administrators, but I'd rather see them run as the 'normal' user.

How do I accomplish that?

/johan/

Answer:
From:
http://go.microsoft.com/fwlink/?LinkId=81232
A frequently asked question is how to
  launch an un-elevated application from
  an elevated process, or more
  fundamentally, how to I launch a
  process using my un-elevated token
  once I’m running elevated.  Since
  there is no direct way to do this, the
  situation can usually be avoided by
  launching the original application as
  standard user and only elevating those
  portions of the application that
  require administrative rights.  This
  way there is always a non-elevated
  process that can be used to launch
  additional applications as the
  currently logged on desktop user.
  Sometimes, however, an elevated
  process needs to get another
  application running un-elevated.  This
  can be accomplished by using the task
  scheduler within Windows Vista.  The
  elevated process can register a task
  to run as the currently logged on
  desktop user.
Here is an example of how to schedule the un-elevated process (again from the same link)
```
```
//---------------------------------------------------------------------
//  This file is part of the Microsoft .NET Framework SDK Code Samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//This source code is intended only as a supplement to Microsoft
//Development Tools and/or on-line documentation.  See these other
//materials for detailed information regarding Microsoft code samples.
//
//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//PARTICULAR PURPOSE.
//---------------------------------------------------------------------

/****************************************************************************
* Main.cpp - Sample application for Task Scheduler V2 COMAPI                * Component: Task Scheduler
* Copyright (c) 2002 - 2003, Microsoft Corporation
* This sample creates a task to that launches as the currently logged on deskup user. The task launches as soon as it is registered.                                                             *
****************************************************************************/
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <comdef.h>
#include <comutil.h>
//Include Task header files - Included in Windows Vista Beta-2 SDK from MSDN
#include <taskschd.h>
#include <conio.h>
#include <iostream>
#include <time.h>

using namespace std;

#define CLEANUP \
pRootFolder->Release();\
        pTask->Release();\
        CoUninitialize();

HRESULT CreateMyTask(LPCWSTR, wstring);

void __cdecl wmain(int argc, wchar_t** argv)
{
wstring wstrExecutablePath;
WCHAR taskName[20];
HRESULT result;

if( argc < 2 )
{
printf("\nUsage: LaunchApp yourapp.exe" );
return;
}

// Pick random number for task name
srand((unsigned int) time(NULL));
wsprintf((LPWSTR)taskName, L"Launch %d", rand());

wstrExecutablePath = argv[1];

result = CreateMyTask(taskName, wstrExecutablePath);
printf("\nReturn status:%d\n", result);

}
HRESULT CreateMyTask(LPCWSTR wszTaskName, wstring wstrExecutablePath)
{
    //  ------------------------------------------------------
    //  Initialize COM.
TASK_STATE taskState;
int i;
    HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    if( FAILED(hr) )
    {
        printf("\nCoInitializeEx failed: %x", hr );
        return 1;
    }

    //  Set general COM security levels.
    hr = CoInitializeSecurity(
        NULL,
        -1,
        NULL,
        NULL,
        RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
        RPC_C_IMP_LEVEL_IMPERSONATE,
        NULL,
        0,
        NULL);

    if( FAILED(hr) )
    {
        printf("\nCoInitializeSecurity failed: %x", hr );
        CoUninitialize();
        return 1;
    }

    //  ------------------------------------------------------
    //  Create an instance of the Task Service.
    ITaskService *pService = NULL;
    hr = CoCreateInstance( CLSID_TaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskService,
                           (void**)&pService );
    if (FAILED(hr))
    {
        printf("Failed to CoCreate an instance of the TaskService class: %x", hr);
        CoUninitialize();
        return 1;
    }

    //  Connect to the task service.
    hr = pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());
    if( FAILED(hr) )
    {
        printf("ITaskService::Connect failed: %x", hr );
        pService->Release();
        CoUninitialize();
        return 1;
    }

    //  ------------------------------------------------------
    //  Get the pointer to the root task folder.  This folder will hold the
    //  new task that is registered.
    ITaskFolder *pRootFolder = NULL;
    hr = pService->GetFolder( _bstr_t( L"\\") , &pRootFolder );
    if( FAILED(hr) )
    {
        printf("Cannot get Root Folder pointer: %x", hr );
        pService->Release();
        CoUninitialize();
        return 1;
    }

    //  Check if the same task already exists. If the same task exists, remove it.
    hr = pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0  );

    //  Create the task builder object to create the task.
    ITaskDefinition *pTask = NULL;
    hr = pService->NewTask( 0, &pTask );

    pService->Release();  // COM clean up.  Pointer is no longer used.
    if (FAILED(hr))
    {
        printf("Failed to CoCreate an instance of the TaskService class: %x", hr);
        pRootFolder->Release();
        CoUninitialize();
        return 1;
    }

    //  ------------------------------------------------------
    //  Get the trigger collection to insert the registration trigger.
    ITriggerCollection *pTriggerCollection = NULL;
    hr = pTask->get_Triggers( &pTriggerCollection );
    if( FAILED(hr) )
    {
        printf("\nCannot get trigger collection: %x", hr );
  CLEANUP
        return 1;
    }

    //  Add the registration trigger to the task.
    ITrigger *pTrigger = NULL;

    hr = pTriggerCollection->Create( TASK_TRIGGER_REGISTRATION, &pTrigger );
    pTriggerCollection->Release();  // COM clean up.  Pointer is no longer used.
    if( FAILED(hr) )
    {
        printf("\nCannot add registration trigger to the Task %x", hr );
        CLEANUP
        return 1;
    }
    pTrigger->Release();

    //  ------------------------------------------------------
    //  Add an Action to the task.
    IExecAction *pExecAction = NULL;
    IActionCollection *pActionCollection = NULL;

    //  Get the task action collection pointer.
    hr = pTask->get_Actions( &pActionCollection );
    if( FAILED(hr) )
    {
        printf("\nCannot get Task collection pointer: %x", hr );
        CLEANUP
        return 1;
    }

    //  Create the action, specifying that it is an executable action.
    IAction *pAction = NULL;
    hr = pActionCollection->Create( TASK_ACTION_EXEC, &pAction );
    pActionCollection->Release();  // COM clean up.  Pointer is no longer used.
    if( FAILED(hr) )
    {
        printf("\npActionCollection->Create failed: %x", hr );
        CLEANUP
        return 1;
    }

    hr = pAction->QueryInterface( IID_IExecAction, (void**) &pExecAction );
    pAction->Release();
    if( FAILED(hr) )
    {
        printf("\npAction->QueryInterface failed: %x", hr );
        CLEANUP
        return 1;
    }

    //  Set the path of the executable to the user supplied executable.
   hr = pExecAction->put_Path( _bstr_t( wstrExecutablePath.c_str() ) );

    if( FAILED(hr) )
    {
        printf("\nCannot set path of executable: %x", hr );
        pExecAction->Release();
        CLEANUP
        return 1;
    }
    hr = pExecAction->put_Arguments( _bstr_t( L"" ) );

   if( FAILED(hr) )
    {
        printf("\nCannot set arguments of executable: %x", hr );
        pExecAction->Release();
        CLEANUP
        return 1;
    }

    //  ------------------------------------------------------
    //  Save the task in the root folder.
    IRegisteredTask *pRegisteredTask = NULL;
    hr = pRootFolder->RegisterTaskDefinition(
            _bstr_t( wszTaskName ),
            pTask,
      TASK_CREATE,
_variant_t(_bstr_t( L"S-1-5-32-545")),//Well Known SID for \\Builtin\Users group
_variant_t(),
TASK_LOGON_GROUP,
            _variant_t(L""),
            &pRegisteredTask);
    if( FAILED(hr) )
    {
        printf("\nError saving the Task : %x", hr );
        CLEANUP
        return 1;
    }
    printf("\n Success! Task successfully registered. " );
    for (i=0; i<100; i++)//give 10 seconds for the task to start
{
pRegisteredTask->get_State(&taskState);
if (taskState == TASK_STATE_RUNNING)
{
printf("\nTask is running\n");
break;
}
Sleep(100);
}
if (i>= 100) printf("Task didn't start\n");

    //Delete the task when done
    hr = pRootFolder->DeleteTask(
            _bstr_t( wszTaskName ),
            NULL);
    if( FAILED(hr) )
    {
        printf("\nError deleting the Task : %x", hr );
        CLEANUP
        return 1;
    }

    printf("\n Success! Task successfully deleted. " );

//  Clean up.
    CLEANUP
    CoUninitialize();
    return 0;
}
```
```


Question: Is there a simple way to convert a string to Title Case? E.g. john smith becomes John Smith. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.

Answer:
```
```
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
      return i.toUpperCase() + (r != null ? r : "");
    }
)
```
```
Seems to work...
Tested with the above, "the quick-brown, fox? /jumps/ ^over^ the ¡lazy! dog..." and "C:/program files/some vendor/their 2nd application/a file1.txt".
If you want 2Nd instead of 2nd, you can change to
```
/([a-z])(\w*)/g
```
.
The first form can be simplified as:
```
```
function toTitleCase(toTransform) {
  return toTransform.replace(/\b([a-z])/g, function (_, initial) {
      return initial.toUpperCase();
  });
}
```
```


Question:
I have an old project that was built using visual studio 2003 and I recompiled it with vs2005 recently.  However, during runtime, I get the following error:

list iterator not incrementable

I traced the program to this function:

void InputQueue::update()
{
    list<PCB>::iterator iter;
    list<PCB>::iterator iterTemp;
    for(iter = begin(); iter != end(); iter++)
    {
        if(iter->arrivalTime == 0)
        {
            ReadyQueue::getInstance()->add(*iter);
            iterTemp = iter;
            iter++;
            erase(iterTemp);
        }
    }
}

I'm not a C++ expert and this is as far as the VS debugger got me.  Could somebody explain to me what the problem is?

Thanks

Answer:
Notice that if
```
iter->arrivalTime == 0
```
, then the list iterator gets incremented twice: once before element removal, and once again at the end of the loop.
If the item to be removed is the last item in the list, this will obviously not work correctly. I dare say that it never did work correctly even in VS2003, but VS2005 alerts you about it better. :-)
Remember, it's undefined behaviour to iterate past
```
end()
```
. Absolutely anything can happen, such as program crash, or (in this case) an error message.


Question:
The rich text editor must be implemented in Java, provide Swing support, and preferably be open source.

I'm looking to integrate it into an existing Java/Swing application.

Thanks.

Answer:
This is probably not as drop-in-place as what you were after... but JTextPane supports rich text and HTML.
Its trivial to get it to
display
rtf or html, just set the encoding type before you fill it with content.
As for making the little "B" and "
I
" etc style-modifying buttons, well if it came down to it, in a pinch that wouldnt be very hard to make yourself.
Think JButtons with Icons set. Their listeners get JTextPane's current selection start and end index positions like this :
```
jpane.getSelectionStart()
```
or
```
jpane.getSelectionEnd()
```
and then insert opening and closing html/rtf tags at those locations.
Undo is easy too - maintain a simple stack of the string contents of the Jpanel, every time the user does an edit action, a simple
```
history.push(jpane.getText())
```
would store the state, and the undo button would be as simple as
```
jpane.setText(history.pop())
```
.
I/you could make one with B,
I
& undo in around 30 min I reckon - other buttons like lists will take longer, but not much so.


Question:
i have a wordpress blog and want to give people the same user experience for adding comments that is in stackoverflow.  There are a number of comments ajax plugins out there but i can't find a working one that allows you to inline on the main page, go in and add comments without first drilling down into a seperate single post page.

Can anyone help here with either a wordpress plugin or php code to do this.

Answer:
I think
AJAXed Wordpress
does what you're looking for, among other things:
AJAXed Wordpress
AJAXed Wordpress (AWP) harnesses the power of both AJAX and Wordpress to improve
the user experience, the administration capabilities and the design potential of
any Wordpress based blog. It works on all WordPress versions from 2.1 - 2.6.
Some of AWP’s features include loading posts inline,
inline comments
, threaded
comments, AJAX comment submission, AJAX Navigation, live comment preview and much
more. AWP is endlessly customizable and extensible. Even though AWP provides many
features, you are never forced to use features that you don’t want. All aspects of
the plugin are easily customized through a single Administration panel.
Demo is available here
http://wordpress.mu/
and you can see the inline comments in action. Looks like what you were asking for.


Question: I am an Ajax developer and I want to build a Flash application. Given my previous experience with JavaScript, what do you thing will be the easiest way to learn ActionScript and what are the obstacles I might encounter?

Answer:
Don't whatever you do start by buying Flash Pro. It is a designer tool and is really rather crap for developing code. By all means invest in it later, but it is a hindrance to coders getting into ActionScript; not an aid. I'd recommend getting yourself either
Flex Builder
if you can afford it, or an open source ActionScript IDE like
FlashDevelop
if not.
Then grab yourself a couple of books on ActionScript and/ or Flex and start reading. Also it is worth downloading any examples of simple Flash apps you can find that include code in order to learn how others do things.
Something to bear in mind when moving from JavaScript to ActionScript is that AS1 was very JavaScript-like, AS2 was less so, and there is little similarity between JavaScript and AS3. Thus if you have the time and inclination, try and pick up a cheap copy of an AS1 and AS2 book and skim through them first to understand the language's history. You'll likely get into AS3 far faster that way. Of course if you are aware of ECMAScript v4 (which will likely now never see the light of day), then you can jump straight to AS3 with confidence.


Question:
I would like to declare a dropdown box in a view in an ASP.NET MVC application, for letting the user select a lookup value. I know how to declare plain text boxes but is there an official helper for declaring dropdown boxes (date time pickers and the rest)?.

I also don't know what structure I should pass to my view for giving the values to the dropdown box. I assume I need both an id and a description.

Finally, how do I pass the selected id from the dropdown box back to my action in the controller?

Answer:
You might check out this blog entry by Scott Guthrie about
Handling Form Edit Post Scenarios
. He uses a drop down list in an example of his.
You can provide a list of complex objects to the drop down list too (Scott Guthrie's example doesn't show that, but it alludes to it).
You can do something like this...
```
```
<%= Html.DropDownList("Select One", "CategoryId", ViewData.Model.Categories, "Id", "Name", ViewData.Model.SelectedCategoryId)) %>
```
```
"Id" and "Name" refer to properties on your ViewData.Model.Categories list of objects.
If SelectedCategoryId has a value, then it will default the dropdownlist.


Question: Is it possible to set a default value for columns in JPA, and if, how is it done using annotations?

Answer:
This isn't possible in JPA.
Here's what you
can
do with the Column annotation:
http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html


Question:
Now that shared_ptr is in tr1, what do you think should happen to the use of std::auto_ptr? They both have different use cases, but all use cases of auto_ptr can be solved with shared_ptr, too. Will you abandon auto_ptr or continue to use it in cases where you want to express explicitly that only one class has ownership at any given point?

My take is that using auto_ptr can add clarity to code, precisely by adding nuance and an indication of the design of the code, but on the other hand, it add yet another subtle issue when training new programmers: they need to understand smart pointers and the fine details of how they work. When you use only one smart pointer everywhere, you can just lay down a rule 'wrap all pointers in shared_ptr' and be done with it.

What's your take on this?

Answer:
I believe that "wrap all pointers in
```
shared_ptr
```
" should indeed be the default mode, and is suitable advice to give to your junior coders. However, in the special ownership cases that you mentioned,
```
auto_ptr
```
is indeed more appropriate and its use should be encouraged under such circumstances.


Question: Is it possible to access the Abstract Syntax Tree(AST) inside the javac.exe programmatically? Could you provide an example?

Answer:
Yes, it is possible, but only since Java 6.
Peter von der Ahé
talks about the two JSRs in
this interview
. Of JSR 199:
The JSR 199 Compiler API consists of three things: The first one basically allows you to invoke a compiler via the API. Second, the API allows you to customize how the compiler finds and writes out files. I mean files in the abstract sense, since the files the compiler deals with aren't necessarily on the file system. JSR 199's file abstraction allows you to have files in a database, and to generate output directly to memory, for example. Finally, the JSR 199 API lets you collect diagnostics from the compiler in a structured way so that you can easily transform error messages, for instance, into lines in an IDE's editor.
JSR 269 is the annotation processing API.
This article
gives an excellent overview of accessing the
Compiler Tree API
. The section "
Accessing the Abstract Syntax Tree: The Compiler Tree API
" seems particularly suitable for your question.
Depending on what you're doing, you may also want to look at the
Jackpot Rule Language
, which is a standalone refactoring engine that plugins into the Compiler Tree.


Question:
What is the most efficient way of turning the list of values of a dictionary into an array?

For example, if I have a Dictionary where Key is String and Value is Foo, I want to get Foo[]

I am using VS 2005, C# 2.0

Answer:
```
```
// dict is Dictionary<string, Foo>

Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);

// or in C# 3.0:
var foos = dict.Values.ToArray();
```
```


Question:
Could you provide an example of accessing the Eclipse Abstract Syntax Tree programmatically for a given piece of code?

eg getting the AST for:

Class1.java

package parseable;

public class Class1 {

/**
 * @param args
 */
public static void main(String[] args) {
    System.out.println("Hello world!");
}

}

Answer:
It is not an
exact
answer, that may give you a place where to start:
As said in this
question
,
A full example is available in this
eclipse corner article
, also more details in the
eclipse help
. And in the slide 59 of
this presentation
, you see how to apply a change to your source code.


Question:
How can I do the Ruby method "Flatten" Ruby Method in C#. This method flattens a jagged array into a single-dimensional array.

For example:

s = [ 1, 2, 3 ]           #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ]   #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ]       #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Answer:
Recursive solution:
```
```
IEnumerable Flatten(IEnumerable array)
{
    foreach(var item in array)
    {
        if(item is IEnumerable)
        {
            foreach(var subitem in Flatten((IEnumerable)item))
            {
                yield return subitem;
            }
        }
        else
        {
            yield return item;
        }
    }
}
```
```
EDIT 1:
Jon
explains in the comments why it cannot be a generic method, take a look!
EDIT 2:
Matt
suggested making it an extension method. Here you go, just replace the first line with:
```
```
public static IEnumerable Flatten(this IEnumerable array)
```
```
and you can use it like this:
```
```
foreach(var item in myArray.Flatten()) { ... }
```
```


Question:
In WPF, there are two ways to set the focus to an element.

You can either call the .Focus() method of the input element, or call Keyboard.Focus() with the input element as parameter.

// first way:
item.Focus();
// alternate way:
Keyboard.Focus(item);

What is the difference between these two? Are there special reasons to use one of them instead of the other in some cases?

So far I noticed no difference - what ever method I used, the item always got logical focus as well as keyboard focus.

Answer:
As per
WPF documentation on MSDN
:
In WPF there are two main concepts that pertain to focus: keyboard focus and logical focus. Keyboard focus refers to the element that receives keyboard input and logical focus refers to the element in a focus scope that has focus.
and
An element that has keyboard focus will also have logical focus, but an element that has logical focus does not necessarily have keyboard focus.


Question:
The following code has a simple binding which binds the Text of the TextBlock named MyTextBlock to TextBox's Text and ToolTip property using the exact same Binding notation:

<StackPanel>
    <TextBlock x:Name="MyTextBlock">Foo Bar</TextBlock>
    <TextBox    Text="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}"
             ToolTip="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}" />
</StackPanel>

The binding also uses the StringFormat property introduced with .NET 3.5 SP1 which is working fine for the above Text property but seems to be broken for the ToolTip. The expected result is "It is: Foo Bar" but when you hover over the TextBox, the ToolTip shows only the binding value, not the string formatted value. Any ideas?

Answer:
ToolTips in WPF can contain anything, not just text, so they provide a ContentStringFormat property for the times you just want text. You'll need to use the expanded syntax as far as I know:
```
```
<TextBox ...>
  <TextBox.ToolTip>
    <ToolTip
      Content="{Binding ElementName=myTextBlock,Path=Text}"
      ContentStringFormat="{}It is: {0}"
      />
  </TextBox.ToolTip>
</TextBox>
```
```
I'm not 100% sure about the validity of binding using the ElementName syntax from a nested property like that, but the ContentStringFormat property is what you're looking for.


Question: In a SQL-database I make some selects, that get an duration (as result of a subtraction between two dates) in seconds as an int. But I want to format this result in a human-readable form like 'hh:mm' or 'dd:hh'. Is that possible in SQL and how can I realize this?

Answer:
In SQL 2005, You can use the following:
```
```
select convert(varchar(8), dateadd(second, [SecondsColumn], 0),  108)
```
```
Which first converts the seconds into a date after 1900-01-01, and then gets the hh:mm:ss part.
If the column is more than 24 hours, this will roll over, if you want days and then hours in that case just do something like:
```
```
case when SecondsColumn> (24*60*60)
        then
            cast(datepart(day,datediff(dd, 0, dateadd(second, SecondsColumn, 0))) as varchar(4))
        +   'd' + convert(varchar(2), dateadd(second, SecondsColumn, 0), 108)
    else
            convert(varchar(8), dateadd(second, SecondsColumn, 0), 108)
    end
```
```


Question:
I'm trying to select data from a table defined similar to the following :

Column     |    Data Type
-------------------------
Id         |    Int
DataType   |    Int
LoggedData |    XML

but I only want to select those rows with a specific DataType value, and that contain a string (or evaluates a piece of XPath) in the LoggedData column.

A quick Google search turned up nothing useful, and I am in a bit of a rush to get an answer...  I'll carry on searching, but if anyone can help me out on this in the mean time, I'd really appreciate it.

EDIT _ Clarification

So, what I'm after is something like this, but in the correct format...

select Id, LoggedData from myTable where DataType = 29 and LoggedData.query('RootNode/ns1:ChildNode[@value="searchterm"]');

Still might not be clear...

Answer:
Is this not doing the trick for you?
```
```
SELECT
  Id,
  LoggedData
FROM
  myTable
WHERE
  DataType = 29
  AND LoggedData.exist('RootNode/ns1:ChildNode[@value="searchterm"]') = 1
```
```


Question:
What is an example of a fast SQL to get duplicates in datasets with hundreds of thousands of records. I typically use something like:

SELECT afield1, afield2 FROM afile a
WHERE 1 < (SELECT count(afield1) FROM afile b WHERE a.afield1 = b.afield1);

But this is quite slow.

Answer:
This is the more direct way:
```
```
select afield1,count(afield1) from atable
group by afield1 having count(afield1) > 1
```
```


Question:
This example is from php.net:

<?php
function Test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

And this is my code:

function getNextQuestionID()
{
    static $idx = 0;
    return $idx++;
}

And I use it in JavaScript:

'quizID=' + "<?php echo getNextQuestionID(); ?>"

Returns 0 everytime. Why?

Answer:
I believe you misunderstand what static vars do. Try this code and you may understand better:
```
```
echo getNextQuestionID() . ", " getNextQuestionID() . ", " getNextQuestionID();
```
```
And you will see what I mean.
The static var only lives as long as the script does.
The reason it is returning 0 on the first run instead of 1 is because you are using the postfix operator $var++ instead of the prefix version - ++$var. The difference is is that the increment only gets applied when using the postfix operator after the function returns - but if you use the prefix operator it is applied before the function returns.


Question:
I'm trying to do the following without too much special case code to deal with invalidated POSITIONs etc:

What's the best way to fill in the blanks?

void DeleteUnreferencedRecords(CAtlMap<Record>& records)
{
   for(____;____;____)
   {
      if( NotReferencedElsewhere(record) )
      {
        // Delete record
        _______;
      }
   }
}

Answer:
My first thoughts would be the save the current POSITION before calling
```
GetNext
```
, then, if you delete the element you can reset it.  However, perhaps the safest way would be to create a new map containing the elements you want to keep, else you could be relying on how the internal implementation of POSITION works.


Question:
I am fairly new to WPF. I want to develop a datagrid control which supports databinding.

There is a lot of information available about databinding to existing controls, but I cannot find any information how to develop a control from scratch which supports databinding.

I do not expect a simple answer to this question, a link to get me started would be nice.

Answer:
Are you planning to build a DatGrid control?. There is one here
http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=14963
Binding is one of the important features of WPF, Dependancyproperty actually gives a control the ability to bind and listen to data change events(Data Binding).
When you develop your control you dont need to do anything special to make the DataBinding work, just need to define appropriate Dependency properties to the control,
You can read more about DataBinding here
http://msdn.microsoft.com/en-us/library/ms752347.aspx


Question: Is there any way to automatically rename accessor/mutator when a variable they get/set gets refactored -> renamed (Eclipse 3.4)?

Answer:
1 - When you select Refactor->Rename on a variable, Eclipse prompts you to enter the new name in an "in-line" box. Directly below it, there is a help message and next to it a small icon (an arrow going down).Click on that arrow and then select "Open Rename Dialog". A new pop-up appears with the checkboxes you need.
2 - Alternatively, select the variable you want to change and press
twice
Alt+Shift+R. Again check the getter/setter checkboxes.


Question: Is there any good bug tracker based on .NET which is free?

Answer:
Two bug trackers I know:
BugTracker.NET
BugTracker.NET is a free, open-source,
  web-based bug tracker or customer
  support issue tracker written using
  ASP.NET, C#, and Microsoft SQL Server
  (or its free cousin, SQL Server
  Express).
BugNET
BugNET is an issue tracking and
  project issue management solution
  built using the ASP.NET web
  application framework. Email
  notifications, reporting and per
  project configuration of fields and
  values allows efficient management of
  bugs, feature requests, and other
  issues for projects of any scale.


Question:
How do I make my application always use English when displaying win32/.net exceptions messages?

I got this message, it looks like someone used babelfish to translate it (it's Swedish):
"System.ComponentModel.Win32Exception: Programmet kunde inte starta eftersom programmets sida-vid-sidakonfiguration är felaktig."

Extremely unhelpful, and Google had a whopping 4 hits for it, none of them helpful.
So I have to guess what the original message was and google that. (It's was: "The application has failed to start because its side-by-side configuration is incorrect.")

This time it was fairly simple to find out what the original error message was, having the message in English from the start would of course save me time.

So how do I do that?

Answer:
You can try setting
```
Thread.CurrentThread.CurrentUICulture
```
and/or
```
.CurrentCulture
```
to
```
CultureInfo("en-US")
```
.


Question:
I can write a trivial script to do this but in my ongoing quest to get more familliar with unix I'd like to learn efficient methods using built in commands instead.

I need to deal with very large files that have a variable number of header lines. the last header line consists of the text 'LastHeaderLine'. I wish to output everything after this line. (I'm not worried about false positive matches.)

Answer:
Using sed:
```
```
sed -ne '/LastHeaderLine/,$p' <inputfile
```
```
will match everything from the regex match to the end of the file. 'p' prints the lines that match.
Edit:
On second thought, you don't want to print the line matching LastHeaderLine. This is difficult to do with sed. In perl, you could do the following:
```
```
perl -ne 'if ($flag) {print;} if (/LastHeaderFile/) {$flag=1;}' <inputfile
```
```
This would print only lines strictly following the regex match.


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

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

Anyone know how to disable this?

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


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

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

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

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

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


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

Requirements:

1.Vector< someclass> inside my class

2.Add and count of vector is needed interface

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


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

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

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

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


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

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

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


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

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


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

"param 1" param2 "param 3"

should result in:

param 1, param2, param 3

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


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

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

What the intention behind this class is

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

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


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

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

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


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

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


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

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

Answer:
Look like the best solution to this is to install the platform specific mysql driver.
```
sudo gem install mysql
```


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

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

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

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

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


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

Computers
    Processors
        Intel
            Pentium
            Core 2 Duo
        AMD
            Athlon

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

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

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


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

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

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

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


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

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

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

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


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

list<Object> myList;

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

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

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


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

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

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

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