q:
I know a few advanced ways, to change directories. pushd and popd (directory stack) or cd - (change to last directory).

But I am looking for quick way to achieve the following:

Say, I am in a rather deep dir:

/this/is/a/very/deep/directory/structure/with\ lot\ of\ nasty/names

and I want to switch to

/this/is/another/very/deep/directory/structure/with\ lot\ of\ nasty/names

Is there a cool/quick/geeky way to do it (without the mouse)?

[A]
Do you mean that the path names are the same, and only one directory name changes ("a" becomes "another")? In that case:
```
```
cd ${PWD/a/another}
```
```
will switch to the other directory.
```
$PWD
```
holds your current directory, and
```
${var/foo/bar}
```
gives you
```
$var
```
with the string 'foo' replaced by 'bar'.


q:
I have a query where I wish to retrieve the oldest X records.  At present my query is something like the following:

SELECT Id, Title, Comments, CreatedDate
FROM MyTable
WHERE CreatedDate > @OlderThanDate
ORDER BY CreatedDate DESC

I know that normally I would remove the 'DESC' keyword to switch the order of the records, however in this instance I still want to get records ordered with the newest item first.

So I want to know if there is any means of performing this query such that I get the oldest X items sorted such that the newest item is first.  I should also add that my database exists on SQL Server 2005.

[A]
Why not just use a subquery?
```
```
SELECT T1.*
FROM
(SELECT TOP X Id, Title, Comments, CreatedDate
FROM MyTable
WHERE CreatedDate > @OlderThanDate
ORDER BY CreatedDate) T1
ORDER BY CreatedDate DESC
```
```

s: huggingface

c: devops

d: intermediate


q:
Technical Debt via Martin Fowler, via Steve McConnell

YAGNI (You Ain't Gonna Need It) via Wikipedia

BDUF (Big Design Up Front) via Wikipedia

UPDATE: To clarify the question, I think I can also state it this way and keep my meaning:

"In what ways do you, as an Agile practioner, find the right balance between "quick and dirty" (unintentionally risking Technical Debt while attempting to adhere to YAGNI) and over-engineering (BDUF) within each iteration?"

[A]
I find Robert Martin's
Test Driven Development
(TDD) approach helps with these concerns.
Why?
You only have to write enough code to pass the next test.
I think testable code is cleaner.
The design has to feed into tests which can help keep the design focused.
When you do have to change (refactor) you have tests to fall back on
Regardless of when the test are written (before or after) I find writing
the test helps you make practical decisions. E.g., we picked design A or B because
A is more testable.


q: How can I open a cmd window in a specific location without having to navigate all the way to the directory I want?

[A]
Try out
this "PowerToy" from Microsoft
:
Open Command Window Here
This PowerToy adds an "Open Command
  Window Here" context menu option on
  file system folders, giving you a
  quick way to open a command window
  (cmd.exe) pointing at the selected
  folder.
EDIT :
This software will not work on any version of Windows apart from Windows XP.


q: I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change.

[A]
From the
EmacsWiki Aquamacs FAQ
:
To change the font used to display the
current frame, go to the font panel.
You can do this with the keystroke
Apple-t, or via the menu: Options →
Show/Hide → Font Panel. Once there,
select the font you want.
To make the current frame’s font the
default, go to Options → Frame
Appearance Styles. Select “use current
style for foo mode”, where foo is the
mode of the current frame (e.g.,
foo=text for text mode), to use the
current style (including the font, but
also any other changes you’ve made to
the frame’s style) for all files of
this type. Select “use current style
as default” to use the current style
for all files for whose major mode no
special style has been defined.
There are also recommendations for monospaced fonts - Monaco or "Vera Sans Mono".


q:
Can I use this approach efficiently?

using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString))
{
    cmd.Connection.Open();
    // set up parameters and CommandType to StoredProcedure etc. etc.
    cmd.ExecuteNonQuery();
}

My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?

[A]
No, Disposing of the
```
SqlCommand
```
will not effect the Connection. A better approach would be to also wrap the
```
SqlConnection
```
in a using block as well:
```
```
using (SqlConnection conn = new SqlConnection(connstring))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand(cmdstring, conn))
    {
        cmd.ExecuteNonQuery();
    }
}
```
```
Otherwise, the Connection is unchanged by the fact that a Command that was using it was disposed (maybe that is what you want?). But keep in mind, that a Connection should
be disposed of as well, and likely more important to dispose of than a command.
EDIT:
I just tested this:
```
```
SqlConnection conn = new SqlConnection(connstring);
conn.Open();

using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 1", conn))
{
    Console.WriteLine(cmd.ExecuteScalar().ToString());
}

using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 2", conn))
{
    Console.WriteLine(cmd.ExecuteScalar().ToString());
}

conn.Dispose();
```
```
The first command was disposed when the using block was exited. The connection was still open and good for the second command.
So, disposing of the command definitely does not dispose of the connection it was using.


q:
How do you create a database from an Entity Data Model.

So I created a database using the EDM Designer in VisualStudio 2008, and now I want to generate the SQL Server Schema to create storage in SQL Server.

[A]
From what I understand you are not just supposed to use EDM as a "pretty" database designer, in fact EDM does not depend on a specific storage layer. It tries to abstract that part for the developer. There are design schemas (CSDL) and storage schemas (SSDL). Anyway, don't mean to lecture you. ;)
There is
EDM Generator
, which you use to create models and class, etc.. For a DDL kind of export, I've never done that but what I did was map my EDM to an existing database, which was easier for me to get started.
There is a great tutorial on MSDN, which details step by step instructions on how to go about using an existing database, but also touches the how to start from scratch approach.
http://msdn.microsoft.com/en-us/magazine/cc163286.aspx


q: I've got a table of URLs and I don't want any duplicate URLs. How do I check to see if a given URL is already in the table using PHP/MySQL?

[A]
You could do this query:
```
```
SELECT url FROM urls WHERE url = 'http://asdf.com' LIMIT 1
```
```
Then check if
mysql_num_rows()
== 1 to see if it exists.


q: I believe the application has some parts that target .NET, and some that don't. I'm particularly interested in looking at the resource files, if there are any.

[A]
If you want to disassemble native x86/64 app use
IDA
, .NET exe/dll can be disassembled using Reflector. There are
tons
of utilities to extract resources. Can you elaborate your question a bit?


q: Having read the threads Is SqlCommand.Dispose enough? and Closing and Disposing a WCF Service I am wondering for classes such as SqlConnection or one of the several classes inheriting from the Stream class does it matter if I close Dispose rather than Close?

[A]
For
```
SqlConnection
```
, from the perspective of the connection itself, they are equivalent.  According to Reflector,
```
Dispose()
```
calls
```
Close()
```
as well as doing a few additional memory-freeing operations -- mostly by setting members equal to null.
For Stream, they actually are equivalent.
```
Stream.Dispose()
```
simply calls Close().


q: Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.

[A]
Assuming a mythical object TreeItem, that conatins a Children collection to represent your hierarchy.
```
```
public void HandleTreeItems(Action<TreeItem> item, TreeItem parent)
    {
        if (parent.Children.Count > 0)
        {
            foreach (TreeItem ti in parent.Children)
            {
                HandleTreeItems(item, ti);
            }
        }

        item(parent);
    }
```
```
Now to call it, passing in the lambda that handles one item, by printing its name to the console.
```
```
HandleTreeItems(item => { Console.WriteLine(item.Name); }, TreeItemRoot);
```
```


q: How do I set up a network between the Host and the guest OS in Windows vista?

[A]
I don't run vista, but virtualbox should do most of the setup for you - all you need to do is assign an IP address, subnet mask, and (optionally) a default gateway to your guest OS, and it should just work.
Don't bother with any of the advanced network settings in the options for the VM - they're useful in some situations, but I've never had to use them, and I've been using virtualbox for some years now.
If you post the specific problem you're having perhaps I can help more. But your question is rather vague...


q:
If you were to self-fund a software project which tools, frameworks, components would you employ to ensure maximum productivity for the dev team and that the "real" problem is being worked on.

What I'm looking for are low friction tools which get the job done with a minimum of fuss. Tools I'd characterize as such are SVN/TortioseSVN, ReSharper, VS itself. I'm looking for frameworks which solve the problems inherient in all software projects like ORM, logging, UI frameworks/components. An example on the UI side would be ASP.NET MVC vs WebForms vs MonoRail.

[A]
Versioning.
Subversion
is the popular choice. If you can afford it,
Team Foundation Server
offers some benefits. If you want to be super-modern, consider a distributed versioning system, such as
git
,
bazaar
or
Mercurial
. Whatever you do, don't use SourceSafe or other lock-based tools, but rather merge-baseed ones. Consider installing both a Windows Explorer client (such as
TortoiseSVN
) as well as a Visual Studio add-in (such as
AnkhSVN
or
VisualSVN
).
Issue tracking.
Given that Joel Spolsky is on this site's staff,
FogBugz
deserves a mention.
Trac
,
Mantis
and
BugZilla
are widespread open-source choices.
Continuous integration.
CruiseControl.NET
is a popular and open-source choice. There's also
Draco.NET
.
Unit testing.
NUnit
is the popular open-source choice. Does the job. Consider installing the
TestDriven.NET
Visual Studio add-in.
That said, you want to look at the answers to
Essential Programming Tools
and
What is your best list of ‘must have’ development tools?
; while not .NET-specific, they should apply anyway.


q:
If I have:

signed char * p;

and I do a comparison:

if ( *p == 0xFF )
   break;

it will never catch 0XFF, but if I replace it with -1 it will:

if ( *p == (signed char)0xFF )
   break;

How can this happen? Is it something with the sign flag? I though that 0xFF == -1 == 255.

[A]
The value
```
0xFF
```
is a signed int value. C will promote the
```
*p
```
to an
```
int
```
when doing the comparison, so the first if statement is equivalent to:
```
```
if( -1 == 255 ) break;
```
```
which is of course false. By using
```
(signed char)0xFF
```
the statement is equivalent to:
```
```
if( -1 == -1 ) break;
```
```
which works as you expect. The key point here is that the comparison is done with
```
int
```
types instead of
```
signed char
```
types.


