q:
I setup phpMyID on one of my machines, and I'm trying to get apache to redirect to HTTPS only when a password is being submitted.  I am doing this as my original setup of redirecting all openid traffic didn't work stackoverflow doesn't like my self signed certificate.  This is the new rule I've written, but its not working:

RewriteRule http://%{SERVER_NAME}/openid/index.php(\?.+)$ https://%{SERVER_NAME}/openid/index.php$1

[A]
You need to use a Cond to test for both port (http or httpd) and query string:
```
```
RewriteCond %{SERVER_PORT} 80
RewriteCond %{QUERY_STRING} (.+)
RewriteRule /openid/index.php https://%{SERVER_NAME}/openid/index.php?%1
```
```
if on .htaccess you must use instead
```
```
RewriteCond %{SERVER_PORT} 80
RewriteCond %{QUERY_STRING} (.+)
RewriteRule openid/index.php https://%{SERVER_NAME}/openid/index.php?%1
```
```


q: There are a lot of new features that came with the .Net Framework 3.5. Most of the posts and info on the subject list stuff about new 3.5 features and C# 3 changes at the same time. But C# 3 can be used without .Net 3.5. Does anyone know of a good post describing the changes to the language? (Besides the boring, explicit official specs at MSDN that is.)

[A]
Update: I can certainly understand.
Eric Lippert has some more indepth posts..
Check them out
.
I liked the series of posts by
scottgu
on the new language features..
Some more info here as well
http://www.danielmoth.com/Blog/2007/11/top-10-things-to-know-about-visual.html
esp the section on language features.

s: huggingface

c: devops

d: intermediate


q: How to post a username, password and multiple binary files from a single html form and process it using php? I'm not allowed to use ajax.

[A]
You should use the
```
$_FILES
```
superglobal and
```
move_uploaded_file()
```
function to see which files were uploaded successfully and move them to their final location in case they were.
The
```
$_POST
```
superglobal will contain the submitted username and password.


q: I'm looking for the most ideal data structure (for performance and ease of use) from which values can be retrieved by string key or index.  Dictionary doesn't work because you can't really retrieve by index.  Any ideas?

[A]
Hash based collections (Dictionary, Hashtable, HashSet) are out because you won't have an index, since you want an index, I'd use a nested generic:
```
```
List<KeyValuePair<K,V>>
```
```
Of course, you lose the O(1) Key lookup that you get with hashes.


q: Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.

[A]
Are homework problems allowed here?
This function does crude "base 5" math to generate a number between 0 and 6.
```
```
function rnd7() {
    do {
        r1 = rnd5() - 1;
        do {
            r2=rnd5() - 1;
        } while (r2 > 1);
        result = r2 * 5 + r1;
    } while (result > 6);
    return result + 1;
}
```
```


q:
I have a report in SSRS 2005 that's based on a query that's similar to this one:

SELECT * FROM MyTable (NOLOCK)
WHERE col1 = 'ABC'
AND col2 LIKE '%XYZ%'

I need to be able to dynamically include the AND part of the WHERE clause in the query based on whether the user has checked a checkbox. Basically, this is a dynamic SQL statement and that's the problem. I tried several approaches to no avail. Is this possible? Does SSRS 2005 supports dynamic SQL? Thanks!

[A]
Perhaps this would work for you:
```
```
if @checked = 1
    select * from mytable (nolock) where col = 'ABC'
else
    select * from mytable (nolock) where col = 'ABC' AND colw Like '%XYZ%'
```
```
I'm sorry I don't use SSRS much, but if you can get the value of the checkbox into the @checked parameter this should work.
Alternately you could use a CASE WHEN statement.


q:
So I am working on a project that uses a ASP.NET server and we have entities being passed over WCF from LINQ-to-Entity queries. I have already overcome the cyclic reference issue with WCF. Now that I am looking toward the next step, the Flex UI, I am wondering what things people have already faced either with dealing with WCF from Flex or using Entities with Flex (Entities from the entity framework)? And Flex suggestions, libraries, patterns and tips would help. Thanks.

Things that would help:

How to "persist" or dupe entities on the UI side.

Security, how to secure communication from the UI to the service.

How to generate/pass new entities from the UI to the service and have then interprete as .NET entities

[A]
You have several options for communicating between Flex application and your WCF service. Flex supports both SOAP web services and REST-like web services so you can choose which approach fits you best. When you receive data on the client, you will need to extract the entities from the response and build the UI accordingly. Similar with updating or creating new entities - you will need to construct a web service request from your user interface controls and send it over the wire.
Also look into AMF which is a binary format for communicating between Flex/Flash and a server. There are .NET implementations out there (AMF.NET for instance) so it may be possible to somehow make it work with WCF - you need to explore this area yourself, I have no direct experience here.


q: Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000.

[A]
If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer.
```
```
SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1
```
```
The newId() will generate a new GUID for you that you can use as your automatically generated id column.


q:
Does your software handle newline characters from other systems?

Linux/BSD    linefeed         ^J    10     x0A
Windows/IBM  return linefeed  ^M^J  13 10  x0D x0A
old Macs     return           ^M    13     x0D
others?

For reasons of insanity, I am going with using the Linux version of the newline character in my text files.  But, when I bring my text files over to say Windows, some programs do not play nicely with newline characters in my text.  How would you deal with this?

[A]
I suspect you will find that most modern Windows programs (with the notable exception of Notepad) handle newline-only files just fine. However, files generated with windows programs still tend to have crlf endings.
Most of the time, the line endings will automatically be handled in a platform-specific way by the runtime library. For example, a C program that opens a file with
```
fopen(..., "r")
```
will see the lines in a consistent way (linefeed only) on any platform regardless of the actual line endings.


q:
We have an existing WCF service that makes use of wsDualHttpBinding to enable callbacks to the client. I am considering moving it to netTcpBinding for better performance, but I'm quite wary of moving away from the IIS-hosted service (a "comfort zone" we currently enjoy) into having our own Windows service to host it. I was hoping we could still host this on IIS 7 but Win2K8 won't be reality for us for some time.

What things should I watch out for when creating our own Windows service to host our WCF service? Things like lifetime management and request throttling are features that come free with IIS hosting so I'd also like to know how we can effectively host our service on our own without the convenience of having IIS do the hard work for us. Thanks! :)

[A]
Hosting in a Windows Service Application (
http://msdn.microsoft.com/en-us/library/ms734781.aspx
) is a good start.
If you can host your service on Vista, you can also benefit from Windows Process Activation Service (WAS). WAS is a generalization of the IIS process activation, which can be used to activate processes over non-HTTP endpoints (TCP, Named Pipe, MSMQ). To learn more about WCF hosted in WAS, read
http://msdn.microsoft.com/en-us/library/ms733109.aspx
. To learn how to install and configure WAS, read
http://msdn.microsoft.com/en-us/library/ms731053.aspx
.


q: Using Ruby and Thin as a web service.  Apache is also loaded.  Can't access the web service because listing ports, such as :3000 or :6600, in the GET url is not allowed.  How is the port requirement removed?

[A]
Use Apache ProxyPass.
cd /etc/apache2/sites-enabled/
sudo vi 000-default
Edit Lines:

    ServerAdmin webmaster@localhost
    ProxyPass /breakfast
http://localhost:4567/breakfast
DocumentRoot /var/www
sudo /etc/init.d/apache2 restart


q:
In Java, there is a practice of declaring every variable (local or class), parameter final if they really are.

Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.

What are your thoughts on this and what do you follow?

[A]
I have never been in a situation where having a final keyword on a variable has stopped me from making a mistake, so for the moment I think it's a giant waste of time.
Unless there is a real reason for doing it (as in you want to make a specific point about that variable being final) I would rather not do it since I find it makes the code less readable.
If, however, you don't find it makes the code harder to read or longer to write then by all means go for it.
Edit:
As a clarification (and an attempt to win back down-votes), I'm not saying don't mark constants as final, I'm saying don't do stuff like:
```
```
public String doSomething() {
  final String first = someReallyComplicatedExpressionToGetTheString();
  final String second = anotherReallyComplicatedExpressionToGetAnother();

  return first+second;
}
```
```
It just makes code (in my opinion) harder to read.
It's also worth remembering that
all
final does is prevent you from reassigning a variable, it doesn't make it immutable or anything like that.


q:
In Vim editor I opted ]I on a function (in C++ code).
This presented a list, which says 'Press ENTER or type command to continue'.

Now to jump to an occurrence say 6, I type 6 - but this is not working.

What commands can I type in such a case, and how do I jump to Nth occurrence from this list?

Update:

Actually I tried :N (eg :6) - but the moment I type : Vim enters Insert mode, and the colon gets inserted in the code instead.

Update

Assuming :N approach is correct, still complete uninstall and install of Vim, without any configuration, too did not help - though now typing : does not switch Vim to insert mode.

[A]
It should present you a list like:
```
```
1:   345 my_func (int var)
2:  4523 my_func (int var)
3: 10032 my_func (3);
```
```
The second column is line numbers. Type :345 to jump to line 345.


q: I'm working on a django app right and I'm using cherrypy as the server. Cherrypy creates a new thread for every page view. I'd like to be able to access all of these threads (threads responsible for talking to django) from within any of them. More specifically I'd like to be able to access the thread_data for each of these threads from within any of them. Is this possible? If so, how do I do it?

[A]
My first response to a question like this isn't to tell you how to do it but to stress that you really should reconsider before moving forward with this. I normally shy away from threaded web-servers, in favor of multi-process or asynchronous solutions. Adding explicit inter-thread communication to the mix only increases those fears.
When a question like this is asked, there is a deeper goal. I suspect that what you think inter-thread communication would solve can actually be solved in some other, safer way.


q: I have an ASP.NET Datagrid with several text boxes and drop down boxes inside it. I want to read all the values in the grid using a JavaScript function. How do i go about it?

[A]
Easily done with jQuery. I don't recall what kind of markup the Datagrid creates but basically something like this will work in Jquery
```
```
$('#client_id_of_datagrid input, #client_id_of_datagrid select')
.each(function() {val = this.value; /* Do Stuff */})
```
```


