q: I have a few batch files I need to run frequently in developing a certain project. I'd like to create a Visual Studio toolbar called "MyProject" and have commands underneath to execute these batch files. What is the easiest way to accomplish this?

[A]
In the
Tools...
menu, select
External Tools...
and add references to the batch files. Then right-click on a toolbar, select
Customize...
, go to the
Toolbars
tab, click on
New...
, name your new toolbar, click on
OK
, go to the
Commands
tab, select the
Tools
category and drag-drop the appropriate
External Command
Command onto your custom tool bar.
If you need to run batch files that always run right before or after a build, you're probably better off making use of
build events
.


q: I've been reading that Adobe has made crossdomain.xml stricter in flash 9-10 and I'm wondering of someone can paste me a copy of one that they know works. Having some trouble finding a recent sample on Adobe's site.

[A]
This is what I've been using for development:
```
```
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
```
```
This is a very liberal approach, but is fine for my application.
As others have pointed out below, beware the risks of this.

s: huggingface

c: devops

d: intermediate


q: How do I go about positioning a JDialog at the center of the screen?

[A]
In Java 1.4+ you can do:
```
```
final JDialog d = new JDialog();
d.setSize(200,200);
d.setLocationRelativeTo(null);
d.setVisible(true);
```
```
Or perhaps (pre 1.4):
```
```
final JDialog d = new JDialog();
d.setSize(200, 200);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenSize();
final int x = (screenSize.width - d.getWidth()) / 2;
final int y = (screenSize.height - d.getHeight()) / 2;
d.setLocation(x, y);
d.setVisible(true);
```
```


q:
I'm trying to pass one method to another in elisp, and then
have that method execute it.  Here is an example:

(defun t1 ()
  "t1")

(defun t2 ()
  "t1")

(defun call-t (t)
  ; how do I execute "t"?
  (t))