q:
What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so:

INSERT INTO some_table (column1, column2, column3)
SELECT
Rows.n.value('(@column1)[1]', 'varchar(20)'),
Rows.n.value('(@column2)[1]', 'nvarchar(100)'),
Rows.n.value('(@column3)[1]', 'int'),
FROM @xml.nodes('//Rows') Rows(n)

However I find that this is getting very slow for even moderate size xml data.

[A]
I'm not sure what is the best method. I used OPENXML construction:
```
```
INSERT INTO Test
SELECT Id, Data
FROM OPENXML (@XmlDocument, '/Root/blah',2)
WITH (Id   int         '@ID',
      Data varchar(10) '@DATA')
```
```
To speed it up, you can create XML indices. You can set index specifically for
value
function performance optimization. Also you can use typed xml columns, which performs better.


q:
I know that tables are for tabular data, but it's so tempting to use them for layout. I can handle DIV's to get a three column layout, but when you got 4 nested DIV's, it get tricky.

Is there a tutorial/reference out there to persuade me to use DIV's for layout?

I want to use DIV's, but I refuse to spend an hour to position my DIV/SPAN where I want it.

@GaryF: Blueprint CSS has to be the CSS's best kept secret.

Great tool - Blueprint Grid CSS Generator.

[A]
This may be unhelpful but I somehow don't understand all these problems related to CSS. If a newspaper designer would try to embed a movie in the ad page, everybody would agree that he's a bit crazy. But still those same people pine after three-column layouts in HTML. HTML is just not apt to handle this kind of layout well at the moment. Furthermore, multi-column layouts are generally not really well-suited for reading on computer monitors. Aren't there enough viable alternatives?
And by the way, even tables don't offer a good way of implementing a fluent column layout so this is no reason at all to resort to such hacks. Assuming a halfway modern browser (i.e. > MSIE 6), tables don't offer any advantages over clean HTML + CSS that I know of.


q:
Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top of your code file.

Now you want to create a class or use a symbol which is defined in multiple namespaces,
e.g. System.Windows.Controls.Image & System.Drawing.Image

Now unless you use the fully qualified name, there will be a crib/build error due to ambiguity inspite of the right 'using' declarations at the top. What is the way out here?

(Another knowledge base post.. I found the answer after about 10 minutes of searching because I didn't know the right keyword to search for)

[A]
Use alias
```
```
using System.Windows.Controls;
using Drawing = System.Drawing;

...

Image img = ... //System.Windows.Controls.Image
Drawing.Image img2 = ... //System.Drawing.Image
```
```
C# using directive


q: What method do you use when you want to get performance data about specific code paths?

[A]
This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.
The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).
It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.
Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.
I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with
DbgView
), including how many times the code was executed (and the average time spent of course)).
```
```
#pragma once
#include <tchar.h>
#include <windows.h>
#include <sstream>
#include <boost/noncopyable.hpp>

namespace scope_timer {
    class time_collector : boost::noncopyable {
        __int64 total;
        LARGE_INTEGER start;
        size_t times;
        const TCHAR* name;

        double cpu_frequency()
        { // cache the CPU frequency, which doesn't change.
            static double ret = 0; // store as double so devision later on is floating point and not truncating
            if (ret == 0) {
                LARGE_INTEGER freq;
                QueryPerformanceFrequency(&freq);
                ret = static_cast<double>(freq.QuadPart);
            }
            return ret;
        }
        bool in_use;

    public:
        time_collector(const TCHAR* n)
            : times(0)
            , name(n)
            , total(0)
            , start(LARGE_INTEGER())
            , in_use(false)
        {
        }

        ~time_collector()
        {
            std::basic_ostringstream<TCHAR> msg;
            msg << _T("scope_timer> ") <<  name << _T(" called: ");

            double seconds = total / cpu_frequency();
            double average = seconds / times;

            msg << times << _T(" times total time: ") << seconds << _T(" seconds  ")
                << _T(" (avg ") << average <<_T(")\n");
            OutputDebugString(msg.str().c_str());
        }

        void add_time(__int64 ticks)
        {
            total += ticks;
            ++times;
            in_use = false;
        }

        bool aquire()
        {
            if (in_use)
                return false;
            in_use = true;
            return true;
        }
    };

    class one_time : boost::noncopyable {
        LARGE_INTEGER start;
        time_collector* collector;
    public:
        one_time(time_collector& tc)
        {
            if (tc.aquire()) {
                collector = &tc;
                QueryPerformanceCounter(&start);
            }
            else
                collector = 0;
        }

        ~one_time()
        {
            if (collector) {
                LARGE_INTEGER end;
                QueryPerformanceCounter(&end);
                collector->add_time(end.QuadPart - start.QuadPart);
            }
        }
    };
}

// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)
#define TIME_THIS_SCOPE(name) \
    static scope_timer::time_collector st_time_collector_##name(_T(#name)); \
    scope_timer::one_time st_one_time_##name(st_time_collector_##name)
```
```


q: I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?


q:
It seems that Silverlight/WPF are the long term future for user interface development with .NET. This is great because as I can see the advantage of reusing XAML skills on both the client and web development sides. But looking at WPF/XAML/Silverlight they seem very large technologies and so where is the best place to get start?

I would like to hear from anyone who has good knowledge of both and can recommend which is a better starting point and why.

[A]
Silverlight is a stripped down version of WPF so it should have fewer things to learn inside. On the other hand, the two platforms have different targets (web & rich client) so I guess it depends on what app you're going to build.
If you just want to learn for yourself (no app in the close future) I'd pick Silverlight because it would be less to assimilate. Still, Silverlight is pretty much a moving target, much more than WPF, so you'll have to keep up with some changes from time to time (the joys of being an early adopter :)).
WPF has lots more stuff that you will probably want to use at some point but I would wait for the needs to arise first.


q: I am trying to retrieve a user on Sharepoint's user photo through the WSS 3.0 object model. I have been browsing the web for solutions, but so far I've been unable to find a way to do it. Is it possible, and if so how?

[A]
Ah, You have to use the UserProfileManager class.
More information here:
http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.userprofilemanager.aspx
Example use:
```
```
public override void ItemAdded(SPItemEventProperties properties)
{
    // Get list item on which the event occurred.
    SPListItem item = properties.ListItem;

    // Set the Author Image field to the user's PictureURL if it exists.
    using (SPWeb web = properties.OpenWeb())
    {
        // Author: {C32DB804-FF2D-4656-A38A-B0394BA5C931}
        SPFieldUserValue authorValue = new SPFieldUserValue(properties.OpenWeb(), item[new Guid("{C32DB804-FF2D-4656-A38A-B0394BA5C931}")].ToString());

        UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(web.Site));
        UserProfile profile = profileManager.GetUserProfile(authorValue.LookupId);
        UserProfileValueCollection values = profile[PropertyConstants.PictureUrl];

        if (values.Count > 0)
        {
            // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F}
            SPFieldUrlValue urlValue = new SPFieldUrlValue(values.Value.ToString());
            item[new Guid("{37A5CA4C-7621-44d7-BF3B-583F742CE52F}")] = urlValue.Url;
        }
    }

    item.Update();

    // News Text: {7F55A8F0-4555-46BC-B24C-222240B862AF}
    //

    // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F}
    //

    // Publish Date: {45E84B8B-E161-46C6-AD51-27A42E4992B5}
    //
}
```
```


q:
I remember back in the day with the old borland DOS compiler you could do something like this:

asm {
 mov ax,ex
 etc etc...
}

Is there a semi-platform independent way to do this now? I have a need to make a BIOS call, so if there was a way to do this without asm code, that would be equally useful to me.

[A]
A good start would be reading this article which talk about inline assembly in C/C++:
http://www.codeproject.com/KB/cpp/edujini_inline_asm.aspx
Example from the article:
```
```
#include <stdio.h>

int main() {
    /* Add 10 and 20 and store result into register %eax */
    __asm__ ( "movl $10, %eax;"
                "movl $20, %ebx;"
                "addl %ebx, %eax;"
    );

    /* Subtract 20 from 10 and store result into register %eax */
    __asm__ ( "movl $10, %eax;"
                    "movl $20, %ebx;"
                    "subl %ebx, %eax;"
    );

    /* Multiply 10 and 20 and store result into register %eax */
    __asm__ ( "movl $10, %eax;"
                    "movl $20, %ebx;"
                    "imull %ebx, %eax;"
    );

    return 0 ;
}
```
```


q:
How do you make your application multithreaded ?
Do you use asynch functions ?
or do you spawn a new thread ?
I think that asynch functions are already spawning a thread so if your job is doing just some file reading, being lazy and just spawning your job on a thread would just "waste" ressources...
So is there some kind of design when using thread or asynch functions ?

[A]
If you are talking about .Net, then don't forget the
ThreadPool
. The thread pool is also what asynch functions often use. Spawning to much threads can actually hurt your performance. A thread pool is designed to spawn just enough threads to do the work the fastest. So do use a thread pool instead of spwaning your own threads, unless the thread pool doesn't meet your needs.
PS: And keep an eye out on the
Parallel Extensions
from Microsoft


q:
I am thinking about the design of an iPhone app I'd like to create.  One possible problem is that this application will have to run as root (to access certain network ports).  In a typical UNIX app, I'd just get the app to run with setuid, but I'm wondering if that is possible with an iPhone app.

I've read this question in Apple's forum, which is discouraging:

http://discussions.apple.com/thread.jspa?threadID=1664575

I understand that Apple wants to limit what a program can do, but there are plenty of good, legitimate reasons for a user to run a program with elevated privileges.  I'm not trying to create a hacker tool here.

I'm sure I could get around this on a jail-broken iPhone, but that's not what I'm after.  Is there any way to run an app with elevated privileges on an unbroken iPhone?

(BTW, there is no need to warn me about the NDA.)

