q:
I know its possible to get the top terms within a Lucene Index, but is there a way to get the top terms based on a subset of a Lucene index?

I.e. What are the top terms in the Index for documents within a certain date range?

[A]
Ideally there'd be a utility somewhere to do this, but I'm not aware of one.  However, it's not too hard to do this "by hand" in a reasonably efficient way.  I'll assume that you already have a
```
Query
```
and/or
```
Filter
```
object that you can use to define the subset of interest.
First, build a list in memory of all of the document IDs in your index subset.  You can use
```
IndexSearcher.search(Query, Filter, HitCollector)
```
to do this very quickly; the
```
HitCollector
```
documentation
includes an example that seems like it ought to work, or you can use some other container to store your doc IDs.
Next, initialize an empty HashMap (or whatever) to map terms to total frequency, and populate the map by invoking one of the
```
IndexReader.getTermFreqVector
```
methods for every document and field of interest.  The three-argument form seems simpler, but either should be just fine.  For the three-argument form, you'd make a
```
TermVectorMapper
```
whose
```
map
```
method checks if
```
term
```
is in the map, associates it with
```
frequency
```
if not, or adds
```
frequency
```
to the existing value if so.  Be sure to use the same
```
TermVectorMapper
```
object across all of the calls to
```
getTermFreqVector
```
in this pass, rather than instantiating a new one for each document in the loop.  You can also speed things up quite a bit by overriding
```
isIgnoringPositions()
```
and
```
isIgnoringOffsets()
```
; your object should return
```
true
```
for both of those.  It looks like your
```
TermVectorMapper
```
might also be forced to define a
```
setExpectations
```
method, but that one doesn't need to do anything.
Once you've built your map, just sort the map items by descending frequency and read off however many top terms you like.  If you know in advance how many terms you want, you might prefer to do some kind of fancy heap-based algorithm to find the top
k
items in linear time instead of using an O(
n
log
n
) sort.  I imagine the plain old sort will be plenty fast in practice.  But it's up to you.
If you prefer, you can combine the first two stages by having your
```
HitCollector
```
invoke
```
getTermFreqVector
```
directly.  This should certainly produce equally correct results, and intuitively seems like it would be simpler and better, but the docs seem to warn that doing so is likely to be quite a bit slower than the two-pass approach (on same page as the HitCollector example above).  Or I could be misinterpreting their warning.  If you're feeling ambitious you could try it both ways, compare, and let us know.


q:
Would it be possible to execute a JSP page and capture its output outside of a web application?
Mode specifically, in my case there still exists a usual web application, but it loads JSP pages not from its classpath, but from an arbitrary source. It seems like I cannot simply  get RequestDispatcher and point it to a JSP file on disk.

[A]
Correct me if I'm wrong, but I think you mean you want to capture the HTML... not the JSP.  A JSP is processed (into a JAVA file) on a servlet-engine (Web app Server) and after the HTML is formatted and served up to the requestor via a Web server (not the same as a web APP server).  You can't get the RequestDispatcher to work on a straight JSP from disk because it hasn't been processed yet by the web app server.
Now, to capture the output of a JSP (in HTML) should be possible, but I've never done that before.  There may be some slick APIs that those out there more knowledgable than I can address, but HTTP is typically done on port 80, so I guess one could read/write to port 80 on a TCPIP socket.  There's probably some more things to do on top of that, but at least that's some point to start looking into.
Sorry I can't provide more details, but hell... it's all theory to me at this point.

s: huggingface

c: devops

d: intermediate


q:
I use public boolean mouseDown(Event ev, int x, int y) to detect a click of the mouse.

I can distinguish between the right mouse button (ev.metaDown() is true) and the left and middle.

How can i differentiate the left from the middle button?
Or if it is impossible with mouseDown, what should i use?

[A]
This might do it:
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/SwingUtilities.html#isMiddleMouseButton(java.awt.event.MouseEvent)
Haven't tried it myself.


q:
Is there an easy way of programmatically checking if a serial COM port is already open/being used?

Normally I would use:

try
{
    // open port
}
catch (Exception ex)
{
    // handle the exception
}