; How do I pass in method reference?
(call-t 't1)

[A]
First, I'm not sure that naming your function
```
t
```
is helping as 't' is used as the
truth value
in lisp.
That said, the following code works for me:
```
```
(defun test-func-1 ()  "test-func-1"
   (interactive "*")
   (insert-string "testing callers"))

(defun func-caller (callee)
  "Execute callee"
  (funcall callee))

(func-caller 'test-func-1)
```
```
Please note the use of 'funcall', which triggers the actual function call.


q:
window.scrollMaxY can be set via that property in IE and older versions of Firefox, but when trying in FF3 it says "Cannot set this property as it only has a getter".

What is my alternative?

EDIT:

The reason why I'm asking is that I'm fixing some very horrible JS written by someone else, it has a function to keep a div centered on the page while scrolling, and has this line:

// Fixes Firefox incrementing page height while scrolling
window.scrollMaxY = scrollMaxY

Obviously this doesn't work, but the main issue is that when the page is scrolled, it grows in length.


q:
I'm storing an ArrayList of Ids in a processing script that I want to spit out as a comma delimited list for output to the debug log. Is there a way I can get this easily without looping through things?

EDIT: Thanks to Joel for pointing out the List(Of T) that is available in .net 2.0 and above. That makes things TONS easier if you have it available.

[A]
Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing:
...in VB.NET:
```
```
String.Join(",", CType(TargetArrayList.ToArray(Type.GetType("System.String")), String()))
```
```
...in C#
```
```
string.Join(",", (string[])TargetArrayList.ToArray(Type.GetType("System.String")))
```
```
The only "gotcha" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly.
EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up!
```
```
String.Join(",", TargetList.ToArray())
```
```


q:
There are many tools out there for writing and managing requirements, but are there any good ones for reviewing them?

I'm not talking about managing reviews, but automation tools that look for common requirement blunders (such as using negative requirements, or ones that are worded in a way that makes testing difficult).

More of a screening tool that someone writing requirements can use to screen their document before distributing to a group of reviewers so that the review process need not be slowed down by everyone commenting on the same easily recognizable issues.

I'm curious if anyone's used anything like this in the past.

[A]
I'm working on a console application that takes a xml configuration file like this:
```
```
<?xml version="1.0" encoding="utf-8"?>
<ReqCheck>
  <Categories name="Reconsider wording">
    <Keyword>may</Keyword>
    <Keyword>should</Keyword>
  </Categories>
  <Categories name="Potential logic problem" format="{0}: consider both then and else conditions.">
    <Keyword>not</Keyword>
  </Categories>
</ReqCheck>
```
```
The application takes a MS-Word document and adds 'balloon-style' comments to the document.


q:
Is it possible to create, for instance, a box model hack while using in-line CSS?

For example:

<div id="blah" style="padding: 5px; margin: 5px; width: 30px; /*IE5-6 Equivalent here*/">

Thanks!

[A]
The most appropriate answer is
don't
. (Edit: to be clear, I mean don't do it inline, I don't mean don't use CSS hacks.)
Edit: This doesn't work, IE ignores the conditional comment. Leaving the answer here to not be a bastard.
The next most appropriate answer is conditional comments:
```
```
<div id="blah" style="padding: 5px; margin: 5px; width: 30px; <!--[if lte IE 6]> ... <![endif]-->">
```
```


q:
I have a generic class in C# with 2 constructors:

public Houses(params T[] InitialiseElements)
{}
public Houses(int Num, T DefaultValue)
{}

Constructing an object using int as the generic type and passing in two ints as arguments causes the 'incorrect' constructor to be called (from my point of view).

E.g. Houses<int> houses = new Houses<int>(1,2) - calls the 2nd construtor. Passing in any other number of ints into the constructor will call the 1st constructor.

Is there any way around this other than removing the params keyword and forcing users to pass an array of T when using the first constructor?

[A]
Perhaps instead of Params you could pass in IEnumerable
```
```
public Houses(IEnumerable<T> InitialiseElements){}
```
```


q: I have a neural network written in Erlang, and I just bought a GeForce GTX 260 card with a 240 core GPU on it. Is it trivial to use CUDA as glue to run this on the graphics card?

[A]
No, using CUDA is not a trivial matter.
The CUDA programming model basically uses C (with some additions) but in order to get the most of the GPGPU's capabilities you would have to ensure that your algorithms follow the CUDA guidelines. (see
NVidia CUDA Programming Guide
)
For example in order to get the best memory performance (somewhere around 70Gbps) you need to access memory in streaming mode with coalescing, also branches are very costly on the GPUs so you should avoid conditionals as much as possible. Check out the guide and samples provided with the SDK, they'll provide an excellent starting point


q:
Is it possible to create Eclipse plugins that auto-discover eachother?

I am developing a set of plugins that need to operate in two primary situations:

individually

in concert with each other.

When run individually, the plugins should "just work" but when in concert, they will be sharing some of the same model content, and one of the plugins should present the user with a list of other plugins to share content with. eg:

Foo Plugin detected the following
  plugins it can share ontologies with:

[ ] Bar plugin

[ ] Baz plugin

[ ] Don't share

Does Eclipse offer any internal publication / detection methods that would facilitate this sort of auto-detection of other plugins?

[A]
The answer should be through
Declarative Service
, which combines the advantages of both eclipse xml extensions and osgi POJO services. Something that is implicitly dynamic like osgi services, but loaded “on demand” like eclipse extensions.
Introduced in 2006 for eclipse3.3, you will find those concepts illustrated in
this presentation
.
Declarative Services gives the option to define reference to other services. It is also possible to specify the cardinality of the reference. The cardinality is specified using two numbers, the first one, 0 or 1, indicates the optionality, the second one, 1 or n, indicates the multiplicity.
In practice, those
DS (Declarative Services)
are not easy to use, as you have to access the BundleContext, meaning keeping track of the BundleActivator,
which is not always easy
...
If what you need is to define some sort of Service Oriented Component Model,
this presentation
should provide you with the different alternatives existing today, as well as detailing those "Declarative Services"
To publish what rcreswick has found in relation with DS:
Getting Started with OSGi:
Introducing Declarative Services
Getting Started with OSGi:
Declarative Services and Dependencies


q:
I am trying to create a new instance of Excel using VBA using:

Set XlApp = New Excel.Application

The problem is that this new instance of Excel doesn't load all the addins that load when I open Excel normally...Is there anything in the Excel Application object for loading in all the user-specified addins?

I'm not trying to load a specific add-in, but rather make the new Excel application behave as though the user opened it themself, so I'm really looking for a list of all the user-selected add-ins that usually load when opening Excel.

[A]
Using
```
CreateObject("Excel.Application")
```
would have the same result as using
```
New Excel.Application
```
, unfortunately.
You will have to load the Addins that you need individually by file path & name using the
```
Application.Addins.Add(string fileName)
```
method.


q:
I develop a number of desktop Java applications using Swing, and while Swing is quite powerful (once you get the hang of it), there are still a lot of cases where I wish some advanced component was available right out of the box.

For example, I'd really like to see easy-to-use components (without writing them myself, which I could do given enough time) like:

Multi-line label

Windows File Explorer-like Icons or Thumbnails view

Drop-down button (like Firefox's old Back button)

5-star rating widget

Combo box with automatic history (like the text field on Google)

An Outlook-style accordion-style bar

and so on

I know of a couple of sources of free Swing components, like SwingLabs, home of JXTable, JXDatePicker, and a few others.

Where do you go for Swing components beyond those included with Java itself?

[A]
The following are worth a look:
swingX
Glazed lists
Substance look'n'feel
Flamingo components
Ken Orr's Mac Widgets
Jide's open source components


q:
Is it currently possible to translate C# code into an Abstract Syntax Tree?

Edit: some clarification; I don't necessarily expect the compiler to generate the AST for me - a parser would be fine, although I'd like to use something "official." Lambda expressions are unfortunately not going to be sufficient given they don't allow me to use statement bodies, which is what I'm looking for.

[A]
Check out .NET
CodeDom
support.  There is an old article on code project for a
C# CodeDOM parser
, but it won't support the new language features.
There is also supposed to be support in #develop for generating a CodeDom tree from C# source code according to this
posting
.


q: I'm having trouble dynamically adding controls inside an update panel with partial postbacks. I've read many articles on dynamic controls and I understand how to add and maintain them with postbacks but most of that information doesn't apply and won't work for partial postbacks. I can't find any useful information about adding and maintaining them with UpdatePanels. I'd like to do this without creating a web service if it's possible. Does anyone have any ideas or references to some helpful information?

[A]
This is, I think, one of the common pitfalls for asp.net programmers but isn't actually that hard to get it right when you know what is going on (always remember your viewstate!).
the following piece of code explains how things can be done. It's a simple page where a user can click on a menu which will trigger an action that will add a user control to the page inside the updatepanel.
(This code is borrowed
from here
, and has lots more of information concerning this topic)
```
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Sample Menu</title>

    <form id="form1" runat="server">
        <asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
            <Items>
                <asp:MenuItem Text="File">
                    <asp:MenuItem Text="Load Control1"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control2"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control3"></asp:MenuItem>
                </asp:MenuItem>
            </Items>
        </asp:Menu>

        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Menu1" />
            </Triggers>
        </asp:UpdatePanel>
    </form>

```
```
and
```
```
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PlainSampleMenuPage : System.Web.UI.Page
{
    private const string BASE_PATH = "~/DynamicControlLoading/";

    private string LastLoadedControl
    {
        get
        {
            return ViewState["LastLoaded"] as string;
        }
        set
        {
            ViewState["LastLoaded"] = value;
        }
    }

    private void LoadUserControl()
    {
        string controlPath = LastLoadedControl;

        if (!string.IsNullOrEmpty(controlPath))
        {
            PlaceHolder1.Controls.Clear();
            UserControl uc = (UserControl)LoadControl(controlPath);
            PlaceHolder1.Controls.Add(uc);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        LoadUserControl();
    }

    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        MenuItem menu = e.Item;

        string controlPath = string.Empty;

        switch (menu.Text)
        {
            case "Load Control2":
                controlPath = BASE_PATH + "SampleControl2.ascx";
                break;
            case "Load Control3":
                controlPath = BASE_PATH + "SampleControl3.ascx";
                break;
            default:
                controlPath = BASE_PATH + "SampleControl1.ascx";
                break;
        }

        LastLoadedControl = controlPath;
        LoadUserControl();
    }
}
```
```
for the code behind.
That's basically it. You can clearly see that the viewstate is being kept with
LastLoadedControl
while the controls themselves are dynamically added to the page (inside the updatePanel (actually inside the placeHolder inside the updatePanel) when the user clicks on a menu item, which will send an asynchronous postback to the server.
More information can also be found here:
http://aspnet.4guysfromrolla.com/articles/081402-1.aspx
http://aspnet.4guysfromrolla.com/articles/082102-1.aspx
and of course on
the website that holds the example code
I used here.


q:
I know how to write trace statements that I can view in a webforms environment, but how do I do this in a windows forms app?

I am inside of a static method, and I want to display the sql query that it is generating.

I don't have access to messagebox.show, what are my options?

[A]
You could use a global logging object:
```
```
enum LogLevel
{
    Info,
    Warning,
    Error
}

delegate void OnLog (string msg, LogLevel level);

interface ILogger
{
    void Log(string msg, LogLevel level);
    event OnLog;
}
```
```
Then extend ILogger with a class that you acquire using a public static method in the Program class.
And in your main form, attach yourself to the OnLog event and use it to print messages on the for itself. Then all you have to do is call the Log method in your static method with the SQL query.
:)


q:
Is there a maximum length when using window.returnValue (variant) in a modal?

I am calling a modal window using showModalDialog() and returning a comma delimited string.  After selecting a group of users, I am putting them into a stringbuilder to display in a literal.

Dim strReturn As New StringBuilder
strReturn.Append("<script type=""text/javascript"">window.returnValue='")
Dim strUsers As New StringBuilder
For Each dtRow As DataRow In GetSelectedUserTable.Rows
    If strUsers.ToString.Length > 0 Then
        strUsers.Append(",")
    End If
    strUsers.Append(dtRow("UserID"))
Next
strReturn.Append(strUsers.ToString)
strReturn.Append("';window.close();</script>")
litReturnJavascript.Text = strReturn.ToString

So would there be a limit on how many characters can be added to the window.returnValue?

[A]
First, in what browser are you having problems?
```
window.returnValue
```
isn't even supported in Firefox, maybe not even other browsers.
Second, have you looked the value of
```
strUsers
```
after building it to make sure there are no single or double quotes in that string?
I would guess that the maximum size/length of that property would be determined more by your system's memory than anything else.
EDIT: Maybe you should look at using
```
window.open()
```
to open a new window and
```
window.opener
```
to set the value on the parent form instead - it is supported by more browsers. Just a suggestion...


q:
I'm working on trying to generate a report from a couple of database tables. The simplified version looks like this

Campaign
----------
CampaignID

Source
-----------------------
Source_ID | Campaign_ID

Content
---------------------------------------------------------
Content_ID | Campaign_ID | Content_Row_ID | Content_Value

The report needs to read like this:

CampaignID - SourceID - ContentRowID(Value(A)) - ContentRowID(Value(B))

Where ContentRowID(Value(A)) means "Find a row the has a given CampaignID, and a ContentRowId of "A" and then get the ContentValue for that row"

Essentially, I have to "pivot" (I think that's the correct term) the rows into columns...

It's an Oracle 10g database...

Any suggestions?

[A]
This is my first stab at it. Refinement coming once I know more about the contents of the Content table.
First, you need a temporary table:
```
```
CREATE TABLE pivot (count integer);
INSERT INTO pivot VALUES (1);
INSERT INTO pivot VALUES (2);
```
```
Now we're ready to query.
```
```
SELECT campaignid, sourceid, a.contentvalue, b.contentvalue
FROM content a, content b, pivot, source
WHERE source.campaignid = content.campaignid
AND pivot = 1 AND a.contentrowid = 'A'
AND pivot = 2 AND b.contentrowid = 'B'
```
```


q: How can I bring a console application window to front in C# (especially when running the Visual Studio debugger)?

[A]
It's hacky, it's horrible, but it works for me (thanks,
pinvoke.net
!):
```
```
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

public class Test
{

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);

    public static void Main()
    {
        string originalTitle = Console.Title;
        string uniqueTitle = Guid.NewGuid().ToString();
        Console.Title = uniqueTitle;
        Thread.Sleep(50);
        IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);

        if (handle == IntPtr.Zero)
        {
            Console.WriteLine("Oops, cant find main window.");
            return;
        }
        Console.Title = originalTitle;

        while (true)
        {
            Thread.Sleep(3000);
            Console.WriteLine(SetForegroundWindow(handle));
        }
    }
}
```
```


q:
I get the following warning when using java.net.URLEncoder.encode:

warning: [deprecation] encode(java.lang.String)
         in java.net.URLEncoder has been deprecated

What should I be using instead?

[A]
Use the other
```
encode
```
method in
URLEncoder
:
```
```
URLEncoder.encode(String, String)
```
```
The first parameter is the text to encode; the second is the name of the character encoding to use (e.g.,
```
UTF-8
```
). For example:
```
```
System.out.println(
  URLEncoder.encode(
    "urlParameterString",
    java.nio.charset.StandardCharsets.UTF_8.toString()
  )
);
```
```


q:
What are the main reasons personal projects (software apps etc) never get to the level of competing with your salary?

To me one big problem is "on-the-fly" feature expansion, with this problem, the end only gets further and further away!

[A]
For me, it's simple: I work 8 hours a day already. I spend a few more hours a day keeping current. I have
a girlfriend,
some local family and a decent circle of friends. I have (gasp) non-computer-related interests and hobbies. In other words, I have a life.
So ...
Time.
Time is not on my side. Would that it was ... My blog might be a bit more current if there were just two more hours in every day. :)
(Originally posted by
John Rudy
.)


q: Is it possible to pass a App setting "string" in the web.config to a Common C# class?

[A]
In any class you can use
```
ConfigurationManager.AppSettings["KeyToSetting"]
```
to access any value in the  element of web.config (or app.config)


q: How would I go about implementing dynamic/docking splitter panes in a vb.net app similar to visual studio?

[A]
Not easily is the short answer.
A high level idea would be to define some regions using divs or a table and using your js framework of choice make these elements resizeable.   that gets you the splitter aspect.
The docking will have to use absoluting positioned elements that you can drag and drop and if you are currently over a docking element, reposition the element to be docked to inside the docking element and change it's position back to normal.  When you want to drag it out you will change it's positioning back to absolute
Also, this is not easy to do and will take a long time and still probably not work correctly.  Sorry to sound pessimistic though.


q:
I'm writing a sample console service host and I want to plug into WCF stack to be able to print a message to console when new message arrives, even if it won't get processed by the service at the moment (because service is working on previous calls).
This is based on my assumption that messages arriving get queued by the WCF, is that correct?

Additionally, I'm using netTcpBinding if this is important.

[A]
You don't want to decode the string into a Unicode representation, you just want to treat it as an array of bytes, right?
Just use
```
PyString_FromString
```
:
```
```
char *cstring;
PyObject *pystring = PyString_FromString(cstring);
```
```
That's all.  Now you have a Python
```
str()
```
object.  See docs here:
https://docs.python.org/2/c-api/string.html
I'm a little bit confused about how to specify "str" or "unicode."  They are quite different if you have non-ASCII characters.  If you want to decode a C string
and
you know exactly what character set it's in, then yes,
```
PyString_DecodeString
```
is a good place to start.


q:
How many can relate do this?

Server Error in / Application

Object reference not set to an object

Description: Object reference not set to an object.

Exception Details: System.NullReferenceException: Object reference not set to an object.

Source Error:

Line 56:    posts.Add(post);

On a more serious note, what are the first things you look for when you see the
yellow screen of death? Half the time the debug trace isn't actually telling you what the problem is (understandable I guess).

I must admit, I still use Response.Write more than I should.  I just get lazy going through the debugger.  What techniques do you use to debug the problem?

[A]
If I'm unable to identify/resolve the issue using the error message that the page presents to me, I will typically try to use the Windows Event Viewer to help me identify what is causing the issue.
For example, SharePoint errors are sometimes far less than descriptive.  So, I'll combine what I'm seeing on the Y.S.O.D. with error messages from the Event Viewer to help me narrow down the cause.
I will do my best to ask a co-worker or other associate that I think might have some experience that might help.  If I'm still unable to identify the cause, I will resort to Google armed with all the information.


q: I am using an ASP page where I have to read a CSV file and insert it into DB table "Employee". I am creating an object of TestReader. How can I write a loop to execute up to the number of rows/records of the CSV file which is being read?

[A]
Do not try to parse the file yourself, you'll just give yourself a headache.  There's quite a bit more to it than splitting on newline and commas.
You can use OLEDB to open up the file in a recordset and read it just as you would a db table.  Something like this:
```
```
Dim strConn, conn, rs

strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
Server.MapPath("path to folder") & ";Extended Properties='text;HDR=Yes;FMT-Delimited';"

Set conn = Server.CreateObject("ADODB.Connection")
conn.Open strConn

Set rs = Server.CreateObject("ADODB.recordset")
rs.open "SELECT * FROM myfile.csv", conn

while not rs.eof
    ...
    rs.movenext
wend
```
```
My vbscript is rusty, so verify the syntax.
edit:
harpo's comment brings up a good point about field definitions.  Defining a schema.ini file allows you to define the number and datatypes of the expected fields.  See:  You can handle this by defining a schema.ini file. see:
http://msdn.microsoft.com/en-us/library/ms709353.aspx


q: I'm trying to use jcarousel to build a container with multiple rows, I've tried a few things but have had no luck. Can anyone make any suggestions on how to create it?

[A]
We have had to make a similar modifiaction.  We do this by extending the default options, to include a rows value, and the width of each item (we call them modules) then divide the width by the number of rows.
Code added to jCarousel function...
Add to default options:
```
```
moduleWidth: null,
rows:null,
```
```
Then set when creating jCarousel:
```
```
$('.columns2.rows2 .mycarousel').jcarousel( {
        scroll: 1,
        moduleWidth: 290,
        rows:2,
        itemLoadCallback: tonyTest,
        animation: 'slow'
    });
```
```
The find and edit the lines in:
```
```
$.jcarousel = function(e, o) {

if (li.size() > 0) {
...
moduleCount = li.size();
wh = this.options.moduleWidth * Math.ceil( moduleCount / this.options.rows );
wh = wh + this.options.moduleWidth;

this.list.css(this.wh, wh + 'px');

// Only set if not explicitly passed as option
if (!o || o.size === undefined)
   this.options.size = Math.ceil( li.size() / this.options.rows );
```
```
Hope this helps,
Tony Dillon


q:
I'm doing something like the following:

SELECT * FROM table WHERE user='$user';
$myrow = fetchRow() // previously I inserted a pass to the db using base64_encode ex: WRM2gt3R=

$somepass = base64_encode($_POST['password']);

if($myrow[1] != $somepass) echo 'error';
else echo 'welcome';

Im always getting error, I even echo $somepass and $myrow[1] they are the same, but still error. What Am I doing wrong? Thanks

[A]
Try using
```
var_dump
```
instead of echo - maybe one of them has a space or newline at the start/end.
Edit:
You must be storing it as CHAR(40):
```
A fixed-length string that is always right-padded with spaces to the specified length when stored
```
Use VARCHAR or
```
trim()
```


q:
We're looking at upgrading from Visual Studio 2005 to Visual Studio 2008. I discovered the following disturbing comment:

http://msdn.microsoft.com/en-us/library/6sehtctf.aspx

"Beginning with Visual C++ 2008, Visual C++ does not support targeting Windows 95, Windows 98, Windows ME, or Windows NT."

Does this mean that if we rebuild our products with visual C++ 2008, they will stop working on Windows 98 machines? It sounds like it, but I have trouble believing they'd make that big a change.

Thanks for your help.

[A]
according to the following link, windows 98 is not supported by .NET 3.5 so I would imagine that is what they mean. You can still do .NET 2.0 and lower development, but if you use the 3.5 libraries, Windows 98 is not supported.
.NET 3.5 information


q:
For example:

from datetime import <c-x><c-o>{list of modules inside datetime package}

[A]
the following steps should work.
make a blank solution, nothing in it.
Move the solution to where you want the web project to live.
Open the solution.
Create the web project in the desired area.
I often do this sort of moving around so that projects will sit nicely in svn.  Don't forget to svn:ignore the *.suo files.


q: I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?

[A]
I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:
```
```
template <template<class> class H, class S>
void f(const H<S> &value) {
}
```
```
Here,
```
H
```
is a template, but I wanted this function to deal with all specializations of
```
H
```
.
NOTE
: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).
I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that
```
std::vector
```
doesn't
have a
```
typedef value_type
```
.
So how would you write a function which can create variables of the right type for the vectors elements? This would work.
```
```
template <template<class, class> class V, class T, class A>
void f(V<T, A> &v) {
    // This can be "typename V<T, A>::value_type",
    // but we are pretending we don't have it

    T temp = v.back();
    v.pop_back();
    // Do some work on temp

    std::cout << temp << std::endl;
}
```
```
NOTE
:
```
std::vector
```
has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.
which you can use like this:
```
```
f<std::vector, int>(v); // v is of type std::vector<int> using any allocator
```
```
or better yet, we can just use:
```
```
f(v); // everything is deduced, f can deal with a vector of any type!
```
```
UPDATE
: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing
```
auto
```
. Now the same function can be written as:
```
```
template <class Cont>
void f(Cont &v) {

    auto temp = v.back();
    v.pop_back();
    // Do some work on temp

    std::cout << temp << std::endl;
}
```
```
which is how I'd prefer to write this type of code.


q:
I need to get a list of all documents in a site collection, which I believe I can do with either the alldocs table or the  alluserdata table (MOSS 2007 SP1) but do not see how I can get the author information for the document.  I do not need the contents of the document (e.g. AllDocStreams content)

Something like this:

SELECT     tp_DirName, tp_LeafName, tp_Version, tp_Modified, tp_Created
FROM         AllUserData
WHERE     (tp_ContentType = 'Document')
AND (tp_LeafName NOT LIKE '%.css')
AND (tp_LeafName NOT LIKE '%.jpg')
AND (tp_LeafName NOT LIKE '%.png')
AND (tp_LeafName NOT LIKE '%.wmf')
AND (tp_LeafName NOT LIKE '%.gif')
AND (tp_DirName NOT LIKE '%Template%')
AND (tp_IsCurrentVersion = 1)
AND (tp_LeafName NOT LIKE '%.xsl')
ORDER BY tp_SiteId, tp_ListId, tp_DirName, tp_LeafName, tp_IsCurrentVersion DESC

Is there a better way to go about this?

[A]
MOSS provides many
webservices
out of the box which make life a little easier.  They are always worth exploring.
For this particular instance, I think the article,
Getting a list of files from a MOSS document library using a SharePoint web service
, will be of assistance.  If this isn't your exact scenario, it will get you on the right track.
If the Document service doesn't help you, the Search service will I'm sure.  Check the documentation for usage.


q:
I'm writing an intranet application for a client and I want to give them the ability to configure through an admin interface, which users and user groups can access certain areas. What I'd like to know is the best way of storing the reference to the user or group that is assigned to an area of the intranet.

Should I be using the domain\username and domain\groupname strings or should i perhaps be using the fully qualified ad name ie ou=computer room;cn=blah etc?

I will be storing the reference in SQL.


q:
I want to check for duplicated words right next to each other, but even if there is punctuation in between.

For example:

Vivamus Vivamus diam, diam, Vivamus Vivamus diam, diam Vivamus

There should be four distinct hits here.

I can't figure out why this isn't working. Why? What should the correct code be?

(\w*(?:[ ,\.])*?)\1

PS: This is not necessarily for the Perl engine.

[A]
The
```
(?:
```
is a non-capturing parenthesis, meaning it won't store the matches.  You will need to use capturing parentheses.
```
```
(\w+)\W+\1
```
```


q:
How can one programmatically sort a union query when pulling data from two tables? For example,

SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY table2.field1

Throws an exception

Note: this is being attempted on MS Access Jet database engine

[A]
The second table cannot include the table name in the
```
ORDER BY
```
clause.
So...
```
```
SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY field1
```
```
Does not throw an exception


q: I've been doing "plain old java objects" programming for 10 years now, with Swing and JDBC, and I consider myself pretty good at it.  But I start a new job in two weeks where they use JBoss, and I'd like to get a heads up and start learning all this stuff before I start.  What are good resources?  On-line tutorials, books, e-books, anything you can suggest, especially ones that don't try to teach you the basics of plain Java first.

[A]
A couple of answers come to mind:
if "plain old java" is what you're used to, you'll probably need a grounding of plain old j2EE more than JBOSS specific stuff. I'd start with
the sun tutorials
, but being familiar with the general structure of servlets, the servlet api, is base.
as application servers go, JBoss is (my biased opinion only) insanely large and complicated. Think "launching the space shuttle" and you won't be far off. A million services. It is specifically noted for having an unusual class loader structure (although this may have changed since I used it last, about 1 -2 years ago), among other things. It also has an extensive list of nice services, like a JMX base (management configuration beans) although documentation is likely to be spotty, as support is a paid service.
Best suggestion- familiarize yourself with the J2EE libraries. Next would be to get a basic site running in JBOSS. More specific stuff that you might want to do is likely to be very specific to their installation (e.g. there's a JMS implementation available in there but they may not be using it) as I've seen people use it for nothing but a servlet container.


q:
So I know that autocommit commits every sql statement, but do updates to the database go directly to the disk or do they remain on cache until flushed?

I realize it's dependent on the database implementation.

Does auto-commit mean
a) every statement is a complete transaction AND it goes straight to disk or
b) every statement is a complete transaction and it may go to cache where it will be flushed later or it may go straight to disk

Clarification would be great.

[A]
Auto-commit simply means that each statement is in its own transaction which commits immediately.  This is in contrast to the "normal" mode, where you must explicitly
```
BEGIN
```
a transaction and then
```
COMMIT
```
once you are done (usually after several statements).
The phrase "auto-commit" has nothing to do with disk access or caching.  As an implementation detail, most databases will write to disk on commit so as to avoid data loss, but this isn't mandatory in the spec.


q:
Many C++ books contain example code like this...

std::cout << "Test line" << std::endl;

...so I've always done that too. But I've seen a lot of code from working developers like this instead:

std::cout << "Test line\n";

Is there a technical reason to prefer one over the other, or is it just a matter of coding style?

[A]
There might be performance issues,
```
std::endl
```
forces a flush of the output stream.


q:
I'm trying to compile a program called ngrep, and when I ran configure, things seemed to go well, but when I run make, I get:

ngrep.c: In function ‘process’:
ngrep.c:544: error: ‘struct udphdr’ has no member named ‘source’
ngrep.c:545: error: ‘struct udphdr’ has no member named ‘dest’
make: *** [ngrep.o] Error 1

What does that mean, and how do I fix it? There are no earlier warnings or errors that suggest the root of the problem.

[A]
Well, there is a struct called udphdr (probably short for udp header). And some part of the program assumes the struct has the members source and dest which it hasn't.
Look at file ngrep.c line 544 and 545 to find the offending lines.
Possible causes:
type name type error.
struct is not completely defined.
using the wrong struct.
Edit: probably related problem:
http://ubuntuforums.org/showthread.php?t=371871


q:
I recently ran into a problem that I thought boost::lambda or boost::phoenix could help be solve, but I was not able to get the syntax right and so I did it another way. What I wanted to do was remove all the elements in "strings" that were less than a certain length and not in another container.

This is my first try:

std::vector<std::string> strings = getstrings();
std::set<std::string> others = getothers();
strings.erase(std::remove_if(strings.begin(), strings.end(), (_1.length() < 24 &&  others.find(_1) == others.end())), strings.end());

How I ended up doing it was this:

struct Discard
{
    bool operator()(std::set<std::string> &cont, const std::string &s)
    {
        return cont.find(s) == cont.end() && s.length() < 24;
    }
};

lines.erase(std::remove_if( lines.begin(), lines.end(), boost::bind<bool>(Discard(), old_samples, _1)), lines.end());

[A]
You need boost::labmda::bind to lambda-ify function calls, for example the length < 24 part becomes:
```
```
bind(&string::length, _1) < 24
```
```
EDIT
See "Head Geek"'s post for why set::find is tricky.  He got it to resolve the correct set::find overload (so I copied that part), but he missed an essential boost::ref() -- which is why the comparison with end() always failed (the container was copied).
```
```
int main()
{
  vector<string> strings = getstrings();
  set<string> others = getothers();
  set<string>::const_iterator (set<string>::*findFn)(const std::string&) const = &set<string>::find;
  strings.erase(
    remove_if(strings.begin(), strings.end(),
        bind(&string::length, _1) < 24 &&
        bind(findFn, boost::ref(others), _1) == others.end()
      ), strings.end());
  copy(strings.begin(), strings.end(), ostream_iterator<string>(cout, ", "));
  return 0;
}
```
```


q:
What new features in java 7 is going to be implemented?
And what are they doing now?

[A]
In addition to what John Skeet said, here's an
overview of the Java 7 project
. It includes a list and description of the features.
Note: JDK 7 was released on July 28, 2011, so you should now go to the official
java SE site
.


q:
I really like Entity Framework, but there are some key pieces that are a challenge to me. Can anyone tell me how to filter an EntityDataSource on an Association column? EF hides the FK values and instead has an Association property. Given an Entity, Person, with a PersonType association, I would have expected something like this to work if I want to filter my Person Entity by Type:

GridDataSource.EntityTypeFilter = "it.PersonType.PersonTypeID = 1";

or

GridDataSource.Where = "it.PersonType.PersonTypeID = '1'";

or even

GridDataSource.WhereParameters.Add(new Parameter("it.PersonType.PersonTypeID", DbType.Object, "1"));

but none of those work. Anybody know how to do this?

[A]
Have you tried applying the filter in memory using LINQ? (or Perhaps against the database?)
```
```
var personType = new PersonType { Id = 1 };
var query = PersonDataSource.Where(p => p.PersonType.Equals(personType));
// use this query as the DataSource for your GridView
```
```
I must admit I haven't done anything like this, but I have used this trick to update/create an entity without loading the associated entities first.


q:
If I have a method such as:

public void MyMethod(int arg1, string arg2)

How would I go about getting the actual names of the arguments?
I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter.

I would like to write a method which looks like this:

public static string GetParamName(MethodInfo method, int index)

So if I called this method with:

string name = GetParamName(MyMethod, 0)

it would return "arg1". Is this possible?

[A]
```
```
public static string GetParamName(System.Reflection.MethodInfo method, int index)
{
    string retVal = string.Empty;

    if (method != null && method.GetParameters().Length > index)
        retVal = method.GetParameters()[index].Name;

    return retVal;
}
```
```
The above sample should do what you need.


q:
I just read the Wikipedia article on mock objects, but I'm still not entirely clear on their purpose. It appears they are objects that are created by a test framework when the actual object would be too complex or unpredictable (you know 100% sure what the values of the mock object are because you fully control them).

However, I was under the impression that all testing is done with objects of known values, so I must be missing something. For example, in a course project, we were tasked with a calendar application. Our test suite consisted of event objects that we knew exactly what they were so we could test the interactions between multiple event objects, various subsystems, and the user interface. I'm guessing these are mock objects, but I don't know why you wouldn't do this because without the objects of known values, you can't test a system.

[A]
Think of the classic case of having client and server software. To test the client, you need the server; to test the server, you need the client. This makes unit testing pretty much impossible - without using mocks. If you mock the server, you can test the client in isolation and vice versa.
The point of the mock is not to duplicate the behaviour of the things its mocking though. It is more to act as a simple state machine whose state changes can be analysed by the test framework. So a client mock might generate test data, send it to the server and then analyse the response. You expect a certain response to a specific request, and so you can test if you get it.


q:
Say you have a standard template with included (parsed) header, body, footer templates.

In the body template a variable like $subject is defined and you want that also displayed in the header template.

In some other template languages like HTML::Mason(perl based) you would evaluate the body template first to pick up the $subject variable but store it's output temporarily in a variable so your final output could end up in the correct order (header, body, footer)

In velocity it would look something like

set ($body=#parse("body.vm"))

parse("header.vm")

${body}

parse("footer.vm")

This however doesn't seem to work,  any thoughts on how to do this?

[A]
You can do this using
VelocityLayoutServlet
which is part of
VelocityTools
.
This allows you to define a layout for your application -- let's call it
```
application.vm
```
-- in which you can parse in headers, footers etc and declare where the main body content is placed using the
```
screen_content
```
declaration, e.g:
```
```
<html>
  <head>
    <title>$subject</title>
  </head>
  <body>
  #parse("header.vm")
  $screen_content
  #parse("footer.vm")
  </body>
</html>
```
```
```
VelocityLayoutServlet
```
will evalulate the templates (and, hence, variables) before rendering which allows you to set a
```
$subject
```
variable in your body template, e.g:
```
```
#set($subject = "My Subject")
<div id="content">
</div>
```
```
More detailed information can be found
in the Velocity documentation
.


q:
Running VISTA 32bit.

I am trying to install c# Visual Express 2008 - but it requires .NET 3.5. One of the prerequisites during the install is .NET 3.5 ... it attempts to install it but fails, with no real error message.

So I downloaded .NET 3.5 standalone from MS website and tried that.Again it fails with the error

[10/17/08,23:17:07] WapUI: [2] DepCheck indicates Microsoft .NET Framework 3.0SP1 (CBS) is not installed.
  [10/17/08,23:50:55] Microsoft .NET Framework 3.0SP1 (CBS): [2] Error: Installation failed for component Microsoft .NET Framework 3.0SP1 (CBS). MSI returned error code 34

I currently have c# Express edition 2005 installed. But everything I read says that I can have these two applications installed together. I believe that 2005 runs Framework 2.0. 2005 express edition works fine. - its just the 2008 edition im having problems installed the .NET 3.5 with ....

any ideas ? thanks

[A] Have you ever installed any of the pre-release versions of 3.0 or 3.5?  I had a lot of trouble installing 3.5 until I realized that I had installed a CTP of WPF.  Go through all of your Microsoft and .NET installs in Add/Remove programs and make sure that you don't have any pre-release versions.


q:
I was getting bad data from an application I was writting using C++ in Visual Studio 2k3 so I decided to debug it. Then I found it was throwing an exception but one I can't track down.

Then I placed some try/catch blocks and low and behold, when I don't debug there is no exception. That is, I have code that looks like this:

std::vector<MyClass*> ListOfStuff;
.
.
.
try
{
.
.
.
   const MyClass * localPointer = ListOfStuff[i]; //This is where the exception occurs
.
.
}
 catch (...)
{
   int x = 0;  //place break here
}

So if I step through the code line by line I'll get an exception and shot to the catch. But if I just let it run with a breakpoint inside the catch nothing happens. Using an iterator has the same behavior. And I can successfully check the size of the vector so I know I'm within the bounds.

Can anyone tell me what's going on? If it matters I'm using some standard windows libraries and openGL.

[A]
Is the exception an ASSERT? These may get compiled out at compile time or otherwise throw an assertion.
For example, you could have
```
```
#ifdef DEBUG
#define ASSERT(cond) if (cond) throw CDebugAssertionObj;
#else
#define ASSERT(cond)
#endif
```
```


q:
Anyone know of a good free winforms html editor for .NET. Ideally I would like html and preview modes along with the possibility of exporting to a pdf, word doc or similar.

Although the export I could probably create myself from the html output.

Another nice feature would be a paste from word that removes all the extra tags you usually end up with but again it's a nice to have not a required.

[A]
You can use the
WebBrowser
control in design mode with a second
```
WebBrowser
```
control set in view mode.
In order to put the
```
WebBrowser
```
control in design mode, you can use the following code.
This code is a super stripped down version of a WYSIWYG editor for one of our software products.
Simply create a new Form, drop a
```
WebBrowser
```
control on it, and put this in the Form.Load:
```
```
Me.WebBrowser1.Navigate("")
Application.DoEvents()
Me.WebBrowser1.Document.OpenNew(False).Write("
Edit this text
")

'turns off document body editing
For Each el As HtmlElement In Me.WebBrowser1.Document.All
    el.SetAttribute("unselectable", "on")
    el.SetAttribute("contenteditable", "false")
Next

'turns on editable div editing
With Me.WebBrowser1.Document.Body.All("editable")
    .SetAttribute("width", Me.Width & "px")
    .SetAttribute("height", "100%")
    .SetAttribute("contenteditable", "true")
End With

'turns on edit mode
Me.WebBrowser1.ActiveXInstance.Document.DesignMode = "On"
'stops right click->Browse View
Me.WebBrowser1.IsWebBrowserContextMenuEnabled = False
```
```


q: I'm working on a table of links within a site using iframes. I'm wondering if there's any way to code a link to go to two simultaneous destinations within two different target frames? I've been reading all afternoon and can't find anything close to what I want to do. Basically I want one link to present a photo in one iframe and some data in another iframe. Any ideas?

[A]
Short answer: No.
Longer answer: With what you describe, using strictly X/HTML, this isn't possible. You could add in javascript to change the iframe src, however. Something like:
```
```
function click_link(id) {
    document.getElementById('iframe1').src = "page.ext?id=" + id;
    document.getElementById('iframe2').src = "other_page.ext?id=" + id;
}
```
```
But of course, you probably shouldn't be using iframes anyways...


q:
I am trying to make my window manager conform to the ICCCM specifications. I fully understand the reason for the _NET_SUPPORTING_WM_CHECK atom - this ensures that no invalid information stays whenever the window manager isn't running anymore.

What I don't understand is why are no other atoms like _NET_NUMBER_OF_DESKTOPS expected on the supporting window besides _NET_WM_NAME and _NET_SUPPORTING_WM_CHECK itself.

Window managers are supposed to set and overwrite the data but this can be misleading in the case the new window manager isn't compliant.

[A]
Well the atoms that you are talking about are not the ICCCM.
They belong to the newer set of
EWMH
So basically it goes like this.
First we had the ICCCM.
They are
old
mature
supported by most window managers (in full or in part)
easy to implement
Unix standard
Then we had EWMH that are
newer (GNOME and KDE)
not many window managers support them
more complex (e.g. virtual desktops)
A freedesktop standard.
Freedesktop wanted to make the EWMH as broad as possible (apart from GNOME and KDE)
and that is why most of the atoms are SHOULD and not MUST. They are giving a chance to small window manager to claim compliance.


q:
I have several user drawn controls on a form, unfortunately when the form is shown the user drawn controls are showing the previous forms background rather than the current forms background.

The OnPaint event is very simple, and the OnBackgroundPaint event is empty...

Like this:

    protected override void OnPaint(PaintEventArgs pe)
    {
        pe.Graphics.DrawImageUnscaled(_bmpImage, 0, 0);
    }

    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        //Leave empty...
    }

How do I get the current background to be the transparency that is shown, rather than the background of the previous form?

[A]
Ruby performs shell expansion when %x is used with a single argument (like you are doing).
Here's my guess as to what is going on:
Ruby scans the command to determine if there are any special characters that would result in the need to perform shell expansion, if so it calls the shell to do that.  In the second example the single quotes are enough to make Ruby want to call the shell to do the expansion, hence the fork. In the first example Ruby can determine that shell expansion is not needed as the command contains no special characters (after variable expansion), hence no fork.  The difference between the two versions probably has to do with an internal change in how ruby tries to determine is shell expansion is needed.  I get a fork for the second example on ruby 1.8.5 on a 32-bit machine.
[EDIT]
Okay, I took a look at the source code for ruby 1.8.4 and 1.8.6 and both versions use the same criteria to determine whether or not to call a shell to perform shell expansion, if any of the following characters exist in the command line the shell will be invoked when one argument to %x is provided:
```
```
*?{}[]<>()~&|\\$;'`"\n
```
```
Ruby is actually calling the shell in both cases (in example that contains the quotes), the reason you are seeing different outputs from
```
pstree
```
is due to differences in the the
```
sh
```
command on the different machines, one calls
```
fork
```
, the other doesn't.  To see this for yourself, run this command on both machines:
```
```
/bin/sh -c "pstree $$"
```
```
This is the command that Ruby is using to execute
```
pstree
```
in the example with quotes on both machines.  You should see
```
bash---pstree
```
on the 32-bit machine and
```
bash---sh---pstree
```
on the other one.
So now I'm curious, what led you to discover this difference and is it causing a problem?


q:
When including a header file in C++, what's the difference between...

including the .h part versus not including .h part when wrapping it in <> signs?

#include <iostream> vs. #include <iostream.h>

wrapping the header name in double quotes versus wrapping it in < > signs?

#include <iostream.h> vs. #include "iostream.h"

[A]
Here is a decent link
article.
To summarize, the reason given:
The version of the iostream library that the Standards Committee
  produced was quite a bit different from the CFront implementation.
  {snip}
To ease transition, the C++ Standards Committee declared that code
  including the standard C++ headers would use include directives that
  lack an extension. This allowed compiler vendors to ship the old style
  C++ library headers with the .h extension and the new style headers
  without.
An advantage of not using the .h version:
There are several reasons why new code should be written using the
  extensionless version of the header files instead of the .h forms. The
  first is the unpredictability of such code when compiled on modern
  compilers. As previously mentioned, the result of using the .h headers
  is implementation specific. And as time goes by, the chance that a
  given compiler will have the old style library available decreases.


q:
Recent conversations with colleagues have produced varying points of view on this matter. What say you, SO members?

I know, even the concept of scalability can be taken in so many different ways and contexts, but that was part of the discussion when this came up. Everyone seemed to have a different take on what scalability really means. I'm curious to see the varying takes here as well. In fact, I posted a question just for that concept.

[A]
It greatly depends on which LINQ provider you are using and how you are using it. LINQ probably is not know for amazing execution speed but is rather provides developers with substantially better productivity.
According to
this
link even with some of the CTPs Linq to SQL was already better than using direct SQL in some cases.
If you are concerned with Speed and are using LINQ to objects alot
here
is a codeplex project (I think) for a provider that can give you 1000x performance improvements.


q:
I have the following snippet of code, changeTextArea is a TextArea object.

changeTextArea.addKeyboardListener(new KeyboardListenerAdapter()
  public void onKeyPress( Widget sender, char keyCode, int modifier){
    //do something
    //I WISH TO STOP THE EVENT THAT MAPS TO THIS KEYPRESS FROM BUBBLING ANY FURTHER
  }
}

How would I stop the Event that is causing this method to be called from bubbling up from changeTextArea into the Panels/Widgets/Composites/Whatever that contain changeTextArea. Put succinctly, how do I stop it from bubbling any further. Any help would be appreciated (especially code samples).

[A]
As far as I know you can't do it via a keyboard listener, but it is possible by adding an event preview using the DOM class:
```
```
DOM.addEventPreview(EventPreview preview)
```
```
Then when you get the event:
```
```
onEventPreview(Event event)
```
```
You should return false, to say you want to cancel the event. The Event object also supports this method:
```
```
public final void cancelBubble(boolean cancel)
```
```
Cancels bubbling for the given event. This will stop the event from being propagated to parent elements.
You can find more details here:
http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html


q: When using Fiddler to monitor HTTP Requests & Responses in Internet Explorer it ignores all traffic directed to http://localhost.

[A]
To get Fiddler to capture traffic when you are debugging on local host, after you hit F5 to begin degugging change the address so that localhost has a "." after it.
For instance, you start debugging and the you have the following URL in the Address bar:
http://localhost:49573/Default.aspx
Change it to:
http://localhost.:49573/Default.aspx
Hit enter and Fidder will start picking up your traffic.


q:
In C# is there any real difference (other than syntax) under the hood between:

myButton.Click += new EventHandler(myMemberMethod);

and

myButton.Click += myMemberMethod;

?

[A]
The second method is a shortcut to the first one, it was introduced in C# 2.0
See also
this thread
.


q:
Does anyone know the bare minimum files required for Ext JS 2.2? I know the ExtJS site has a feature to "build" a small version of ExtJS (ext.js) as a replacement for ext-all.js but that's for minimizing the size of ExtJS on the client. I'm interested in minimizing what's on the server. Currently the SDK comes with the following subdirectories:

ext-2.2/

adapter
air
build
docs
examples
resources
source

I think its pretty safe to remove examples, docs, and air. However, are there other things we can remove to make this smaller or is there a resource (besides the large javascript source code corpus) that documents the minimum required files?

[A]
This link explains the include order
What is the proper include order for my JavaScript files?
This is the minimum include set
```
```
<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css">
<script type="text/javascript" src="../extjs/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../extjs/ext-all.js"></script>
```
```
The ext-all.css depends on files in ../extjs/resources/css so you should include that entire directory structure also.
So you'd need the following files at a minimum
extjs/resources/**/*
extjs/adapter/ext/ext-base.js
extjs/ext-all.js
If you're not using Ext JS for any of the UI components then you don't need any of the stylesheets and supporting images, but in that case you'd have to question why you're using Ext JS since that's it's strong point.


q: Using any tools which you would expect to find on a nix system (in fact, if you want, msdos is also fine too), what is the easiest/fastest way to calculate the mean of a set of numbers, assuming you have them one per line in a stream or file?

[A]
Perl.
```
```
@a = <STDIN>;

for($i = 0; $i < #@a; $i++)
{
   $sum += $a[i];
}

print $a[i]/#@a;
```
```
Caveat Emptor: My syntax may be a little whiffly.


q:
I would like to embed Flash Player directly inside a C++ or Java application.

I found an article that describes how to do this for C#:
http://www.adobe.com/devnet/flash/articles/stock_history03.html

Unfortunately, I have no experience with C#, COM or ActiveX. I need someone to translate this code to C++, allowing me to embed the Flash Player into a Win32 Window. Ultimately I'd like to use this information to embed Flash into a Java application.

I am looking for three main functionalities:

Ability to play a Flash movie

Ability to receive events (such as mouse clicks)

Ability to send events

Edit: I prefer an open-source solution if possible.

[A]
I don't know how to embed flash in C++, but Christopher Deckers (of
SWTSwing
fame) has developed an interesting hack which allows it to be embedded in Java.  You can find more information in
the Javalobby announcement thread
.
Here is an updated link:
https://github.com/Chrriis/DJ-Native-Swing


q: How can I set the location (as it's picked up in CoreLocation services) in the iPhone Simulator?

[A]
In my delegate callback, I check to see if I'm running in a simulator (
```
#if TARGET_ IPHONE_SIMULATOR
```
) and if so, I supply my own, pre-looked-up, Lat/Long. To my knowledge, there's no other way.


q:
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);

If 'table' has no rows. whats the easiest way to check for this.?

[A]
You could use
mysql_num_rows($results)
to check if 0 rows were returned, or use this faster alternative:
```
```
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
```
```


q:
I want to check if a given date is more than a month earlier than today's date using LINQ.

What is the syntax for this?

Thanks in advance.

[A]
I assume that you're talking about in the where clause.  It's basically the same way you would compare two DateTime objects elsewhere.
```
```
using (DataContext context = new DataContext()) {
   var query = from t in context.table
               where t.CreateDate.Date < DateTime.Today.AddMonths(-1)
               select t;
}
```
```


q: I would like to show a set of consecutive numbers in a UIPickerView component but have it wrap around like the seconds component of the Clock->Timer application. The only behavior I can enable looks like the hours component of the Timer application, where you can scroll in only one direction.

[A]
I found my answer here:
http://forums.macrumors.com/showthread.php?p=6120638&highlight=UIPickerView#post6120638
When it asks for the title of a row, give it:
Code:
```
```
return [rows objectAtIndex:(row % [rows count])];
```
```
When it says the user didSelectRow:inComponent:, use something like this:
Code:
```
```
//we want the selection to always be in the SECOND set (so that it looks like it has stuff before and after)
if (row < [rows count] || row >= (2 * [rows count]) ) {
    row = row % [rows count];
    row += [rows count];
    [pickerView selectRow:row inComponent:component animated:NO];
}
```
```
It appears that the UIPickerView does not support wrapping around natively, but you can fool it by inserting more sets of data to be displayed and when the picker stops, centering the component to the middle of the data set.


q:
I am completely new to programming - my interest lies in PHP & MySql for building a dynamic web application for Military Band Administration purposes. i.e. General info and social networking for members + added functionality for the management team to communicate effectively.

OK so the question - as I learn more about PHP there are terms used that I do not understand that must come from a common basis of familiarity between all languages i.e. "stack overflow" appears to be an obvious one - "using too many recursive functions may smash the stack" is another.

So is there a book (a primer perhaps) about programming in general which allows someone like me to have a better understanding of what all this means?

Bear in mind I am 57 years old (young) and am really just starting out.

Steve

[A]
To get a good understanding of the inner workings of computer hardware and software in a very readable (not too technical) manner, I can recommend
Code,The Hidden Language of Computer Hardware and Software
by Charles Petzold.
The later chapters in particular talk about some of these more general programming concepts that are present in most programming languages.  The earlier chapters focus on more the history of the computer and software, so not as relevant to your question.
However it's not a large book so the reading it all should be interesting/useful anyway.
There are better books if you are looking for an introduction to PHP/MySQL programming specifically, however if you want more general knowledge about how software and hardware works, Code is great.


q:
The following Perl statements behave identically on Unixish machines.  Do they behave differently on Windows?  If yes, is it because of the magic \n?

  split m/\015\012/ms, $http_msg;
  split m/\015\012/s, $http_msg;

I got a failure on one of my CPAN modules from a Win32 smoke tester.  It looks like it's an \r\n vs \n issue.  One change I made recently was to add //m to my regexes.

[A]
For these regexes:
```
```
m/\015\012/ms
m/\015\012/s
```
```
Both /m and /s are meaningless.
/s: makes
```
.
```
match
```
\n
```
too.
Your regex doesn't contain
```
.
```
/m: makes
```
^
```
and
```
$
```
match next to embedded
```
\n
```
in the string.
Your regex contains no
```
^
```
nor
```
$
```
, or their synonyms.
What is possible is indeed if your input handle (socket?) works in text mode, the
```
\r
```
(
```
\015
```
) characters will have been deleted on Windows.
So, what to do? I suggest making the
```
\015
```
characters optional, and split against
```
```
/\015?\012/
```
```
No need for /m, /s or even the leading
```
m//
```
. Those are just cargo cult.


q:
A long time ago when I was a young lat I used to do a lot of assembler and optimization programming. Today I mainly find myself building web apps (it's alright too...). However, whenever I create fields for database tables I find myself using values like 16, 32 & 128 for text fields and I try to combine boolean values into SET data fields.

Is giving a text field a length of 9 going to make my database slower in the long run and do I actually help it by specifying a field length that is more easy memory aligned?

[A]
Database optimization is quite unlike machine code optimization. With databases, most of the time you want to reduce disk I/O, and wastefully trying to align fields will only make less records fit in a disk block/page. Also, if any alignment is beneficial, the database engine will do it for you automatically.
What will matter most is indexes and how well you use them. Trying tricks to pack more information in less space can easily end up making it harder to have good indexes. (Do not overdo it, however; not only do indexes slow down INSERTs and UPDATEs to indexed columns, they also mean more work for the planner, which has to consider all the possibilities.)
Most databases have an EXPLAIN command; try using it on your selects (in particular, the ones with more than one table) to get a feel for how the database engine will do its work.


q:
On the Python side, I can create new numpy record arrays as follows:

numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])

How do I do the same from a C program?  I suppose I have to call PyArray_SimpleNewFromDescr(nd, dims, descr), but how do I construct a PyArray_Descr that is appropriate for passing as the third argument to PyArray_SimpleNewFromDescr?

[A]
See the
Guide to NumPy
, section 13.3.10.  There's lots of different ways to make a descriptor, although it's not nearly as easy as writing
```
[('a', 'i4'), ('b', 'U5')]
```
.


q:
Is there a good way to add a .swf programatically to a panel on an asp.net page - ie: I know i could just insert the html tags:

ie:

<object type="application/x-shockwave-flash" data="yourflash.swf" width="" height="">
<param name="movie" value="yourflash.swf">
</object>

But is there an existing .net or free FLASH component already that you just set the properties on, or do i need to create a custom web control myself (not preferred) so i dont have to continously do this?

Thank you.

[A]
Just a guess here, but it looks like you are inheriting either the Static Edge or Client Edge style from you theme.  I create most of my dialogs from the resource editor and set these properties there.
In your case, you can replace your CreateWindow with a
CreateWindowEx
to set these extended styles, which are probably being defaulted in CreateWindow.  Specifically check out
```
WS_EX_STATICEDGE, WS_EX_WINDOWEDGE and WS_EX_CLIENTEDGE
```
Edit: I'm assuming that this is not happening because you button is the default control in the dialog, which would also give a black edge.


q: I'm looking for something that will let me parse Atom and RSS in Ruby and Rails. I've looked at the standard RSS library, but is there one library that will auto-detect whatever type of feed it is and parse it for me?

[A]
Googleage reveals some things.  Were they not acceptable?
Simple RSS
Ruby-Feedparser
```
```
require 'simple-rss'
require 'open-uri'
rss = SimpleRSS.parse open('http://slashdot.org/index.rdf')
rss.channel.title # => "Slashdot"
```
```


q: I'm trying to solve this flickering problem on the iphone (open gl es game).  I have a few images that don't have pow-of-2 dimensions.  I'm going to replace them with images with appropriate dimensions... but why do the dimensions need to be powers of two?

[A]
Typically, graphics hardware works natively with textures in power-of-2 dimensions.  I'm not sure of the implementation/construction details that cause this to be the case, but it's generally how it is everywhere.
EDIT:  With a little research, it turns out my knowledge is a little out of date -- a lot of modern graphics cards can handle arbitrary texture sizes now.  I would imagine that with the space limitations of a phone's graphics processor though, they'd probably need to omit anything that would require extra silicon like that.


q: Now that the G1 with Google's Android OS is now available (soon), will the android platform ever support .Net?

[A]
Yes, it will be possible and it won't be that difficult. All what's needed at this point to start with is some kind of converter that will turn MSIL into
Dalvik bytecode
. Since both formats are open-sourced and well documented, there won't be any problem with it.
So, writing Android applications in C# or VB.NET will be possible, question is how much of .NET framework standard libraries will be supported. But that's another issue.
Oscar Reyes wrote:
I'm pretty sure if google hand ANY
  interest in .net, they would've design
  something while Android was in the
  first stages, not now when they are in
  production stages. I don't mean it is
  not possible, what I'm saying is
  they're not interested. Maybe in mmm
  hhhh 10 yrs.
Actually what they've already designed is
very compatible
with Java and .NET
They can't do everything at once, but if you look into Android SDK, there is a tool called
dx
. This tool converts Java bytecode into Dalvik bytecode, so in other words, you can run programs written in Java on Android with no effort today. Now the same tool is needed for .NET.
Considering how similar .NET and Java are, it's really a matter of time.
ddimitrov wrote:
The .Net->Java->Dalvik translation can
  be done even now
  (
http://dev.mainsoft.com/
), but I
  think you underestimate the lack of
  .Net libraries. Of course somebody can
  port Mono, but it's definitely a
  non-trivial effort.
No need to port Mono. Android already has VM and some basic API. All what's needed is CIL->Dalvik converter and tiny .NET wrapper for Android API (and maybe some basic implementation of some standard .NET classes). That's it.
Update:
.NET already works on Android - you will need product called Monodroid (
http://monodroid.net
) as stated above.


q:
I have a webservice, which takes java.lang.object objects as parameters (because at runtime only know hte type of object)...after doing process, reply response setting java.lang.Object to it.

I am able to send the reuest objects to webservice from calling program, but getting NotSerializable exception while building the response from webservice.

I came to know that 'if we implement, java.io.serializable, the mebmers also should be serializable objects'... here Object isnot a serializable object..it doesn't impllement Serializable....

If anyone could guide mw with right solution..I wouold be thankful.

Thanks
Bhaskar

[A]
If the members of the class don't implement Serializable then you can't use native Java serialisation for it.  That's basically what your error message is telling you.
If you cannot cause the underlying objects to implement Serializable, then you are probably going to have to find a different method of serialisation for passing in and out of your web service.  Popular varieties from Java are XML, JSON, AMF, although you can always roll your own.
If you have Java objects on either end of your request then make sure you factor your code so that your serialisation and de-serialisation code is in a library that can be used at both ends.  That will greatly ease the burden of testing in your implementation.
I would recommend keeping all the serialisation code out of the domain objects themselves.  Think about using a factory pattern for creation of your objects.
HTH


q:
It's just so much HRESULT E_FAIL, if you know what I'm talking about.

And if you use Visual Studio, you know what I'm talking about.

Similar thread, but not a duplicate: Is the design view for aspx pages in Visual Studio useful?

Any insight, including input from Microsoft MVPs (oh, I know you're out there) would be super cool.

[A]
Try this:
Put your MasterPages in a seperate folder (if they aren't already.  Call it
```
masterpages
```
.  Then add this to your
```
web.config
```
:
```
```
<location path="MasterPage">
<system.web>
  <authorization>
    <allow users="?" />
  </authorization>
</system.web>
```
```
This will allow anonymous access to that folder and allow access to the masterpage.  Also, are these nested masterpages?


q:
I have two windows services running on the same machine. Both the services uses

private HttpListener listener;

I specify the baseURL as "http://IPAddress:8080/" & "http://IPAddress:8081/" respectively for each of the services. Then I do the needful and call

listener.Start();

The first service starts successfully at 8080 port. But when I now start the 2nd service,
I get HTTPListenerException "The process cannot access the file because it is being used by another process" for listener object.

Could anybody please tell me:
1) If it is possible to start two HTTP listeners on the same IIS at two different ports.
2) If yes, how can we achecive this?
3) Is there any other way of doing this?

For your information:
I am using C#.NET 2.0 and IIS 6.0 server.

Thanks & Regards,

Hari

[A]
Doesn't HttpListener work independently from IIS? Can you stop the IIS service and see what happens?
Or maybe port 8081 is
used by another program
or process. I suggest to try to set the port to another number. You could open a command line and execute the "
netstat
" command to see
if the port is used
before starting your services.
(source:
googlepages.com
)


q:
Is there a clever way of adding XML serialization instructions without modifying the serialized class?

I don’t like the default serialization and I can’t modify the class. I was considering inheriting the class, and using Shadows (VB.NET) to re-implement the properties (with the serialization instructions), but it results in a lot of duplicate code and just looks terrible.

The ideal solution I'm looking for is basically a method to keep all the serialization instructions in a separate file.

[A]
Use reflection to get the values of all the properties from the class then write them as attributes on to an XmlNode
```
```
PropertyInfo[] properties = control.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
  object o = property.GetValue(control, null);
  // write value of o.ToString() out as an attribute on a XmlNode
  // where attribute name is property.Name
}
```
```