q:
I am looking for all addresses related to:

3.x eclipse itself (milestones and/or integration builds)

3.x other components (GEF, GMF, EMF, ...)

In the spirit of answering my own question, I do have an answer for:

3.5 eclipse itself, with some details and caveats,

3.6 Helios, with the steps involved to follow the updates.

However, If you have further addresses, either for eclipse or other eclipse components, please publish them here.

[A]
Update September 2009
: see also
addresses for eclipse 3.6 Helios
For eclipse itself, the
eclipse wiki
3.5milestones
http://download.eclipse.org/eclipse/updates/3.5milestones
3.5-I-builds
http://download.eclipse.org/eclipse/updates/3.5-I-builds
However, the Milestone names are not there yet.
(For instance, the build number there is 20080807 is assumed to be 3.5M1)
The update site will be added as a location for builds in order to get published to automatically:
see bug
248509
Warning: the update process in itself might generate some freeze (see bug
234916
) which might be solved by using a local http client (bug
220240
).
Meaning you should first update your eclipse installation with the
ECF_Apache_Httpclient-Based_Provider update site
(
http://download.eclipse.org/technology/ecf/httpclientrepo
), then try the different update sites mentionned for eclipse components.
Update May 2009
The page "
compare package
" now provides all links to different released packages
(See links to the left of the page: Europa 3.3, Ganymede 3.4, Ganymede SR1, and Galileo 3.5Mx)
The
current available Galileo M6
lists packages built with M6 release. That address will soon be not valid since
Galileo M7 has just been published
(May, 2d 2009).
The new Galileo packages (M7) will then be at
this address
.


q:
Is it possible to call a COM API from Java (specifically the HP/Mercury Quality Center OTA API)? If so, what's the best way?

Is something like JACOB appropriate?

Code fragments would be helpful for the basics :-)

[A]
jacob : yes,
http://sourceforge.net/projects/jacob-project/
is an active project that will suite your purpose pretty well.
you can see multiple examples :
http://jacob-project.wiki.sourceforge.net/Event+Callbacks
but if you want something that is more tested and are willing to pay money, then go for
http://www.nevaobject.com/_docs/_java2com/java2com.htm
.


q:
After a bind a method to an event of a Tkinter element is there a way to get the method back?

>>> root = Tkinter.Tk()
>>> frame = Tkinter.Frame(root, width=100, height=100)
>>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed
>>> frame.pack()
>>> bound_event_method = frame.???

[A]
Doesn't appear to be... why not just save it yourself if you're going to need it, or use a non-anonymous function?
Also, your code doesn't work as written:
```
lambda
```
functions can only contain expressions, not statements, so
```
print
```
is a no-go (this will change in Python 3.0 when
```
print()
```
becomes a function).


q: Is there something like Python's getattr() in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.

[A]
Use reflection for this.
```
Type.GetProperty()
```
and
```
Type.GetProperties()
```
each return
```
PropertyInfo
```
instances, which can be used to read a property value on an object.
```
```
var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null)
```
```
```
Type.GetMethod()
```
and
```
Type.GetMethods()
```
each return
```
MethodInfo
```
instances, which can be used to execute a method on an object.
```
```
var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null);
```
```
If you don't necessarily know the type (which would be a little wierd if you new the property name), than you could do something like this as well.
```
```
var result = dt.GetType().GetProperty("Year").Invoke(dt, null);
```
```


q:
The questions says everything, take this example code:

<ul id="css-id">
    <li>
    <something:CustomControl ID="SomeThingElse" runat="server" />
    <something:OtherCustomControl runat="server" />
    </li>
</ul>

Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions?

[A]
You can catch all exception not handled elswhere in the Global.asax page / class.
Look at:
```
```
protected void Application_Error(Object sender, EventArgs e)
```
```
method.


q:
Scenario: C# apps uses SQL2000. It excecute 3 stored procs within a try catch in the app. In the catch the error is suppressed. Due to some legalities, the c# code cannot be changed and implemented.

Q: How do I trap the actual SQL error in the stored proc into a log file or other table? @@Error returns an error message to the app but when evaluated in query analyzer it is always 0 although the 'If @@Error <> 0' does fire. I try to store the @@Error number, but it is always 0.

Please help.

[A]
Haven't got an example to hand, but look at using
```
```
RAISERROR ... WITH LOG
```
```
see:
http://msdn.microsoft.com/en-us/library/aa238452(SQL.80).aspx
for more on this.
Or use:
```
```
xp_logevent {error_number, 'message'} [, 'severity']
```
```
to write to the event log.  More details at
http://msdn.microsoft.com/en-us/library/aa260695(SQL.80).aspx


q:
I have a Window where I have put a Frame. I would like to add a Page to the Frame when I click a button that is also on the Window but not in the Frame. There are several buttons in the Window and each click on a button should load a different Page in the Frame.

Since I'm a total newbie on this WPF stuff it's quite possible that this approach is not the best and I have thought about replacing the Frame with a Canvas and then make UserControls instead of Pages that will be added to the Canvas. I welcome any ideas and suggestions on how to best solve this.

I aiming for a functionality that is similar to the application Billy Hollis demonstrated in dnrtv episode 115. (http://dnrtv.com/default.aspx?showID=115).

[A]
the Frame class exposes a method named "Navigate" that takes the content you want to show in your frame as parameter.
try calling
```
```
myFrame.Navigate(myPageObject);
```
```
this should work


q: Is there a way in Delphi 7 to find out if a pop-up menu is visible (shown on the screen) or not, since it lacks a Visible property.

[A]
You could make your own flag by setting it in the OnPopup event. The problem is knowing when the popupmenu is closed.
Peter Below
has a solution for that.
But my I ask why you would want this? Maybe there is a better way to solve the underlying problem.


q:
Is there an app that can change the order of images inside an icon?

Thanks!

[A]
What you'll need to do that is a resource editor. A
google search
will reveal many free ones out there. The
restorator
is a great one, but not free and over-priced IMO.
Any decent resource editor will allow you to see icons in the exe or dll and save them or replace them. I don't know of any that will allow you to reorder them, but just about any out there would allow you to save the icons out and then replace them back in the exe/dll in whatever order you'd like.


q: how to send rich text message in system.net.mail need code for send a mail as html

[A]
```
```
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
mm.Body = "<html>...</html>";
mm.IsBodyHtml = true;
```
```


q: What essential things (functions, aliases, start up scripts) do you have in your profile?

[A]
```
```
##############################################################################
# Get an XPath Navigator object based on the input string containing xml
function get-xpn ($text) {
    $rdr = [System.IO.StringReader] $text
    $trdr = [system.io.textreader]$rdr
    $xpdoc = [System.XML.XPath.XPathDocument] $trdr
    $xpdoc.CreateNavigator()
}
```
```
Useful for working with xml, such as output from svn commands with --xml.


q:
I use several referenced tables with integer primary keys. Now I want to change ints to GUIDs leaving all references intact. What is the easiest way to do it?

Thank you!

Addition

I do understand the process in general, so I need more detailed advices, for example, how to fill new GUID column. Using default value newid() is correct, but what for already existing rows?

[A]
Firstly: Dear God why?!?!?
Secondly, you're going to have to add the GUID column to all your tables first, then populate them based on the int value.  Once done you can set the GUIDs to primary/foreign keys then drop the int columns.
To update the value you'd do something like
Set the new GUIDs in the primary key table
Run this:
.
```
```
UPDATE foreignTable f
SET f.guidCol = p.guidCol
FROM primaryTable p
WHERE p.intCol = f.intCol
```
```


q:
In the Flex framework a custom preloader can be used while the site is loading.

In the Adobe docs it specifies that 'the progress bar [preloader] is displayed if less than half of the application is downloaded after 700 milliseconds of downloading.'

However I ALWAYS want the preloader to appear instantly since I know that 95% of our users are first time visitors and the site is over 500kb. I dont want people to have to wait .7 seconds for the preloader animation to appear.

I would think in theory that it is possible to 'monkey patch' the framework to remove this .7 second limitation. I dont have time to figure out how, and I've never done it before.

Anybody help?

[A]
This is in mx.preloaders::DownloadProgressBar.as, line 1205 in the
```
showDisplayForDownloading
```
function.
Old school monkey-patching is out with AS3, but you can either edit the Flex source and compile yourself a new framework.swc (apparently a pain), or just include it in your source path (source paths override .swcs); or derive your own preloader class from DownloadProgressBar that just overrides
```
showDisplayForDownloading
```
and returns true.
You can find the framework source in '%PROGRAMFILES%\Adobe\Flex Builder 3[ Plug-in]\sdks\3.0.0\frameworks\projects\framework\src', then the package path. Change the sdk version if you are using 3.1, or whatever.


q:
Is it possible for a stand alone executable to generate a report and output it as PDF (or one of the other export options available from the report viewer) without displaying the ReportViewer control?

The report definition should be embedded in the executable and should not use the Reporting Services web service.

[A]
You don't have to show the control itself.
```
```
ReportViewer rv = new ReportViewer();
rv.LocalReport.ReportPath = "templatepath";
// or use file from resource with rv.LocalReport.ReportEmbeddedResource

// add parameters, datasource, etc.

Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;

byte[] bytes;
bytes = rv.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);

// save byte[] to file with FileStream or something else
```
```
However it can render only PDF and XLS (as ReportViewer control cannot export to Word and others as Reportig Service can).
I forgot to mention that the above code is C#, using .NET framework and ReportViewer control. Check out
GotReportViewer
for a quickstart.


q: Does anybody know a good tutorial about Squid plug-in development?

[A]
There is one in the squid documentation.  IIRC it's fairly straightforward - squid forks a process and passes data down a pipe to the process.  A somewhat out-of-date but still relevant programmer's guide can be found
Here
.


q:
I am trying to access a Windows Media Player library from ASP.NET.

The following code:

WMPLib.WindowsMediaPlayer mplayer = new WMPLib.WindowsMediaPlayer();

