Question:
here is the input  i am getting from my flash file

process.php?Q2=898&Aa=Grade1&Tim=0%3A0%3A12&Q1=908&Bb=lkj&Q4=jhj&Q3=08&Cc=North%20America&Q0=1

and in php i use this code
foreach ($_GET as $field => $label)
{
    $datarray[]=$_GET[$field];

echo  "$field :";
echo $_GET[$field];;
echo "<br>";

i get this out put

Q2 :898
Aa :Grade1
Tim :0:0:12
Q1 :908
Bb :lkj
Q4 :jhj
Q3 :08
Cc :North America
Q0 :1

now my question is how do i sort it alphabaticaly so it should look like this
Aa :Grade1
Bb :lkj
Cc :North America
Q0 :1
Q1 :908

and so on....before i can insert it into the DB

Answer:
```
```
ksort($_GET);
```
```
This should
ksort
the
```
$_GET
```
array by it's keys.
krsort
for reverse order.


Question:
How do you tell if a function in JavaScript is defined?

I want to do something like this

function something_cool(text, callback) {
    alert(text);
    if( callback != null ) callback();
}

But it gets me a

callback is not a function

error when callback is not defined.

Answer:
```
```
typeof callback === "function"
```
```


Question:
I've got just one page that I want to force to be accessed as an HTTPS page (PHP on Apache). How do I do this without making the whole directory require HTTPS? Or, if you submit a form to an HTTPS page from an HTTP page, does it send it by HTTPS instead of HTTP?

Here is my example:

http://www.example.com/some-page.php

I want it to only be accessed through:

https://www.example.com/some-page.php

Sure, I can put all of the links to this page pointed at the HTTPS version, but that doesn't stop some fool from accessing it through HTTP on purpose...

One thing I thought was putting a redirect in the header of the PHP file to check to be sure that they are accessing the HTTPS version:

if($_SERVER["SCRIPT_URI"] == "http://www.example.com/some-page.php"){
  header('Location: https://www.example.com/some-page.php');
}

But that can't be the right way, can it?

Answer:
You could do it with a  directive and mod_rewrite on Apache:
```
```
<Location /buyCrap.php>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</Location>
```
```
You could make the Location smarter over time using
regular expressions
if you want.


Question:
Currently I'm doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(), execute() and cleanup() functions. But they are not mandatory. I'd like to test if they are or are not defined.

I did this previously by greping and seding the source, but it seemed wrong. Is there a more elegant way to do this?

Edit: The following sniplet works like a charm:

fn_exists()
{
    LC_ALL=C type $1 | grep -q 'shell function'
}

Answer:
Like this:
```
[[ $(type -t foo) == function ]] && echo "Foo exists"
```
The built-in
```
type
```
command will tell you whether something is a function, built-in function, external command, or just not defined.
Additional examples:
```
```
$ LC_ALL=C type foo
bash: type: foo: not found

$ LC_ALL=C type ls
ls is aliased to `ls --color=auto'

$ which type

$ LC_ALL=C type type
type is a shell builtin

$ LC_ALL=C type -t rvm
function

$ if [ -n "$(LC_ALL=C type -t rvm)" ] && [ "$(LC_ALL=C type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi
rvm is a function
```
```


Question:
I'm trying to determine if there's a way in Visual Basic 2008 (Express edition if that matters) to do inline collection initialization, a la JavaScript or Python:

Dim oMapping As Dictionary(Of Integer, String) = {{1,"First"}, {2, "Second"}}

I know Visual Basic 2008 supports array initialization like this, but I can't seem to get it to work for collections... Do I have the syntax wrong, or is it just not implemented?

Answer:
Visual Basic 9.0
doesn't support this yet. However,
Visual Basic 10.0
will
.


Question:
I have an old .dot file with a few dozen styles in it.

I need to place them into another .dot file  that I received.  Is there a better way to get them in there than manually recreating each style?

Answer:
There is a 'Style Organizer' tool within Word which will let you copy styles from one document to another if they are both open at once.
In Word 2007:
Open the styles dialog (Home tab -> Styles -> Bottom Right button).
Click the 'manage styles' button.
Click 'Import/Export...'
I can't remember what the option is in Word 2003. I think it was Tools -> Style Organizer or similar.


Question: For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo.  I'm using Oracle 10G.

Answer:
This should work (or something close):
```
```
select table_name
from all_constraints
where constraint_type='R'
and r_constraint_name in
  (select constraint_name
  from all_constraints
  where constraint_type in ('P','U')
  and table_name='<your table here>');
```
```


Question:
How do I enumerate the properties of a JavaScript object?

I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.

Answer:
Simple enough:
```
```
for(var propertyName in myObject) {
   // propertyName is what you want
   // you can get the value like this: myObject[propertyName]
}
```
```
Now, you will not get private variables this way because they are not available.
EDIT:
@bitwiseplatypus
is correct that unless you use the
```
hasOwnProperty()
```
method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.
Now, that said,
```
hasOwnProperty()
```
is
useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.
EDIT 2:
@bitwiseplatypus
brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use
```
hasOwnProperty()
```
. Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via
```
jQuery.extend
```
and
```
jQuery.fn.extend
```
).


Question:
I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with  a clean install of Windows, without actually going on the net.  Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it.

I want my program to download the apps to program files\any name here\

So basically I need a function that checks if a folder exists, and if it doesn't it creates it.

Answer:
Try this:
```
Directory.Exists(TheFolderName)
```
and
```
Directory.CreateDirectory(TheFolderName)
```
(You may need:
```
Imports System.IO
```
)


Question:
How do i measure how long a client has to wait for a request.

On the server side it is easy, through a filter for example.
But if we want to take into accout the total time including latency and data transfer, it gets diffcult.

is it possible to access the underlying socket to see when the request is finished?
or is it neccessary to do some javascript tricks? maybe through clock synchronisation between browser and server? are there any premade javascripts for this task?

Answer:
You could set a 0 byte socket send buffer  (and I don't exactly recommend this) so that when your blocking call to HttpResponse.send() you have a closer idea as to when the last byte left, but travel time is not included.
Ekk
--I feel queasy for even mentioning it.  You can do this in Tomcat with connector specific settings. (
Tomcat 6 Connector documentation
)
Or you could come up with some sort of javascript time stamp approach, but I would not expect to set the client clock.  Multiple calls to the web server would have to be made.
timestamp query
the real request
reporting the data
And this approach would cover latency, although you still have have some jitter variance.
Hmmm...interesting problem you have there.  :)


Question:
If you are using HAML and SASS in your Rails application, then any templates you define in public/stylesheet/*.sass will be compiled into *.css stylesheets. From your code, you use stylesheet_link_tag to pull in the asset by name without having to worry about the extension.

Many people dislike storing generated code or compiled code in version control, and it also stands to reason that the public/ directory shouldn't contain elements that you don't send to the browser.

What is the best pattern to follow when laying out SASS resources in your Rails project?

Answer:
If I can manage it, I like to store all of my styles in SASS templates when I choose HAML/SASS for a project, and I'll remove application.css and scaffold.css. Then I will put SASS in public/stylesheets/sass, and add /public/stylesheets/*.css to .gitignore.
If I have to work with a combination of SASS and CSS based assets, it's a little more complicated. The simplest way of handling this is to have an output subdirectory for generated CSS within the stylesheets directory, then exclude that subdirectory in .gitignore. Then, in your views you have to know which styling type you're using (SASS or CSS) by virtue of having to select the public/stylesheets/foo stylesheet or the public/stylesheets/sass-out/foo stylesheet.
If you have to go the second route, build a helper to abstract away the sass-out subdirectory.


Question: I'm wondering the best way to start a pthread that is a member of a C++ class? My own approach follows as an answer...

Answer: I usually use a static member function of the class, and use a pointer to the class as the void * parameter.  That function can then either perform thread processing, or call another non-static member function with the class reference.  That function can then reference all class members without awkward syntax.


Question:
I have a WinForms application with a DataGridView control and a column of DataGridViewButtonCell cells within that. When I click on one of these buttons, it starts a background task, and I'd like to disable the buttons until that task completes.

I can disable the DataGridView control, but it gives no visual indication that the buttons are disabled. I want the user to see that the buttons are disabled, and to notice that the task has finished when the buttons are enabled again.

Bonus points for a method that allows me to disable the buttons individually, so I can leave one of the buttons enabled while the task runs. (Note that I can't actually give out bonus points.)

Answer:
Here's the best solution I've found so far. This
MSDN article
gives the source code for a cell class that adds an Enabled property.
It works reasonably well, but there are two gotchas:
You have to invalidate the grid after setting the Enabled property on any cells. It shows that in the sample code, but I missed it.
It's only a visual change, setting the Enabled property doesn't actually enable or disable the button. The user can still click on it. I could check the enabled property before executing the click event, but it also seemed to be messing up the appearance when the user clicked on it. Instead, I just disabled the entire grid. That works alright for me, but I'd prefer a method that allows me to disable some buttons without disabling the entire grid.
There's a similar sample in the
DataGridView FAQ
.


Question:
I can make a DAO recordset in VB6/Access do anything - add data, clean data, move data, get data dressed in the morning and take it to school. But I don't even know where to start in .NET.

I'm not having any problems retrieving data from the database, but what do real people do when they need to edit data and put it back?

What's the easiest and most direct way to edit, update and append data into related tables in .NET and SQL Server?

Answer:
Look in the enclosing directories. They need to be at least mode 711. (
```
drwx--x--x
```
)
Also, look in
```
/var/log/apache2/error_log
```
(Or whatever the concatenation of
```
ServerRoot
```
and
```
ErrorLog
```
is from the
```
httpd.conf
```
) for a possibly more-detailed error message.
Finally, ensure you restart apache after messing with
```
httpd.conf
```
.


Question: I need to get the default printer name. I'll be using C# but I suspect this is more of a framework question and isn't language specific.

Answer:
The easiest way I found is to create a new
```
PrinterSettings
```
object.  It starts with all default values, so you can check its
Name
property to get the name of the default printer.
```
PrinterSettings
```
is in System.Drawing.dll in the namespace
```
System.Drawing.Printing
```
.
```
```
PrinterSettings settings = new PrinterSettings();
Console.WriteLine(settings.PrinterName);
```
```
Alternatively, you could maybe use the static
```
PrinterSettings.InstalledPrinters
```
method to get a list of all printer names, then set the
PrinterName
property and check the
IsDefaultPrinter
.  I haven't tried this, but the documentation seems to suggest it won't work.  Apparently
IsDefaultPrinter
is only true when
PrinterName
is not explicitly set.


Question: Polyglot, or multiple language, solutions allow you to apply languages to problems which they are best suited for.  Yet, at least in my experience, software shops tend to want to apply a "super" language to all aspects of the problem they are trying to solve.  Sticking with that language come "hell or high water" even if another language is available which solves the problem simply and naturally. Why do you or do you not implement using polyglot solutions?

Answer:
One issue that I've run into is that Visual Studio doesn't allow multiple languages to be mixed in a single project, forcing you to abstract things out into separate DLLs for each language, which isn't necessarily ideal.
I suspect the main reason, however, is the perception that switching back and forth between many different languages leads to programmer inefficiency.  There is some truth to this, I switch constantly between JavaScript, C#, VBScript, and VB.NET and there is a bit of lost time as I switch from one language to another, as I mix my syntax a bit.
Still, there is definitely room for more "polyglot" solutions particularly that extend beyond using JavaScript and whatever back-end programming language.


Question:
Reading through the Flickr API documentation it keeps stating I require an API key to use their REST protocols. I am only building a photo viewer, gathering information available from Flickr's public photo feed (For instance, I am not planning on writing an upload script, where a API key would be required). Is there any added functionality I can get from getting a Key?

Update I answered the question below

Answer:
The Flickr API is very nice and easy to use and will be much easier than scraping the feed yourself.
Getting a key takes about 2 minutes - you fill in a form on the website and then email it to you.


Question:
Does anyone know of any 'standard' way to interface with a telephony system (think Cisco CCM) from a C/C++ app in *nix?  I have used MS TAPI in the past but this is Windows only and don't want to go the jTAPI (Java) route, which seems to be the only option on the face of it.

I want to monitor the phone system for logging purposes (so I know when users have made calls, received calls, etc.).  TAPI is good at this sort of thing but I can't be the first person who wants to do something similar without having a Windows server.

Note that I need to integrate with existing PABX systems - notably Cisco CCM and Nortel BCM.

Answer:
I have experience with two telephony standards TAPI, and CSTA, as far as I know there is no such agreement between vendors (e.g. Cisco, Nortel, NEC) regarding THE standard API.
I would recommend looking at the availability of
SMDR
(Station Messaging Detail Recording) on the PBX platforms you are targeting, assuming that no call/device control is required. This will allow you to access the PBX activity as a text stream and you can parse the data for further manipulations to suit your purpose.
Most likely the format between the PBX vendors will be different but hopefully this could be abstracted away so that the core application functionality is re-usable.
This is likely to be a more portable option, again assuming no call/device control is required, as you are not relying on the vendor providing CTI connectivity on your platform of choice.


Question:
I have a Perl script that I'm attempting to set up using Perl Threads (use threads).  When I run simple tests everything works, but when I do my actual script (which has the threads running multiple SQLPlus sessions), each SQLPlus session runs in order (i.e., thread 1's sqlplus runs steps 1-5, then thread 2's sqlplus runs steps 6-11, etc.).

I thought I understood that threads would do concurrent processing, but something's amiss.  Any ideas, or should I be doing some other Perl magic?

Answer:
Actually, you have no way of guaranteeing in which order threads will execute. So the behavior (if not what you expect) is not really wrong.
I suspect you have some kind of synchronization going on here. Possibly SQL*Plus only let's itself be called once? Some programs do that...
Other possiblilties:
thread creation and process creation (you
are
creating subprocesses for SQL*Plus, aren't you?) take longer than running the thread, so thread 1 is finished before thread 2 even starts
You are using transactions in your SQL scripts that force synchronization of database updates.


Question:
I normally run VS 2008 at home and LINQ is built in.  At work we are still using VS 2005 and I have the opportunity to start a new project that I would like to use LINQ to SQL.

After doing some searching all I could come up with was the MAY 2006 CTP of LINQ would have to be installed for LINQ to work in VS 2005.

Does someone know the proper add ins or updates I would need to install to use LINQ in VS 2005 (preferably without having to use the CTP mentioned above).

Answer:
Actually, you have no way of guaranteeing in which order threads will execute. So the behavior (if not what you expect) is not really wrong.
I suspect you have some kind of synchronization going on here. Possibly SQL*Plus only let's itself be called once? Some programs do that...
Other possiblilties:
thread creation and process creation (you
are
creating subprocesses for SQL*Plus, aren't you?) take longer than running the thread, so thread 1 is finished before thread 2 even starts
You are using transactions in your SQL scripts that force synchronization of database updates.


Question: I am attempting to find xml files with large swaths of commented out xml.  I would like to programmatically search for xml comments that stretch beyond a given number of lines.  Is there an easy way of doing this?

Answer:
Considering that XML doesn't use a line based format, you should probably check the number of characters. With a regular expression, you can create a pattern to match the comment prefix and match a minimum number of characters before it matches the first comment suffix.
http://www.regular-expressions.info/
Here is the pattern that worked in some preliminary tests:
```
```
<!-- (.[^-->]|[\r\n][^-->]){5}(.[^-->]|[\r\n][^-->])*? -->
```
```
It will match the starting comment prefix and everything including newline character (on a windows OS) and it's lazy so it will stop at the first comment suffix.
Sorry for the edits, you are correct here is an updated pattern. It's obviously not optimized, but in some tests it seems to resolve the error you pointed out.


Question:
Let's say I have an aspx page with this calendar control:

<asp:Calendar ID="Calendar1" runat="server"  SelectedDate="" ></asp:Calendar>

Is there anything I can put in for SelectedDate to make it use the current date by default, without having to use the code-behind?

Answer:
If you are already doing databinding:
```
```
<asp:Calendar ID="Calendar1" runat="server"  SelectedDate="<%# DateTime.Today %>" />
```
```
Will do it.  This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control).   If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.


Question:
Would it not make sense to support a set of languages (Java, Python, Ruby, etc.) by way of a standardized virtual machine hosted in the browser rather than requiring the use of a specialized language -- really, a specialized paradigm -- for client scripting only?

To clarify the suggestion, a web page would contain byte code instead of any higher-level language like JavaScript.

I understand the pragmatic reality that JavaScript is simply what we have to work with now due to evolutionary reasons, but I'm thinking more about the long term.  With regard to backward compatibility, there's no reason that inline JavaScript could not be simultaneously supported for a period of time and of course JavaScript could be one of the languages supported by the browser virtual machine.

Answer:
Well, yes. Certainly if we had a time machine, going back and ensuring a lot of the Javascript features were designed differently would be a major pastime (that, and ensuring the people who designed IE's CSS engine never went into IT). But it's not going to happen, and we're stuck with it now.
I suspect, in time, it will become the "Machine language" for the web, with other better designed languages and APIs compile down to it (and cater for different runtime engine foibles).
I don't think, however, any of these "better designed languages" will be Java, Python or Ruby. Javascript is, despite the ability to be used elsewhere, a Web application scripting language. Given that use case, we can do better than any of those languages.


Question: I would like to reload an <iframe> using JavaScript. The best way I found until now was set the iframe’s src attribute to itself, but this isn’t very clean. Any ideas?

Answer:
```
```
window.frames['frameNameOrIndex'].location.reload();
```
```


Question:
I am re-building our poorly designed web application from scratch, and wanted to get into TDD and basically "do things right" as kind of a learning project.  What tools, processes, and resources are recommended to do it "right" from the start?  I will be working alone as the architect and developer, with the backup of a business analyst and business owners for usability testing and use cases.

EDIT:
Right now we use SourceSafe for source control, is there any reason technologically that I'd want to try to get us to switch to subversion?

EDIT #2:
Looks like the consensus is:
Cruise Control.NET
Subversion(if I want to stop using SourceSafe)
ASP.NET MVC
NUnit for unit testing
Resharper

Answer:
I highly recommend that you take a look at
MVC for ASP.NET
if you want to make unit testing a high priority in your development process.  It sounds like it is perfect for what you are trying to do.
I would also recommend
CruiseControl.NET
for continuous integration (this is important if your team is going to grow).
Subversion is my favorite source control system when I am working on small teams.  Use
Tortoise SVN
for Windows Explorer integration.


Question:
ASP.NET 2.0 provides the ClientScript.RegisterClientScriptBlock() method for registering JavaScript in an ASP.NET Page.

The issue I'm having is passing the script when it's located in another directory.  Specifically, the following syntax does not work:

ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "../dir/subdir/scriptName.js", true);

Instead of dropping the code into the page like this page says it should, it instead displays ../dir/subdir/script.js , my question is this:

Has anyone dealt with this before, and found a way to drop in the javascript in a separate file?  Am I going about this the wrong way?

Answer:
Your script value has to be a full script, so put in the following for your script value.
```
```
<script type='text/javascript' src='yourpathhere'></script>
```
```


Question:
I'm using CVS on Windows (with the WinCVS front end), and would like to add details of the last check in to the email from our automated build process, whenever a build fails, in order to make it easier to fix.

I need to know the files that have changed, the user that changed them, and the comment.

I've been trying to work out the command line options, but never seem to get accurate results (either get too many result rather than just from one checkin, or details of some random check in from two weeks ago)

Answer:
CVS does not provide this capability. You can, however, get it by buying a license for
FishEye
or possibly by using
CVSTrac
(note: I have not tried CVS Trac).
Or you could migrate to SVN, which does provide this capability via atomic commits. You can check in a group of files and have it count as a single commit. In CVS, each file is a separate commit no matter what you do.


Question: I have an Ant script that performs a copy operation using the 'copy' task. It was written for Windows, and has a hardcoded C:\ path as the 'todir' argument. I see the 'exec' task has an OS argument, is there a similar way to branch a copy based on OS?

Answer:
You can't use a variable and assign it depending on the type? You could put it in a
```
build.properties
```
file. Or you could assign it using a
condition
.


Question:
I have a application deployed through clickonce, but How can I modify the config file on the deployment server?.  I mean, once the product is tested, it should be deployed in our production server, but need to modify some of the config parameters to consume production resources?. I heard we should use MageUI.exe, but still not sure.

I appreciate for your help.

Thank

Answer:
Yes, the best way to do it would probably be MageUI.  Just open your manifests with MageUI, click
Save
and it should prompt you to resign the manifests.
You have two options when signing manifests.  You can use a self-certificate or purchase a certificate.  Self certificates are easy to use but when the app is installed the publisher will appear as
Unknown
.  If you purchase a certificate, use these instructions to create the files needed to sign ClickOnce manifests -
http://www.softinsight.com/bnoyes/CommentView.aspx?guid=78d107d1-3937-4d8d-81d9-73cb6ae18eee
.


Question: I've seen a few fixes for allowing PNG images to have transparency in Internet Explorer 6, but I've yet to find one that also allows you to set the background position in CSS. If you use sprites, it's a deal-breaker. I've resorted to using GIF's (which are not as high quality), not using transparent images at all, or serving a completely different stylesheet to IE6. Is there a fix for IE6 that allows for PNG transparencies AND background positioning?

Answer:
Yes.  Convert your images to use indexed pallets (png256).  You can support transparency (just like gif), but not an alpha channel.
You can do this using
Irfanview
and the pngout plugin,
pngquant
or
pngnq
.
The YUI performance team also did a
great presentation
that covers this an many other image optimization concepts.


Question: What do you think is the best way to create SEO friendly URLs (dynamically) in Rails?

Answer:
Override the
```
to_param
```
method in your model classes so that the default numeric ID is replaced with a meaningful string. For example, this very question uses
best-permalinking-for-rails
in the URL.
Ryan Bates has a
Railscast on this topic
.


Question:
I have two classes, and want to include a static instance of one class inside the other and access the static fields from the second class via the first.

This is so I can have non-identical instances with the same name.

Class A
{
    public static package1.Foo foo;
}

Class B
{
    public static package2.Foo foo;
}

//package1
Foo
{
    public final static int bar = 1;
}

// package2
Foo
{
    public final static int bar = 2;
}

// usage
assertEquals(A.foo.bar, 1);
assertEquals(B.foo.bar, 2);

This works, but I get a warning "The static field Foo.bar shoudl be accessed in a static way".
Can someone explain why this is and offer a "correct" implementation.

I realize I could access the static instances directly, but if you have a long package hierarchy, that gets ugly:

assertEquals(net.FooCorp.divisions.A.package.Foo.bar, 1);
assertEquals(net.FooCorp.divisions.B.package.Foo.bar, 2);

Answer:
You should use:
```
```
Foo.bar
```
```
And not:
```
```
A.foo.bar
```
```
That's what the warning means.
The reason is that
```
bar
```
isn't a member of an
instance
of
```
Foo
```
.  Rather,
```
bar
```
is global, on the class
```
Foo
```
.  The compiler wants you to reference it globally rather than pretending it's a member of the instance.


Question:
I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted.

Right now, I call to_json and my JSON is all on one line.  At times this can be difficult to see if there is a problem in the JSON output stream.

Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?

Answer:
Use the
```
pretty_generate()
```
function, built into later versions of JSON. For example:
```
```
require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)
```
```
Which gets you:
```
```
{
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}
```
```


Question:
I'm trying to create a build script for my current project, which includes an Excel Add-in.  The Add-in contains a VBProject with a file modGlobal with a variable version_Number.   This number needs to be changed for every build.  The exact steps:

Open XLA document with Excel.

Switch to VBEditor mode. (Alt+F11)

Open VBProject, entering a password.

Open modGlobal file.

Change variable's default value to the current date.

Close & save the project.

I'm at a loss for how to automate the process.  The best I can come up with is an excel macro or Auto-IT script.  I could also write a custom MSBuild task, but that might get... tricky.  Does anyone else have any other suggestions?

Answer:
I'm not 100% sure how to do exactly what you have requested. But guessing the goal you have in mind there are a few possibilities.
1)
Make part (or all) of your Globals a separate text file that is distributed with the .XLA I would use this for external references such as the version of the rest of your app. Write this at build time and distribute, and read on the load of the XLA.
2)
I'm guessing your writing the version of the main component (ie: the non XLA part) of your application. If this is tru why store this in your XLA? Why not have the main part of the app allow certain version of the XLA to work. Version 1.1 of the main app could accept calls from Version 7.1 - 8.9 of the XLA.
3)
If you are just looking to update the XLA so it gets included in your version control system or similar (i'm guessing here) maybe just touch the file so it looks like it changed.
If it's the version of the rest of the app that you are controlling i'd just stick it in a text file and distribute that along with the XLA.


Question:
Say I have two strings,

String s1 = "AbBaCca";
String s2 = "bac";

I want to perform a check returning that s2 is contained within s1. I can do this with:

return s1.contains(s2);

I am pretty sure that contains() is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:

return s1.toLowerCase().contains(s2.toLowerCase());

All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?

Answer:
Yes, contains is case sensitive.  You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:
```
```
Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();
```
```
EDIT:
If s2 contains regex special characters (of which there are many) it's important to quote it first.  I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.


Question:
I'm designing a web site navigation hierarchy. It's a tree of nodes.  Nodes represent web pages.

Some nodes on the tree are special.  I need a name for them.

There are multiple such nodes. Each is the "root" of a sub-tree with pages that have a distinct logo, style sheet, or layout. Think of different departments.

site map with color-coded sub-trees http://img518.imageshack.us/img518/153/subtreesfe1.gif

What should I name this type of node?

Answer:
How about Root (node with children, but no parent), Node (node with children and parent) and Leaf (node with no children and parent)?
You can then distinguish by name and position within the tree structure (E.g. DepartmentRoot, DepartmentNode, DepartmentLeaf) if need be..
Update Following Comment from OP
Looking at your question, you said that "some" are special, and in your diagram, you have different nodes looking differently at different levels. The nodes may be different in their design, you can build a tree structure many ways. For example, a single abstract class that
can
have child nodes, if no children, its a leaf, if no parent, its a root but this can change in its lifetime. Or, a fixed class structure in which leafs are a specific class type that
cannot
have children added to them in any way.
IF your design does not need you to distinguish nodes differently depending on their position (relative to the root) it suggests that you have an abstract class used for them all.
In which case, it raises the question,
how is it different?
If it is simply the same as the standard node everywhere else, but with a bit of styling, how about
StyledNode
? Do you even need it to be seperate (no style == no big deal, it doesn't render).
Since I don't know the mechanics of how the tree is architected, there could possibly be several factors to consider when naming.


Question: I've recently embarked upon the grand voyage of Wordpress theming and I've been reading through the Wordpress documentation for how to write a theme.  One thing I came across here was that the style.css file must contain a specific header in order to be used by the Wordpress engine.  They give a brief example but I haven't been able to turn up any formal description of what must be in the style.css header portion.  Does this exist on the Wordpress site?  If it doesn't could we perhaps describe it here?

Answer:
You are probably thinking about this:
```
```
/*
THEME NAME: Parallax
THEME URI: http://parallaxdenigrate.net
VERSION: .1
AUTHOR: Martin Jacobsen
AUTHOR URI: http://martinjacobsen.no
*/
```
```
If I'm not way off, Wordpress uses this info to display in the "Activate Design" dialog in the admin backend.


Question:
I'm using exim on both the sending and relay hosts, the sending host seems to offer:

HELO foo_bar.example.com

Response:

501 Syntactically invalid HELO argument(s)

Answer:
Possibly a problem with underscores in the hostname?
http://www.exim.org/lurker/message/20041124.113314.c44c83b2.en.html


Question:
I am looking for a tool that can serialize and/or transform SQL Result Sets into XML. Getting dumbed down XML generation from SQL result sets is simple and trivial, but that's not what I need.

The solution has to be database neutral, and accepts only regular SQL query results (no db xml support used). A particular challenge of this tool is to provide nested XML matching any schema from row based results. Intermediate steps are too slow and wasteful - this needs to happen in one single step; no RS->object->XML, preferably no RS->XML->XSLT->XML. It must support streaming due to large result sets, big XML.

Anything out there for this?

Answer:
Not that I know of.  I would just roll my own.  It's not that hard to do, maybe something like this:
```
```
#!/usr/bin/env jruby

import java.sql.DriverManager

# TODO  some magic to load the driver
conn = DriverManager.getConnection(ARGV[0], ARGV[1], ARGV[2])
res = conn.executeQuery ARGV[3]

puts "<result>"
meta = res.meta_data
while res.next
  puts "<row>"

  for n in 1..meta.column_count
    column = meta.getColumnName n
    puts "<#{column}>#{res.getString(n)}</#{column}"
  end

  puts "</row>"
end
puts "</result>"
```
```
Disclaimer:
I just made all of that up, I'm not even bothering to pretend that it works.  :-)


Question:
I have a simple xml document that looks like the following snippet. I need to write a XSLT transform that basically 'unpivots' this document based on some of the attributes.

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:z="foo">
    <z:row A="1" X="2" Y="n1" Z="500"/>
    <z:row A="2" X="5" Y="n2" Z="1500"/>
</root>

This is what I expect the output to be -

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:z="foo">
    <z:row A="1" X="2"  />
    <z:row A="1" Y="n1" />
    <z:row A="1" Z="500"/>
    <z:row A="2" X="5" />
    <z:row A="2" Y="n2"/>
    <z:row A="2" Z="1500"/>
</root>

Appreciate your help.

Answer:
Here is a bit of a brute force way:
```
```
<xsl:template match="z:row">
    <xsl:element name="z:row">
        <xsl:attribute name="A">
            <xsl:value-of select="@A"/>
        </xsl:attribute>
        <xsl:attribute name="X">
            <xsl:value-of select="@X"/>
        </xsl:attribute>
    </xsl:element>
    <xsl:element name="z:row">
        <xsl:attribute name="A">
            <xsl:value-of select="@A"/>
        </xsl:attribute>
        <xsl:attribute name="Y">
            <xsl:value-of select="@Y"/>
        </xsl:attribute>
    </xsl:element>
    <xsl:element name="z:row">
        <xsl:attribute name="A">
            <xsl:value-of select="@A"/>
        </xsl:attribute>
        <xsl:attribute name="Z">
            <xsl:value-of select="@Z"/>
        </xsl:attribute>
    </xsl:element>
</xsl:template>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>
```
```


Question: Unix.....>>netstat -al | grep 8787 (will see packets on port 8787)

Answer: What is the nature of the question here? Are you trying to see packets on port 8787? Are you looking for services listening on port 8787? Most importantly, how is this a programming-related question?


Question:
I have an application with multiple "pick list" entities, such as used to populate choices of dropdown selection boxes. These entities need to be stored in the database. How do one persist these entities in the database?

Should I create a new table for each pick list?  Is there a better solution?

Answer:
Depending on your needs, you can just have an options table that has a list identifier and a list value as the primary key.
```
```
select optionDesc from Options where 'MyList' = optionList
```
```
You can then extend it with an order column, etc. If you have an ID field, that is how you can reference your answers back... of if it is often changing, you can just copy the answer value to the answer table.


Question:
Where can I download the JSSE and JCE source code for the latest release of Java?  The source build available at https://jdk6.dev.java.net/ does not include the javax.crypto (JCE) packages nor the com.sun.net.ssl.internal (JSSE) packages.

Not being able to debug these classes makes solving SSL issues incredibly difficult.

Answer:
there:
openjdk javax.net
in the security group
```
```
src/share/classes/javax/net
src/share/classes/com/sun/net/ssl
src/share/classes/sun/security/ssl
src/share/classes/sun/net/www/protocol/https
```
```
also on this page:
```
```
src/share/classes/javax/crypto
src/share/classes/com/sun/crypto/provider
src/share/classes/sun/security/pkcs11
src/share/classes/sun/security/mscapi
```
```
These directories contain the core
  cryptography framework and three
  providers (SunJCE, SunPKCS11,
  SunMSCAPI).
SunJCE
contains Java
  implementations of many popular
  algorithms, and the latter two
  libraries allow calls made through the
  standard Java cryptography APIs to be
  routed into their respective native
  libraries.


Question: I've setup a new .net 2.0 website on IIS 7 under Win Server 2k8 and when browsing to a page it gives me a 404.17 error, claiming that the file (default.aspx in this case) appears to be a script but is being handled by the static file handler.  It SOUNDS like the module mappings for ASP.Net got messed up, but they look fine in the configurations.  Does anyone have a suggestion for correcting this error?

Answer:
I had this problem on IIS6 one time when somehow the ASP.NET ISAPI stuff was broke.
Running
```
```
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i
```
```
to recreate the settings took care of it.


Question: I had data in XML  that had line feeds, spaces, and tabs that I wanted to preserve in the output HTML (so I couldn't  use <p>) but I also wanted the lines to wrap when the side of the screen  was reached (so I couldn't use <pre>).

Answer:
I and a co-worker (Patricia Eromosele) came up with the following solution:  (Is there a better solution?)
```
<p>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="text"/>
</xsl:call-template>
</p>
<xsl:template name="prewrap">
<xsl:param name="text" select="."/>
<xsl:variable name="spaceIndex" select="string-length(substring-before($text, '  '))"/>
<xsl:variable name="tabIndex" select="string-length(substring-before($text, '	'))"/>
<xsl:variable name="lineFeedIndex" select="string-length(substring-before($text, '
'))"/>
<xsl:choose>
<xsl:when test="$spaceIndex = 0 and $tabIndex = 0 and $lineFeedIndex = 0"><!-- no special characters left -->
<xsl:value-of select="$text"/>
</xsl:when>
<xsl:when test="$spaceIndex > $tabIndex and $lineFeedIndex > $tabIndex"><!-- tab -->
<xsl:value-of select="substring-before($text, '	')"/>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="substring-after($text,'	')"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="$spaceIndex > $lineFeedIndex and $tabIndex > $lineFeedIndex"><!-- line feed -->
<xsl:value-of select="substring-before($text, '
')"/>
<br/>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="substring-after($text,'
')"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="$lineFeedIndex > $spaceIndex and $tabIndex > $spaceIndex"><!-- two spaces -->
<xsl:value-of select="substring-before($text, '  ')"/>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="substring-after($text,'  ')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise><!-- should never happen -->
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
```
Source:
http://jamesjava.blogspot.com/2008/06/xsl-preserving-line-feeds-tabs-and.html


Question:
There seems to be no good way to localize a WPF application.  MSDN seems to think that littering my XAML with x:Uid's, generating CSV files, and then generating new assemblies (using their sample code!) is the answer.  Worse, this process doesn't address how to localize images, binary blobs (say, PDF files), or strings that are embedded in code.

So, how might you localize an application that:

Contains several assemblies

Contains images and other binary blobs (eg: PDF docs) that need to be localized

Has string data that isn't in XAML (eg: MessageBox.Show("Hello World");)

Answer:
Not an expert here, but "littering" your xaml with x:Uids is not worse than "littering" your Windows Forms code with all the string table nonsense you have to do for localizing them.
As far as I understand, WPF apps still support "all the Framework CLR resources including string tables, images, and so forth." which means you can have localized resources.
Of course, it would be much simpler if you created a markup extension that handled much of this nonsense for you.
You can find an example of someone doing this here.
And there was another, similar solution at
```
http://blog.taggersoft.com/2008/07/wpf-application-localization-pattern_29.html
```
, but that link no longer works.


Question:
Does anyone know of a .NET library that will process HTML e-mails and can be used to trim out the reply-chain?  It needs to be able to accept HTML -or- text mails and then trim out everything but the actual response, removing the trail of messages that are not original content.  I don't expect it to be able to handle responseswhen they're interleaved into the previous mail ("responses in-line") - that case can fail.

We have a home-built one based on SgmlReader and a series of XSL transforms, but it requires constant maintenance to deal with new e-mail clients.  I'd like to find one I can buy... :)

Thanks,
Steve

Answer:
Not an expert here, but "littering" your xaml with x:Uids is not worse than "littering" your Windows Forms code with all the string table nonsense you have to do for localizing them.
As far as I understand, WPF apps still support "all the Framework CLR resources including string tables, images, and so forth." which means you can have localized resources.
Of course, it would be much simpler if you created a markup extension that handled much of this nonsense for you.
You can find an example of someone doing this here.
And there was another, similar solution at
```
http://blog.taggersoft.com/2008/07/wpf-application-localization-pattern_29.html
```
, but that link no longer works.


Question: After reading this description of late static binding (LSB) I see pretty clearly what is going on. Now, under which sorts of circumstances might that be most useful or needed?

Answer:
I needed LSB this for the following scenario:
Imagine you're building a "mail processor" daemon that downloads the message from an email server, classifies it, parses it, saves it, and then does something, depending on the type of the message.
Class hierarchy: you have a base Message class, with children "BouncedMessage" and "AcceptedMessage".
Each of the message types has its own way to persist itself on disk. For example, all messages of type BouncedMessage try to save itself as BouncedMessage-id.xml. AcceptedMessage, on the other hand, needs to save itself differently - as AcceptedMessage-timestamp.xml. The important thing here is that the logic for determining the filename pattern is different for different subclasses, but
shared
for all items within the subclass. That's why it makes sense for it to be in a static method.
Base Message class has an abstract static method (yes, abstract
AND
static) "save". BouncedMessage implements this method with a concrete static method. Then, inside the class that actually retrieves the message, you can call "::save()"
If you want to learn more about the subject:
http://www.qcodo.com/forums/topic.php/2356
http://community.livejournal.com/php/585907.html
http://bugs.php.net/bug.php?id=42681


Question:
It is obviosly some Perl extensions. Perl version is 5.8.8.

I found Error.pm, but now I'm looking for Core.pm.

While we're at it: how do you guys search for those modules. I tried Google, but that didn't help much. Thanks.

And finally, after I built everything, running:

./Build install

gives me:

Running make install-lib
/bin/ginstall -c -d /usr/lib/perl5/site_perl/5.8.8/i486-linux-thread-multi/Alien/SVN --prefix=/usr
/bin/ginstall: unrecognized option `--prefix=/usr'
Try `/bin/ginstall --help' for more information.
make: *** [install-fsmod-lib] Error 1
installing libs failed at inc/My/SVN/Builder.pm line 165.

Looks like Slackware's 'ginstall' really does not have that option. I think I'm going to Google a little bit now, to see how to get around this.

Answer:
It should be compatible. The
CPAN Tester's matrix
shows no failures for Perl 5.8.8 on any platform.
Per the
README
, you can install it by doing:
```
```
perl Makefile.pl
make
make test
make install
```
```


Question:
default is 49

how to edit to higher?

Answer:
You will need to issue the following command (connected as a user that has alter system privileges, sys will do it)
alter system set sessions=
numberofsessions
scope=spfile;
Have you been getting an ORA-12516 or ORA-12520 error?
If so it's probably a good idea to increase the number of processes too
alter system set processes=
numberofprocesses
scope=spfile;
IIRC you'll need to bounce the database after issuing these commands.
This link
http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf
has some good information about configuring XE.
I consulted it when I ran into similar issues using XE.


Question:
I need to find the frequency of a sample, stored (in vb) as an array of byte. Sample is a sine wave, known frequency, so I can check), but the numbers are a bit odd, and my maths-foo is weak.
Full range of values 0-255. 99% of numbers are in range 235 to 245, but there are some outliers down to 0 and 1, and up to 255 in the remaining 1%.
How do I normalise this to remove outliers, (calculating the 235-245 interval as it may change with different samples), and how do I then calculate zero-crossings to get the frequency?
Apologies if this description is rubbish!

Answer:
Use the Fourier transform, it's much more noise insensitive than counting zero crossings
Edit: @WaveyDavey
I found an F# library to do an FFT:
From here
As it turns out, the best free
implementation that I've found for F#
users so far is still the fantastic
FFTW library. Their site has a
precompiled Windows DLL. I've written
minimal bindings that allow
thread-safe access to FFTW from F#,
with both guru and simple interfaces.
Performance is excellent, 32-bit
Windows XP Pro is only up to 35%
slower than 64-bit Linux.
Now I'm sure you can call F# lib from VB.net, C# etc, that should be in their docs


Question:
Although I don't have an iPhone to test this out, my colleague told me that embedded
media files such as the one in the snippet below, only works when the iphone is connected over the
WLAN connection or 3G, and does not work when connecting via GPRS.

<html><body>
<object data="http://joliclic.free.fr/html/object-tag/en/data/test.mp3" type="audio/mpeg">
   <p>alternate text</p>
</object>
</body></html>

Is there an example URL with a media file, that will play in an iPhone browser
when the iphone connects using GPRS (not 3G)?

Answer:
I wasn't aware of that limitation.  Although it does make sense to disable potentially data-hefty OBJECT or EMBED tags when on the cellular data service for which your provider may be charging by the byte, if that were the reason it wouldn't make sense that it would still work on 3G and only not on GPRS.
Perhaps the problem is one of basic data throughput?  Not having an iPhone yourself (or myself) makes it difficult to test your colleague's statement.
Remember that GPRS is much slower than Wi-Fi or 3G.  According to Wikipedia, GPRS will provide between 56 and 114 kbps of total duplex throughput, not all of which is in the download direction.  You can already see that's not fast enough to instantly stream a typical 128 kbps mp3, even if you were getting the optimal throughput and getting it all as download speed.
Looking at
this forum discussion
as an example that came up on Google, the GPRS customers (the ones not using Telestra, which is an EDGE provider in that area) are getting around 40 kbps.  So if as the question implies, you're stuck in EDGEland, NOT 3Gland or anything inbetween, it's going to take about 20 seconds of buffering to play a 30 second mp3.  And when you use a behaviour-ambiguous tag like OBJECT or EMBED, there's no guarantee in how the browser will interpret it and whether it's going to try to intelligently stream the file rather than having to download the whole thing before starting it.
So, it's quite possible your colleague just didn't wait long enough to see if whatever embedded media he chose as a test started to play (assuming he wasn't using your 17KB test mp3 there).  It's also possible that the iPhone does indeed have this limitation, though I'd think Google would be more forthcoming with it than my quick search uncovered, since people have been vocal enough with other things they don't like about iPhone.  Another possibility would be that it's a limitation in the build of Safari that currently ships with the iPhone which might be changed in future versions or in another browser.
Ultimately though, the question is, what kind of user experience do you really want?  Embedded audio on GPRS is going to take a long time to load, and users aren't going to enjoy the experience, or potentially even experience it at all if it's supposed to start playing on page visit and it doesn't load before they navigate away.  It might not be a goal worth striving towards in that case.


Question:
What's a good algorithm for calculating frames per second in a game? I want to show it as a number in the corner of the screen. If I just look at how long it took to render the last frame the number changes too fast.

Bonus points if your answer updates each frame and doesn't converge differently when the frame rate is increasing vs decreasing.

Answer:
You need a smoothed average, the easiest way is to take the current answer (the time to draw the last frame) and combine it with the previous answer.
```
```
// eg.
float smoothing = 0.9; // larger=more smoothing
measurement = (measurement * smoothing) + (current * (1.0-smoothing))
```
```
By adjusting the 0.9 / 0.1 ratio you can change the 'time constant' - that is how quickly the number responds to changes. A larger fraction in favour of the old answer gives a slower smoother change, a large fraction in favour of the new answer gives a quicker changing value.   Obviously the two factors must add to one!


Question:
I need to get a list of attribute values from child elements in Python.

It's easiest to explain with an example.

Given some XML like this:

<elements>
    <parent name="CategoryA">
        <child value="a1"/>
        <child value="a2"/>
        <child value="a3"/>
    </parent>
    <parent name="CategoryB">
        <child value="b1"/>
        <child value="b2"/>
        <child value="b3"/>
    </parent>
</elements>

I want to be able to do something like:

>>> getValues("CategoryA")
['a1', 'a2', 'a3']
>>> getValues("CategoryB")
['b1', 'b2', 'b3']

It looks like a job for XPath but I'm open to all recommendations. I'd also like to hear about your favourite Python XML libraries.

Answer:
I must admit I'm a fan of
xmltramp
due to its ease of use.
Accessing the above becomes:
```
```
import xmltramp

  values = xmltramp.parse('''...''')

  def getValues( values, category ):
    cat = [ parent for parent in values['parent':] if parent(name) == category ]
    cat_values = [ child(value) for child in parent['child':] for parent in cat ]
    return cat_values

  getValues( values, "CategoryA" )
  getValues( values, "CategoryB" )
```
```


Question:
I have a test project using MbUnit and TestDriven.Net.

If I right-click on an individual test method and say "Run Tests" the test runs successfully.  Same thing if I click on a file name in the solution explorer.

However, if I right click and say run tests on the project or the solution, TestDriven.Net reports "0 Passed, 0 Failed, 0 Skipped."

I have other similar projects that work just fine, and yes, the classes are labeled [TestFixture] and the methods are labeled [Test].

Answer:
You need to add testing attributes for your favorite testing framework.  TestDriven picks up these attributes by reflection in order to know what tests to run.
For example, using NUnit.Framework - each test class needs [TextFixture] and each test method needs [Test]
Here's an
example


Question:
Are there any good resources for planning how exceptions will be used from an architecture perspective?  (Or provide your suggestions directly here.)  In projects on which I have worked I find that a few common Exceptions are used over and over again and tend to lose their meaning.
From: http://jamesjava.blogspot.com/2007/10/exception-plan.html

Answer:
"Effective Java," 2nd. ed. Bloch
, has some good advice in chapter 9.
"Hardcore Java," Simmons
, has some good advice in chapter 5.
I'll also shamelessly mention that I've written
a small tool
to manage Java exception source code. Exception code is often very redundant, all that you usually care about is the type. My tool accepts a configuration file that names exception types, then generates code for those exceptions.


Question:
I need to write a function that receives a string and a regex. I need to check if there is a match and return the start and end location of a match. (The regex was already compiled by qr//.)

The function might also receive a "global" flag and then I need to return the (start,end) pairs of all the matches.

I cannot change the regex, not even add () around it as the user might use () and \1. Maybe I can use (?:).

Example: given "ababab" and the regex qr/ab/, in the global case I need to get back 3 pairs of (start, end).

Answer:
The pos function gives you the position of the match. If you put your regex in parentheses you can get the length (and thus the end) using
```
length $1
```
.  Like this
```
```
sub match_positions {
    my ($regex, $string) = @_;
    return if not $string =~ /($regex)/;
    return (pos($string) - length $1, pos($string));
}
sub all_match_positions {
    my ($regex, $string) = @_;
    my @ret;
    while ($string =~ /($regex)/g) {
        push @ret, [pos($string) - length $1, pos($string)];
    }
    return @ret
}
```
```


Question:
After compiling a simple C++ project using Visual Studio 2008 on vista, everything runs fine on the original vista machine and other vista computers. However, moving it over to an XP box results in an error message: "The application failed to start because the application configuration is incorrect".

What do I have to do so my compiled EXE works on XP and Vista? I had this same problem a few months ago, and just fiddling with some settings on the project fixed it, but I don't remember which ones I changed.

Answer:
You need to install the runtime redistributable files onto the machine you are trying to run the app on.
The redistributable for 2008 is
here
.
The redistributable for 2005 is
here
.
They can be installed side-by-side, in case you need both.


Question:
I have a class with many embedded assets.

Within the class, I would like to get the class definition of an asset by name.  I have tried using getDefinitionByName(), and also ApplicationDomain.currentDomain.getDefinition() but neither work.

Example:

public class MyClass
{
  [Embed(source="images/image1.png")] private static var Image1Class:Class;
  [Embed(source="images/image2.png")] private static var Image2Class:Class;
  [Embed(source="images/image3.png")] private static var Image3Class:Class;

  private var _image:Bitmap;

  public function MyClass(name:String)
  {
    var ClassDef:Class = getDefinitionByName(name) as Class;  //<<-- Fails
    _image = new ClassDef() as Bitmap;
  }
}

var cls:MyClass = new MyClass("Image1Class");

Answer:
This doesn't answer your question, but it may solve your problem.  I believe doing something like this should work:
```
```
public class MyClass
{
  [Embed(source="images/image1.png")] private static var Image1Class:Class;
  [Embed(source="images/image2.png")] private static var Image2Class:Class;
  [Embed(source="images/image3.png")] private static var Image3Class:Class;

  private var _image:Bitmap;

  public function MyClass(name:String)
  {
    _image = new this[name]() as Bitmap;
  }
}

var cls:MyClass = new MyClass("Image1Class");
```
```
I'm having a tough time remembering if bracket notation works on sealed classes.  If it doesn't, a simple solution is to mark the class as dynamic.


Question:
Continuing my problem from yesterday, the Silverlight datagrid I have from this issue
is now causing Stack Overflow errors when sorting a column with a large amount of data (Like the text column that contains a where clause for a SQL statment).  When you sort, it'll fire the SelectedIndexChanged event for the datagrid and then still try to stort.  If you click the header again the stack overflow occours.

Does anyone have an idea on how to stop the sorting on this control for a column?  All the other columns sort fine (but still fire that darn SelectedIndexChanged event), but if I could shut off the column for whereClause it'd be perfect.

Does anyone have a better idea at how to get this to work?

Answer:
Give this a shot:
```
```
dataGridView1.Columns[*Numberofthecolumnyoudontwantsorted*].SortMode
= DataGridViewColumnSortMode.NotSortable;
```
```


Question:
I need to know if it is possible to dynamically bind a textbox residing within a datarepeater to a 'dynamically' created BindingSource.  I am using VB.net.  The database I am using is a MySQL database.

I have to use the connection dynamically due to the fact that the database my not permanently reside on the same server.

[edit]

ok, so it seams that I am a dolt when asking questions.  The app that I am making is not web based.  it is a simple (I hope) app that connects to a MySQL database, accesses a table so I can edit/view it.  Current setup is using the Add DataSource wizard.  I have successfully connected to the dbase dynamically using the mysql connector dll but without the textboxes set at design time to a datasource, I am unsure on how to 'link' them via the datarepeater.

Answer:
Your connection string should be defined in your Web.Config, and if you move your database to a different server, it's just a matter of modifying the web.config entry. As long as you keep the connection string name the same, the BindingSource object will pick up the new value from the config.
edit
In truth, the same concept should apply here as it does in the web app answer listed above.
All of your data objects should be hard-coded, and it's just the connection string (which you'll have to either ask the user for, or push out as update when the DB moves) which will get modified.
For example, create a App.Config file in your project. Have one of your configuration values  be the connection string. This config value will be where you go to get the connection string whenever you need it. Then your wizard will be there to allow users to easily modify the connection.


Question:
If the major axis of the ellipse is vertical or horizontal, it's easy to calculate the bounding box, but what about when the ellipse is rotated?

The only way I can think of so far is to calculate all the points around the perimeter and find the max/min x and y values. It seems like there should be a simpler way.

If there's a function (in the mathematical sense) that describes an ellipse at an arbitrary angle, then I could use its derivative to find points where the slope is zero or undefined, but I can't seem to find one.

Edit: to clarify, I need the axis-aligned bounding box, i.e. it should not be rotated with the ellipse, but stay aligned with the x axis so transforming the bounding box won't work.

Answer:
I think the most useful formula is this one. An ellipsis rotated from an angle phi from the origin has as equation:
where (h,k) is the center, a and b the size of the major and minor axis and t varies from -pi to pi.
From that, you should be able to derive for which t dx/dt or dy/dt goes to 0.


Question:
I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL.

Results would be something like:

TableName, ColumnName

Answer:
sys.columns.is_identity = 1
e.g.,
```
```
select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1
```
```


Question: How do you connect to Oracle using PHP on MAC OS X?

Answer:
I would think OCI would be the way to go. PHP has a
module
for it.


Question:
Say I have the following class

MyComponent : IMyComponent {
  public MyComponent(int start_at) {...}
}

I can register an instance of it with castle windsor via xml as follows

<component id="sample"  service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample">
  <parameters>
    <start_at>1</start_at >
  </parameters>
</component>

How would I go about doing the exact same thing but in code?  (Notice, the constructor parameter)

Answer:
You need to pass in an IDictionary when you ask the container for the instance.
You'd use this Resolve overload of the IWindsorContainer:
```
```
T Resolve<T>(IDictionary arguments)
```
```
or the non generic one:
```
```
object Resolve(Type service, IDictionary arguments)
```
```
So, for example: (assuming container is an IWindsorContainer)
```
```
IDictionary<string, object> values = new Dictionary<string, object>();
values["start_at"] = 1;
container.Resolve<IMyComponent>(values);
```
```
Note that the key values in the dictionary are case sensitive.


Question:
I am about to move to SVN as my RCS of choice (after many years using CVS) and have a basic question...

I have a number of shared projects - code that I want to use with lots of different projects.  Is it possible to 'link' these shared folders to the projects that need them, so checking out a project will also checkout the shared code?

For example, suppose my repository looks like this:

root

--project1

--project2

--shared

--smtp

When I checkout project1, I also want to checkout shared and smtp.

Back in my CVS days I would of used a Unix symbolic link in one of the project folders, but as my new SVN repository won't necessarily be hosted on a Unix box, I can't do the same.

Answer:
SVN Externals are what you want to do. The SVN book explains it in great detail
here
. That's one thing I love about SVN, the wonderful documentation.


Question:
I am trying to build a dependency graph of tables based on the foreign keys between them.  This graph needs to start with an arbitrary table name as its root.  I could, given a table name look up the tables that reference it using the all_constraints view, then look up the tables that reference them, and so on, but this would be horrible inefficient.  I wrote a recursive query that does this for all tables, but when I add:

START WITH Table_Name=:tablename

It doesn't return the entire tree.

Answer:
Simplest way to do this is to copy all the FK info into a simple, 2-column (parent,child) table, and then use the following algorithm:
```
```
while (rows left in that table)
  list = rows where table name exists in child but not in parent
  print list
  remove list from rows
```
```
that's all. Basically, you first print and remove all the nodes that don't depend on anything. After that being done, some other nodes will get free and you can repeat process.
P.S. Make sure you don't insert self-referencing tables in the initial list (child=parent)


Question:
anyone have any experience using this?
if so, is it worth while?

Answer:
JDB is incredibly difficult to use. Placing System.outs or using an IDE debugger will produce better results. And for the more interesting features (e.g. tracking threads, heap size, etc.), you can get the information graphically with the
JConsole
tool.


Question:
I am trying to build out a useful 3d game engine out of the Ogre3d rendering engine for mocking up some of the ideas i have come up with and have come to a bit of a crossroads. There are a number of scripting languages that are available and i was wondering if there were one or two that were vetted and had a proper following.

LUA and Squirrel seem to be the more vetted, but im open to any and all.

Optimally it would be best if there were a compiled form for the language for distribution and ease of loading.

Answer:
I'd go with Lua since writing bindings is extremely easy, the license is very friendly (MIT) and existing libraries also tend to be under said license. Scheme is also nice and easy to bind which is why it was chosen for the Gimp image editor for example. But Lua is simply great. World of Warcraft uses it, as a very high profile example. LuaJIT gives you native-compiled performance. It's
less than an order of magnitude
from pure C.


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

smith.jack or smith.jack.s

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

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

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

Frustrating.

Answer:
```
```
[^\s.]+\.[^\s.]+(\.[^\s.]+)?
```
```
BTW what you asked for allows "." and ".."


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

Environment:

CF8 Standard

IIS 6

Win2k3

SQL2k5 on a separate box

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


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

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


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

Thanks

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


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

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

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

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

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

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

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

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

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


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

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

Thanks!

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

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


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

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

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

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

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


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

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

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


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

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

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


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

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

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


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

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


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

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

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


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

Do you use DTO ?

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

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

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


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

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

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

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


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

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

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


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

java.lang.OutOfMemoryError: PermGen space

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

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

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


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

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

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


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

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

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

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


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

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

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

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

but it looks like trash.

Does anyone have a better method?

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


Question:
I have a class:

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

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

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

But I get...

NameError: global name 'Error' is not defined

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

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

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

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

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

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


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

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

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

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


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

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

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

public class UIWrapper
{
private TextBox textBox;

public TextBox TextBox
{
get {return textBox;}
}

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

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

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


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

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

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

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

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


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

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

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

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


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

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

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

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

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


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

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


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

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


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

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

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

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

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

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

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

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


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

if (condition) { do something }

or as

(condition) and do { do something }

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

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


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

cin >> a >> b >> c;

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

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

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


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

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


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

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

but so far I've had no success.

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

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

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