q:
Essentially what I want is a BlockingQueue of size=1. I have a "listener" thread that simply waits, blocking until an object is put into the queue, and then retrieves it--and a "producer" thread that actually puts the object into the queue.

I can implement this with some synchronized blocks and a BlockingQueue implementation, but that seems like overkill. Is there a better, simpler way to do what I want?

Example interface:

public interface Wait<T> {
  /**
   * If "put" has never been called on this object, then this method will
   * block and wait until it has. Once "put" has been called with some T, this
   * method will return that T immediately.
   */
  public T get() throws InterruptedException;

  /**
   * @param object The object to return to callers of get(). If called more
   * than once, will throw an {@link IllegalStateException}.
   */
  public void put(T object);
}


q:
I'm looking for a library to save an array of colour data to a PNG file. (That's all there is to it, right? I know very little about the internals of a PNG.)

This is for use in Nintendo DS development, so something lightweight is preferable. I don't need any other fancy features like rotation, etc.

[A]
Have you looked at libpng?
http://www.libpng.org/pub/png/libpng.html
I'm not sure whether the memory footprint will be acceptable, but you should probably be aware that PNG files are a lot more involved than just an array of colors. Performance is likely to be a concern on a DS.
If you go with libpng, you'll also need zlib, and if you're using DevKitPro, you'll probably run into some missing functions (from playing with the code for 5 minutes, it looks like it relies on pow() which doesn't seem to be in libnds.) I have no idea what the official Nintendo SDK offers in the way of a standard library - you might be in better shape if that's what you're using.