[A]
Section 3.3.4 of the iPhone SDK Agreement suggests that you mustn't work outside your sandbox.
Given that
Apple has been somewhat arbitrary on which applications they permit
, you should definitely double-check with them
before
you start developing.
Compared to 2.0.x,
the sandbox restrictions have actually increased in 2.1
; you can no longer even read from another application's sandbox. So, even if it currently
is
possible to elevate your app's privileges, it very likely won't be in a future release.


q:
Should I still be using tables anyway?

The table code I'd be replacing is:

<table>
    <tr>
        <td>Name</td><td>Value</td>
    </tr>
    ...
</table>

From what I've been reading I should have something like

<label class="name">Name</label><label class="value">Value</value><br />
...

Ideas and links to online samples greatly appreciated.  I'm a developer way out of my design depth.

EDIT: My need is to be able to both to display the data to a user and edit the values in a separate (but near identical) form.

[A]
I think tables are best used for tabular data, which it seems you have there.
If you do not want to use tables, the best thing would be to use definition lists(
```
<dl> and <dt>
```
). Here is how to style them to look like your old
```
<td>
```
layout.
http://maxdesign.com.au/articles/definition/


q:
I want to write an onClick event which submits a form several times, iterating through selected items in a multi-select field, submitting once for each.

How do I code the loop?

I'm working in Ruby on Rails and using remote_function() to generate the JavaScript for the ajax call.

[A]
My quick answer (as I've not coded it yet) would be to create another function that creates a POST using XMLHTTPRequest and the specific parameters for a single call. Then inside your onClick() handler call that function as you loop through your selected items.
I would suggest that you do a Proof of Concept just using a dummy HTML page and javascript and then try to figure out how to get it to work in RoR.
Also, why are you attempting to make the multiple calls from the browser as opposed to handling the looping conditions in the RoR controller?


q:
I'm sure most of you are writing lots of automated tests and that you also have run into some common pitfalls when unit testing.

My question is do you follow any rules of conduct for writing tests in order to avoid problems in the future? To be more specific: What are the properties of good unit tests or how do you write your tests?

Language agnostic suggestions are encouraged.

[A]
Keep these goals in mind (adapted from the book xUnit Test Patterns by Meszaros)
Tests should reduce risk, not
introduce it.
Tests should be easy to run.
Tests should be easy to maintain as
the system evolves around them
Some things to make this easier:
Tests should only fail because of
one reason.
Tests should only test one thing
Minimize test dependencies (no
dependencies on databases, files, ui
etc.)
Don't forget that you can do intergration testing with your xUnit framework too
but keep intergration tests and unit tests separate


q:
In evaluating different systems integration strategies, I've come across some words of encouragement, but also some words of frustration over BizTalk Server.

What are some pros and cons to using BizTalk Server (both from a developer standpoint and a business user), and should companies also consider open source alternatives? What viable alternatives are out there?

EDIT: Jitterbit seems like an interesting choice. Open Source and seems to be nicely engineered. Anyone on here have any experience working with it?

[A]
My experience with BizTalk was basically a frustrating waste of time.
There are so many edge cases and weird little business logic tweaks you have to make when you are doing B2B data integration (which is probably the hardest part of any enterprise application) that you just need to roll your own solution.
How hard is it to parse data files and convert them to a different format?  Not that hard.  Unless you're trying to inject a bloated middleware system like Biztalk into the middle of it.


q:
I've just created a new Windows XP VM on my Mac using VMware Fusion. The VM is using NAT to share the host's internet connection.

How do I access a Rails application, which is accessible on the Mac itself using http://localhost:3000?

[A]
On the XP machine, find your IP address by going to the command prompt and typing
```
ipconfig
```
. Try replacing the last number with 1 or 2. For example, if your IP address is 192.168.78.128, use
http://192.168.78.1:3000
.


q:
I need to figure out what div is visible out of four possible divs using jQuery.  Only one of those div's will be visible at any given time.

This is what I have that works so far:

$("#FeatureImage1:visible, #FeatureImage2:visible, #FeatureImage3:visible, #FeatureImage4:visible").attr("id");

Is there a way to refactor this?  Is there an easier way to figure this out?

[A]
Assign the same class to each div then:
```
```
$("div.myClass:visible").attr("id");
```
```


q:
With all the fuss about opensource projects, how come there is still not a strong standard that enables you to make portable code (I mean in C/C++ not Java or C#)
Everyone is kind of making it's own soup.

There are even some third party libs like Apache Portable Runtime.

[A]
I think the main reason there isn't any single library anyone agrees on is that everyone's requirements are different. When you want to wrap system libraries you'll often need to make some assumptions about what the use cases will be, unless you want to make the wrapper huge and impossible to work with. I think that might be the main reason there's no single, common cross platform runtime.
For GUI, the reason would be that each platform has its own UI conventions, you can't code one GUI that fits all, you'll simply get one that fits just one or even none at all.


q:
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:

>>> class Foo:
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }

NOTE: It should not include methods. Only fields.

[A]
The
```
dir
```
builtin will give you all the object's attributes, including special methods like
```
__str__
```
,
```
__dict__
```
and a whole bunch of others which you probably don't want. But you can do something like:
```
```
>>> class Foo(object):
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> [name for name in dir(f) if not name.startswith('__')]
[ 'bar', 'baz' ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__'))
{ 'bar': 'hello', 'baz': 'world' }
```
```
So can extend this to only return data attributes and not methods, by defining your
```
props
```
function like this:
```
```
import inspect

def props(obj):
    pr = {}
    for name in dir(obj):
        value = getattr(obj, name)
        if not name.startswith('__') and not inspect.ismethod(value):
            pr[name] = value
    return pr
```
```


q: There is a lot of information out there on object-relational mappers and how to best avoid impedance mismatch, all of which seem to be moot points if one were to use an object database.  My question is why isn't this used more frequently?  Is it because of performance reasons or because object databases cause your data to become proprietary to your application or is it due to something else?

[A]
Familiarity.
The administrators of databases know relational concepts; object ones, not so much.
Performance.
Relational databases have been proven to scale far better.
Maturity.
SQL is a powerful, long-developed language.
Vendor support.
You can pick between many more first-party (SQL servers) and third-party (administrative interfaces, mappings and other kinds of integration) tools than is the case with OODBMSs.
Naturally, the object-oriented model is more familiar to the
developer
, and, as you point out, would spare one of ORM. But thus far, the relational model has proven to be the more workable option.
See also the recent question,
Object Orientated vs Relational Databases
.


q:
I have a network C++ program in Windows that I'd like to test for network disconnects at various times.  What are my options?

Currently I am:

Actually disconnecting the network wire from the back of my computer

using ipconfig /release

Using the cports program to close out the socket completely

None of these methods though are ideal for me, and I'd like to emulate network problems more easily.

I would like for sometimes connects to fail, sometimes socket reads to fail, and sometimes socket writes to fail.  It would be great if there was some utility I could use to emulate these types of problems.

It would also be nice to be able to build some automated unit tests while this emulated bad network is up.

[A]
The closest I can think of is doing something similar with
VEDekstop
from Shunra..
Simulating High Latency and Low Bandwidth in Testing of Database Applications
Shunra VE Desktop Standard is a Windows-based client software solution that simulates a wide area network link so that you can test applications under a variety of current and potential network conditions – directly from your desktop.


q:
I get a URL from a user. I need to know:

a) is the URL a valid RSS feed?

b) if not is there a valid feed associated with that URL

using PHP/Javascript or something similar

(Ex. http://techcrunch.com fails a), but b) would return their RSS feed)

[A]
a) Retrieve it and try to parse it. If you can parse it, it's valid.
b) Test if it's an HTML document (server sent
```
text/html
```
) MIME-type. If so, run it through an HTML parser and look for
```
<link>
```
elements with RSS feed relations.


q:
Alan Storm's comments in response to my answer regarding the with statement got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of with, while avoiding its pitfalls.

Where have you found the with statement useful?

[A]
Visual Basic.NET has a similar
```
With
```
statement. One of the more common ways I use it is to quickly set a number of properties. Instead of:
```
```
someObject.Foo = ''
someObject.Bar = ''
someObject.Baz = ''
```
```
, I can write:
```
```
With someObject
    .Foo = ''
    .Bar = ''
    .Baz = ''
End With
```
```
This isn't just a matter of laziness. It also makes for much more readable code. And unlike JavaScript, it does not suffer from ambiguity, as you have to prefix everything affected by the statement with a
```
.
```
(dot). So, the following two are clearly distinct:
```
```
With someObject
    .Foo = ''
End With
```
```
vs.
```
```
With someObject
    Foo = ''
End With
```
```
The former is
```
someObject.Foo
```
; the latter is
```
Foo
```
in the scope
outside
```
someObject
```
.
I find that JavaScript's lack of distinction makes it far less useful than Visual Basic's variant, as the risk of ambiguity is too high. Other than that,
```
with
```
is still a powerful idea that can make for better readability.


q:
In python, you can have a function return multiple values.  Here's a contrived example:

def divide(x, y):
    quotient = x/y
    remainder = x % y
    return quotient, remainder

(q, r) = divide(22, 7)

This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value.  Let's have X return that value also").

When should you draw the line and define a different method?

[A]
Firstly, note that Python allows for the following (no need for the parenthesis):
```
```
q, r = divide(22, 7)
```
```
Regarding your question, there's no hard and fast rule either way. For simple (and usually contrived) examples, it may seem that it's always possible for a given function to have a single purpose, resulting in a single value. However, when using Python for real-world applications, you quickly run into many cases where returning multiple values is necessary, and results in cleaner code.
So, I'd say do whatever makes sense, and don't try to conform to an artificial convention. Python supports multiple return values, so use it when appropriate.


q:
When I downloaded Skype, I noticed that, in place of a normal "disk image" icon, there was a custom icon, and when I double clicked on the icon, the window used a colorful image as the background, prompting me to drag the skype icon into the applications folder.

How can I do that with my applications?

Thanks,
Jason