However, I would like to programatically check so I can attempt to use another COM port or some such.

[A]
I needed something similar some time ago, to search for a device.
I obtained a list of available COM ports and then simply iterated over them, if it didn't throw an exception i tried to communicate with the device. A bit rough but working.
```
```
var portNames = SerialPort.GetPortNames();

foreach(var port in portNames) {
    //Try for every portName and break on the first working
}
```
```


q: Where does Internet Explorer store the history data, i.e. the list of URL that have been visited? I am using Windows XP SP3 and IE7. Basically I would like to read the list of URL and make some statistics on how often what pages are visited.

[A]
Internet Explorer seems to keep its history in hidden directories under C:\Documents and Settings\USERNAME\Local Settings\History\History.IE5.  Note that some directories in this path are also marked hidden or system.  The history's format is opaque, but
there's code at CodeProject
that can decode the contents.  You can also find a list of typed URLs under HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs.
An easier alternative might be to setup an HTTP proxy between the IE and the internet, and then examine the proxy's log.


q:
I accidentally coded SELECT $FOO.. and got the error "Invalid pseudocolumn "$FOO".

I can't find any documentation for them.   Is it something I should know?

Edit: this is a MS SQL Server specific question.

[A]
A simple Google search brings up
this
from Oracle's reference:
A pseudocolumn behaves like a table
  column, but is not actually stored in
  the table. You can select from
  pseudocolumns, but you cannot insert,
  update, or delete their values.
I think that the error you got is simply because there is no column $FOO, so the query parser tests to see if there's a psuedocolumn named $FOO as a fallback. And since there is no pseudocolumn named "$FOO" (and there are no other fallback) you get the error "Invalid pseudocolumn $FOO". This is a guess, though. I'm no expert when it comes to databases.


q:
What to use for a medium to large python WSGI application, Apache + mod_wsgi or Nginx + mod_wsgi?

Which combination will need more memory and CPU time?

Which one is faster?

Which is known for being more stable than the other?

I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this?

Note: I didn't use any Python Web Framework, I just wrote the whole thing from scratch.

Note': Other suggestions are also welcome.

[A]
One thing that CherryPy's webserver has going for it is that it's a pure python webserver (AFAIK), which may or may not make deployment easier for you.  Plus, I could see the benefits of using it if you're just using a server for WSGI and static content.
(shameless plug warning:  I wrote the WSGI code that I'm about to mention)
Kamaelia
will have WSGI support coming in the next release.  The cool thing is that you'll likely be able to either use the pre-made one or build your own using the existing HTTP and WSGI code.
(end shameless plug)
With that said, given the current options, I would personally probably go with CherryPy because it seems to be the simplest to configure and I can understand python code moreso than I can understand C code.
You may do best to try each of them out and see what the pros and cons of each one are for your specific application though.


q: As the question states - is there a good tool out there which lists methods an unmanaged DLL exports? I would like it to list COM methods and interfaces too.

[A]
Take a look at
Dependency Walker
to get a list of unmanaged functions exported from a DLL.
You can't easily get a l list of COM classes exported from a DLL. What you'd have to do is something like to through the registry and find all objects that reference the DLL in question. DLLs advertise their classes via registration in the registry...


q:
I am taking my first steps programming in Lua and get this error when I run my script:

attempt to index upvalue 'base' (a function value)

It's probably due to something very basic that I haven't grasped yet, but I can't find any good information about it when googling. Could someone explain to me what it means?

[A]
In this case it looks
```
base
```
is a function, but you're trying to index it like a table (eg.
```
base[5]
```
or
```
base.somefield
```
).
The 'upvalue' part is just telling you what kind of variable
```
base
```
is, in this case an upvalue (aka external local variable).


q:
Does anybody know how to determine the location of a file that's in one of the folders specified by the PATH environmental variable other than doing a dir filename.exe /s from the root folder?

I know this is stretching the bounds of a programming question but this is useful for deployment-related issues, also I need to examine the dependencies of an executable. :-)

[A]
You can use the
```
where.exe
```
utility in the
```
C:\Windows\System32
```
directory.


q: I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity?