q: Apparently, they're "confusing". Is that seriously the reason? Can you think of any others?

[A]
Have you seen how many developers don't really understand ref/out?
I use them where they're really necessary, but not otherwise. They're usually only useful if you want to effectively return two or more values - in which case it's worth at least
thinking
about whether there's a way of making the method only do one thing instead. Sometimes using ref/out
is
the most appropriate approach - the various TryParse methods etc.


q:
I can think of plenty of good reasons to using it; however, what are the downsides to it?

(Apart from buying another server)

What are some advantages to using a daily build instead of it?

[A]
I don't think there are any downsides to it. But for the sake of the argument, here is
Eric Minick's article on UrbanCode
("It's about tests not builds.")
He criticises the tools that are based on
Martin Fowler's work
saying that they don't let enough time for tests.
"To be truly successful in CI, Fowler asserts that the build should be self-testing and that these tests include both unit and end-to-end testing. At the same time, the build should be very fast - ideally less than ten minutes - because it should run on every commit. If there are a significant number of end-to-end tests, executing them at build time while keeping the whole process under ten minutes is unrealistic.
Add in the demand for a build on every commit, and the requirements start to feel improbable. The options are either slower feedback or the removal of some tests."


q:
I'm using the contentEditable attribute on a DIV element in Firefox 3.03.  Setting it to true allows me to edit the text content of the DIV, as expected.