[A]
Let me add to the other answers
jwz's howto
on setting view options on .dmg files. This is the simplest one that I got to work with no problems.
Also, to change the icon from the default .dmg icon:
In the Finder, open an inspector window (^I) for the file whose icon you want to use, click on the icon at the top (it will get a blue border) and copy it to the clipboard (^C).
Then open another inspector for your .dmg, click on the icon and press ^V to paste
(you can change the icon for any file like this).
For this kind of thing, you can always look at open-source programs and see what they do to get a similar result. For example here are the relevant source files for building pretty dmg files in:
Adium
Miro


q:
How do I use the profiler in Visual Studio 2008?

I know theres a build option in Config Properties -> Linker -> Advanced -> Profile (/PROFILE), however I can't find anything about actauly using it, only articles I was able to find appear to only apply to older versions of Visual Studio (eg most say to goto Build->Profile to bring up the profile dialog box, yet in 2008 there is no such menu item).

Is this because Visual Studio 2008 does not include a profiler, and if it does where is it and where is the documentation for it?

[A]
The profiler is only available in the Team System editions of Visual Studio 2008. The last version that I used that included a profiler was Visual C++ 6.0.
For Visual Studio 2005, you could try
Compuware DevPartner Performance Analysis Community Edition
.


q:
I'm reading lines of input on a TCP socket, similar to this:

class Bla
  def getcmd
    @sock.gets unless @sock.closed?
  end

  def start
    srv = TCPServer.new(5000)
    @sock = srv.accept
    while ! @sock.closed?
      ans = getcmd
    end
  end
end

If the endpoint terminates the connection while getline() is running then gets() hangs.

How can I work around this? Is it necessary to do non-blocking or timed I/O?

[A]
If you believe the
rdoc
for ruby sockets, they don't implement
```
gets
```
. This leads me to believe gets is being provided by a higher level of abstraction (maybe the IO libraries?) and probably isn't aware of socket-specific things like 'connection closed.'
Try using
```
recvfrom
```
instead of
```
gets
```


q:
Suppose I have a COM object which users can access via a call such as:

Set s = CreateObject("Server")

What I'd like to be able to do is allow the user to specify an event handler for the object, like so:

Function ServerEvent

   MsgBox "Event handled"

End Function

s.OnDoSomething = ServerEvent

Is this possible and, if so, how do I expose this in my type library in C++ (specifically BCB 2007)?

[A]
I'm a little hazy on the details, but maybe the link below might help:
http://msdn.microsoft.com/en-us/library/ms974564.aspx
It looks like your server object needs to implement
```
IProvideClassInfo
```
and then you call
```
ConnectObject
```
in your VBScript code. See also:
http://blogs.msdn.com/ericlippert/archive/2005/02/15/373330.aspx


q:
I need to create a 2D int array of size 800x800.  But doing so creates a stack overflow (ha ha).

I'm new to C++, so should I do something like a vector of vectors?  And just encapsulate the 2d array into a class?

Specifically, this array is my zbuffer in a graphics program.  I need to store a z value for every pixel on the screen (hence the large size of 800x800).

Thanks!

[A]
You need about 2.5 megs, so just using the heap should be fine.  You don't need a vector unless you need to resize it.  See
C++ FAQ Lite
for an example of using a "2D" heap array.
```
```
int *array = new int[800*800];
```
```
(Don't forget to
```
delete[]
```
it when you're done.)


q:
The .NET Setup project seems to have a lot of options, but I don't see an "Uninstall" option.

I'd prefer if people could "uninstall" from the standard "start menu" folder rather than send them to the control panel to uninstall my app, so can someone please tell me how to do this?

Also, I am aware of non Microsoft installers that have this feature, but if possible I'd like to stay with the Microsoft toolkit.

[A]
You can make shortcut to:
```
```
msiexec /uninstall [path to msi or product code]
```
```


q:
I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it.

I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely?


q:
Until recently we were using Inno Setup for our installations, something I would like to continue doing, unless we can get an uninstall option in the start menu (thanks Giovanni Galbo), however we now need to GAC some external libraries, something I suspect is only doable (or at least only supported) though the .NET Setup Project.

Is it possible to call a GAC'ing library from another setup application?

[A]
Not sure about library, but you can call
gacutil.exe
to install/uninstall assemblies.


q:
I'm drawing old school (unthemed - themed radios are a whole other problem) radio buttons myself using DrawFrameControl:

DrawFrameControl(dc, &rectRadio, DFC_BUTTON, isChecked() ? DFCS_BUTTONRADIO | DFCS_CHECKED : DFCS_BUTTONRADIO);

I've never been able to figure out a sure fire way to figure out what to pass for the RECT. I've been using a 12x12 rectangle but I'de like Windows to tell me the size of a radio button.

DrawFrameControl seems to scale the radio button to fit the rect I pass so I have to be close to the "right" size of the radio looks off from other (non-owner drawn) radios on the screen.

Anyone know how to do this?

[A]
It has been a while since I worked on this, so what I am describing is what I did, and not necessarily a direct answer to the question.
I happen to use bit maps 13 x 13 rather than 12 x 12.   The bitmap part of the check box seems to be passed in the WM_DRAWITEM.  However, I had also set up WM_MEASUREITEM and fed it the same values, so my answer may well be "Begging the question" in the correct philosophical sense.
```
case WM_MEASUREITEM:
            lpmis = (LPMEASUREITEMSTRUCT) lParam;

            lpmis->itemHeight = 13;
            lpmis->itemWidth = 13;

            break;

        case WM_DRAWITEM:
            lpdis = (LPDRAWITEMSTRUCT) lParam;
            hdcMem = CreateCompatibleDC(lpdis->hDC);

            if (lpdis->itemState & ODS_CHECKED)  // if selected
                {
                SelectObject(hdcMem, hbmChecked);
                }
            else
                {
                if (lpdis->itemState & ODS_GRAYED)
                    {
                    SelectObject(hdcMem, hbmDefault);
                    }
                else
                    {
                    SelectObject(hdcMem, hbmUnChecked);
                    }
                }
            StretchBlt(
                lpdis->hDC,         // destination DC
                lpdis->rcItem.left, // x upper left
                lpdis->rcItem.top,  // y upper left

                // The next two lines specify the width and
                // height.
                lpdis->rcItem.right - lpdis->rcItem.left,
                lpdis->rcItem.bottom - lpdis->rcItem.top,
                hdcMem,    // source device context
                0, 0,      // x and y upper left
                13,        // source bitmap width
                13,        // source bitmap height
                SRCCOPY);  // raster operation

            DeleteDC(hdcMem);
            return TRUE;
```
This seems to work well for both Win2000 and XP, though I have nbo idea what Vista might do.
It might be worth an experiment to see what leaving out WM_MEASUREITEM does, though I usually discover with old code that I usually had perfectly good reason for doing something that looks redundant.


q: How can I get PDO to work on my mac (os x 10.5)? I'm using the built in php and php in Zend/Eclipse. Can't seem to find useful drivers for it at all.

[A]
I'm not sure this will help with the PDO drivers specifically, but you might look into
BitNami's MAPPStack
.
I had a ton of trouble with Postgres, PHP, and Apache on my Mac, some of it having to do with 64- vs 32-bit versions of some or all of them.  So far, the BitNami MAPPStack install is working nicely in general.  Maybe it will help with your PDO issues as well.


q:
I am using a rich text editor on a web page.  .NET has feature that prevent one from posting HTML tags, so I added a JavaScript snippet to change the angle brackets to and alias pair of characters before the post. The alias is replaced on the server with the necessary angle bracket and then stored in the database.  With XSS aside, what are common ways of fixing this problem. (i.e. Is there a better way?)

If you have comments on XSS(cross-site scripting), I'm sure that will help someone.

[A] My first comment would be to avoid using JavaScript to change the angle brackets. Bypassing this is as simple as disabling JavaScript in the browser. Almost all server-side languages have some utility method that converts some HTML characters into their entity counterparts. For instance, PHP uses htmlentities(), and I am sure .NET has an equivalent utility method. In the least, you can do a regex replace for angle brackets, parenthesis and double quotes, and that will get you a long way toward a secure solution.


q: Navision is also known as Microsoft Dynamics NAV.

[A]
Navision's application logic is written using a proprietary language called C/AL, which is loosely based on Pascal.  It currently offers both a native database option as well as MS SQL Server.
The next version (NAV 2009) will use .NET assemblies served via IIS.  C/AL logic will be translated to C# code and deployed to the server.


q:
I'm just curious if any project exists that attempts to group all (or most) of PHP's built-in functions into a more object-oriented class hierarchy. For example, grouping all the string functions into a single String class, etc.

I realize this won't actually solve any problems (unless the modifications took place at the PHP source code level), since all the built-in functions would still be accessible in the global namespace, but it would certainly make usability much easier.

[A] I think something like this is intergral for PHP to move forward.  Being mainly a .Net programmer, I find PHP painful to work in with it's 1 million and 1 global functions.  It's nice that PHP 5.3 has namespaces, but it doesn't help things much when their own libraries aren't even object oriented, let alone employ namespaces.  I don't mind PHP as a language so much, but their API is terribly disorganized, and it probably needs a complete overhaul.  Kind of like what VB went through when it became VB.Net.


q:
I'm looking for a Java profiler that works well with the JVM coming with WebSphere 6.0.2 (IBM JVM 1.4.2). I use yourkit for my usual profiling needs, but it specifically refuses to work with this old jvm (I'm sure the authors had their reasons...).

Can anybody point to a decent profiler that can do the job? Not interested in a generic list of profilers, BTW, I've seen the other stackoverflow theread, but I'd rather not try them one by one.

I would prefer a free version, if possible, since this is a one-off need (I hope!) and I would rather not pay for another profiler just for this.

[A]
What are you looking to profile?  Is it stuff in the JVM or the App Server? If it's the latter, there's loads of stuff in WAS 6 GUI to help with this.  Assuming you really want to see stuff like the heap etc, then the IBM
HeapAnalyzer
might help.  There are other tools listed off the bottom of this page.
Something else I've learned, ideally, youll be able to connect your IDE's profiler to the running JVM.  Some let you do this to a remote one as well as the local one you are developing on.  Is the JVM you wish to profile in live or remote?  If so, you might have to force dumps and take them out of the live environment to look at at your leisure.  Otherwise, set up something local and get the info from it that way.