WMPLib.IWMPStringCollection list = mplayer.mediaCollection.getAttributeStringCollection("artist", "audio");

Returns an non-empty list when run using the VS2005 development web server but an empty list when using IIS.

Setting impersonation with:

System.Security.Principal.WindowsImpersonationContext impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();

Doesn't help. It seems that WMPLib still doesn't thinks its running as a user who has a library.

Is there a way to get around this?

[A]
Have you tried configuration via web.config in ASP.NET? When you're running in the VS2005 debugger, you're (probably) running code as yourself, but when under IIS you'll be running it as IUSR_
machinename
or another low-permission system account.
Try adding something like this to your web.config file:
```
```
<system.web>
<identity impersonate="true" userName="MYDOMAIN\myuser" password="p@ssw0rd" />
</system.web>
```
```
No idea whether this works with Media Player specifically, but it works for other identity/security related problems like this.


q: I have recently run across these terms few times but I am quite confused how they work and when they are usualy implemented?

[A]
Well, think of it this way.
If you use an array, a simple index-based data structure, and fill it up with random stuff, finding a particular entry gets to be a more and more expensive operation as you fill it with data, since you basically have to start searching from one end toward the other, until you find the one you want.
If you want to get faster access to data, you typicall resort to sorting the array and using a binary search. This, however, while increasing the speed of looking up an existing value, makes inserting new values slow, as you need to move existing elements around when you need to insert an element in the middle.
A hashtable, on the other hand, has an associated function that takes an entry, and reduces it to a number, a hash-key. This number is then used as an index into the array, and this is where you store the entry.
A hashtable revolves around an array, which initially starts out empty. Empty does not mean zero length, the array starts out with a size, but all the elements in the array contains nothing.
Each element has two properties, data, and a key that identifies the data. For instance, a list of zip-codes of the US would be a zip-code -> name type of association. The function reduces the key, but does not consider the data.
So when you insert something into the hashtable, the function reduces the key to a number, which is used as an index into this (empty) array, and this is where you store the data, both the key, and the associated data.
Then, later, you want to find a particular entry that you know the key for, so you run the key through the same function, get its hash-key, and goes to that particular place in the hashtable and retrieves the data there.
The theory goes that the function that reduces your key to a hash-key, that number, is computationally much cheaper than the linear search.
A typical hashtable does not have an infinite number of elements available for storage, so the number is typically reduced further down to an index which fits into the size of the array. One way to do this is to simply take the modulus of the index compared to the size of the array. For an array with a size of 10, index 0-9 will map directly to an index, and index 10-19 will map down to 0-9 again, and so on.
Some keys will be reduced to the same index as an existing entry in the hashtable. At this point the actual keys are compared directly, with all the rules associated with comparing the data types of the key (ie. normal string comparison for instance). If there is a complete match, you either disregard the new data (it already exists) or you overwrite (you replace the old data for that key), or you add it (multi-valued hashtable). If there is no match, which means that though the hash keys was identical, the actual keys were not, you typically find a new location to store that key+data in.
Collision resolution has many implementations, and the simplest one is to just go to the next empty element in the array. This simple solution has other problems though, so finding the right resolution algorithm is also a good excercise for hashtables.
Hashtables can also grow, if they fill up completely (or close to), and this is usually done by creating a new array of the new size, and calculating all the indexes once more, and placing the items into the new array in their new locations.
The function that reduces the key to a number does not produce a linear value, ie. "AAA" becomes 1, then "AAB" becomes 2, so the hashtable is not sorted by any typical value.
There is a good wikipedia article available on the subject as well,
here
.


q: I create a GUID (as a string) and get the hash of it. Can I consider this hash to be unique?

[A]
Not as reliably unique as the GUID itself, no.
Just to expand, you are reducing your uniqueness by a factor of 4, going from 16 bytes to 4 bytes of possible combinations.
As pointed out in the comments the hash size will make a difference. The 4 byte thing was an assumption, horrible at best I know, that it may be used in .NET, where the default hash size is 4 bytes (int). So you can replace what I said above with whatever byte size your hash may be.


q:
I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image.

Example:

<object id="img" data="image.svg" width="500" height="300"/>
<script>document.getElementById("img").addData([1,23,4]);</script>

Is it at all possible to call methods on the SVG document? If so, how do I declare the methods to expose in the SVG file, and how do I call them from the HTML document?

[A]
Solution:
in svg:
```
```
<script>document.method = function() {}</script>
```
```
in html (using prototype to add event listeners):
```
```
<script>$("img").observe("load", function() {$("img").contentDocument.method()});
```
```
You need to listen to the load event on the image. Once the image is loaded, you can use the
```
element.contentDocument
```
to access the document variable on the svg document. Any methods added to that, will be available.


q: The CSRF prevention built in to Rails is causing some problems for some automated load testing we are doing, and I want to turn it off for the duration of the process. How do I do this?

[A]
I love simple questions with clear answers.
```
```
#I go in application.rb
self.allow_forgery_protection = false
```
```
If you want to do this for testing only you can move that into one of the environment files (obviously, you'll be touching
```
Application
```
then rather than
```
self
```
).  You could also write something like:
```
```
#I still go in application.rb
self.allow_forgery_protection = false unless ENV["RAILS_ENV"] == "production"
```
```
See
here
for details.  (Continuing Rails' wonderful tradition of having documentation of core features in 2 year old blog posts, which were distilled from commit logs.)


q:
I would like to create a page where all images which reside on my website are listed with title and alternative representation.

I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract src, title and alt from this HTML:

<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny" />

I guess this should be done with some regex, but since the order of the tags may vary, and I need all of them, I don't really know how to parse this in an elegant way (I could do it the hard char by char way, but that's painful).