Then, when I set contentEditable to "false", the div is no longer editable, also as expected.

However the flashing caret (text input cursor) remains visible even though the text is no longer editable.  The caret is now also visible when I click on most other text in the same page, even in normal text paragraphs.

Has anyone seen this before?  Is there any way to force the caret hidden?

(When I either resize the browser or click within another application, and come back, the caret magically disappears.)

[A]
I've dealt with this and my workaround is clearing the selection when I disable contentEditable:
```
```
if ($.browser.mozilla) { // replace with browser detection of your choice
  window.getSelection().removeAllRanges();
}
```
```
I am actually removing the "contenteditable" attribute for browsers other than IE, rather than setting it to false:
```
```
if ($.browser.msie) {
  element.contentEditable = false;
}
else {
  $(element).removeAttr( 'contenteditable' );
}
```
```
The browsers manage the contentEditable attribute inconsistently and my testing revealed that this worked better overall. I don't remember if this contributed to fixing the caret problem, but I'm throwing it in here just in case.


q:
I'm trying to find some references in regards to x86 Assembly languages. Tutorials/Examples to help my understanding.
-Thanks

[A]
Programming from the Ground Up
(free book, highly recommended)
x86 Assembly
(wikibooks.org)
Essential Resources for x86 Programmers


q: What is a StackOverflowError, what causes it, and how should I deal with them?