[A]
```
Pop()
```
for the last element ought to be O(1) since you only need to return the element referred to by the last element in the array and update the index of the last element.  I would expect
```
pop()
```
for an arbitrary element to be O(N) and require on average N/2 operations since you would need to move any elements beyond the element you are removing one position up in the array of pointers.


q:
I am trying to figure out Messagebox( ownerWindow, ... ).

Using reflector I see that the ownerWindow defaults to the ActiveWindow for the thread.

So the only time I need the ownerWindow parameter is to call Show from another thread.

However when I try this, I get a cross threading exception.

    private void button1_Click( object sender, EventArgs e ) {
        new Thread( () => MessageBox.Show( this, "Test" ) ).Start();
    }

So it looks like the only time I need the explicitly state the owner window, I cann't use it!

[A]
You will have to do a BeginInvoke to marshal the call to the UI thread.
The code below is a simple example how you can do it. I haven't compiled it, so there might be errors in it, but it might give you some pointers.
```
```
private delegate void ThreadExecuteDelegate(object args);

public void StartThread
{
   Thread thread = new Thread(new ParameterizedThreadStart(ThreadExecute));
   thread.Start((IWin32Window)this);
}

private void ThreadExecute(object args)
{
    if(this.InvokeRequired)
    {
        this.BeginInvoke(new ThreadExecuteDelegate(ThreadExecute), args);
        return;
    }

    IWin32Window window = (IWin32Window)args;
    MessageBox.Show(window, "Hello world");
}
```
```


q:
I have heard of desktop applications whose code has been open-sourced, but are there any websites whose code has been open-sourced? I don't think I have heard of any. If there are aren't any, are there any reasons why?

This will have the advantage of not having to wait for the web development team to include a new feature. Also, this would ensure that more eyes see the code, ensuring a lower bug count. Of course, hacking would be easy.

[A]
Pastebin:
http://pastebin.com/
The wiki behind Wikipedia et al:
http://www.mediawiki.org/wiki/MediaWiki
GrailsCrowd:
http://grailscrowd.com/
Slashcode [slashdot engine]:
http://www.slashcode.com/
The reason that not as many people do it is because it would be easy for someone to set up a complete clone of your website without making any useful changes. OK, that's strictly allowed with true 'open source' code, but it's not quite within the spirit of the thing (IMO) and if the site became even moderately popular there would be a
lot
of useless clones. The site would become essentially worthless.
Those are -websites- that are open source. There is a huge amount of web application software that is open source [some of it shitty]
WordPress
InkType
Joomla
osCommerce
ZenCart
Drupal


q:
Is it possible to copy a single file to multiple directories using the cp command ?

I tried the following , which did not work:

cp file1 /foo/ /bar/
cp file1 {/foo/,/bar}

I know it's possible using a for loop, or find. But is it possible using the gnu cp command?

[A]
No,
```
cp
```
can copy multiple sources but will only copy to a single destination. You need to arrange to invoke
```
cp
```
multiple times - once per destination - for what you want to do; using, as you say, a loop or some other tool.


q:
I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).

Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.

Thanks

[A]
I am not sure what your problem is, but perhaps your approach should be a little different. Try putting code into the iframe what would call functions of the parent. These functions would display the proper table:
```
```
<!-- in the main page --->
function showTable1() {}

<!-- in the iframe -->
window.onload = function () {
    parent.showTable1();
}
```
```
This would put a lot of control into your iframe, away from the main page.


q:
Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction.  There's no reason for my mock class to actually create and close threads.  But, to mock a class, I have inherit from it.  When I create a new instance of my mock class, the base classes constructor is called, creating the thread.  When my mock object is destroyed, the base classes destructor is called, attempting to close the thread.

How does one mock an RAII class without having to deal with the actual resource?

[A]
You instead make an interface that describes the type, and have both the real class and the mock class inherit from that. So if you had:
```
```
class RAIIClass {
 public:
  RAIIClass(Foo* f);
  ~RAIIClass();
  bool DoOperation();