[A]
Just to give a small example of using PHP's XML functionality for the task:
```
```
$doc=new DOMDocument();
$doc->loadHTML("Test
");
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$images=$xml->xpath('//img');
foreach ($images as $img) {
    echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title'];
}
```
```
I did use the
```
DOMDocument::loadHTML()
```
method because this method can cope with HTML-syntax and does not force the input document to be XHTML. Strictly speaking the conversion to a
```
SimpleXMLElement
```
is not necessary - it just makes using xpath and the xpath results more simple.


q:
here is my directory structure.

/user/a
/user/b
/user/b

inside folder a,b,c there is a file person.java (it is the Same file, just a one line modification.

now, on my shell, im on my /user/ directory and i try to do

   javac */person.java

the shell returns the following error,

person.java:14: duplicate class: person

Is there anything to resolve this?

[A]
I think the problem here might be, that javac tries to compile everything in one go, which naturally results in duplicated class definitions.
A simple way to resolve this would be
```
find . -name '*.java' -exec javac {} \;
```
Edit:
Or to be more precise
```
find . -name 'person.java' -maxdepth 2 -exec javac {} \;
```


q:
I unpacked a zip-file delivery into a clearcase view. Now I want to add the complete file tree to the repository. The GUI only provides an "Add to source control ..." for individual files/directories. Do you know how to recursively add the whole tree?

(I'm on a Windows system, but have Cygwin installed.)

[A]
You have to use the commandline. The Context menu in Explorer doesnt do this recursively!
```
```
clearfsimport –recurse /usr/src/projectx /vobs/projectx/src
```
```


q:
Requirements:

free, preferably open-source

implemented in one of the .NET managed langs

Google found these:

A Generic, Reusable Diff
Algorithm on codeproject

An O(ND) Difference Algorithm for C#

Diff/Merge/Patch Library for C#/.NET by Joshua Tauberer

EDIT:

No apps please, only libraries.

[A]
I think the "Generic - Reusable Diff Algorithm in C#" on Codeproject is the best you can find as a .NET-Engine for diff/patch/merge. I made a project on my own with it and it fits my needs with most scenarios. There are one or two worst-case scencario when the algorithm made the patch-file larger than it have to be. But in most of the cases it works just fine for me (textfiles with a size of >30 MB).
I'm currently testing another Codeproject-Project you can find here:
http://www.codeproject.com/KB/applications/patch.aspx
It's using some DLLs from Microsoft for patching, so it looks interesting. But those DLLs are unmanaged and this project is only some sort of wrapper for it. But maybe it can help you
Edit:
Just found another project,
DiffPlex
:
http://diffplex.codeplex.com/
It's
a combination of a .NET Diffing Library with both a Silverlight and HTML diff viewer
. As stated
there
, DiffPlex is the library that CodePlex leverages to generate the diffs of files.


q: When I am unsure about some thing for a project, I usually use a small separate project and make it my playground for things need to be tested. How do you do that ?

[A] I do it the same way. A temporary project has some disadvantages... You have to setup a new project as soon as you want to test something else. Also I found playgrounds to be pretty good references. Often I remember that I tried something previously and then I can look into the old playground files and even change it to adapt to new requirements.


q:
I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running.

I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery?

<?php

echo( "We'll email you as soon as this is done." );

header( "Connection: Close" );

// do some stuff that will take a while

mail( 'dude@thatplace.com', "okay I'm done", 'Yup, all done.' );

?>

[A]
You could try to do multithreading.
you could whip up a script that makes a system call ( using
shell_exec
) that calls the php binary with the script to do your work as the parameter. But I don't think that is the most secure way. Maybe you can thighten stuff up by chrooting the php process and other stuff
Alternatively, there's a class at phpclasses that do that
http://www.phpclasses.org/browse/package/3953.html
. But I don't know the specifics of the implementation


q:
What happens if I use SHGetFolderPath api call in a 32 bit system with CSIDL_PROGRAM_FILESx86 folder id instead of the CSIDL_PROGRAM_FILES id?

Theoretically CSIDL_PROGRAM_FILESx86 should map to C:\program files (x86) in a 64 bit system but what does it map to in a 32 bit system where this path doesn't exist?

[A]
The different scenarios are described in
this article on MSDN
.
Scroll down to remarks, "FOLDERID_ProgramFiles"
```
```
The interpretation of certain KNOWNFOLDERID values depends on whether the folder is part of a 32-bit or 64-bit application and whether that application is running on a 32-bit or 64-bit operating system. If your application needs to distinguish between, for example, Program Files and Program Files (x86), you must use the right KNOWNFOLDERID for the situation.

The following tables summarize the KNOWNFOLDERID use in those cases.

FOLDERID_ProgramFiles
OS  Application KNOWNFOLDERID   Default Path    CSIDL Equivalent
32 bit  32 bit  FOLDERID_ProgramFiles   %SystemDrive%\Program Files CSIDL_PROGRAM_FILES
32 bit  32 bit  FOLDERID_ProgramFilesX86    %SystemDrive%\Program Files CSIDL_PROGRAM_FILESX86
32 bit  32 bit  FOLDERID_ProgramFilesX64 (undefined)    Not applicable  Not applicable
64 bit  64 bit  FOLDERID_ProgramFiles   %SystemDrive%\Program Files CSIDL_PROGRAM_FILES
64 bit  64 bit  FOLDERID_ProgramFilesX86    %SystemDrive%\Program Files (x86)   CSIDL_PROGRAM_FILESX86
64 bit  64 bit  FOLDERID_ProgramFilesX64    %SystemDrive%\Program Files None
64 bit  32 bit  FOLDERID_ProgramFiles   %SystemDrive%\Program Files (x86)   CSIDL_PROGRAM_FILES
64 bit  32 bit  FOLDERID_ProgramFilesX86    %SystemDrive%\Program Files (x86)   CSIDL_PROGRAM_FILESX86
64 bit  32 bit  FOLDERID_ProgramFilesX64    %SystemDrive%\Program Files None
```
```
Summary: It will point to %SystemDrive%\Program Files


q: We're considering writing the next version of out project in using .Net 3, but are wondering if we can take the hit on forcing end users to install the .net framework version 3.

[A] If you want to ensure you are only using .NET 2.0 compatible functionality then you should only use .NET 2.0 assemblies. Then you know your safe and sound.


q:
I have a HTML report, which needs to be printed landscape because of the many columns. It there a way to do this, without the user having to change the document settings?

And what are the options amongst browsers.

[A]
You can also use the non-standard IE-only css attribute
writing-mode
```
```
div.page    {
   writing-mode: tb-rl;
}
```
```


q:
From within my Java program I want to determine which .NET Framework is installed on the system. What is the best (and easiest) way to do this?

Answer Thanks scubabbl! It worked to check the directory System.getenv( "WINDIR" ) + "\\Microsoft.NET\\Framework" for its directories starting with the letter "v".

[A]
From what I understand, the actual file structure in c:\windows\Microsoft.Net\Framework has folders with versions of .Net installed. On my computer, I have folders up to v3.5, or
c:\windows\Microsoft.Net\Framework\v3.5.
There are lots of issues with this, including security issues though.
The second, and probably better answer would be to check the windows registry.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
The Version key will have the value you are looking for.
Edit: stackoverflow question regarding reading the registry with java.
read/write to Windows Registry using Java
This library
http://www.trustice.com/java/jnireg/
will allow you to read the registry.


q: Is it possible to send my own developed exceptions over Soap to a client using http.sys??

[A] Yes, you can throw your own exceptions. Any uncaught exception that does not derive from SoapException will be bottled up by the .NET framework into a SoapException. You can derive from SoapException if you want to control how certain parts of the SoapException are formed (for instance, the fault and detail portions).


q:
How does one handle a DateTime with a NOT NULL?

I want to do something like this:

SELECT * FROM someTable WHERE thisDateTime IS NOT NULL

But how?

[A]
erm it does work? I've just tested it?
```
```
/****** Object:  Table [dbo].[DateTest]    Script Date: 09/26/2008 10:44:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DateTest](
    [Date1] [datetime] NULL,
    [Date2] [datetime] NOT NULL
) ON [PRIMARY]

GO
Insert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')
Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')
Go
SELECT * FROM DateTest WHERE Date1 is not NULL
GO
SELECT * FROM DateTest WHERE Date2 is not NULL
```
```


q:
How would you go about producing reports by user selected date ranges in a rails app?  What are the best date range pickers?

edit in response to patrick : I am looking for a bit of both widget and active record advice but what I am really curious about is how to restfully display a date ranged list based on user selected dates.

[A]
Are we asking an interface question here (i.e. you want a widget) or an ActiveRecord question?
Date Picking Widgets
1)
Default Rails Solution
: See
```
date_select
```
documentation
here
.
2)
Use a plugin
: Why write code?  I personally like the
CalendarDateSelect
plugin, using a pair of the suckers when I need a range.
3)
Adapt a Javascript widget to Rails
: It is almost trivial to integrate something like the Yahoo UI library (YUI)
Calendar
, which is all Javascript, to Rails.  From the perspective of Rails its just another way to populate the
```
params[:start_date]
```
and
```
params[:end_date]
```
.  YUI Calendar has native support for ranges.
Getting the data from the Widgets
1)
Default Rails Solution
See
```
date_select
```
documentation
here
.
```
```
#an application helper method you'll find helpful
#credit to http://blog.zerosum.org/2007/5/9/deconstructing-date_select

# Reconstruct a date object from date_select helper form params
def build_date_from_params(field_name, params)
  Date.new(params["#{field_name.to_s}(1i)"].to_i,
       params["#{field_name.to_s}(2i)"].to_i,
       params["#{field_name.to_s}(3i)"].to_i)
end

#goes into view
<%= date_select "report", "start_date", ... %>
<%= date_select "report", "end_date", ... %>

#goes into controller -- add your own error handling/defaults, please!
report_start_date = build_date_from_params("start_date", params[:report])
report_end_date = build_date_from_params("end_date", params[:report])
```
```
2)
CalendarDateSelect
: Rather similar to the above, just with sexier visible UI.
3)
Adapt a Javascript widget
: Typically this means that some form element will have the date input as a string.  Great news for you, since Date.parse is some serious magic.  The params[:some_form_element_name] will be initialized by Rails for you.
```
```
#goes in controller.  Please handle errors yourself -- Javascript != trusted input.
report_start_date = Date.parse(params[:report_start_date])
```
```
Writing the call to ActiveRecord
Easy as pie.
```
```
#initialize start_date and end_date up here, by pulling from params probably
  @models = SomeModel.find(:all, :conditions => ['date >= ? and date <= ?',
    start_date, end_date])
  #do something with models
```
```


q:
How can I iterate over each file in a directory using a for loop?

And how could I tell if a certain entry is a directory or if it's just a file?

[A]
```
```
for %1 in (*.*) do echo %1
```
```
Try "HELP FOR" in cmd for a full guide
This is the guide for XP commands.
http://www.ss64.com/nt/


q:
I have mixed data i nvarchar column (words and numbers).
Which is fastest way to sort data in this column in Numeric Order.

Result example:

1

2

3

...

10

11

...

aaaa

aaab

b

ba

ba

...

[A]
Cast it.
```
```
SELECT * FROM foo ORDER BY CAST(somecolumn AS int);
```
```
Been a while since I've touched SQL Server, so my syntax might be entirely incorrect though :)


q:
My understanding of the MVC is as follows (incase it's horribly wrong, I am afterall new to it)

Models are the things that interface with the database

Views are the design/layout of the page

Controllers are where everything starts and are essentially the page logic

I'm using CodeIgniter but I would hazard a guess it's not just limited to that or possibly even just to PHP frameworks.

Where do I put global classes?

I may have a model for Products and I then run a query that collects 20 products from the database. Do I now make 20 models or should I have a separate class for it, if the latter, where do I put this class (other controllers will need to use it too)

[A]
In
CakePHP
there are 3 more "parts" :
Behaviors
Components
Helpers
Logic that are used by many models should be made as a behavior. I do not know if CodeIgniter have this logic or not, but if it doesnt, I would try to implement it as such. You can read about behaviors
here
.
(Components helps controller share logic and helpers help views in the same way).


q:
I know there's some JAVA_OPTS to set to remotely debug a Java program.

What are they and what do they mean ?

[A]
I have
this article
bookmarked on setting this up for Java 5 and below.
Basically
run it with
:
```
```
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044
```
```
For
Java 5 and above
, run it with:
```
```
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044
```
```
If you want Java to
wait for you to connect
before executing the application, replace
```
suspend=n
```
with
```
suspend=y
```
.


q:
In continuation of the my previous question, are the any good controls for text diffs visualization?

Something like StackOverflow's revision diff viewer but for WinForms or WPF

Requirements:

free, preferably open-source

based on WPF or WinForms

No apps please, only components.

I'm not interested in OSS diff tools

[A]
I never heard about a specific .NET component for diff visualization (it's kind a niche), but perhaps you could rely on advanced editor to build your own without too much trouble.
Syncfusion proposes a
complete component suite
dedicated to text/code edition, with a lot of built in features that you might find useful :
Line and selection background
Text highlighting
(colored underline, waveline, borders, strike, etc.)
Selection margin
Text selection
Syntax highlighting
Important note : it is
not
free.


q:
I didn't find an explicit answer to this question in the WiX Documentation (or Google, for that matter). Of course I could just write the appropriate registry keys in HKCR, but it makes me feel dirty and I'd expect this to be a standard task which should have a nice default solution.

For bonus points, I'd like to know how to make it "safe", i.e. don't overwrite existing registrations for the file type and remove the registration on uninstall only if it has been registered during installation and is unchanged.

[A]
"If your application handles its own file data type, you will need to register a file association for it. Put a ProgId inside your component. FileId should refer to the Id attribute of the File element describing the file meant to handle the files of this extension. Note the exclamation mark: it will return the short path of the file instead of the long one:"
```
```
<ProgId Id='AcmeFoobar.xyzfile' Description='Acme Foobar data file'>
  <Extension Id='xyz' ContentType='application/xyz'>
     <Verb Id='open' Sequence='10' Command='Open' Target='[!FileId]' Argument='"%1"' />
  </Extension>
</ProgId>
```
```
Reference:
https://www.firegiant.com/wix/tutorial/getting-started/beyond-files/


q:
I need to replace character (say) x with character (say) P in a string, but only if it is contained in a quoted substring.
An example makes it clearer:

axbx'cxdxe'fxgh'ixj'k  -> axbx'cPdPe'fxgh'iPj'k

Let's assume, for the sake of simplicity, that quotes always come in pairs.

The obvious way is to just process the string one character at a time (a simple state machine approach);

however, I'm wondering if regular expressions can be used to do all the processing in one go.

My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.

[A]
Not with plain regexp. Regular expressions have no "memory" so they cannot distinguish between being "inside" or "outside" quotes.
You need something more powerful, for example using
gema
it would be straighforward:
```
```
'<repl>'=$0
repl:x=P
```
```


q:
I need to convert HTML documents into valid XML, preferably XHTML. What's the best way to do this? Does anybody know a toolkit/library/sample/...whatever that helps me to get that task done?

To be a bit more clear here, my application has to do the conversion automatically at runtime. I don't look for a tool that helps me to move some pages to XHTML manually.

[A]
Convert from HTML to XML with HTML Tidy
Downloadable Binaries
JRoppert, For your need, i guess you might want to look at the
Sources
```
```
c:\temp>tidy -help
tidy [option...] [file...] [option...] [file...]
Utility to clean up and pretty print HTML/XHTML/XML
see http://tidy.sourceforge.net/

Options for HTML Tidy for Windows released on 14 February 2006:

File manipulation
-----------------
 -output <file>, -o  write output to the specified <file>
 <file>
 -config <file>      set configuration options from the specified <file>
 -file <file>, -f    write errors to the specified <file>
 <file>
 -modify, -m         modify the original input files

Processing directives
---------------------
 -indent, -i         indent element content
 -wrap <column>, -w  wrap text at the specified <column>. 0 is assumed if
 <column>            <column> is missing. When this option is omitted, the
                     default of the configuration option "wrap" applies.
 -upper, -u          force tags to upper case
 -clean, -c          replace FONT, NOBR and CENTER tags by CSS
 -bare, -b           strip out smart quotes and em dashes, etc.
 -numeric, -n        output numeric rather than named entities
 -errors, -e         only show errors
 -quiet, -q          suppress nonessential output
 -omit               omit optional end tags
 -xml                specify the input is well formed XML
 -asxml, -asxhtml    convert HTML to well formed XHTML
 -ashtml             force XHTML to well formed HTML
 -access <level>     do additional accessibility checks (<level> = 0, 1, 2, 3).
                     0 is assumed if <level> is missing.

Character encodings
-------------------
 -raw                output values above 127 without conversion to entities
 -ascii              use ISO-8859-1 for input, US-ASCII for output
 -latin0             use ISO-8859-15 for input, US-ASCII for output
 -latin1             use ISO-8859-1 for both input and output
 -iso2022            use ISO-2022 for both input and output
 -utf8               use UTF-8 for both input and output
 -mac                use MacRoman for input, US-ASCII for output
 -win1252            use Windows-1252 for input, US-ASCII for output
 -ibm858             use IBM-858 (CP850+Euro) for input, US-ASCII for output
 -utf16le            use UTF-16LE for both input and output
 -utf16be            use UTF-16BE for both input and output
 -utf16              use UTF-16 for both input and output
 -big5               use Big5 for both input and output
 -shiftjis           use Shift_JIS for both input and output
 -language <lang>    set the two-letter language code <lang> (for future use)

Miscellaneous
-------------
 -version, -v        show the version of Tidy
 -help, -h, -?       list the command line options
 -xml-help           list the command line options in XML format
 -help-config        list all configuration options
 -xml-config         list all configuration options in XML format
 -show-config        list the current configuration settings

Use --blah blarg for any configuration option "blah" with argument "blarg"

Input/Output default to stdin/stdout respectively
Single letter options apart from -f may be combined
as in:  tidy -f errs.txt -imu foo.html
For further info on HTML see http://www.w3.org/MarkUp
```
```


q: How do you compress Script Resources of ASP.Net? I saw a file there reached up to 255 KB! I tried finding solutions, but so far it only talks about scripting dynamic and static files. I checked the compression temp folder of IIS and found no compressed scripted resource there. That led me to the conclusion that these files are transferred over with high bandwidth.

[A]
If you're running IIS6 the guys at OrcsWeb have a nice wee article -
http://weblogs.asp.net/owscott/archive/2004/01/12/57916.aspx
We have customers running the port80 software because they get more control:
http://www.port80software.com/products/zipenable/
http://www.port80software.com/products/httpzip/


q:
I have successfully added a custom assembly, added it to the report using AddTrustedCodeModuleInCurrentAppDomain. I am executing the report in the current appdomain.

When I try to access SQL I get reporting services System.Data.SqlClient.SqlClientPermission failed. I have tried adding System.Data to the trusted assemblies as above but it doesn't help.

How do I ensure that this permission is present?


q:
I have a set of XSDs from which I generate data access classes, stored procedures and more.

What I don't have is a way to generate database table from these - is there a tool that will generate the DDL statements for me?

This is not the same as Create DB table from dataset table, as I do not have dataset tables, but XSDs.

[A]
Commercial Product:  Altova's
XML Spy
.
Note that there's no general solution to this.  An XSD can easily describe something that does not map to a relational database.
While you can try to "automate" this, your XSD's must be designed with a relational database in mind, or it won't work out well.
If the XSD's have features that don't map well you'll have to (1) design a mapping of some kind and then (2) write your own application to translate the XSD's into DDL.
Been there, done that.  Work for hire -- no open source available.


q: What is the right way of initializing a static map? Do we need a static function that will initialize it?

[A]
Using C++11:
```
```
#include <map>
using namespace std;

map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
```
```
Using
Boost.Assign
:
```
```
#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;

map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
```
```


q:
Are there good efficiency savings using Sql Server 2005 over Sql Server 2000?

Or does it just have more services etc

Has anyone seen their system work any quicker after making the upgrade?

[A]
The surrounding tools such as Analysis Services were substantially rewritten and can get you a variety of wins depending on your requirements.  However I don't see a lot of really fundamental changes from 2000 to 2005 in the core database engine.
There are some improvements that may get you better performance in certain situations.  SQL2005 has much better support for 64-bit architectures and better table partitioning than SQL2000 (you can partition a table as opposed to making partitioned views).  64-bit support is the most likely to give you a performance win on a large system as it allows you to set up much larger caches.
Apart from those features I don't believe that there is really a large difference.  There are probably minor performance tweaks.
The main reason to move from SQL2000 to SQL2005 will be when SQL2000 goes out of support.  If you have a running application on SQL2000 there are not a lot of compelling reasons to switch to 2005 while 2000 is still supported by Microsoft.
Data Warehouse systems will get quite a few wins from moving to SQL2005.  SSIS, SSAS2005 and SSRS2005 are much better than their SQL2000 counterparts.


q:
I need to enumerate all running applications. In particular, all top windows. And for every window I need to add my custom item to the system menu of that window.

How can I accomplish that in C++?

Update.

I would be more than happy to have a solution for Windows, MacOS, and Ubuntu (though, I'm not sure if MacOS and Ubuntu have such thing as 'system menu').

[A]
Once you have another window's top level handle, you may be able to call
GetMenu()
to retrieve the Window's system menu and then modify it, eg:
```
```
HMENU hMenu = GetMenu(hwndNext);
```
```


q:
Is there a way to create an html link using h:outputLink, other JSF tag or code to create a non faces request (HTTP GET) with request parameters?

For example I have the following navigation-rule

<navigation-rule>
    <navigation-case>
        <from-outcome>showMessage</from-outcome>
        <to-view-id>/showMessage.jsf</to-view-id>
        <redirect/>
    </navigation-case>
</navigation-rule>

In my page I would like to output the following html code:

<a href="/showMessage.jsf?msg=23">click to see the message</a>

I could just write the html code in the page, but I want to use the navigation rule in order to have all the urls defined in a single configurable file.

[A]
Have you considered a form?
```
```
<h:form>
    <h:commandLink value="Click to see the message" action="#{handler.outcome}" />
    <h:inputHidden id="msgId" value="#{bean.msgId}"/>
</h:form>
```
```


q:
I have a base class object array into which I have typecasted many different child class objects and am passing it to a sub vi. Is there any way by which I can find out the original type of the object of each individual elements in the array?

Thanks ...

[A]
NI has a good
overview of LVOOP
that is a must-read, since OO is implemented in a unique way for LabVIEW.
Have you tried the '
to more generic class
' and '
to more specific class
' functions, on the application control palette?


q:
Can I expose a class from another .net namespace as a class in my namespace?  I use a class - antlr.collections.AST - as the return type for a function belonging to a class in my namespace; as a result, the user has to have

using antlr.collections;
using myNamespace;

at the top of their files in order to use my function.  Can I make myNamespace.AST an alias for antlr.collections.AST, such that the user only has to have

using myNamespace;

at the top of their files?

[A]
How about deriving a class using the same name in the new namespace? I meant:
```
```
namespace MyForms {
    class Class1 : Some.Other.Namespace.Class1 {
        // ...
    }
}
```
```


q: How can i check in JavaScript if a variable is defined in a page? Suppose I want to check if a variable named "x" is defined in a page, if I do if(x != null), it gives me an error.

[A]
try to use
undefined
```
```
if (x !== undefined)
```
```
This is how checks for specific Browser features are done.


q:
Is there any way to automatically wrap comments at the 80-column boundary as you type them? ..or failing that, any way to display a faint line at the coulmn 80 boundary to make wrapping them manually a little easier?

Several other IDEs I use have one or other of those functions and it makes writing comments that wrap in sensible places much easier/quicker.

[Edit] If (like me) you're using Visual C++ Express, you need to change the VisualStudio part of the key into VCExpress - had me confused for a while there!

[A]
Take a look at the question here:
Hidden Features of Visual Studio (2005-2010)?
It shows how to do that:
"Under "HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor" Create a String called "Guides" with the value "RGB(255,0,0) 79" to have a red line at column 80 in the text editor."


q:
A client of mine uses Oracle 9i's utl_smtp to send mails out notifications to managers when their employees have made travel requests and they woul like quite a few changes made to the mailouts done.

We're having a lot of problems getting utl_smtp to talk to any smtp server on our network. We've even tried installing free smtp server on the oracle box but it will not spot the mail server running on port 25. The error code is ORA-29278.

So two questions really.

Does anyone have any experience setting up email using Oracle's utl_smtp utility and have any suggestions as to where we might be going wrong.

Does anyone know if it is possible to get utl_smtp to dump text emails to a directory much as you can do if you're using system.net.mail's specifiedpickupdirectory config setting. This would be by far the preferable option.

Thanks, Dan

[A]
Yes, we can telnet to the server.
```
```
-- ****** Object: Stored Procedure TRAVELADMIN_DEV.HTML_EMAIL Script Date: 22/08/2008 12:41:02 ******
CREATE PROCEDURE "HTML_EMAIL"  (
    p_to            in varchar2,
    p_cc            in varchar2,
    p_from          in varchar2,
    p_subject       in varchar2,
    p_text          in varchar2 default null,
    p_html          in varchar2 default null
    )
is
    l_boundary      varchar2(255) default 'a1b2c3d4e3f2g1';
    l_connection    utl_smtp.connection;
    l_body_html     clob := empty_clob;  --This LOB will be the email message
    l_offset        number;
    l_ammount       number;
    l_temp          varchar2(32767) default null;
    p_smtp_hostname varchar2(30):= 'rockies';
    p_smtp_portnum  varchar2(2) := '25';
begin
    l_connection := utl_smtp.open_connection( p_smtp_hostname, p_smtp_portnum );
    utl_smtp.helo( l_connection, p_smtp_hostname );
    utl_smtp.mail( l_connection, p_from );
    utl_smtp.rcpt( l_connection, p_to );
    l_temp := l_temp || 'MIME-Version: 1.0' ||  chr(13) || chr(10);
    l_temp := l_temp || 'To: ' || p_to || chr(13) || chr(10);
    IF ((p_cc <> NULL) OR (LENGTH(p_cc) > 0)) THEN
      l_temp := l_temp || 'Cc: ' || p_cc || chr(13) || chr(10);
      utl_smtp.rcpt( l_connection, p_cc );
    END IF;
    l_temp := l_temp || 'From: ' || p_from || chr(13) || chr(10);
    l_temp := l_temp || 'Subject: ' || p_subject || chr(13) || chr(10);
    l_temp := l_temp || 'Reply-To: ' || p_from ||  chr(13) || chr(10);
    l_temp := l_temp || 'Content-Type: multipart/alternative; boundary=' ||
                         chr(34) || l_boundary ||  chr(34) || chr(13) ||
                         chr(10);
    ----------------------------------------------------
    -- Write the headers
    dbms_lob.createtemporary( l_body_html, false, 10 );
    dbms_lob.write(l_body_html,length(l_temp),1,l_temp);
    ----------------------------------------------------
    -- Write the text boundary
    l_offset := dbms_lob.getlength(l_body_html) + 1;
    l_temp   := '--' || l_boundary || chr(13)||chr(10);
    l_temp   := l_temp || 'content-type: text/plain; charset=us-ascii' ||
                  chr(13) || chr(10) || chr(13) || chr(10);
    dbms_lob.write(l_body_html,length(l_temp),l_offset,l_temp);
    ----------------------------------------------------
    -- Write the plain text portion of the email
    l_offset := dbms_lob.getlength(l_body_html) + 1;
    dbms_lob.write(l_body_html,length(p_text),l_offset,p_text);
    ----------------------------------------------------
    -- Write the HTML boundary
    l_temp   := chr(13)||chr(10)||chr(13)||chr(10)||'--' || l_boundary ||
                    chr(13) || chr(10);
    l_temp   := l_temp || 'content-type: text/html;' ||
                   chr(13) || chr(10) || chr(13) || chr(10);
    l_offset := dbms_lob.getlength(l_body_html) + 1;
    dbms_lob.write(l_body_html,length(l_temp),l_offset,l_temp);
    ----------------------------------------------------
    -- Write the HTML portion of the message
    l_offset := dbms_lob.getlength(l_body_html) + 1;
    dbms_lob.write(l_body_html,length(p_html),l_offset,p_html);
    ----------------------------------------------------
    -- Write the final html boundary
    l_temp   := chr(13) || chr(10) || '--' ||  l_boundary || '--' || chr(13);
    l_offset := dbms_lob.getlength(l_body_html) + 1;
    dbms_lob.write(l_body_html,length(l_temp),l_offset,l_temp);
    ----------------------------------------------------
    -- Send the email in 1900 byte chunks to UTL_SMTP
    l_offset  := 1;
    l_ammount := 1900;
    utl_smtp.open_data(l_connection);
    while l_offset < dbms_lob.getlength(l_body_html) loop
        utl_smtp.write_data(l_connection,
                            dbms_lob.substr(l_body_html,l_ammount,l_offset));
        l_offset  := l_offset + l_ammount ;
        l_ammount := least(1900,dbms_lob.getlength(l_body_html) - l_ammount);
    end loop;
    utl_smtp.close_data(l_connection);
    utl_smtp.quit( l_connection );
    dbms_lob.freetemporary(l_body_html);
end;
```
```


q:
I'm trying to learn RegEx in Ruby, based on what I'm reading in "The Rails Way". But, even this simple example has me stumped. I can't tell if it is a typo or not:

text.gsub(/\s/, "-").gsub([^\W-], '').downcase

It seems to me that this would replace all spaces with -, then anywhere a string starts with a non letter or number followed by a dash, replace that with ''. But, using irb, it fails first on ^:

syntax error, unexpected '^', expecting ']'

If I take out the ^, it fails again on the W.

[A]
You forgot the slashes. It should be
```
/[^\W-]/
```


q:
I have a JComboBox and would like to have a separator in the list of elements. How do I do this in Java?

A sample scenario where this would come in handy is when making a combobox for font-family-selection; similar to the font-family-selection-control in Word and Excel. In this case I would like to show the most-used-fonts at the top, then a separator and finally all font-families below the separator in alphabetical order.

Can anyone help me with how to do this or is this not possible in Java?

[A]
You can use a custom
```
ListCellRenderer
```
which would draw the separator items differently. See
docs
and a small
tutorial
.


q:
If I am iterating over each file using :

@echo off

FOR %%f IN (*\*.\**) DO (
    echo %%f
)

how could I print the extension of each file? I tried assigning %%f to a temporary variable, and then using the code : echo "%t:~-3%" to print but with no success.

[A]
The FOR command has several built-in switches that allow you to modify file names. Try the following:
```
```
@echo off
for %%i in (*.*) do echo "%%~xi"
```
```
For further details, use
```
help for
```
to get a complete list of the modifiers - there are quite a few!


q:
Currently I use .Net WebBrowser.Document.Images() to do this. It requires the Webrowser to load the document. It's messy and takes up resources.

According to this question XPath is better than a regex at this.

Anyone know how to do this in C#?

[A]
If it's valid xhtml, you could do this:
```
```
XmlDocument doc = new XmlDocument();
doc.LoadXml(html);
XmlNodeList results = doc.SelectNodes("//img/@src");
```
```


q:
I would like to know when I should include external scripts or write them inline with the html code, in terms of performance and ease of maintenance.

What is the general practice for this?

Real-world-scenario - I have several html pages that need client-side form validation. For this I use a jQuery plugin that I include on all these pages. But the question is, do I:

write the bits of code that configure this script inline?

include all bits in one file that's share among all these html pages?

include each bit in a separate external file, one for each html page?

Thanks.

[A]
At the time this answer was originally posted (2008), the rule was simple: All script should be external. Both for maintenance and performance.
(Why performance? Because if the code is separate, it can easier be cached by browsers.)
JavaScript doesn't belong in the HTML code and if it contains special characters (such as
```
<
```
,
```
>
```
) it even creates problems.
Nowadays, web scalability has changed. Reducing the number of requests has become a valid consideration due to the latency of making multiple HTTP requests. This makes the answer more complex: in most cases, having JavaScript external is
still
recommended. But for certain cases, especially very small pieces of code, inlining them into the site’s HTML makes sense.


q:
Since I upgraded to Visual Studio 2008 from vs2005, I have found a very annoying behaviour when debugging large projects.  If I attempt to step into inline code, the debugger appears to lock up for tens of seconds.  Each time that I step inside such a function, there is a similar pause.  Has anyone experienced this and is anyone aware of a work around?

Postscript:

After learning that MS had a service pack for vs2008 and needing to get it because of other compiling issues, the problem that I was encountering with the debugger was resolved.

[A]
I get delays like this when debugging ASP.NET apps and it seems to happen when a symbol(pdb) file is getting accessed in the background. The larger the library, the longer the wait. My delay is at most about 10 seconds, but it does seem to happen with symbols that have already been accessed.
I do get a lot of 1-3 second waits when i try to step over items that cause VS to give me the "Step into Specific" message (
http://blogesh.wordpress.com/category/visual-studio-2008/
#3). Perhaps this may be causing a real blow up for you.


q:
I need to get UTF-8 working in my Java webapp (servlets + JSP, no framework used) to support äöå etc. for regular Finnish text and Cyrillic alphabets like ЦжФ for special cases.

My setup is the following:

Development environment: Windows XP

Production environment: Debian

Database used: MySQL 5.x

Users mainly use Firefox2 but also Opera 9.x, FF3, IE7 and Google Chrome are used to access the site.

How to achieve this?

[A]
Answering myself as the FAQ of this site encourages it. This works for me:
Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters.
To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following:
Configuring Tomcat's server.xml
It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters:
```
```
<Connector port="8080" maxHttpHeaderSize="8192"
 maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
 enableLookups="false" redirectPort="8443" acceptCount="100"
 connectionTimeout="20000" disableUploadTimeout="true"
 compression="on"
 compressionMinSize="128"
 noCompressionUserAgents="gozilla, traviata"
 compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript"
 URIEncoding="UTF-8"
/>
```
```
The key part being
URIEncoding="UTF-8"
in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded.
As a result, when the user writes the following to the address bar of the browser:
```
```
https://localhost:8443/ID/Users?action=search&name=*ж*
```
```
the character ж is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as
%D0%B6
.
POST request are not affected by this.
CharsetFilter
Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following:
```
```
package fi.foo.filters;

import javax.servlet.*;
import java.io.IOException;

public class CharsetFilter implements Filter {

    private String encoding;

    public void init(FilterConfig config) throws ServletException {
        encoding = config.getInitParameter("requestEncoding");
        if (encoding == null) encoding = "UTF-8";
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
            throws IOException, ServletException {
        // Respect the client-specified character encoding
        // (see HTTP specification section 3.4.1)
        if (null == request.getCharacterEncoding()) {
            request.setCharacterEncoding(encoding);
        }

        // Set the default response content type and encoding
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        next.doFilter(request, response);
    }

    public void destroy() {
    }
}
```
```
This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8.
The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application.
This filter has to be added to the
web.xml
or the deployment descriptor of the webapp:
```
```
<!--CharsetFilter start-->

  <filter>
    <filter-name>CharsetFilter</filter-name>
    <filter-class>fi.foo.filters.CharsetFilter</filter-class>
      <init-param>
        <param-name>requestEncoding</param-name>
        <param-value>UTF-8</param-value>
      </init-param>
  </filter>

  <filter-mapping>
    <filter-name>CharsetFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
```
```
The instructions for making this filter are found at the
tomcat wiki (
http://wiki.apache.org/tomcat/Tomcat/UTF-8
)
JSP page encoding
In your
web.xml
, add the following:
```
```
<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>
```
```
Alternatively, all JSP-pages of the webapp would need to have the following at the top of them:
```
```
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
```
```
If some kind of a layout with different JSP-fragments is used, then this is needed in
all
of them.
HTML-meta tags
JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding.
Then it's time to tell the browser in which encoding the html page is:
This is done with the following at the top of each xhtml page produced by the webapp:
```
```
<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi">
   <head>
   <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
   ...
```
```
JDBC-connection
When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in
context.xml
or wherever the JDBC connection is defiend as follows:
```
```
<Resource name="jdbc/AppDB"
        auth="Container"
        type="javax.sql.DataSource"
        maxActive="20" maxIdle="10" maxWait="10000"
        username="foo"
        password="bar"
        driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/      ID_development?useEncoding=true&characterEncoding=UTF-8"
    />
```
```
MySQL database and tables
The used database must use UTF-8 encoding. This is achieved by creating the database with the following:
```
```
CREATE DATABASE `ID_development`
   /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */;
```
```
Then, all of the tables need to be in UTF-8 also:
```
```
CREATE TABLE  `Users` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `name` varchar(30) collate utf8_swedish_ci default NULL
    PRIMARY KEY  (`id`)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC;
```
```
The key part being
CHARSET=utf8
.
MySQL server configuration
MySQL serveri has to be configured also. Typically this is done in Windows by modifying
my.ini
-file and in Linux by configuring
my.cnf
-file.
In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8.
```
```
[client]
   port=3306
   default-character-set=utf8

   [mysql]
   default-character-set=utf8
```
```
Mysql procedures and functions
These also need to have the character set defined. For example:
```
```
DELIMITER $$

   DROP FUNCTION IF EXISTS `pathToNode` $$
   CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8
   READS SQL DATA
   BEGIN

    DECLARE path VARCHAR(255) CHARACTER SET utf8;

   SET path = NULL;

   ...

   RETURN path;

   END $$

   DELIMITER ;
```
```
GET requests: latin1 and UTF-8
If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly:
```
```
https://localhost:8443/ID/Users?action=search&name=Petteri
   https://localhost:8443/ID/Users?action=search&name=ж
```
```
Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly.
The Cyrillic character ж is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as
%D0%B6
.
If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as
%D0%B6
.
The end result is that all users with name "Petteri" are found and also all users with the name "ж" are found.
But what about äåö?
HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following
```
```
https://localhost:8443/ID/Users?action=search&name=*Päivi*
```
```
in to the encoded version
```
```
https://localhost:8443/ID/Users?action=search&name=*P%E4ivi*
```
```
In latin1 the character
ä
is encoded as
%E4
.
Even though the page/request/everything is defined to use UTF-8
. The UTF-8 encoded version of ä is
%C3%A4
The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8.
Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8
Stuff to read
A very big thank you for the writers of the following for giving the answers for my problem:
http://tagunov.tripod.com/i18n/i18n.html
http://wiki.apache.org/tomcat/Tomcat/UTF-8
http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/
http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html
http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html
http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html
http://jeppesn.dk/utf-8.html
http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html
http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html
http://www.utf8-chartable.de/
Important Note
mysql
supports the
Basic Multilingual Plane
using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of
```
VARBINARY
```
column type or use the
```
utf8mb4
```
character set
(which requires MySQL 5.5.3 or later). Just be aware that using the
```
utf8
```
character set in MySQL won't work 100% of the time.
Tomcat with Apache
One more thing If you are using Apache + Tomcat + mod_JK connector then you also need to do following changes:
Add URIEncoding="UTF-8" into tomcat server.xml file for 8009 connector, it is used by mod_JK connector.
```
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>
```
Goto your apache folder i.e.
```
/etc/httpd/conf
```
and add
```
AddDefaultCharset utf-8
```
in
```
httpd.conf file
```
.
Note:
First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.


q: When I save a file with an .htm or .html extension, which one is correct and what is different?

[A]
Neither is wrong, it's a matter of preference. Traditionally, MS software uses
```
htm
```
by default, and *nix prefers
```
html
```
.
As oded pointed out below, the .htm tradition was carried over from win 3.xx, where file extensions were limited to three characters.


q:
Is there any way to find out if a file is a directory?

I have the file name in a variable. In Perl I can do this:

if(-d $var) { print "it's a directory\n" }

[A]
You can do it like so:
```
```
IF EXIST %VAR%\NUL ECHO It's a directory
```
```
However, this only works for directories without spaces in their names.  When you add quotes round the variable to handle the spaces it will stop working.  To handle directories with spaces, convert the filename to short 8.3 format as follows:
```
```
FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory
```
```
The
```
%%~si
```
converts
```
%%i
```
to an 8.3 filename.  To see all the other tricks you can perform with
```
FOR
```
variables enter
```
HELP FOR
```
at a command prompt.
(Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the
```
%%
```
with
```
%
```
in both places.)


q:
I just started learning JSP technology, and came across a wall.

How do you output HTML from a method in <%! ... %> JSP declaration block?

This doesn't work:

<%!
void someOutput() {
    out.println("Some Output");
}
%>
...
<% someOutput(); %>

Server says there's no “out”.

U: I do know how to rewrite code with this method returning a string, but is there a way to do this inside <%! void () {  } %> ? Though it may be non-optimal, it's still interesting.

[A]
You can't use the 'out' variable (nor any of the other "predeclared" scriptlet variables) inside directives.
The JSP page gets translated by your webserver into a Java servlet. Inside tomcats, for instance, everything inside scriptlets (which start "<%"), along with all the static HTML, gets translated into one giant Java method which writes your page, line by line, to a JspWriter instance called "out". This is why you can use the "out" parameter directly in scriptlets. Directives, on the other hand (which start with "<%!") get translated as separate Java methods.
As an example, a very simple page (let's call it foo.jsp):
```
```

        <%!
            String someOutput() {
                return "Some output";
            }
        %>
        <% someOutput(); %>

```
```
would end up looking something like this (with a lot of the detail ignored for clarity):
```
```
public final class foo_jsp
{
    // This is where the request comes in
    public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        // JspWriter instance is gotten from a factory
        // This is why you can use 'out' directly in scriptlets
        JspWriter out = ...;

        // Snip

        out.write("");
        out.write("");
        out.write("");
        out.write(someOutput()); // i.e. write the results of the method call
        out.write("");
        out.write("");
    }

    // Directive gets translated as separate method - note
    // there is no 'out' variable declared in scope
    private String someOutput()
    {
        return "Some output";
    }
}
```
```


q: Dear Stacktoverflow, can you show me an example of how to use a QScrollBar? Thanks.

[A] It will come down to you using the QScrollArea, it is a widget that implements showing something that is larger than the available space. You will not need to use QScrollBar directly. I don't have a PyQt example but there is a C++ example in the QT distribution it is called the "Image Viewer". The object hierarchy will still be the same


q:
I need to find out the file/directory name that a .lnk is pointing to using c#.

What is the simplest way to do this?

Thanks.

[A]
This may help:
http://www.neowin.net/forum/index.php?s=3ad7f1ffb995ba84999376f574e9250f&showtopic=658928&st=0&p=589667108&#entry589667108
In essence...
Add reference to Windows Script Host Object Model in COM tab of Add Reference dialogue.
```
```
IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();

IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(link);

Console.WriteLine(shortcut.TargetPath);
```
```


q:
I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:

my @search_results = `grep -i -l \"$string\" *.pdf`;

where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.

What can I do that's easiest?

Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.

Final solution using Adam Bellaire's suggestion below:

@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;

[A]
The PerlMonks thread
here
talks about this problem.
It seems that for your situation, it might be simplest to get
pdftotext
(the command line tool), then you can do something like:
```
```
my @search_results = `pdftotext myfile.pdf - | grep -i -l \"$string\"`;
```
```


q: I'd like my application to have a full-screen mode. What is the easiest way to do this, do I need a third party library for this or is there something in the JDK that already offers this?

[A]
Try the
Full-Screen Exclusive Mode API
.  It was introduced in the JDK in release 1.4.  Some of the features include:
Full-Screen Exclusive Mode
- allows you to suspend the windowing system so that drawing can be done directly to the screen.
Display Mode
- composed of the size (width and height of the monitor, in pixels), bit depth (number of bits per pixel), and refresh rate (how frequently the monitor updates itself).
Passive vs. Active Rendering
- painting while on the main event loop using the paint method is passive, whereas rendering in your own thread is active.
Double Buffering and Page Flipping
- Smoother drawing means better perceived performance and a much better user experience.
BufferStrategy and BufferCapabilities
- classes that allow you to draw to surfaces and components without having to know the number of buffers used or the technique used to display them, and help you determine the capabilities of your graphics device.
There are several full-screen exclusive mode examples in the linked tutorial.


q:
I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?

String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = new [UnknownClass]().format(unformattedXml);

Note: My input is a String. My output is a String.

(Basic) mock result:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <tag>
    <nested>hello</nested>
  </tag>
</root>

[A]
```
```
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
```
```
Note: Results may vary depending on the Java version. Search for workarounds specific to your platform.


q:
Does anyone know how to get the HTML out of an IFRAME I have tried several different ways:

document.getElementById('iframe01').contentDocument.body.innerHTML
document.frames['iframe01'].document.body.innerHTML
document.getElementById('iframe01').contentWindow.document.body.innerHTML

etc

[A]
If you take a look at
JQuery
, you can do something like:
```
```
<iframe id="my_iframe" ...></iframe>

$('#my_iframe').contents().find('html').html();
```
```
This is assuming that your iframe parent and child reside on the same server, due to the
Same Origin Policy
in Javascript.


q:
i have a number of jsp files under web-inf folder. Inside my web.xml i specify an errorppage for 404 amd 403 and java.lang.exception. Do i need to include a page directive for each of my jsp's or will they automatically get forwarded to the exception handling page because they are under web-inf?

If this is true does this mean that jsps which are not placed under web-inf do need to have the page directive added in order to forward them to the exception handling page?

thank you ,  im just trying to understand the consequences of web-inf

[A]
You just need to have whatever errorpage you would like to use in your app available with all the other jsps.  So in the following example you would just need to have the error pages in the root of the context path(where all of the other jsps are).  Anytime the webapp receives a 404 or 403 error it will try to display one of these pages. .
```
```
<error-page>
   <error-code>404</error-code>
   <location>/404Error.jsp</location>
</error-page>
<error-page>
   <error-code>403</error-code>
   <location>/403Error.jsp</location>
</error-page>
```
```
Just make sure 404Error.jsp and 403Error.jsp contain:
```
```
<%@ page isErrorPage="true" %>
```
```
If you are actually using jsps for error pages (instead of just static html)


q:
I am building a menu in HTML/CSS/JS and I need a way to prevent the text in the menu from being highlighted when double-clicked on. I need a way to pass the id's of several divs into a function and have highlighting turned off within them.

So when the user accidentally (or on purpose) double clicks on the menu, the menu shows its sub-elements but its text does not highlight.

There are a number of scripts out there floating around on the web, but many seem outdated. What's the best way?

[A]
You could:
Give it ("it" being your text) a onclick event
First click sets a variable to the current time
Second click checks to see if that variable is x time from the current, current time (so a double click over, for example, 500ms, doesn't register as a double click)
If it
is
a double click, do something to the page like adding hidden HTML, doing document.focus(). You'll have to experiment with these as some might cause unwanted scrolling.


q:
I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.

I want to call the help function on each one. In Ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in Python?

e.g. something like:

from somemodule import foo
print(foo.methods)  # or whatever is the correct method to call

[A]
You can use
```
dir(module)
```
to see all available methods/attributes.  Also check out PyDocs.


q: So many different controls to choose from!  What are best practices for determining which control to use for displaying data in ASP.NET?

[A]
It all comes down to how you want to layout your data.
If you need to control the layout (like tables versus CSS versus whatever), when use a Repeater or ListView. Between the two, ListView gives you a lot more events and built-in commands for editing, selecting, inserting. Additionally paging and grouping functionality. A Repeater is extremely simple, it repeats a layout with the data. Since you're building the layout by hand, Listview and Repeater require more code.
GridView is an updated DataGrid so there is hardly any reason to use DataGrid. GridView works really well when hooked up to standard ASP.NET datasources, but restricts you to a tabular layout with lots of layout rules. GridView requires less code since you're using a built-in layout.


q:
Or do you populate your form controls manually by a method?

Is either considered a best practice?


q:
I've added cookie support to SOAPpy by overriding HTTPTransport.  I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service.  Without these cookies, the server will think it is an unauthorized request and it will fail.

How can I add cookies from a Python CookieJar to ZSI requests?

[A]
If you read the
_Binding class in client.py of ZSI
you can see that it has a variable cookies, which is an instance of
Cookie.SimpleCookie
. Following the
ZSI example
and the
Cookie example
that is how it should work:
```
```
b = Binding(url='/cgi-bin/simple-test', tracefile=fp)
b.cookies['foo'] = 'bar'
```
```


q:
The most egregiously redundant code construct I often see involves using the code sequence

if (condition)
    return true;
else
    return false;

instead of simply writing

return (condition);

I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java.  What other such constructs would you flag in a code review?

[A]
Returning uselessly at the end:
```
```
// stuff
   return;
}
```
```


q:
When you are learning a new language, what is there a particularly good/effective exercise to help get the hang of it? And why?

EDIT:
Preferably looking for things that are more complicated that 'Hello World'.

[A]
'hello world!'
I really do think this a good place to start. Its basic and only takes a few seconds but you make sure your compiler is running and you have everything in place.  Once you have that done you can keep going. Add a variable, print to database, print to file.  Make sure you know how to leave comments.  This could all take a mater of 5 minutes. But its important stuff.


q:
How to get the relative path in t sql? Take for example a .sql file is located in the folder D:\temp, I want to get path of the file hello.txt in the folder  D:\temp\App_Data. How to use the relative path reference?

Let's say I am executing the sql file inside the SQL server management studio.

[A]
The .sql file is just.... a file.  It doesn't have any sense of its own location.  It's the thing that excutes it (which you didn't specify) that would have a sense of its location, the file's location.
I notice that you mentioned an App_Data folder, so I guess that ASP.NET is involved.  If you want to use relative paths in your web app, see MapPath
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx


q:
what is an efficient way to get a certain time for the next day in Java?
Let's say I want the long for tomorrow 03:30:00.
Setting Calendar fields and Date formatting are obvious.
Better or smarter ideas, thanks for sharing them!

Okami

[A]
I'm curious to hear what other people have to say about this one. My own experience is that taking shortcuts (i.e., "better or smarter ideas") with
```
Date
```
s almost always lands you in trouble. Heck, just using
```
java.util.Date
```
is asking for trouble.
Added: Many have recommended
Joda Time
in other Date-related threads.


q: How to set all the values in a std::map to the same value, without using a loop iterating over each value?

[A]
Using a loop
is
by far the simplest method. In fact, it’s a one-liner:
[C++17]
```
```
for (auto& [_, v] : mymap) v = value;
```
```
Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use
```
std::fill
```
.
To use them anyway (pre-C++20), we need to write adapters — in the case of
```
std::fill
```
, an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do
not
advise using it as-is. Use a library (such as
Boost.Iterator
) for a more general, production-strength implementation.
```
```
template <typename M>
struct value_iter : std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type> {
    using base_type = std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type>;
    using underlying = typename M::iterator;
    using typename base_type::value_type;
    using typename base_type::reference;

    value_iter(underlying i) : i(i) {}

    value_iter& operator++() {
        ++i;
        return *this;
    }

    value_iter operator++(int) {
        auto copy = *this;
        i++;
        return copy;
    }

    reference operator*() { return i->second; }

    bool operator ==(value_iter other) const { return i == other.i; }
    bool operator !=(value_iter other) const { return i != other.i; }

private:
    underlying i;
};

template <typename M>
auto value_begin(M& map) { return value_iter<M>(map.begin()); }

template <typename M>
auto value_end(M& map) { return value_iter<M>(map.end()); }
```
```
With this, we can use
```
std::fill
```
:
```
```
std::fill(value_begin(mymap), value_end(mymap), value);
```
```


q: In a user defined wizard page, is there a way to capture change or focus events of the controls? I want to provide an immediate feedback on user input in some dropdowns (e.g. a message box)

[A]
Since the scripting in innosetup is loosely based on Delphi, the controls should have some events like
```
OnEnter
```
(= control got focus) and
```
OnExit
```
(= control lost focus).  You can assign procedures to these events, something like this:
    ComboBox.OnExit := ComboBoxExit;
```
```
procedure ComboBoxExit(Sender: TObject);
begin

end;
```
```
I don't have access to Innosetup right now, so you will need to lookup the available events and parameters for the procedures.


q:
I mean, how does Java decide which protocols are available? I run some code from inside Eclipse, and it works just fine. Then I run the same code from outside Eclipse, and I get "unknown protocol" MalformedURLException. Probably it has to do with the code base, or something? Any hints would be helpful.

Thanks!

[A]
The work of resolving the protocol is done by the
```
URLStreamHandler
```
, which are stored in
```
URL.handlers
```
by protocol in lowercase. The handler, in turn, is created by the
```
URLStreamHandlerFactory
```
at
```
URL.factory
```
. Maybe eclipse is monkeying with that?
Some of the
URL constructors
take stream handlers and you can set the factory with
URL.setURLStreamHandlerFactory
.
Here's a web post about
developing protocol handlers
.


q:
I've worked on a few projects managed through the use of a Gantt chart.  Some of these have has a massive number of tasks and the project manager spends all their time wrestling with MS Project instead of making good choices.

I can see the point if there are a number of separate teams working towards something (e.g. legal, IT, marketing) to manage a project overall.

Has anyone participated in a software development project that has used a Gantt chart with any success?

[A]
A Gantt chart is only useful if it has sufficient details for a project manager to see what is the status of the project, and to have dependencies and resources properly accounted for.
You can always stick several sheets together with sticky tape.
The discipline of analyzing the project - breaking it down into phases, steps, deliverables,  determining the resource requirements is probably even more important than printing out a pretty chart.
Many of my non-trivial development projects have benefited from the sensible use of project planning tools.


q: Should I stick with Sun's Java code conventions for PHP code?

[A]
For PHP, i'd suggest to follow
Zends suggestions
As you might know,
Zend is the most widely used framework!