[A]
Like you say, you need to show some code. :-)
A stack overflow error usually happens when your function calls nest too deeply. See the
Stack Overflow Code Golf
thread for some examples of how this happens (though in the case of that question, the answers intentionally cause stack overflow).


q:
I am writing an .NET wrapper API for the Netflix API.

At this point I can choose to represent URLs as either strings or URI objects. Seems to me there is a good case for both.

So if you were using an API, which would you prefer?

[A]
The below quote is from:
Framework Design Guildelines
I
highly
recommend this book to anyone developing frameworks on .Net
Do use
System.Uri to represent URI / URL data.
(For Parameters,
  properties, and return values)
System.Uri is a much safer and richer
  way of representing URIs. Extensive
  manipulation of URI-related data using
  plain strings has been shown to cause
  many security and correctness
  problems.
Consider
providing string-based overloads for most commonly used
  members with System.Uri parameters.
In cases where the usage pattern of
  taking a string from a user will be
  common enough, you should consider
  adding a convenience overload
  accepting a string. The string-based
  overload should be implemented in
  terms of the Uri-based overload.
Do Not
automatically overload all Uri-based members with a version that
  accepts a string.
Generally, Uri-based APIs are
  preferred. String-based overloads are
  meant to be helpers for the most
  common scenarios. Therefore, you
  should not automatically provide
  string-based overloads for all
  variants of the Uri-based members. Be
  selective and provide such helpers
  just for the most commonly used
  variants.