q:
I am wondering what the best way to obtain the current domain is in ASP.NET?

For instance:

http://www.domainname.com/subdir/ should yield http://www.domainname.com
http://www.sub.domainname.com/subdir/ should yield http://sub.domainname.com

As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.

[A]
As per
this link
a good starting point is:
```
```
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
```
```
However, if the domain is
http://www.domainname.com:500
this will fail.
Something like the following is tempting to resolve this:
```
```
int defaultPort = Request.IsSecureConnection ? 443 : 80;
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
  + (Request.Url.Port != defaultPort ? ":" + Request.Url.Port : "");
```
```
However, port 80 and 443 will depend on configuration.
As such, you should use
```
IsDefaultPort
```
as in the
Accepted Answer
above from Carlos Muñoz.


q:
Anyone using WPF for real LOB applications?

We have all seen the clever demos of WPF showing videos mapped onto 3D elements. These look great but what about the real world of line-of-business applications that make up the majority of developers efforts. Is WPF just for nice eye candy?

[A]
I feel the eye candy demos are targeted mostly towards designers. Having said that, there is a huge potential in improving usability of LOB apps using WPF.
Check this article about the potential of Silverlight
.
Line-of-business applications have a notorious reputation for being all business and no pleasure. The fact is that "user experience" has never really been a top concern when developing line-of-business (LOB) applications. While many LOB-style applications are putting an increasing emphasis on usability, they often fall short on appeal. User experience is actually a combination of both usability and appeal.


q:
I am attempting to copy a custom struct from kernel space to user space. inside user space errno returns 'bad address'.  What is the usual cause of a bad address error?

if(copy_to_user(info, &kernel_info, sizeof(struct prinfo)))

[A]
Bad Address error means that the address location that you have given is invalid. With the case you have above I would guess it is because you are passing a copy of
```
info
```
instead of a pointer to
```
info
```
's memory location.
Looking at the docs,
```
copy_to_user
```
is defined as
```
```
copy_to_user(void __user * to, const void * from, unsigned long n);
```
```
So unless your
```
info
```
variable is a pointer I would update your code to be:
```
```
if(copy_to_user(&info, &kernel_info, sizeof(struct prinfo)) ) {
    //some stuff here i guess
}
```
```


q: I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles.  I saw it done here: http://www.dayah.com/periodic/.  Click on an element and the iframe is displayed and links to the article only (no wrapper).  So how'd they do that?  Seems like JavaScript handles showing the iframe and constructing the href but after browsing the pages javascript (http://www.dayah.com/periodic/Script/interactivity.js) I still can't figure out how the url is built.  Thanks.

[A]
You could always download the site and scrap it. I think everything inside
```
<div id="bodyContent">
```
is the content of the article - sans navigation, header, footer, etc..
Don't forget to credit. ;)


q:
Let's say I have the following simple enum:

enum Response
{
    Yes = 1,
    No = 2,
    Maybe = 3
}

How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?

[A]
I probably wouldn't
bind
the data as it's an enum, and it won't change after compile time (unless I'm having one of those
stoopid
moments).
Better just to iterate through the enum:
```
```
Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Response))

For i As Integer = 0 To itemNames.Length - 1
    Dim item As New ListItem(itemNames(i), itemValues(i))
    dropdownlist.Items.Add(item)
Next
```
```
Or the same in C#
```
```
Array itemValues = System.Enum.GetValues(typeof(Response));
Array itemNames = System.Enum.GetNames(typeof(Response));

for (int i = 0; i <= itemNames.Length - 1 ; i++) {
    ListItem item = new ListItem(itemNames[i], itemValues[i]);
    dropdownlist.Items.Add(item);
}
```
```


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

declare @databases table
(
    DatabaseID    int,
    Name        varchar(15),
    Server      varchar(15)
)
-- insert a bunch rows into @databases

Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?

[A]
You can use a while loop:
```
```
While (Select Count(*) From #TempTable) > 0
Begin
    Insert Into @Databases...

    Delete From #TempTable Where x = x
End
```
```


q: Best recommendations for accessing and manipulation of sqlite databases from JavaScript.

[A]
Well, if you are working on client side JavaScript, I think you will be out of luck... browsers tend to sandbox the JavaScript environment so you don't have access to the machine in any kind of general capacity like accessing a database.
If you are talking about an SQLite DB on the server end accessed from the client end, you could set up an AJAX solution that invokes some server side code to access it.
If you are talking about Rhino or some other server side JavaScript, you should look into the host language's API access into SQLite (such as the JDBC for Rhino).
Perhaps clarify your question a bit more...?


q:
Given the following XML:

<current>
  <login_name>jd</login_name>
</current>
<people>
  <person>
    <first>John</first>
    <last>Doe</last>
    <login_name>jd</login_name>
  </preson>
  <person>
    <first>Pierre</first>
    <last>Spring</last>
    <login_name>ps</login_name>
  </preson>
</people>

How can I get "John Doe" from within the current/login matcher?

I tried the following:

<xsl:template match="current/login_name">
  <xsl:value-of select="../people/first[login_name = .]"/>
  <xsl:text> </xsl:text>
  <xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>

[A]
I think what he actually wanted was the replacement in the match for the "current" node, not a match in the person node:
```
```
<xsl:variable name="login" select="//current/login_name/text()"/>

<xsl:template match="current/login_name">
<xsl:value-of select='concat(../../people/person[login_name=$login]/first," ", ../../people/person[login_name=$login]/last)'/>

</xsl:template>
```
```


q:
I was wondering if anybody knew of a method to configure apache to fall back to returning a static HTML page, should it (Apache) be able to determine that PHP has died?  This would provide the developer with a elegant solution to displaying an error page and not (worst case scenario) the source code of the PHP page that should have been executed.

Thanks.

[A]
I would assume that this typically results in a 500 error, and you can configure apaches 500 handler to show a static page:
ErrorDocument 500 /500error.html
You can also read about error handlers on
apaches documentation site


q:
I'm trying to construct a find command to process a bunch of files in a directory using two different executables.  Unfortunately, -exec on find doesn't allow to use pipe or even \| because the shell interprets that character first.

Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command):

find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print

[A]
As this outputs a list would you not :
```
```
find /path/to/jpgs -type f -exec jhead -v {} \; | grep 123
```
```
or
```
```
find /path/to/jpgs -type f -print -exec jhead -v {} \; | grep 123
```
```
Put your grep on the results of the find -exec.


q:
I need to build something that starts serving a H.264 encoded video to a flash player halfway through the file (to support skipping to a point in the video that has not been buffered yet).

Currently, the videos are in the FLV container format, but transcoding is an option. I managed to re-write the file header and metadata information for a given byte offset. This works for older videos, but not for H.264 encoded files. I suspect this is because the video tags inside the file also have to be altered, which is not feasible (it would take too much processing power).

What is the "proper" way to do it?

[A]
@yoavf - I think the OP is interested in server-side aspects of streaming on-demand h.264 inside of FLV files.  Reuse of existing players would be nice for him, I think.  Or maybe that is my own needs coming out?  <:S
From yoavf's second link, there is another link to Tinic Uro's
What just happened to video on the web?
.  A relevant quote:
Will it be possible to place H.264 streams into the traditional FLV file structure? It will, but we strongly encourage everyone to embrace the new standard file format. There are functional limits with the FLV structure when streaming H.264 which we could not overcome without a redesign of the file format. This is one reason we are moving away from the traditional FLV file structure. Specifically dealing with sequence headers and enders is tricky with FLV streams.
So, it seems one can either tinker with ffmpeg encoding (if that is how you are getting your FLVs, like I am) or one can get into the new format.  Hmmmm....


q:
I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.

1) Is it actually worth taking such things into account?

2) Assuming it is worth taking it into account, how do I do this?

I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.

[A]
If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes.
Nonetheless you can use the time command to measure everything and can compare it with the timing within a script.
Like this:
```
```
$ time script.php
HI!

real    0m3.218s
user    0m0.080s
sys     0m0.064s
```
```
It will give you clock time, user time (php interpreter) and sys time (OS time)
If you are thinking web, then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if, say, you are using WSGI v/s mod_php. Then you'd have to hook probes into the webserving parts of the chain as well


q:
I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!

Suppose I have the following XML (using e4x):

var xml:XML = <root><example>foo</example></root>

I can change the contents of the example node using the following code:

xml.example = "bar";

However, if I have this:

var xml:XML = <root>foo</root>

How do i change the contents of the root node?

xml = "bar";

Obviously doesn't work as I'm attempting to assign a string to an XML object.