 private:
  ...
};
```
```
You would make an interface like:
```
```
class MockableInterface {
 public:
  MockableInterface(Foo* f);
  virtual ~MockableInterface();
  virtual bool DoOperation() = 0;
};
```
```
And go from there.


q:
I have an XML file, which I open in F# like this:

let Bookmarks(xmlFile:string) =
    let xml = XDocument.Load(xmlFile)

Once I have the XDocument I need to navigate it using LINQ to XML and extract all specific tags. Part of my solution is:

let xname (tag:string) = XName.Get(tag)
let tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href")
                            attribute.Value
let Bookmarks(xmlFile:string) =
    let xml = XDocument.Load(xmlFile)
    xml.Elements <| xname "A" |> Seq.map(tagUrl)

How can I extract the specific tags from the XML file?

[A]
Caveat: I've never done linq-to-xml before, but looking through other posts on the topic, this snippet has some F# code that compiles and does
something
, and thus it may help you get started:
```
```
open System.IO
open System.Xml
open System.Xml.Linq

let xmlStr = @"<?xml version='1.0' encoding='UTF-8'?>
<doc>
    <blah>Blah</blah>

    <yadda>
        <blah>Blah</blah>

    </yadda>
</doc>"

let xns = XNamespace.op_Implicit ""
let a = xns + "a"
let reader = new StringReader(xmlStr)
let xdoc = XDocument.Load(reader)
let aElements = [for x in xdoc.Root.Elements() do
                 if x.Name = a then
                     yield x]
let href = xns + "href"
aElements |> List.iter (fun e -> printfn "%A" (e.Attribute(href)))
```
```


q: I'm writing a Rails application, but can't seem to find how to do relative time, i.e. if given a certain Time class, it can calculate "30 seconds ago" or "2 days ago" or if it's longer than a month "9/1/2008", etc.

[A]
You can use the arithmetic operators to do relative time.
```
```
Time.now - 2.days
```
```
Will give you 2 days ago.


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

[A] 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.


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

[A]
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.


q:
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:
 ...
}

[A]
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).


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

[A]
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


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

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

[A]
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.


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

[A]
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.


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

[A]
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>
```
```


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

[A]
```
#define TEST_FUN_NAME #FUNC_NAME
```
see
here


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

[A]
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).


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

[A]
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).


q:
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 :(

[A]
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
    }
});
```
```


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

[A]
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.


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

[A]
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.


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

[A]
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.


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

[A]
(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.


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

[A]
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.


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


q:
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');

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


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

[A]
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.


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

[A]
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


q:
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?).

[A]
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


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

[A]
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.


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

[A]
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.


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

[A]
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.


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

[A]
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.


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

[A]
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.


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

[A]
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);
...
```
```


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

[A]
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;
```


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

[A]
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.


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

[A]
(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.


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

[A]
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.


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

[A]
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?


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

[A]
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.


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

[A]
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 :)


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

[A]
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.


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

[A]
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.


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

[A]
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];
```
```


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

[A]
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.


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

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


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

[A]
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


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

[A]
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).


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

[A]
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()
```
```


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

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


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

[A]
```
```
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.


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

[A]
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.


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

[A]
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.


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

[A]
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;
```
```


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

[A]
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)
```
```


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

[A]
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


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

[A]
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.


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

[A]
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>
```
```


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

[A]
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.)


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

[A]
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.


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

[A]
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>
```
```


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

[A]
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.


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

[A]
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))
```
```


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

[A]
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.


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

[A]
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.


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

[A]
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;
}
```
```


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

[A]
```
```
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();
  });
}
```
```


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

[A]
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.


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

[A]
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.


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

[A]
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.


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

[A]
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.


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

[A]
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.


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

[A]
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


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

[A]
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.


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

[A]
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.


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

[A]
```
```
// 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();
```
```


q:
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!");
}

}

[A]
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.


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

[A]
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()) { ... }
```
```


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

[A]
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.


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

[A]
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.


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

[A]
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
```
```


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

[A]
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
```
```


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

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


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

[A]
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.


q:
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
        _______;
      }
   }
}

[A]
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.


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

[A]
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


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

[A]
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.


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

[A]
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.


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

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


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

[A]
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.