EDIT (per comments):
The book specifically states:
"Extensive manipulation of URI-related data using plain strings has been shown to cause many security and correctness problems."
I am not sure what additional justification you want for using System.Uri / UriBuilder. Additionally, why wouldn't you want to take advantage of the framework to read/manipulate a URI?
When designing an API that will be used by others it is important to make them approachable,
as well as reliable
. For this reason the book does mention, you should provide "nice" overloads for common functionality. However, to ensure correctness, you should always implement the underlying code with URIs.
Can you please clarify your wants, or reasons to use only strings?


q: For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?

[A]
```
```
>>> import time
>>> timestamp = "2008-09-26T01:51:42.000Z"
>>> ts = time.strptime(timestamp[:19], "%Y-%m-%dT%H:%M:%S")
>>> time.strftime("%m/%d/%Y", ts)
'09/26/2008'
```
```
See the documentation of the Python
```
time
```
module for more information.


q:
There are some fairly powerful tools like SIMBL or Airfoil/Instant Hijack which use code injection.

As far as I understand this, these tools inject their own code in other programs. This idea sounds dangerous to me as this seems to have the potential to make perfectly stable software fragile and "buggy". Also this seems to pose security risks.

Should these tools be avoided for stability or security reasons?

[A]
I believe it does not just refer to that
kind of code injection
for hacking or cracking a system.
It is also a technique often used in java world, with tools like
AOP
or
IPojo
.
When they make sense, they complement the current code, allowing them:
to function within a given framework (OSGI Declarative Services for IPojo)
to add functionalities (logging services for AOP)
As long as the initial code can run without that code injection, the stability is less an issue.
Stability and security - in the case of those two benevolent usages of code injection - of the injected code should be evaluated in a separate test code.