[A]
If you're trying to change the root element of a document, you don't really need to-- just throw out the existing document and replace it. Alternatively, just wrap your  element in a more proper root element (you shouldn't be editing the root node anyway) and you'd be set.
Of course, that doesn't answer your question. There's an ugly JS hack that can do what you want, but bear in mind that it's likely far slower than doing the above. Anyway, here it is:
```
```
var xml = <root>foo</root>; // </fix_syntax_highlighter>
var parser = new DOMParser();
var serializer = new XMLSerializer();

// Parse xml as DOM document
// Must inject "<root></root>" wrapper because
// E4X's toString() method doesn't give it to us
// Not sure if this is expected behaviour.. doesn't seem so to me.
var xmlDoc = parser.parseFromString("<root>" +
  xml.toString() + "</root>", "text/xml");

// Make the change
xmlDoc.documentElement.firstChild.nodeValue = "CHANGED";

// Serialize back to string and then to E4X XML()
xml = new XML(serializer.serializeToString(xmlDoc));
```
```
You can ignore the fix_syntax_highlighter comment.


q: I've just heard the term covered index in some database discussion - what does it mean?

[A]
A
covering index
is an index that contains all of, and possibly more, the columns you need for your query.
For instance, this:
```
```
SELECT *
FROM tablename
WHERE criteria
```
```
will typically use indexes to speed up the resolution of which rows to retrieve using
criteria
, but then it will go to the full table to retrieve the rows.
However, if the index contained the columns
column1, column2
and
column3
, then this sql:
```
```
SELECT column1, column2
FROM tablename
WHERE criteria
```
```
and, provided that particular index could be used to speed up the resolution of which rows to retrieve, the index already contains the values of the columns you're interested in, so it won't have to go to the table to retrieve the rows, but can produce the results directly from the index.
This can also be used if you see that a typical query uses 1-2 columns to resolve which rows, and then typically adds another 1-2 columns, it could be beneficial to append those extra columns (if they're the same all over) to the index, so that the query processor can get everything from the index itself.
Here's an
article: Index Covering Boosts SQL Server Query Performance
on the subject.


q: I've been wondering what exactly are the principles of how the two properties work. I know the second one is universal and basically doesn't deal with time zones, but can someone explain in detail how they work and which one should be used in what scenario?

[A]
DateTime.UtcNow
tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer.
DateTime.Now
gives the date and time as it would appear to someone in your current locale.
I'd recommend using
```
DateTime.Now
```
whenever you're displaying a date to a human being - that way they're comfortable with the value they see - it's something that they can easily compare to what they see on their watch or clock. Use
```
DateTime.UtcNow
```
when you want to store dates or use them for later calculations that way (in a client-server model) your calculations don't become confused by clients in different time zones from your server or from each other.


q:
Several times now I've been faced with plans from a team that wants to build their own bug tracking system - Not as a product, but as an internal tool.

The arguments I've heard in favous are usually along the lines of :

Wanting to 'eat our own dog food' in terms of some internally built web framework

Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way

Believing that it isn't difficult to build a bug tracking system

What arguments might you use to support buying an existing bug tracking system? In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked?

[A]
The most basic argument for me would be the time loss. I doubt it could be completed in less than a month or two. Why spend the time when there are soooo many good bug tracking systems available? Give me an example of a feature that you have to tweak and is not readily available.
I think a good bug tracking system has to reflect your development process. A very custom development process is inherently bad for a company/team. Most agile practices favor
Scrum
or these kinds of things, and most bug tracking systems are in line with such suggestions and methods. Don't get too bureaucratic about this.


q:
To commemorate the public launch of Stack Overflow, what's the shortest code to cause a stack overflow? Any language welcome.

ETA: Just to be clear on this question, seeing as I'm an occasional Scheme user: tail-call "recursion" is really iteration, and any solution which can be converted to an iterative solution relatively trivially by a decent compiler won't be counted. :-P

ETA2: I've now selected a “best answer”; see this post for rationale. Thanks to everyone who contributed! :-)

[A]
My current best (in x86 assembly) is:
```
```
push eax
jmp short $-1
```
```
which results in 3 bytes of object code (
```
50 EB FD
```
). For 16-bit code, this is also possible:
```
```
call $
```
```
which also results in 3 bytes (
```
E8 FD FF
```
).


q:
An instance of class A instantiates a couple of other objects, say for example from class B:

$foo = new B();

I would like to access A's public class variables from methods within B.

Unless I'm missing something, the only way to do this is to pass the current object to the  instances of B:

$foo = new B($this);

Is this best practice or is there another way to do this?

[A]
I would first check if you are not using the wrong pattern: From your application logic, should B really know about A? If B needs to know about A, a parent-child relationship seems not quite adequate. For example, A could be the child, or part of A's logic could go into a third object that is "below" B in the hierarchy (i. e. doesn't know about B).
That said, I would suggest you have a method in B to register A as a data source, or create a method in A to register B as an
Observer
and a matching method in B that A uses to notify B of value changes.


q: Is there an easy way to avoid dealing with text encoding problems?

[A]
The obvious names for these classes are ReaderInputStream and WriterOutputStream. Unfortunately these are not included in the Java library. However, google is your friend.
I'm not sure that it is going to get around all text encoding problems, which are nightmarish.
There is an RFE,
but it's Closed, will not fix.


q:
I am trying to refactor some code I have for software that collects current status of agents in a call queue. Currently, for each of the 6 or so events that I listen to, I check in a Mnesia table if an agent exists and change some values in the row depending on the event or add it as new if the agent doesn't exist. Currently I have this Mnesia transaction in each event and of course that is a bunch of repeated code for checking the existence of agents and so on.

I'm trying to change it so that there is one function like change_agent/2 that I call from the events that handles this for me.

My problems are of course records.... I find no way of dynamically creating them or merging 2 of them together or anything. Preferably there would be a function I could call like:

change_agent("001", #agent(id = "001", name = "Steve")).
change_agent("001", #agent(id = "001", paused = 0, talking_to = "None")).

[A]
It is difficult to write generic access functions for records.
One workaround for this is the
'exprecs'
library, which
will generate code for low-level record access functions.
The thing you need to do is to add the following lines to
a module:
```
```
-compile({parse_transform, exprecs}).
-export_records([...]).  % name the records that you want to 'export'
```
```
The naming convention for the access functions may look strange, but was inspired by a proposal from Richard O'Keefe. It is, at least, consistent, and unlikely to clash with existing functions. (:


q:
I recently asked about keyword expansion in Git and I'm willing to accept the design not to really support this idea in Git.

For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:

svn propset svn:keywords "Id" expl3.dtx

to keep this string up-to-date:

$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $

But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:

"We ignore all SVN properties except svn:executable"

But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?

[A]
You could set the ident attribute on your files, but that would produce strings like
```
```
$Id: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef$
```
```
where
```
deadbeef...
```
is the sha1 of the blob corresponding to that file. If you really need that keyword expansion, and you need it in the git repo (as opposed to an exported archive), I think you're going to have to go with the
```
ident
```
gitattribute with a custom script that does the expansion for you. The problem with just using a hook is then the file in the working tree wouldn't match the index, and git would think it's been modified.


q:
I have a winform app that calls a web service to check for updates.  This works in dev and it also works everywhere else I've tried it, just not on the installed copy on my machine (which happens to be the same in dev).

The error is:

Cannot execute a program. The command being executed was "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe" /noconfig /fullpaths @"C:\Documents and Settings\Giovanni.DOUBLE-AFSSZ043\Local Settings\Temp\squ8oock.cmdline".

The firewall is disabled and I've looked for "C:\Documents and Settings\Giovanni.DOUBLE-AFSSZ043\Local Settings\Temp\squ8oock.cmdline" and it is not there.  Note that every time I try to use the web service the ".cmdline" file is different, for example the second time I ran it it was "dae8rgen.cmdline."  No matter what name it has, I can never find the file.

Any suggestions?

[A]
The ".cmdline" file is an autogenerated file produced by the .NET framework. The application is attempting to real-time compile an XML Serializer used to parse the data from the web service.
Have you verified that you can execute "csc.exe" from a command-line window? Even just typing "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe /?" should get you a list of compiler options (or should give you an error if you don't have permissions to execute it).
What user account are you running this under, and does it have permissions to execute .exe files in the windows directory? Similarly, I know you said this happens with the installed copy on your machine, but is it possible it's executing off a network share and receiving limited Code Access Security permissions which would prevent it from running local executables?
For reference, here is a KB article showing a similar error that can occur in ASP.NET when the user account doesn't have enough permissions.
http://support.microsoft.com/kb/315904


q: How is it possible to read/write to the Windows registry using Java?

[A]
Yes, using the java.util.Preferences API, since the Windows implementation of it uses the Registry as a backend.
In the end it depends on what you're wanting to do: storing preferences for your app is what the Preferences does just great. If you're wanting to actually change registry keys not having to do with your app, you'll need some JNI app, as described by Mark (shameless steal here):
From a quick google:
Check the WinPack for JNIWrapper. It has full Windows Registry access support including Reading and Writing.
The WinPack Demo has Registry Viewer implemented as an example.
Check at
http://www.teamdev.com/jniwrapper/winpack/#registry_access
And...
There is also try JNIRegistry @
http://www.trustice.com/java/jnireg/
There is also the option of invoking an external app, which is responsible for reading / writing the registry.


q: In PHP, how can I replicate the expand/contract feature for Tinyurls as on search.twitter.com?

[A]
If you want to find out where a tinyurl is going, use fsockopen to get a connection to tinyurl.com on port 80, and send it an HTTP request like this
```
```
GET /dmsfm HTTP/1.0
Host: tinyurl.com
```
```
The response you get back will look like
```
```
HTTP/1.0 301 Moved Permanently
Connection: close
X-Powered-By: PHP/5.2.6
Location: http://en.wikipedia.org/wiki/TinyURL
Content-type: text/html
Content-Length: 0
Date: Mon, 15 Sep 2008 12:29:04 GMT
Server: TinyURL/1.6
```
```
example code...
```
```
<?php
$tinyurl="dmsfm";

$fp = fsockopen("tinyurl.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET /$tinyurl HTTP/1.0\r\n";
    $out .= "Host: tinyurl.com\r\n";
    $out .= "Connection: Close\r\n\r\n";

    $response="";

    fwrite($fp, $out);
    while (!feof($fp)) {
        $response.=fgets($fp, 128);
    }
    fclose($fp);

    //now parse the Location: header out of the response

}
?>
```
```


q:
I have a solution with multiple project. I am trying to optimize AssemblyInfo.cs files by linking one solution wide assembly info file. What are the best practices for doing this? Which attributes should be in solution wide file and which are project/assembly specific?

Edit: If you are interested there is a follow up question What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

[A]
Using a single AseemblyInfo.cs file for multiple projects is not recommended.
The AssemblyInfo file includes information that might be relevant only for that specific assembly. The two most obvious pieces of information are the
```
AssemblyTitle
```
and
```
AssemblyVersion
```
.
A better solution might be to use
```
targets
```
file, which are handled by the MSBuild, in order to "inject" assembly attributes to more than one project.


q:
Say I have an ASMX web service, MyService.  The service has a method, MyMethod.  I could execute MyMethod on the server side as follows:

MyService service = new MyService();
service.MyMethod();

I need to do similar, with service and method not known until runtime.

I'm assuming that reflection is the way to go about that.  Unfortunately, I'm having a hard time making it work.  When I execute this code:

Type.GetType("MyService", true);

It throws this error:

Could not load type 'MyService' from assembly 'App_Web__ktsp_r0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

Any guidance would be appreciated.

[A]
I'm not sure if this would be the best way to go about it.  The most obvious way to me, would be to make an HTTP Request, and call the webservice using an actual HTTP GET or POST. Using your method, I'm not entirely sure how you'd set up the data you are sending to the web service. I've added some sample code in VB.Net
```
```
Dim HTTPRequest As HttpWebRequest
Dim HTTPResponse As HttpWebResponse
Dim ResponseReader As StreamReader
Dim URL AS String
Dim ResponseText As String

URL = "http://www.example.com/MyWebSerivce/MyMethod?arg1=A&arg2=B"

HTTPRequest = HttpWebRequest.Create(URL)
HTTPRequest.Method = "GET"

HTTPResponse = HTTPRequest.GetResponse()

ResponseReader = New StreamReader(HTTPResponse.GetResponseStream())
ResponseText = ResponseReader.ReadToEnd()
```
```


q: It's big problem to convert mod_rewrite rules to lighttpd format

[A]
It is generally a case of just going through one by one and converting them.  I don't know of any automated means,
The docs -
http://redmine.lighttpd.net/projects/1/wiki/Docs:ModRewrite
- has the regexes available, and some examples.
if there are any particularly problematical items, I'd edit the question to show them, and ask for the answers here.


q:
What are the advantages/disadvantages between MS VS C++ 6.0 and MSVS C++ 2008?

The main reason for asking such a question is that there are still many decent programmers that prefer using the older version instead of the newest version.

Is there any reason the might prefer the older over the new?

[A]
Well, for one thing it may be because the executables built with MSVS 6 require only msvcrt.dll (C runtime) which is shipped with Windows now.
The MSVS 2008 executables need msvcrt9 shipped with them (or already installed).
Plus, you have a lot of OSS libraries already compiled for Windows 32 bit with the 6.0 C runtime, while for the 2008 C runtime you have to take the source and compile them yourself.
(most of those libraries are actually compiled with MinGW, which too uses the 6.0 C runtime - maybe that's another reason).


q:
We are developing a middleware SDK, both in C++ and Java to be used as a library/DLL by, for example, game developers, animation software developers, Avatar developers to enhance their products.

What I would like to know is this: Are there standard "Best Practices" for the development of these types of API?

I am thinking in terms of usability, readability, efficiency etc.

[A]
There are lots of ways to design apis, depending on what you are solving. I think a full answer to this question would be worthy off a whole book, such as the
gang of four patterns book
. For Java specifically, and also just OO programming in general, I would recommend
Effective Java 2nd Edition
. The first is general and a lot of popular programming patterns, when they apply and their benefits. Effective Java is Java centered, but parts of it is general enough to apply to any programming language.


q: Rather than rewriting the entire contents of an xml file when a single element is updated, is there a better alternative to updating the file?

[A]
I would recommend using VTD-XML
http://vtd-xml.sourceforge.net/
From their FAQ (
http://vtd-xml.sourceforge.net/faq.html
):
Why should I use VTD-XML for large XML files?
For numerous reasons summarized below:
Performance: The performance of VTD-XML is far better than SAX
Ease to use: Random access combined with XPath makes application easy to write
Better maintainability: App code is shorter and simpler to understand.
Incremental update: Occasional, small changes become very efficient.
Indexing: Pre-parsed form of XML will further boost processing performance.
Other features: Cut, paste, split and assemble XML documents is only possible with VTD-XML.
In order to take advantage of VTD-XML, we recommended that developers split their ultra large XML documents into smaller, more manageable  chucks (<2GB).


q: I have looked in vain for a good example or starting point to write a java based facebook application...  I was hoping that someone here would know of one.  As well, I hear that facebook will no longer support their java API is this true and if yes does that mean that we should no longer use java to write facebook apps??

[A]
Facebook stopped supporting the official Java API on 5 May 2008 according to their
developer wiki
.
In no way does that mean you shouldn't use Java any more to write FB apps. There are several alternative Java approaches outlined on the wiki.
You might also want to check
this project
out; however, it only came out a few days ago so YMMV.


q:
I load some XML from a servlet from my Flex application like this:

_loader = new URLLoader();
_loader.load(new URLRequest(_servletURL+"?do=load&id="+_id));

As you can imagine _servletURL is something like http://foo.bar/path/to/servlet

In some cases, this URL contains accented characters (long story). I pass the unescaped string to URLRequest, but it seems that flash escapes it and calls the escaped URL, which is invalid. Ideas?

[A]
I'm not sure if this will be any different, but this is a cleaner way of achieving the same URLRequest:
```
```
var request:URLRequest = new URLRequest(_servletURL)
request.method = URLRequestMethod.GET;
var reqData:Object = new Object();

reqData.do = "load";
reqData.id = _id;
request.data = reqData;

_loader = new URLLoader(request);
```
```


q:
Nokia has stopped offering its Developer's Suite, relying on other IDEs, including Eclipse. Meanwhile, Nokia changed its own development tools again and EclipseMe has also changed. This leaves most documentation irrelevant.

I want to know what does it take to make a simple Hello-World?

(I already found out myself, so this is a Q&A for other people to use)

[A]
Here's what's needed to make a simple hello world -
Get
Eclipse
IDE for Java. I used Ganymede. Set it up.
Get Sun's
Wireless Toolkit
. I used 2.5.2. Install it.
Get Nokia's SDK (
found here
), in my case for S40 6230i Edition, and install it choosing the option to
integrate with Sun's WTK
Follow the instructions at
http://www.eclipseme.org/
to download and install Mobile Tools Java (MTJ). I used version 1.7.9.
When configuring devices profiles in MTJ (inside Eclipse) use the Nokia device from the WTK folder and NOT from Nokia's folder.
Set the WTK root to the main installation folder - for instance c:\WTK2.5.2; Note that the WTK installer creates other folders apparently for backward compatibility.
Get
Antenna
and set its location in MTJ's property page (in Eclipse).
Here's an HelloWorld sample to test the configuration.
Note: It worked for me on WindowsXP.
Also note: This should work for S60 as well. Just replace the S40 SDK in phase 3 with S60's.


q:
I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using STL techniques such as vectors.

Essentially I want my integer array dimensions to look like:

[ x ][ y ][ z ]

x and y are in the range 20-6000
z is known and equals 4.

[A]
Have a look at the Boost
multi-dimensional array
library. Here's an example (adapted from the Boost documentation):
```
```
#include "boost/multi_array.hpp"

int main() {
  // Create a 3D array that is 20 x 30 x 4
  int x = 20;
  int y = 30;
  int z = 4;

  typedef boost::multi_array<int, 3> array_type;
  typedef array_type::index index;
  array_type my_array(boost::extents[x][y][z]);

  // Assign values to the elements
  int values = 0;
  for (index i = 0; i != x; ++i) {
    for (index j = 0; j != y; ++j) {
      for (index k = 0; k != z; ++k) {
        my_array[i][j][k] = values++;
      }
    }
  }
}
```
```


q: What is the dependency inversion principle and why is it important?

[A]
Check this document out:
The Dependency Inversion Principle
.
It basically says:
High level modules should not depend upon low-level modules. Both should depend upon abstractions.
Abstractions should never depend upon details. Details should depend upon abstractions.
As to why it is important, in short: changes are risky, and by depending on a concept instead of on an implementation, you reduce the need for change at call sites.
Effectively, the DIP reduces coupling between different pieces of code. The idea is that although there are many ways of implementing, say, a logging facility, the way you would use it should be relatively stable in time. If you can extract an interface that represents the concept of logging, this interface should be much more stable in time than its implementation, and call sites should be much less affected by changes you could make while maintaining or extending that logging mechanism.
By also making the implementation depend on an interface, you get the possibility to choose at run-time which implementation is better suited for your particular environment. Depending on the cases, this may be interesting too.


q:
I would like to move a file or folder from one place to another within the same repository without having to use Repo Browser to do it, and without creating two independent add/delete operations.  Using Repo Browser works fine except that your code will be hanging in a broken state until you get any supporting changes checked in afterwards (like the .csproj file for example).

Update: People have suggested "move" from the command line. Is there a TortoiseSVN equivalent?

[A]
From the command line, you can type
```
svn mv path1 path2
```
. This will create an add and a delete operation, but there's not really a way around that - as far as I know - in Subversion.


q:
How do you define your UserControls as being in a namespace below the project namespace, ie. [RootNameSpace].[SubSectionOfProgram].Controls?

Edit due to camainc's answer: I also have a constraint that I have to have all the code in a single project.

Edit to finalise question: As I suspected it isn't possible to do what I required so camainc's answer is the nearest solution.

[A]
I'm not sure if this is what you are asking, but this is how we do it.
We namespace all of our projects in a consistent manner, user controls are no different. We also namespace using the project settings window, although you could do it through a combination of the project window and in code.
Each solution gets a namespace like this:
```
```
[CompanyName].[SolutionName].[ProjectName]
```
```
So, our user controls are normally in a project called "Controls," which would have a namespace of:
```
```
OurCompany.ThisSolution.Controls
```
```
If we have controls that might span several different solutions, we just namespace it like so:
```
```
OurCompany.Common.Controls
```
```
Then, in our code we will import the library, or add the project to the solution.
```
```
Imports OurCompany
Imports OurCompany.Common
Imports OurCompany.Common.Controls
```
```
We also name the folders where the projects live the same as the namespace, down to but not including the company name (all solutions are assumed to be in the company namespace):
\Projects
\Projects\MySolution
\Projects\MySolution\Controls
-- or --
\Projects\
\Projects\Common
\Projects\Common\Assemblies
\Projects\Common\Controls
etc.
Hope that helps...


q:
I'm trying to install Laconica, an open-source Microblogging application on my Windows development server using XAMPP as per the instructions provided.

The website cannot find PEAR, and throws the below errors:

Warning: require_once(PEAR.php) [function.require-once]: failed to open stream: No such file or directory in C:\xampplite\htdocs\laconica\lib\common.php on line 31

Fatal error: require_once() [function.require]: Failed opening required 'PEAR.php' (include_path='.;\xampplite\php\pear\PEAR') in C:\xampplite\htdocs\laconica\lib\common.php on line 31

PEAR is located in C:\xampplite\php\pear

phpinfo() shows me that the include path is .;\xampplite\php\pear

What am I doing wrong? Why isn't the PEAR folder being included?

[A]
Try adding the drive letter:
```
```
include_path='.;c:\xampplite\php\pear\PEAR'
```
```
also verify that PEAR.php is actually there, it might be in \php\ instead:
```
```
include_path='.;c:\xampplite\php'
```
```


q: What Direct3D render states should be used to implement Java's Porter-Duff compositing rules (CLEAR, SRC, SRCOVER, etc.)?

[A]
I'm haven't used Java too much, but based on the
white paper from 1984
, it should be a fairly straightforward mapping of render state blend modes.
There are of course more that you can do than just these, like normal alpha blending (SourceAlpha, InvSourceAlpha) or additive (One, One) to name a few.
(I assume that you are asking about these specifically because you are porting some existing functionality? In that cause you may not care about other combinations...)
Anyway, these assume a BlendOperation of Add and that AlphaBlendEnable is true.
Clear
```
```
SourceBlend = Zero
DestinationBlend = Zero
```
```
A
```
```
SourceBlend = One
DestinationBlend = Zero
```
```
B
```
```
SourceBlend = Zero
DestinationBlend = One
```
```
A over B
```
```
SourceBlend = One
DestinationBlend = InvSourceAlpha
```
```
B over A
```
```
SourceBlend = InvDestinationAlpha
DestinationBlend = One
```
```
A in B
```
```
SourceBlend = DestinationAlpha
DestinationBlend = One
```
```
B in A
```
```
SourceBlend = Zero
DestinationBlend = SourceAlpha
```
```
A out B
```
```
SourceBlend = InvDestinationAlpha
DestinationBlend = Zero
```
```
B out A
```
```
SourceBlend = Zero
DestinationBlend = InvSourceAlpha
```
```
A atop B
```
```
SourceBlend = DestinationAlpha
DestinationBlend = InvSourceAlpha
```
```
B atop A
```
```
SourceBlend = InvDestinationAlpha
DestinationBlend = SourceAlpha
```
```
A xor B
```
```
SourceBlend = InvDestinationAlpha
DestinationBlend = InvSourceAlpha
```
```
Chaining these is a little more complex and would require either multiple passes or multiple texture inputs to a shader.


q:
I'm trying to implement a data compression idea I've had, and since I'm imagining running it against a large corpus of test data, I had thought to code it in C (I mostly have experience in scripting languages like Ruby and Tcl.)

Looking through the O'Reilly 'cow' books on C, I realize that I can't simply index the bits of a simple 'char' or 'int' type variable as I'd like to to do bitwise comparisons and operators.

Am I correct in this perception?   Is it reasonable for me to use an enumerated type for representing a bit (and make an array of these, and writing functions to convert to and from char)?  If so, is such a type and functions defined in a standard library already somewhere?  Are there other (better?) approaches?   Is there some example code somewhere that someone could point me to?

Thanks -

[A]
It is possible.
To set the nth bit, use OR:
```
```
x |= (1 << 5); // sets the 5th-from right
```
```
To clear a bit, use AND:
```
```
x &= ~(1 << 5); // clears 5th-from-right
```
```
To flip a bit, use XOR:
```
```
x ^= (1 << 5); // flips 5th-from-right
```
```
To get the value of a bit use shift and AND:
```
```
(x & (1 << 5)) >> 5 // gets the value (0 or 1) of the 5th-from-right
```
```
note: the shift right 5 is to ensure the value is either 0 or 1. If you're just interested in 0/not 0, you can get by without the shift.


q: Is there a way to draw a line along a curved path with a gradient that varies in a direction perpendicular to the direction of the line? I am using the GDI+ framework for my graphics.

[A] The simple answer is no. You can create a GraphicsPath in order to describe what you would like to draw, using AddPoint/AddLine/AddBezier and so forth as needed to describe the complex path of what you want to draw. When you draw the path you can provide a Brush which can be something like LinearGradientBrush or RadialGradientBrush. Neither of those gradient brushes reacts to the actual path being drawn in the sense of changing direction as the drawing occurs. You have to specify the angles etc as constant for the entire gradient area.


q:
How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?

I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel.

What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard.

Help, please.

[A]
It seems to me that you might be better off breaking this into smaller tasks/questions.
You have a few issues you are stuck on from the way it sounds.
You have multiple 'child' windows open. Is this an MDI application?
When an action is performed on one of those child windows, it should fire an event in that window's event handlers. That is your first thing to set up. If this is a datagridview I would suggest a simple test to start. Try trapping the
DataGridView.SelectionChanged
event. Just throw in something like
```
MessageBox.Show("I copied your datas!");
```
for now.
This should get you started where you will at least understand how this event will be raised to you.
From here, we will need to know a little more about your datagrid, and the rows and child controls in those rows. Then we can likely create events in the render events that will be raised at the appropriate times, with the appropriate scope.


q:
I've been using some basic AOP style solutions for cross-cutting concerns like security, logging, validation, etc.  My solution has revolved around Castle Windsor and DynamicProxy because I can apply everything using a Boo based DSL and keep my code clean of Attributes. I was told at the weekend to have a look at PostSharp as it's supposed to be a "better" solution.  I've had a quick look at PostSharp, but I've been put off by the Attribute usage.

Has anyone tried both solutions and would care to share their experiences?

[A]
I only looked at castle-windsor for a short time (yet) so I can't comment on that but I did use postsharp.
Postsharp works by weaving at compile time. It ads a post-compile step to your build where it modifies your code. The code is compiled as if you just programmed the cross cutting concerns into you code. This is a bit more performant than runtime weaving and because of the use of attributes Postsharp is very easy to use. I think using attributes for AOP isn't as problematic as using it for DI. But that's just my personal taste.
But...
If you already use castle for dependency injection I don't see a good reason why you shouldn't also use it for AOP stuff. I think though the AOP at runtime is a bit slower than at compile time it's also more powerful. AOP and DI are in my opinion related concepts so I think it's a good idea to use one framework for both. So I'll probably look at the castle stuff again next project I need AOP.


q:
Is there a standard library method that converts a string that has duration in the standard ISO 8601 Duration (also used in XSD for its duration type) format into the .NET TimeSpan object?

For example, P0DT1H0M0S which represents a duration of one hour, is converted into New TimeSpan(0,1,0,0,0).

A Reverse converter does exist which works as follows:
Xml.XmlConvert.ToString(New TimeSpan(0,1,0,0,0))
The above expression will return P0DT1H0M0S.

[A]
This will convert from xs:duration to TimeSpan:
```
```
System.Xml.XmlConvert.ToTimeSpan("P0DT1H0M0S")
```
```
See
http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.totimespan.aspx


q: Is there any difference between a binary semaphore and mutex or are they essentially the same?

[A]
A
mutex
can be released only by
the thread that had acquired it
.
A
binary semaphore
can be signaled
by any thread
(or process).
so semaphores are more suitable for some synchronization problems like producer-consumer.
On Windows, binary semaphores are more like event objects than mutexes.


q:
My initial tests have shown that Robot won't work without an active, visible desktop. For example, while a scheduled task (or executed command from the continuous integration server) may be able to start robot as a command-line process, Robot will actually fail to execute the recorded script.

Logging into the build machine to allow it an "active desktop" is not an acceptable solution.

Am I missing something? Is it possible to run a pre-recorded Rational Robot script on a continuous integration server in a manner that doesn't require the machine to be physically logged into?

[A]
You can run Rational Robot from the command line, so you should be able to set up a scheduled task to run a .BAT file to do this for you. The command is something like:
[path to Rational Robot]\rtrobo [script file] /user "user name" /project [project file] /play /build "build name" /nolog /close
The Robot documentation will have other arguments you can pass in, depending on your situation.
If a simple scheduled task doesn't work, then you can try setting up a STAF (
http://staf.sourceforge.net/index.php
) environment and create a job to run this.
Good luck :)


q:
I am working with Cognos8 Report Studio. In my report there are two date prompts: START date and END date. Users can select two different dates or make them both the same date. But the report has valid data only for the last business date of each month. For example, if Jan 31 is Sunday, valid data is available only for Jan 29 which is Friday (the last business day of the month).

Can I have a customized "Date Prompt" where I can disable all other dates except the last business day of each month? Users should be able to select only month-end dates and no other dates?


q:
Is it possible to determine the MAC address of the originator of a remote connection under Windows NT 4? The remote PC opens a socket connection into my application and I can get the IP address. However I need to determine the MAC address from the information available from the socket such as the IP address of the remote device.

I have tried using SendARP but this doesn't seem to be supported in Windows NT4.

[A] Try GetIpNetTable. This function is documented as supported as of NT 4.0 SP4.


q:
Developer looking for best method to identify a deadlock on a specific transaction inside a specific thread.  We are getting deadlock errors but these are very general in FB 2.0

Deadlocks happening and they are leading to breakdowns in the DB connection between client and the DB.

We send live ( once a second) data to the DB.

We open a thread pool of around 30 threads and use them to ingest the data ( about 1-2 kB each second).

Sometimes the DB can only take so much that we use the next thread in the pool to keep the stream current as possible.

On occasion this produces a deadlock in addition to reaching the max thread count and breaking the connection.

So we really need opinions on if this is the best method to ingest this amount of data every second.  We have up to 100 on these clients hitting the DB at the same time.

Average transactions are about 1.5 to 1.8 million per day.

[A]
I don't know of a specific way to identify the particular thread or statement. I've had to deal with FB deadlocks many times. You probably have two theads that are trying to update the same row in some table but they are doing it in separate transactions.
The best solution I've found is to design things so threads never have to update a row that any other thread might update. Sometimes that means having a thread that just exists to update a common table/row. The worker threads send a message to this thread. (The message could be done via another table.)
We run FB in many systems in the field that generate transactions (not millions per day) and we have found FB to be rock solid once we get the design correct.