q:
I have two projects in CPP. One defines a function which I'd like to invoke from the other.
I added a reference to the first project.
I still get the message of "identifier not found".
Assuming that the CPP file in the first project doesn't have a header, how do I make the second project know about its functions?

[A]
If the first project doesn't have a header and you don't want to add one, then use the
```
extern
```
keyword to declare a prototype for the function you want to call in the second project source:
```
```
extern function_in_first_project(int args_go_here);
```
```
Make 100% sure that the function declaration (including argument list and calling convention) matches that of the actual function or you'll run into further problems.
This may not be the only thing you have to do to make your project link, depending on how you've got your projects set up.


q:
Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by overwrting python modules and changing dll versions globaly...)?

Specifically I would like python to use my version of the sqlite3.dll, rather than the version that came with python (which is older and doesn't appear to have the fts3 module).

[A]
If your version of sqlite is in sys.path
before
the systems version it will use that. So you can either put it in the current directory or change the
```
PYTHONPATH
```
environment variable to do that.


q:
I have an Internet Explorer only web application.

I'm exploring what we can do to automate the testing.

Selenium looks like a good tool, but to be able to activate links etc. I need to tell it where they are. The application wasn't built with this kind of testing in mind, so there generally aren't id attributes on the key elements.

No problem, I think, I can use XPath expressions. But finding the correct XPath for, say, a button, is a royal pain if done by inspecting the source of the page.

With Firefox / Firebug, I can select the element then use "Copy XPath" to get the expression.

I have the IE Developer Toolbar and it's frustratingly close. I can click to select the element of interest and display all sorts of information about it. but I can't see any convenient way of determining the XPath for it.

So is there any way of doing this with IE?

[A]
I would use bookmarklets. I have one XPath related, but I don't know if it works in IE. I gotta go but I will test it and give it if it works on IE.
Two bookmarklet sites for Web developers from my bookmarks:
Subsimple's bookmarklets
and
Squarefree's Bookmarklets
. Lot of useful things there...
[EDIT] OK, I am back. The bookmarklet I had was for FF only, and wasn't optimal. I finally rewrote it, although using ideas from the original one. Can't find back where I found it.
Expanded JS:
```
```
function getNode(node)
{
  var nodeExpr = node.tagName;
  if (nodeExpr == null)  // Eg. node = #text
    return null;
  if (node.id != '')
  {
    nodeExpr += "[@id='" + node.id + "']";
    // We don't really need to go back up to //HTML, since IDs are supposed
    // to be unique, so they are a good starting point.
    return "/" + nodeExpr;
  }
// We don't really need this
//~   if (node.className != '')
//~   {
//~     nodeExpr += "[@class='" + node.className + "']";
//~   }
  // Find rank of node among its type in the parent
  var rank = 1;
  var ps = node.previousSibling;
  while (ps != null)
  {
    if (ps.tagName == node.tagName)
    {
      rank++;
    }
    ps = ps.previousSibling;
  }
  if (rank > 1)
  {
    nodeExpr += '[' + rank + ']';
  }
  else
  {
    // First node of its kind at this level. Are there any others?
    var ns = node.nextSibling;
    while (ns != null)
    {
      if (ns.tagName == node.tagName)
      {
        // Yes, mark it as being the first one
        nodeExpr += '[1]';
        break;
      }
      ns = ns.nextSibling;
    }
  }
  return nodeExpr;
}

var currentNode;
// Standard (?)
if (window.getSelection != undefined)
  currentNode = window.getSelection().anchorNode;
// IE (if no selection, that's BODY)
else
  currentNode = document.selection.createRange().parentElement();
if (currentNode == null)
{
  alert("No selection");
  return;
}
var path = [];
// Walk up the Dom
while (currentNode != undefined)
{
  var pe = getNode(currentNode);
  if (pe != null)
  {
    path.push(pe);
    if (pe.indexOf('@id') != -1)
      break;  // Found an ID, no need to go upper, absolute path is OK
  }
  currentNode = currentNode.parentNode;
}
var xpath = "/" + path.reverse().join('/');
alert(xpath);
// Copy to clipboard
// IE
if (window.clipboardData) clipboardData.setData("Text", xpath);
// FF's code to handle clipboard is much more complex
// and might need to change prefs to allow changing the clipboard content.
// I omit it here as it isn't part of the original request.
```
```
You have to select the element and activate the bookmarklet to get its XPath.
Now, the bookmarklet versions (thanks to
Bookmarklet Builder
):
IE
(I had to break it in two parts, because IE doesn't like very long bookmarklets (max size varies depending on IE versions!). You have to activate the first one (function def) then the second one. Tested with IE6.)
```
```
javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}
javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o__o();
```
```
FF
```
```
javascript:function o__o(){function getNode(node){var nodeExpr=node.tagName;if(nodeExpr==null)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps!=null){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns!=null){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}var currentNode=window.getSelection().anchorNode;if(currentNode==null){alert("No selection");return;}var path=[];while(currentNode!=undefined){var pe=getNode(currentNode);if(pe!=null){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');alert(xpath);}o__o();
```
```


q:
I want to keep my website/s in version control (Subversion specifically) and use svn co to update it when there are stable versions to update, but I'm concerned about the security of doing so, as all the .svn folders will be public, and these include all sorts of private data, not least of which is complete source code to my website!

Is there anything I can I do to prevent this?

[A]
This can be achieved server-wide (recommended), on a single virtual-host basis, or even inside
```
.htaccess
```
files if your server is somewhat permissive with what is allowed in them. The specific configuration you need is:
```
```
RewriteEngine On
RewriteRule /\.svn /some-non-existant-404-causing-page

<IfModule autoindex_module>
    IndexIgnore .svn
</IfModule>
```
```
The first section requires
```
mod_rewrite
```
. It forces any requests with "/.svn" in them (ie. any request for the directory, or anything inside the directory) to be
internally
redirected to a non-existant page on your website. This is completely transparent to the end-user and undetectable. It also forces a 404 error, as if your
```
.svn
```
folders just disappeared.
The second section is purely cosmetic, and will hide the
```
.svn
```
folders from the autoindex module if it is activated. This is a good idea too, just to keep curious souls from getting any ideas.


q: Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc.

[A]
I have no idea about exception safely here but I go this way. Let's imagine it's a templated array wrapper. Hope it helps :)
```
```
Array(const Array& rhs)
    {
        mData = NULL;
        mSize = rhs.size();
        *this = rhs;
    }

    Array& operator=(const Array& rhs)
    {
        if(this == &rhs)
        {
            return *this;
        }

        int len = rhs.size();

        delete[] mData;

        mData = new T[len];

        for(int i = 0; i < len; ++i)
        {
            mData[i] = rhs[i];
        }

        mSize = len;

        return *this;
    }
```
```


q:
Is it possible, with Javascript or some other technology to determine which hyperlink a user has clicked on, without changing the hyperlink source code.

For example:
Can you click on a 'tag' button, then click on a hyperlink hosted in a different iframe, and be able to calculate which hyperlink the user clicked on, without changing any of the source code in that iframe?

[A]
you need to put an event on each a link ,
and then you will get all the information about the specific click.
this will work only in the some document,
so if you try to do a test between the link inside an iframe and a link in your page you will not get an event for the iframe link.
in order to attach the event for all link you need to run on all the links in the page ,
the best way to do that is by jQuery selector. or other js framework like YUI
$("a").click(function () {
      alert('')
});
getElementsByTagName("a") - will give you all the links in the page.


q:
I'm trying to assign application pool to one web site in IIS7 using vb script:

' Connect to the WMI WebAdministration namespace.'
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")

' Retrieve the application and display its Web site name and path.'
Set oApp = oWebAdmin.Get("Application.SiteName='Default Web Site',Path='/site'")

' Specify a new application pool name and save it.'
oApp.ApplicationPool = "NewAppPool"
oApp.Put_

the above script is not working!

Is there is a better way to assign application pool to web site under IIS (Using script)?

[A]
Are you setting the app pool on a web site or a virtual directory?
i.e., "Default Web Site/site" (virtual directory) or just "Site" (web site).
If you trying to set it on a web site, not a virtual directory, you need to do something like:
```
```
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")
Set oSite = oWebAdmin.Get("Site.Name='Site'")
oSite.ApplicationDefaults.ApplicationPool = "NewAppPool"
oSite.Put_
```
```


q:
When using C++ namespaces, do you prefer to explicitly name them, like this:

std::cout << "Hello, world!\n";

Or do you prefer using namespace:

using namespace std;
cout << "Hello, world!\n";

And if if you prefer the latter, do you declare your usings at file or function scope?

Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. std and boost) I find it more readable.

[A]
I always use
```
using namespace
```
for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code.
In headers, I never use
```
using namespace
```
to avoid polluting the global namespace of the #including source.


q: How to dynamically bind data to <%Html.Dropdownlist.... in ASP.NET MVC?

[A]
Just pass the correct IEnumerable as the typed model or ViewData. Try something like this (out of my head):
```
```
<%= Html.DropDownList(string.Empty,
    "myDropDownList",
    new SelectList((IEnumerable)ViewData["stuff"],
        "DescriptionProperty",
        "ValueProperty"))
%>
```
```
With that drop down list helper in MVC, you do not really "bind" data to it in the way it is done in the old ASP.NET.


q:
I am trying to connect to simple webparts in my sharepoint team site, i need one of the webparts to filter its information based on what it recieves from another webpart

I am using the query string filter webpart and the a list view webpart but no matter how i connect them always i am getting this error

"Web Part Error:  This page has exceeded its data fetch limit for connected Web Parts. Try disconnecting one or more Web Parts to correct the problem."

What should I do and what am I doing wrong

update:
 i can connect to web parts on some other pgae, but getting this error on the DispForm.aspx page of a certain item , is webpart connections not allowed there ??!!

[A]
There is an issue with creating QueryString filter webparts in sharepoint, when you're not using the Web UI (I'm making an assumption that you aren't).
This fella here has a post about it and how he hacked around the issue.
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/0328f1b2-20cd-427f-887a-e2925bd695e3/
Another option is not using the QueryString filter web part at all, and just passing querystrings to a regular web part.
http://mo.notono.us/2008/04/moss-filter-views-through-url-query.html