q: Hey everyone. I'm trying to make a swing GUI with a button and a label on it.  im using a border layout and the label ( in the north field ) shows up fine, but the button takes up the rest of the frame (it's in the center field).  any idea how to fix this?

[A]
You have to add the button to another panel, and then add that panel to the frame.
It turns out the BorderLayout expands what ever component is in the middle
Your code should look like this now:
Before
```
```
public static void main( String [] args ) {
    JLabel label = new JLabel("Some info");
    JButton button = new JButton("Ok");

    JFrame frame = ...

    frame.add( label, BorderLayout.NORTH );
    frame.add( button , BorderLayout.CENTER );
    ....

}
```
```
Change it to something like this:
```
```
public static void main( String [] args ) {
    JLabel label = new JLabel("Some info");
    JButton button = new JButton("Ok");
    JPanel panel = new JPanel();
     panel.add( button );

    JFrame frame = ...

    frame.add( label, BorderLayout.NORTH );
    frame.add( panel , BorderLayout.CENTER);
    ....

}
```
```
Before/After
Before http://img372.imageshack.us/img372/2860/beforedl1.png
After http://img508.imageshack.us/img508/341/aftergq7.png


q:
I've got a method JSNI that calls a Java method that take a Hasmap as input.
I've tried

handler.@com.mypackage::myMethod(Ljava/util/Hashmap;)(myHashMap);
handler.@com.mypackage::myMethod(Ljava/util/Hashmap<Ljava/lang/String,Ljava/lang/String>;)(myHashMap);

I'm can't seem to define the correct type signature to include the Strings or find if this usage is even allowed.

Since I'm doing this in gwt I though it might be the implementation of hashmap and the alternative approach I've though takes a String[][] array as input

I was hoping for somwthing like

handler.@com.mypackage::myMethod([[Ljava/lang/String;)(myArray);

However, I hit another issue of finding the correct JNSI sntax for the 2nd dimension of the array

A single dimension array ie. [Ljava/lang/String; is fine but I need the 2nd dimension.

Any help/ideas or links to good jnsi doc appreciated.

[A]
Can you post the error that your getting, and also what kind of javascript object your trying to pass as a hashmap. I'm assuming you're getting a compile time error?
Here is a good start for JSNI documentation:
GWT JSNI doc
GWT Blog post on JSNI

s: huggingface

c: devops

d: intermediate


q: I've read a few instances in reading mathematics and computer science that use the equivalence symbol ≡, (basically an '=' with three lines) and it always makes sense to me to read this as if it were equality.  What is the difference between these two concepts?

[A]
In languages that I have seen that differentiate between equality and equivalence, equality usually means the type
and
value are the same while equivalence means that just the values are the same.  For example:
```
```
int i = 3;
double d = 3.0;
```
```
i and d would be have an equivalence relationship since they represent the same value but not equality since they have different types.  Other languages may have different ideas of equivalence (such as whether two variables represent the same object).


q:
So the following rewrite rules always seem to fire.  This has the effect of hiding another domain that I am hosting on the server?

I can't seem to figure out what's wrong and it is time to call in the experts:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^danielhonig.com
RewriteRule ^(.*)$ http://www.danielhonig.com/$1 [R=permanent,L]

RedirectMatch ^/$ http://www.danielhonig.com/gravl
Options None

[A]
Place the rewrite rules inside your
```
<VirtualHost>
```
directive, then it will not affect your other domain.


q:
How do I make gdb print functions of interest as they are called, indented according to how deep in the stack they are?

I want to be able to say something like (made up):

(gdb) trace Foo* Bar* printf

And have gdb print all functions which begin with Foo or Bar, as they are called. Kind of like gnu cflow, except using the debugging symbols and only printing functions which actually get called, not all possible call flows.

Tools which won't help include cachegrind, callgrind and oprofile, which order the results by which functions were called most often. I need the order of calling preserved.

The wildcarding (or equivalent) is essential, as there are a lot of Foo and Bar funcs. Although I would settle for recording absolutely every function. Or, perhaps telling gdb to record all functions in a particular library.

Some GDB wizard must have a script for this common job!

[A]
Did you see litb's excellent anwser to a similar post
here
?
He uses readelf to get interesting symbols, gdb commands to get the trace, and awk to glue all that.
Basically what you have to change is to modify his gdb command script to remove the 1 depth from backtrace to see the stack and filter specific functions, and reformat the output with an awk/python/(...) script to present it as a tree. (I admit I'm too lazy to do it now...)


q:
Is there any good way to unit test destructors?  Like say I have a class like this (contrived) example:

class X
{
private:
    int *x;

public:
    X()
    {
         x = new int;
    }

    ~X()
    {
         delete x;
    }

    int *getX() {return x;}
    const int *getX() const {return x;}
};

Is there any good way to unit test this to make sure x gets deleted without cluttering up my hpp file with #ifdef TESTs or breaking encapsulation?  The main problem that I'm seeing is that it's difficult to tell if x really got deleted, especially because the object is out of scope at the time the destructor is called.

[A]
Some compilers will overwrite deleted memory with a known pattern in debug mode to help detect access to dangling pointers. I know Visual C++ used to use 0xDD, but I haven't used it in a while.
In your test case, you can store a copy of x, let it go out of scope and make sure that *x == 0xDDDDDDDD:
```
```
void testDestructor()
{
    int *my_x;
    {
        X object;
        my_x = object.getX();
    }
    CPPUNIT_ASSERT( *my_x == 0xDDDDDDDD );
}
```
```


q:
I've been doing html, css and javascript for quite a long time, mostly for my very own enjoyment. I would say I know fairly much, I've created many simple games and apps and experiments with javascript. However there is only so much that is possible to do in the browser, for any more "complete" websites I am constantly confronted with my ignorance on server side programming.

So, what do I need. I need to get my head around how to use databases and how to use some server side programming language, I guess. What is the right choice? What should I avoid?

Thanks.

[A]
PHP
and
MySQL
have a pretty low barrier to entry (they're both free and ubiquitous).  I'd start with those, since most hosts provide them for you.  As an added bonus, they work really well together (and PHP isn't very hard to learn coming from a web development background).
Head First SQL
is a great book for learning MySQL.  All of the examples in the book are done on MySQL.  The book even explains where to get it and how to install it.  As for PHP, the
introductory tutorial
at official website is the best place to learn it.
Update:
Head First PHP & MySQL
is now available.  I haven't read this one yet, but other books in the series and by the same author are great for learning new languages from scratch.


q:
I am trying to create a custom accordion for my page to that display my posts. I have it in list format using HTML and I am trying to create an effect when you click each header to expand to show more information.

But I don't want to have say six blocks of code for six of the <li> elements I have on the page.

Is there a way to run it through .each(); perhaps? Instead of creating each section? Try a more dynamic approach.

[A]
Did you take a look at
this tutorial
?
Because, as this
example illustrates
, one does not need multiple conditions to achieve this.
```
```
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
  //hide the all of the element with class msg_body
  $(".msg_body").hide();
  //toggle the componenet with class msg_body
  $(".msg_head").click(function()
  {
    $(this).next(".msg_body").slideToggle(600);
  });
});
</script>
```
```
All the element with the class name “msg_body” is collapsed when the page is loaded.
The “slideToggle()” function of jQuery is used to expand and collapse the “div” with class “msg_body”.
When user clicks on the element with the class “.msg_head”, then div with class “msg_body” next to it, gets toggled with sliding effect, making toggle panel using jQuery.


q: We all know that premature optimization is the root of all evil because it leads to unreadable/unmaintainable code.  Even worse is pessimization, when someone implements an "optimization" because they think it will be faster, but it ends up being slower, as well as being buggy, unmaintainable, etc.  What is the most ridiculous example of this that you've seen?

[A]
Nothing Earth-shattering, I admit, but I've caught people using StringBuffer to concatenate Strings outside of a loop in Java.  It was something simple like turning
```
```
String msg = "Count = " + count + " of " + total + ".";
```
```
into
```
```
StringBuffer sb = new StringBuffer("Count = ");
sb.append(count);
sb.append(" of ");
sb.append(total);
sb.append(".");
String msg = sb.toString();
```
```
It used to be quite common practice to use the technique in a loop, because it was measurably faster.  The thing is, StringBuffer is synchronized, so there's actually extra overhead if you're only concatenating a few Strings.  (Not to mention that the difference is absolutely trivial on this scale.)  Two other points about this practice:
StringBuilder is unsynchronized, so should be preferred over StringBuffer in cases where your code can't be called from multiple threads.
Modern Java compilers will turn readable String concatenation into optimized bytecode for you when it's appropriate anyway.


q:
I have a system that creates an order and that order can be billed to a house account, sent Cash on Delivery (COD), or charged to a credit card.  I've created the following tables:

ORDERS

order_id

billingoption_id

BILLINGOPTIONS

billingoption_id

I'm unsure of how the next table should be built for the billing data.  Should I build a separate table for each type of billing option (ie. COD, Credit Cards, and House Account)?  Then would I have another foreign key column on the Orders table that would refer to a record for the billing data?

[A]
Focus on things.  Actual things.  Try to describe things simply, directly, and in natural language first.
Then, when you ask for design guidance, you can provide definitions.  In some cases, the act of writing definitions will make the design crystalize.
Orders
are things.  What are the attributes of an order?  Customer, Product, Payment/Billing options.
Billing Options
are (almost) things.  You can, apparently, define and identify them.  (I'm not sure I could.  From your question, it appears that you might be able to.  But without a one-sentence summary, I'm not sure what's going on with Billion Options.
What's a "billing data?"  What kind of thing is this?  What attributes (or properties) does it have?
How does a "Billing Data" relate to an Order?  How does it relate to a Billing Option?
Feel free to update the question with definitions for each thing.


q:
I have two tables in a DataSet in .NET. I want to join them on an ID column. Then I want a DataGridView to display two columns from the first table and one column from the second table.

If it makes it easier, the relation between the two tables is one-to-one.

Can it be done?

[A]
Well, is it read only? In .NET 3.5 / C# 3.0 you could probably use a LINQ join and an anonymous output type pretty easily:
```
```
DataTable left = new DataTable
        {
            Columns = { {"PK", typeof(int)}, {"Name", typeof(string)}},
            Rows = {{1,"abc"},{2,"def"}}
        }, right = new DataTable
        {
            Columns = { { "FK", typeof(int) }, { "Value", typeof(decimal) } },
            Rows = { { 1, 123.45M }, { 2, 678.9M } }
        };
        var qry = from x in left.Rows.Cast<DataRow>()
                  join y in right.Rows.Cast<DataRow>()
                  on x.Field<int>("PK") equals y.Field<int>("FK")
                  select new
                  {
                      Name = x.Field<string>("Name"),
                      Value = y.Field<decimal>("Value")
                  };
        var data = qry.ToList();
```
```
You can then bind to "Name" and "Value" of data. Note it is easier with typed data-sets, since you can lose the
```
Cast<>
```
and
```
Field<>
```
rubbish.


q:
I'd like a textbox that allows for certain text within to be "constant" and uneditable while the rest of the text is editable.  For instance, I'd like to define a template like this:

<Name:>[]
<Address:>[] <City>:[]

So that the user could later enter:

<Name:>[Stefan]
<Address:>[Nowhere] <City>:[Alaska]

But not:

<I'm typing here lol:>[Stefan]
<Address:>[Nowhere] <State>:[Alaska]

Ideally, they wouldn't even be able to put their cursor in between the <>, similar to Microsoft Word templates.

Any ideas?  The masked textbox control seems to be along the right path, but isn't multiline and doesn't allow you to enter a variable number of characters in between the braces, for instance.

Thanks in advance.

[A]
I don't know of any ready-made components. But you could try this simple method.
Create a normal multi-line text box control
Create a regex-based template that has
```
(.*)
```
or
```
([a-z]*)
```
or whatever wherever you want the user to add text.
Whenever the text is changed, checked if it still matches the regex. If it does, accept the chagne. If it doesn't, reject the change.
You can then use the same regex to extract your data from the text box.
You could even use a RichTextBox and use the regex to perform formatting.
Update
Here's what I wrote. It seems to work:
```
```
[DefaultProperty("Regex")]
public partial class MaskedEdit : UserControl
{
    private Regex regex = new Regex("");
    private bool myChange = false;

    private string goodText;
    private Font dataFont;

    public MaskedEdit()
    {
        myChange = true;
        InitializeComponent();
        myChange = false;
        dataFont = new Font(Font, FontStyle.Bold);
        goodText = Text;
    }

    [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design", typeof(UITypeEditor)), Localizable(true)]
    [DefaultValue("")]
    public String Regex
    {
        get { return regex.ToString(); }
        set
        {
            if (value != null)
            {
                regex = new Regex(value);
            }
        }
    }

    [EditorBrowsable(EditorBrowsableState.Always)]
    [Browsable(true)]
    [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design", typeof(UITypeEditor)), Localizable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public override string Text
    {
        get { return rtf.Text; }
        set {
            int selSt = rtf.SelectionStart;
            int selLen = rtf.SelectionLength;

            rtf.Text = value;

            rtf.SelectionStart = selSt;
            rtf.SelectionLength = selLen;
        }
    }

    private void rtf_TextChanged(object sender, EventArgs e)
    {
        if (myChange) return;
        Match m = regex.Match(Text);
        if (m.Success)
        {
            goodText = Text;
            Colorize(m);
        }
        else
        {
            myChange = true;
            Text = goodText;
            myChange = false;
            m = regex.Match(Text);
            if (m.Success)
            {
                Colorize(m);
            }
        }
    }

    public IEnumerable<string> Data
    {
        get
        {
            Match m = regex.Match(Text);
            bool first = true;
            foreach (Group g in m.Groups)
            {
                if (first) { first = false; continue; }
                yield return Text.Substring(g.Index, g.Length);
            }
        }
    }

    private void Colorize(Match m)
    {
        int selSt = rtf.SelectionStart;
        int selLen = rtf.SelectionLength;

        rtf.SelectionStart = 0;
        rtf.SelectionLength = rtf.TextLength;
        rtf.SelectionFont = Font;
        bool first = true;
        foreach (Group g in m.Groups)
        {
            if (first) { first = false; continue; }
            rtf.SelectionStart = g.Index;
            rtf.SelectionLength = g.Length;
            rtf.SelectionFont = dataFont;
        }

        rtf.SelectionStart = selSt;
        rtf.SelectionLength = selLen;
    }

    private void MaskedEdit_FontChanged(object sender, EventArgs e)
    {
        dataFont = new Font(Font, FontStyle.Bold);
    }
}
```
```


q:
is there any way to make IE6 understand double classes,
say I have a class MenuButton with a color class and possibly a clicked class;
like :

.LeftContent a.MenuButton {..general rules..}
.LeftContent a.MenuButton.Orange {..sets background-image..}
.LeftContent a.MenuButton.Clicked {...hum ta dum...}

Now, IE6 understands <a class="MenuButton Orange">, but when adding
Clicked, like <a class="MenuButton Orange Clicked">, IE just ignores the
Clicked rule.

Of course, I could rewrite my CSS, and have own rules for .MenuButtonOrange

and such (and it'd probably taken a lot shorter time than asking this question ;-),

but golly, it just so unappealing and Web 0.9...

Cheers!

[A]
IE6 doesn't support multiple class selectors. The reason you see a change with the
```
Orange
```
class is because
```
a.MenuButton.Orange
```
is interpreted by IE6 as
```
a.Orange
```
.
I recommend structuring your markup in such a way that you can work around this:
```
```

One

Two

```
```
By grouping by a more specific ancestor you can create variation with classes scoped by that ancestor (in this example
```
navmenu
```
):
```
```
.leftcontent .navmenu a { /* ... basic styles ... */ }
.leftcontent .navmenu a.orange { /* ... extra orange ... */ }
.leftcontent .navmenu a.clicked { /* ... bold text ... */ }
```
```
It's not as good as multiple classes, but I've used it to work around the lack of support in IE.


q:
I have a class Agent with a property Id

Given a collection of Agents I need to check if any of them have duplicate Ids.

I am currently doing this with a hash table but am trying to get Linq-ified, what's a good way of doing this?

[A]
```
```
foreach(var agent in Agents) {
    if(Agents.Count(a => a.ID == agent.ID) > 1)
        Console.WriteLine("Found: {0}", agent.ID);
}
```
```


q:
i m trying to design a mmo game using python...

I have evaluated stackless and since it is not the general python and it is a fork, i dont want to use it

I am trying to chose between
pysage
candygram
dramatis
and
parley

any one try any of these libraries?

Thanks a lot for your responses

[A]
I would go for
pysage
.
It has the highest level of abstraction and a lightweight messaging API which will give you lots of flexibility.   I would imagine when designing an MMO you will want as much flexibility as possible.
It also takes a page from Erlang's Actor model which is really solid.
That's great you are trying to build an MMO via python!  It has great OpenGL bindings when you want to add graphics which is great!
Hope that helps.


q:
I know how to do this using for loops.  Is it possible to do something like this using LINQ or lambdas?

int[] a = { 10, 20, 30 };
int[] b = { 2, 4, 10 };
int[] c = a * b; //resulting array should be { 20, 80, 300 }

[A]
You can do something like this:
```
```
int[] a = {10, 20, 30};
int[] b = {2, 4, 10};

if (a.Length == b.Length)
{
  int[] result = (from i in Enumerable.Range(0, a.Length)
          let operation = a[i]*b[i]
        select operation).ToArray();
}
```
```
But I recommend you if you will work with matrices and more advanced mathematical topics to get a good Math library, like
NMath
or search for a
Matrix class
implementation, there are many out there...


q:
I have a simple function in which an array is declared with size
depending on the parameter which is int.

    void f(int n){
        char a[n];
    };

    int main() {
        return 0;
    }

This piece of code compiles fine on GNU C++, but not on MSVC 2005.

I get the following compilation errors:

    .\main.cpp(4) : error C2057: expected constant expression
    .\main.cpp(4) : error C2466: cannot allocate an array of constant size 0
    .\main.cpp(4) : error C2133: 'a' : unknown size

What can I do to correct this?

(I'm interested in making this work with MSVC,without using new/delete)

[A]
Your method of allocating from the stack is a g++ extension. To do the equivalent under MSVC, you need to use _alloca:
```
```
char *a = (char *)_alloca(n);
```
```


q:
Getting started with jquery and having trouble getting hello world type example going for asp.net mvc. I get a runtime error "object expected" when trying to load a page with this script.

A. Where should script tags be placed in a master page?
B. What might I be doing wrong? There are definitely "a" elements in my page?

<script src="../Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>

            <script src="../Scripts/jquery.corner.js" type="text/javascript"></script>

            <script type="text/javascript">
                $(document).ready(function() {
                    $("a").click(function(event) {
                        alert("Thanks for visiting!");
                    });
                });
            </script>

[A]
Hmmm ...
To answer your first question:  They should be put in the
```
<head>
```
element.
Also, usually I use the
'bind' method
when sinking events in the DOM (like it looks like you're trying to do).
So, code would look like:
```
```
$(document).ready(function()
{
    //  Bind each link to a handler:
    $("a").bind('click dblclick', function(event)
    {
         alert('click');
    })
});
```
```
Also, a few design tips (since you're working with something close to my heart (ASP.NET MVC with jQuery):
Add an extra 'ContentPlaceHolder' at the bottom of your master page's
```
<head>
```
element.  This will allow you to have page specific javascript run in it's proper location:  in the 'head' section of the page, and it'll allow you to make page-specific javascript includes.
It'll look something like this:
```
```
<asp:ContentPlaceHolder ID="HeadContent" runat="server" />
</head>
```
```
Why is this useful?
I'll tell you:  That jQuery rounded corners plugin you're using might only be used on a few pages -- why include it on every page?


q:
How would I go about implementation the queries required for pagination?

Basically, when page 1 is requested, get the first 5 entries. For page 2, get the next 5 and so on.

I plan to use this via the couchdb-python module, but that shouldn't make any difference to the implementation.

[A]
This is what I have came up with so far - to get the ids of all posts, then retrieve the actual items for the first x number of IDs..
It's not terribly efficient, but more so than retrieving all the posts, then throwing most of the away. That said, to my surprise, it seemed to run quite quickly - I ran the
```
posthelper.page()
```
method 100 times and it took about 0.5 seconds.
I didn't want to post this in the actual question, so it wouldn't influence the answers as much - here's the code:
```
```
allPostsUuid = """
function(doc) {
if(doc.type == 'post'){
    emit(doc._id, null);
}
}
"""

class PostsHelper:
    def __init__(self):
        server = Server(config.dbhost)
        db = server[config.dbname]
        return db

    def _getPostByUuid(self, uuid):
        return self.db.get(uuid)

    def page(self, number = 1):
        number -= 1 # start at zero offset
        start = number * config.perPage
        end = start + config.perPage

        allUuids = [
            x.key for x in self.db.query(allPostsUuid)
        ]
        ret = [
            self._getPostByUuid(x) for x in allUuids[start : end]
        ]

        if len(ret) == 0:
            raise Error404("Invalid page (%s results)" % (len(allUuids)))
        else:
            return ret
```
```


q:
I am given an integer (lets call it x) and I need to generate an array of arrays, where each subarray is a list of elements which are one of a given set of integers, and the sum of all of the elements of each subarray is x. The array of arrays needs to contain all possible distinct subarrays of this form.

For example, if x is 3 and the list of possible elements is {1, 2}, I'm looking to generate {{1, 2}, {2, 1}}.

What would be the best way to go about doing this (in pseudocode or Java)? Is this 2D array the best way to store this type of data? I couldn't think of anything better, but I'm guessing there is something out there.

[A]
Since you don't know the size of the "subarrays," I suggest you use one of the collections from Java such as
```
ArrayList<E>
```
.


q:
I want to use part of the output of a command run from the command line in another xterm, or as part of a different command.  For instance:

> grep error error.log
error: can't find file ~/<some very long path>/thisfile

and I want to do this:

>ls ~/<some very long path>/

I know two ways to do this:

1. copy ~/<some very long path>/ with the mouse.

2. use some combination of head/tail/awk/sed/perl/cut/etc... to extract only what I need from the output and then use that inside backticks.

Is there any way to copy text without using the mouse?  The example that comes to mind is visual mode inside VIM, but I don't know how to do that inside the xterm.

[A]
You can use GNU screen's copy and paste commands.
Quick tutorial:
Open screen:
```
screen
```
(or
```
screen myprog my args here
```
)
Run your program, producing output you want copied
Enter copy mode:
Control
+
a
+
[
Move your cursor to the start point
Hit
Enter
Move your cursor to the end point
Hit
Enter
Paste:
Control
+
a
+
]
Screen is much more powerful than that (I use it to tab several virtual terminals without the need for a special terminal emulator, and also so that I don't loose my sessions when X crashes or something).  To get out of screen, simply end your shell session, or type
Ctrl
+
a
,
Ctrl
+
\
.


q:
I already have a deploy.rb that can deploy my app on my production server.

My app contains a custom rake task (a .rake file in the lib/tasks directory).

I'd like to create a cap task that will remotely run that rake task.

[A]
```
```
run("cd #{deploy_to}/current && /usr/bin/env rake `<task_name>` RAILS_ENV=production")
```
```
Found it with Google --
http://ananelson.com/said/on/2007/12/30/remote-rake-tasks-with-capistrano/
The
```
RAILS_ENV=production
```
was a gotcha -- I didn't think of it at first and couldn't figure out why the task wasn't doing anything.


q:
When working with PDFs, I've run across the MIME types application/pdf and application/x-pdf among others.

Is there a difference between these two types, and if so what is it? Is one preferred over the other?

I'm working on a web app which must deliver huge amounts of PDFs and I want to do it the correct way, if there is one.

[A]
The standard Media Type (formerly known as MIME types) is
```
application/pdf
```
. The assignment is defined in
RFC 3778, The application/pdf Media Type
, referenced from the
Media Types registry
.
Media Types are controlled by a standards body, The
Internet Assigned Numbers Authority
(IANA). This is the same organization that manages the root name servers and the IP address space.
The use of
```
x-pdf
```
predates the standardization of the Media Type for PDF. Media Types in the
```
x-
```
namespace are considered experimental, just as those in the
```
vnd.
```
namespace are considered vendor-specific.
```
x-pdf
```
might be used for compatibility with old software.


q: I want to know what's the difference between string and stream in c++, and what's stringstream?

[A] Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.


q: Are there any good and easy to use options for sending secure email?  Why is this not commonplace?

[A]
SMTP has extensions which support encryption which are supported by most vendors. The receiving server is required to have a certificate (not the sender). So configuring your outbound mail relay to insist upon encrypted connections and verify certificates will usually do it.
If you want to encrypt it as far as the end user, S/MIME or GPG are the two main options. S/MIME support is built into mail clients MS Outlook, Thunderbird and some others.
However, there is still a significant problem of certificate management, which is a royal pain in the arse most of the time.


q:
How do I draw procedural graphics in a Vista Sidebar gadget?

I have a gadget that collects data over time and I want to draw animating graphs.  My current approach is to draw the graph with VML that I update from JScript on a timer tick.  Is this the best way?  Can I return bitmap bits from a DLL function as the srouce to an <IMG>?  Embed bitmap bits into the HTML itself (and again update it via JScript)?  I'd love to hear some ideas.

Thanks!

[A]
The way I currently do it is with Javascript and Adobe Flash Player communicating via the ExternalInterface in ActionScript. It seamlessly integrates local Javascript instances with an instance of a Flash Player and you can communicate just about anything between the two. You can use the fantastic drawing API in ActionScript and really get some power into you hands for charting or just embed some tools off the net.
But then, if the sandbox permits it, generating data by targeting DLLs would be great! I don't have anything functional at hand to test it, so I leave it to other contributors.


q:
I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.

Related:

How can I download all emails with attachments from Gmail?

[A]
You will have to enable IMAP access to your GMail account (Settings → Forwarding and POP/IMAP), and then use
```
imaplib.IMAP4_SSL
```
to access it.
Use the raw text of every message as an argument to
```
email.message_from_string
```
in order to process any attachments.


q:
On Vista, I got a problem with the application crash handler. Basically, if something unexpected occurs which cannot be captured by SEH, I get this pop-up window with "The application stopped working", blablabla, "Close program/Debug program" -- that is, after I disable the error reporting using the system control panel. With error reporting enabled, you would get a task dialog with search for solution online, close, debug.

This is not so funny if it happens in automated tools, and I wonder whether there is a way to get rid of it totally, read, if my app crashes, it just crashes to the command line or disappears but does not bring up a dialog.

[A]
Use
```
```
SetErrorMode(SetErrorMode(0)|SEM_NOGPFAULTERRORBOX);
```
```
But I would suggest to install an exceptions handler which creates a dump so you can verify what happened. For example
crashrpt
(or
here
).
See also
http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx


q: If we implement a stack using arrays in C++, what is the best way to reduce the chance of an overflow condition?  Also while keeping in mind the time-space trade off?

[A]
Just resize your array when you get close to the "overflow condition", i.e. when the next element wouldn't fit any longer. Or use a
```
std::vector
```
, which you can resize easily.
Not sure, but you are aware of the
```
std::stack
```
class, which implements a stack which resizes automatically in C++?
[EDIT] If you don't want to resize, but fail properly, throwing an exception is the best thing you can do. For example, you could define a
```
StackOverflowException
```
and throw it if there is no space left, so clients can react.


q:
I have a variable of type Hashmap<String,Integer>.

In this, the Integer value might have to go some manipulation depending upon the value of a flag variable. I did it like this...

Hashmapvariable.put( somestring,
    if (flag_variable) {
     //manipulation code goes here
     new Integer(manipulated value);
    } else {
     new Integer(non-manipulated value);
    }
);

But I get an error:

Syntax error on token(s), misplaced
  constructs.

at the Hashmapvariable.put call.

I also get another error

Syntax error on token ")", delete this
  token.

at the final ");" line. But I can't delete the ")" - its the closing parentheses for the put method call.

I don't get this. What mistake am I doing?

[A]
You cannot place a statement in the method call.
However, one option could be to make an method that returns a
```
Integer
```
such as:
```
```
private Integer getIntegerDependingOnFlag(boolean flag)
{
    if (flag)
        return new Integer(MANIPULATED_VALUE);
    else
        return new Integer(NON-MANIPULATED_VALUE);
}
```
```
Then, you can make a call like this:
```
```
hashmap.put(someString, getIntegerDependingOnFlag(flag));
```
```


q: Pretty much as the question asks. Answers preferably in pseudo code and referenced. The correct answer should value speed over simplicity.

[A]
See
Intersections of Rays, Segments, Planes and Triangles in 3D
. You can find ways to triangulate polygons.
If you really need ray/polygon intersection, it's on 16.9 of
Real-Time Rendering
(13.8 for 2nd ed).
We first compute the intersection
  between the ray and [the plane of the
  ploygon]
```
pie_p
```
, which is easily done
  by replacing
```
x
```
by the ray.
```
```
n_p DOT (o + td) + d_p = 0 <=> t = (-d_p - n_p DOT o) / (n_p DOT d)
```
```
If the denominator
```
|n_p DOT d| < epsilon
```
, where
```
epsilon
```
is very small
  number, then the ray is considered
  parallel to the polygon plane and no
  intersection occurs. Otherwise, the
  intersection point,
```
p
```
, of the ray and
  the polygon plane is computed:
```
p = o + td
```
. Thereafter, the problem of
  deciding whether
```
p
```
is inside the
  polygon is reduced from three to two
  dimentions...
See the book for more details.


q:
I would like to know if you guys have any suggestions about debug levels when writing an application.

I thought about 4 levels:

0 : No Debug

1 : All inputs and outputs

2 : "I am here" notification from significant functions with main parameters

3 : All variables verbose

[A]
Whatever you choose, there will be something you wanted to see which is just into the next level...
I don't think there is a general answer to this question, because it's so dependent on what the application is doing.  Much like the oily pages in the Haynes manual (UK readers will know what I mean), I tend to find that you end up with heavy logging in the areas which have traditionally been troublesome, and almost none in the area which is going to cause you trouble
next
.


q:
I have a project where I've been using TDD and unit tests as "software vises". In essence I translate the requirements into tests that verify that the code conforms to the requirements. I rarely have to go back and edit the unit tests, which rather is the point: only the "real" code should be modified. At the moment, there are 900 unit tests.

Now some requirements have been changed by the gold-owners. Since the former requirements are so thorougly encoded in the existing unit tests, it seems that changing them to conform to the new requirements would be inviting disaster. How do you adapt your unit test suites to handle this kind of change?

[A]
Per definition the
unit-tests
don't replicate the requirements for the application. They describe the requirements for a module. That's a difference, the module can be reused even in an application with different requirements or isn't used at all. So the changing requirements don't affect real unit-tests (except that you have to write new for new modules or abandon old tests for modules no longer needed for the changed requirements).
On the other hand:
acceptance-tests
deal with the requirements on application-level. So I think you talk about acceptance-tests.
I would add the new requirements as new acceptance-test. But for the old ones you have to look through them, how they are invalidated by the changed requirements.


q:
I have the following (shortened query):

SELECT
    `Statistics`.`StatisticID`,
    COUNT(DISTINCT `Flags`.`FlagType`) AS `FlagCount`
FROM `Statistics`
LEFT JOIN `Flags` ON `Statistics`.`StatisticID` = `Flags`.`StatisticID`
WHERE `FlagCount` = 0
GROUP BY `Statistics`.`StatisticID`
ORDER BY `SubmittedTime` DESC
LIMIT 0, 10

Now, neither FlagCount = 0 or COUNT(Flags.FlagType) work in the WHERE clause. I thought about using a SET but I'm not sure how I'd add that to the query. Any ideas?

Thanks,

[A]
Use
```
HAVING COUNT(DISTINCT Flags.FlagType) = 0
```
.


q:
I recently read a question on here about static and dynamic linking, which reminded me of some questions I've had about it. From that post, I can see what the technical difference is (including object file contents directly instead of merely pointing to it), but I'd like to know a bit more about the pros/cons of doing so.

A while ago, a friend of mine who's been programming several years was lamenting that C# isn't statically linked and saying that that was the feature he desired most for a future version. Unfortunately I'm a novice and don't really understand this statement.

Thanks for any enlightenment!

[A]
A statically executable contains all the objects that it needs so no external DLL will be called when executed. The advantaje is that is is portable accross a lot of platforms no matter what version of DLLs have been installed on that system. The BIG disadvantage is that you are probable wasting disk space since you are including in your executable code that is already present in system/external DLLs. Moreover I think, but I'm not very sure, that DLLs are loaded in main memory only once, no matter how many executables are using them, but if you link statically the library objects inside your executable you load the same code twice (one for the DLL used by the rest of the programs and one for your executable). On the other hand this could be an advantage instead a disatvadvantage, since the executable contains only the objects of the external libraries that it needs, not the whole library. A DLL is loaded in memory as a whole when an application needs it.
Static linking is ideal to compile small apps that you want to carry from one system to another as a small tool. I.e. it was really useful for me to have a statically compiled version of tcpdump when it was not included in every Linux distro. It was bound to work on every Linux no matter what version of Kernel, glibc or other system libraries had. Perhaps it has not so much sense in Windows world since the platforms are much more homogeneus. If you compile for Windows XP / NET vX.X it will work across a lot of computers. If you compile something for Debian X.X it will surely not work on older/newer Debians or other distros such as Redhat.
This
thread
can also solve your questions.


q:
After attending a talk on Oslo/M I am struggling a bit to see the advantages of using it over existing methods and in what situation it would be useful.

I know its quite new and not all details have been released etc but can some one give me some advantages and when you might use it?

Thanks,

Alex

[A]
This questions seems to have the answer you're looking for:
What is model driven development good for?
Erik Wynne has a nice blog-post on this topic:
Oslo == 42
He also links to a post on MSDN, that contains some interesting thoughts:
Why do we need Oslo?


q:
I'm not good at programming and my trying to open one of my spreadsheet documents.
Below in the basic login im using, I then request a list all my spreadsheet, which is returned in $feed.

And now I'm worried I'm not on the right track with opening a document so I can read and write cells.

<?php

require_once '../library/Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
$user="username";
$pass="user password";

// login
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);

$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
$feed = $spreadsheetService->getSpreadsheetFeed();

print_r ($feed);
?>

[A]
You're on the right track.  Are you using the information found
http://framework.zend.com/manual/en/zend.gdata.spreadsheets.html
?
Your code is getting a spreadsheet feed which lists all the available spreadsheets, which is an important step.  You'll want to follow the link above to get a list-based feed or a cell-based feed.
The documentation is pretty good I would recommend just reading through it all(yes it's long).


q:
How do I split a list of arbitrary length into equal sized chunks?

See How to iterate over a list in chunks if the data result will be used directly for a loop, and does not need to be stored.

For the same question with a string input, see Split string every nth character?. The same techniques generally apply, though there are some variations.

[A]
Here's a generator that yields evenly-sized chunks:
```
```
def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]
```
```
```
```
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [70, 71, 72, 73, 74]]
```
```
For Python 2, using
```
xrange
```
instead of
```
range
```
:
```
```
def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in xrange(0, len(lst), n):
        yield lst[i:i + n]
```
```
Below is a list comprehension one-liner. The method above is preferable, though, since using named functions makes code easier to understand. For Python 3:
```
```
[lst[i:i + n] for i in range(0, len(lst), n)]
```
```
For Python 2:
```
```
[lst[i:i + n] for i in xrange(0, len(lst), n)]
```
```


q:
I have made a small project in Oracle, by using the oracle forms builder - how do I create an installer (setup.exe) for my project (one that would setup the application on MS Windows?)

Please... help me, and thanks a lot

[A]
What version of oracle forms are you using?
In my last job we used Forms v4.5 (Developer 2000) - and for that version (which is quite old now) the Forms Runtime software had to be installed on the client computers.
Then, when the user double clicked on an .FMX file the Forms runtime (F45run32.exe) would load and run the form.
Which is a long way of saying that for v4.5 you couldn't create a stand alone install.  (That may have changed with future versions)


q:
I have a client with a LAMP website serving mostly video. He is currently on one server with all components. He is having some scaling problems. What are some of the techniques that can be used to help.

I used separating out the DB to another server with a GB Ethernet between it and the webserver. Maybe adding more web servers with some load balancing and additional MySQL servers with replication?

Would like some medium, large, super large examples on how to scale if possible.

The video is actually coming as jpg images. Similiar to this website:

http://www.webcams.travel/webcam/1170170095

And to add some details. I figure the max visitors per hour would be 1000, and I think would be lucky to have that. Maybe closer to 1000 a day.

[A]
You need to work out exactly what the problem is - there is no general solution.
You need to build a performance test environment with real hardware and something which can simulate lots of clients. This may be quite expensive.
If the problem is the database (which it may be) then the solution is often to split it into several databases each holding part of the data.
But I wouldn't imagine that any sane person would store video on MySQL - if he is doing that, then a refactoring may be in order.


q:
Need help narrowing the scope of this Regex to not return records if there is an alphanumeric character preceding the first "I"

"I([ ]{1,2})([a-zA-Z]|\d){2,13}"

Want to capture I APF From this string, but not the I ARPT.

I APF                     'NAPLES MUNI ARPT.            ' 42894 JEB 29785584

Thanks!

[A]
```
\b
```
represents a word boundary in regular expressions, so the following should work (assuming you're happy with the rest of the regex):
```
```
("\bI([ ]{1,2})([a-zA-Z]|\d){2,13}")
```
```
A word boundary is defined as the zero-width space between a word character and a non-word character. Depending on your regex engine a word character is likely to be an alphanumeric character or an underscore, so using \b will match I ALF in
```
-I ALF
```
but not in
```
_I ALF
```


q:
I'm adding an existing site to SVN.

The files already exist on the webserver, and now identical copies (- configuration files) exist in the repository.

I want to convert the webserver directory into an SVN working copy, but when I run:

svn checkout http://path.to/svn/repo/httpdocs .

I get the error:

svn: Failed to add file '': object of the same name already exists

How do I tell SVN to just overwrite those files whose contents are the same?

[A]
Pull from the repository to a new directory, then rename the old one to
```
old_crufty
```
, and the new one to
```
my_real_webserver_directory
```
, and you're good to go.
If your intention is that every single file is in SVN, then this is a good way to test your theory. If your intention is that some files are not in SVN, then use Brian's copy/paste technique.


q:
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?

Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module>
    from django.core import management
ImportError: No module named django.core

[A]
You must make sure that django is in your PYTHONPATH.
To test, just do a
```
import django
```
from a python shell. There should be no output:
```
```
ActivePython 2.5.1.1 (ActiveState Software Inc.) based on
Python 2.5.1 (r251:54863, May  1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>>
```
```
If you installed django via
```
setuptools
```
(
```
easy_install
```
, or with the
```
setup.py
```
included with django), then check in your
```
site-packages
```
if the
```
.pth
```
file (
```
easy-install.pth
```
,
```
django.pth
```
, ...) point to the correct folder.
HIH.


q:
I have some XSD-s that define my objects hierarchy. for example math.xsd, base.xsd
while math.xsd is depends on base.xsd. I need to generate classes from those xsd-s.

I've already read about those two tools:
CodeXS tool  and  XSD.exe.
the problem with the xsd.exe is that I didn't succeed generating classes from two xsd-s that depends on each other. is there anyone who knows the right parameters for using the xsd.exe for such case?

moreover, I am looking for:
 - more tools
 - comparison between those tools
 - xsd to object using .net 3.5
Thanks.

[A]
Microsoft: XSDObjectGen - Sample Code Generator 1.4.2.1
Stackoverflow: XSDObjectGen.exe vs XSD.exe


q:
I am trying to get pylons to debug in Eclipse under Ubuntu.
Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog.

(this is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my system)

Can anyone help?

[A]
I've managed to fix this now.
In
```
Window>Preferences>Pydev>Interpreter-Python
```
remove the python interpreter and reload it (select
```
New
```
) after installing pylons.
In the Terminal cd into the projects directory. Then type
```
sudo python setup.py develop
```
Not sure what this does, but it does the trick (if any one wants to fill me in, please do)
In
```
Run>Open Debug Dialog
```
enter the location of paster in
```
Main Module
```
. For me this is
```
/usr/bin/paster
```
. Then in the
```
Arguments
```
tab in
```
Program arguments
```
enter
```
serve /locationOfYourProject/development.ini
```
All set to go.
It took a lot of search for me to find out that it does not work if the arguments includes
```
--reload
```


q:
My Aim: Sending an email (e.g. support request, error report) out of a C# Windows forms application. I know how do do this technically but here is the catch:

In order to authenticate myself on the mail server (e.g. gmx, yahoo, own website) I need to store the login details inside the application (which runs on the client system). If someone extracts it or sniffs the network traffic he will have access to my email account. Maybe the second threat could be eliminated using a secure connection. However, it is still possible to get the password out of the application regardless if it is obfuscated or not.

So is there are 'secure' concept enabling me to send e-mail messages out of my program, which runs on the client pc without the need to store a password in accessible form and not requirering a special web service?

[A]
I had such a requirement in the past which we solved by using a web service to post messages.
If for example a user wanted to submit a bug report it would be turned into a web service call to our web server and it would then be forwarded accordingly.
To answer your question:
There is no way you can hide you mail server. If your program can send emails, so can the user with another program. (the same goes for a web service.) What you can do is use an open smtp server (smtp relay) but that is just asking for trouble.


q:
I am creating a Firefox Extension...what would be the javascript to open a URL in the current tab from a menuitem?

e.g. in my overlay.xul file i have the following line:

<menuitem label="Visit homepage" oncommand="window.location='http://www.somepage.com'"/>

but in firefox, when i click on the menu item, it opens the URL but it screws up the entire layout of the browser.

What's the correct way to do this?

[A]
After browsing around, I found that I had to replace the above code with this:
```
```
<menuitem label="Visit homepage" oncommand="content.wrappedJSObject.location='http://www.somepage.com'"/>
```
```


q: I am not a mathematician. I enjoy a good math puzzle, but I admit my weaknesses whole heartedly. That said, I've always had an interest in Neural Networks, and while I understand them enough to implement them from scratch, I hit a wall when I need to understand any concept that I can only find mathematic proofs for. Where is the programmer's guide to neural networks, using code instead of formula to explain the practical reasonings?

[A]
Unfortunately, I don't know if there's a good single "programmers source" that will give you all of the concepts.  I liked
Neural and Adaptive Systems: Fundamentals through Simulations
.
The best way to have a "programmer's understanding" of neural networks is not so much by examining the code, but in the problem and the correct results.  So, if you don't want to look at math, I recommend you look at a given problem.  For example, consider the XOR problem as an example of why you need non-linear activation functions, look at the number of variables and their possible values for understanding why a neural network needs to be of a certain size and toplogy to be effective, and split your data into train/test regimes and do studies to see why overfitting is dangerous.  Examine the code with the data.
I also recommend not getting too hung up, but reading further.  Certain practices in feed-forward networks become more clear once you see their generalization in recurrent and constructive neural networks.  I also recommend going wider:  Bayesian networks, fuzzy cognitive maps, SOM, Boltzman machines, simulated annealing, and reinforcement learning all have intuitions.
Does this go towards answering your question?


q:
I have to give a general note to some huge Java project for which I have but little visibility and I was wondering if there were any guidelines for determining:

what number of classes per package can be considered right, to low, or to high (this project has 3.89 classes per package, which seems a bit too small for me),

number of methods per class? (this project has 6.54 methods per class...

number of lines per method? (this project has about 7 lines per method (seems pretty good to me, maybe a bit low))

I should note that this question is only dealing with volumetry. I have a bunch of reports from quality tools (checkstyle, jdepend, cpd, pmd, ncss) that give me more vision about code redundancy, classes usage, bugs, etc.

[A]
I think stats like that are pretty useless, how does knowing the lines per method show whether its any use to the project or not; i think you should be looking more along the lines of:
Do your packages encompass like
classes?
Do your classes work as an
entity on their own?
Do the methods
within the classes function
correctly and efficiently?
Surely other than memory usage, it doesn't matter whether the method is large or not? the other thing to look for in very protracted methods is whether the stack trace is going to be bigger than adding that functionality to a parent method.  I'd be wary of measuring a projects success based on the lines of code.


q:
I thought that if a c pointer pointing to a char array was incremented then it would point to the next element in that array. But when I tried this I found that I had to increment it twice. Trying the increment using sizeof(char) I found that adding the size of a char was too much so it had to be divided by two.

#include <stdio.h>

int main(int argc, char * argv[]){
   char *pi;
   int i;
   pi = argv[1];
   printf("%d args.\n",argc-1);
   printf("input: ");
   for(i=0;i<argc-1;i++){
      printf("%c, ",*pi);
      /*The line below increments pi by 1 char worth of bytes */
      //pi+=sizeof(pi)/2;
      /* An alternative to the above line is putting pi++ twice - why? */
      pi++;
      pi++;
   }
   printf("\n");
   return 0;
}

Am I doing something wrong? or am I misunderstanding the method of incrementing pointers?

[A]
If you have a pointer
```
ptr
```
of type
```
T*
```
and you add
```
N
```
, then the pointer will be advanced by
```
N * sizeof (*ptr)
```
or equivalent
```
N * sizeof (T)
```
bytes. You simply forgot to dereference
```
pi
```
. So what you got with
```
sizeof (pi)
```
was the sizeof of the
```
char*
```
, but not the sizeof of a
```
char
```
. Your line was equivalent to
```
pi+=sizeof(char*)/2;
```
Pointers on your platform are 4 bytes big. Thus in effect you did
```
pi+=2;
```
. Write
```
pi+=2
```
if you want to increment 2 times. Note that
```
char
```
has an sizeof of 1 by definition. You don't need to do
```
sizeof (char)
```
, it is always 1.


q:
if __name__=='__main__':
    parser = OptionParser()
    parser.add_option("-i", "--input_file",
                    dest="input_filename",
                      help="Read input from FILE", metavar="FILE")

    (options, args) = parser.parse_args()
    print options

result is

$ python convert.py -i video_*
{'input_filename': 'video_1.wmv'}

there are video_[1-6].wmv in the current folder.
Question is why video_* become video_1.wmv. What i'm doing wrong?

[A]
Python has nothing to do with this -- it's the shell.
Call
```
```
$ python convert.py -i 'video_*'
```
```
and it will pass in that wildcard.
The other six values were passed in as args, not attached to the
```
-i
```
, exactly as if you'd run
```
python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6
```
, and the
```
-i
```
only attaches to the immediate next parameter.
That said, your best bet might to be just read your input filenames from
```
args
```
, rather than using
```
options.input
```
.


q:
First off, how do I know if my html file is running on localhost in Xampp?
Is there a tutorial on how to manage files/directories and get that all working under htdocs?
Is there a good tutorial on how to setup includes?

I want to use "includes" in Xampp with my html.
Can I use both html includes AND php includes?
Do I have to put shtml?
Can I use shtml, html, htm, and php includes?
Do they have to be in an includes directory that is a subdirectory right under htdocs?
Can I reference includes in some other subdirectory?
My site will have over 100 pages, and I am trying to do "experiments" with different versions until I am happy. So, I have subdirectories for the various drop down menus. Unfortunately, I don't seem to be able to get this working in xampp.
Having trouble getting my javascript menus from Vista Buttons to show up, now that I moved my main directory for my site to the htdocs directory.

[A]
To answer your first question, can you access
http://localhost/
? If so, then xampp is running correctly and there is nothing more that you need to do.
EDIT:
If you want to ensure that things are working correctly, place foo.html under /xampp/htdocs and then access it in a browser at
http://localhost/foo.html
. If you can't get this page then xampp still isn't running correctly.
In answer to your second question, all Includes whether in the HTML or within PHP are server side. If you have xampp installed correctly, then you can begin working in PHP immediately and can use the include functions within PHP (please note that even if a page only contains HTML, if you're using PHP it must still have a .php extension).
If you would rather use SSI in your .html pages, then
this link
might provide some help on how to set up and debug SSI in xampp.
Additionally, if you are not already doing so I would recommend that you work in Firefox with Firebug installed. Firebug will handle most of your JavaScript debugging needs.
As a final note, if you've moved directories and the like, the first thing I would check would be the src attributes on your script tags.


q:
I'm trying to create an algorithm in C# which produces the following output strings:

AAAA
AAAB
AAAC
...and so on...
ZZZX
ZZZY
ZZZZ

What is the best way to accomplish this?

public static IEnumerable<string> GetWords()
{
    //Perform algorithm
    yield return word;
}

[A]
well, if the length is a constant 4, then this would handle it:
```
```
public static IEnumerable<String> GetWords()
{
    for (Char c1 = 'A'; c1 <= 'Z'; c1++)
    {
        for (Char c2 = 'A'; c2 <= 'Z'; c2++)
        {
            for (Char c3 = 'A'; c3 <= 'Z'; c3++)
            {
                for (Char c4 = 'A'; c4 <= 'Z'; c4++)
                {
                    yield return "" + c1 + c2 + c3 + c4;
                }
            }
        }
    }
}
```
```
if the length is a parameter, this recursive solution would handle it:
```
```
public static IEnumerable<String> GetWords(Int32 length)
{
    if (length <= 0)
        yield break;

    for (Char c = 'A'; c <= 'Z'; c++)
    {
        if (length > 1)
        {
            foreach (String restWord in GetWords(length - 1))
                yield return c + restWord;
        }
        else
            yield return "" + c;
    }
}
```
```


q:
I have a winforms application that is doing the following:

on each query:

Db connect

Db query

Db disconnect

as we are trying to avoid having to keep the db connection open.  This suffers from performance as we have to connect / disconnect everytime.

What is the idealized model here to have the fastest performance but without having open connection for too long.  Is there a best practice here?

[A]
The most efficient means is connection pooling, and
ADO.NET does this automatically for you
as long as you make sure to close your connections. Just wrap your
```
SqlConnection
```
objects into
```
using
```
statements, and you won't have to worry about it.


q: Does anyone have any experience with the triangulated GPS used by the non-3G iPhone?  How does it compare with 3G positioning?  Does the iPhone 3G use triangulation in the event that there is no GPS signal available? Is there anyway to determine the accuracy of the non 3G coordinates? Thanks.

[A]
I have done a lot of mobile software with a bunch of different devices including 3G iphones and 3G blackberry's and here is what I have found.
The blackberry and iPhone GPS is really good when you have clear line of sight and at least 9 satellites present.  In some dense residential or urban areas you might only get 5-6 satellites which can take a while to converge.
If you do not have a signal, GSM phones like the iPhone will try and find your position using cell tower signal strength but it is NOT as accurate as GPS... not by a long shot.
I have heard, though this has not been confirmed that the iPhone also uses some server side machine learning when it can't find a GPS lock meaning that it takes the average all of the cell towers, plus the average of all the users who have used GPS in your area to try and find your best position.  This is sometimes called AGPS or assisted GPS where the GPS information and cell tower strength are used together.
Also, the only thing I can think of for finding the accuracy of the non 3G coordinates would be to programmaticly switch providers in your code, or simply go into preferences and turn off 3G and write an application that does some tests.
The Pragmatic Programmers have a great
iPhone SDK book
that just added a chapter on using the Location API, so that might be a great place to start.
Hope this helps.


q: What is the best way to abstract the episerver infrastructure for easier testing?

[A]
Perhaps this post will help:
EPiServer CMS 5 R2 and unit testing


q: We recently had a code review . One of my classes was used so that I could return/pass more than one type of data from/to methods . The only methods that the class had were getters/setters . One of the team's members ( whose opinion I respect ) said that having a class like that is bad practice ( and not very OOP ) . Why is that ?

[A]
In general, you'll want to isolate the knowledge needed to operate upon a class into the class itself.  If you have a class like this, either it is used in multiple places, and thus can take on some of the functionality in both of those places, or it is in a single place, and should be an inner class.  If it is used in multiple ways, but in completely different ways, such that there is no shared functionality, having it be a single class is misleading, indicating a shared functionality where there is none.
However, there are often specific reasons for where these general rules may or may not apply, so it depends on what your class was supposed to represent.


q: I want to play around a bit with FLASH for app development. I'm looking for a good IDE for that.  Someone suggested Flash Develop.

[A]
Major reason to use FlexBuilder: has a real debugger you can set breakpoints and single step and watch/edit variables.
Unless FlashDevelop has .. developed .. don't think it got any of that yet.
BTW - if you are a student/teacher FlexBuilder can be had for
free


q:
What is the Python equivalent of the following code in Ruby?

def loop
  cont=nil
  for i in 1..4
    puts i
    callcc {|continuation| cont=continuation} if i==2
  end
  return cont
end

> c=loop
1
2
3
4
> c.call
3
4

Reference: Secrets of lightweight development success, Part 9: Continuations-based frameworks

[A]
take a look at the
yield
statement to make generators.
I don't speak any ruby, but it seems like you're looking for this:
```
```
def loop():
    for i in xrange(1,5):
        print i
        if i == 2:
            yield

for i in loop():
    print "pass"
```
```
Edit: I realize this is basically a specialization of real continuations, but it should be sufficient for most purposes. Use
```
yield
```
to return the continuation and the
```
.next()
```
message on the generator (returned by just calling
```
loop()
```
) to reenter.


q:
I am building an Entity Framework model for a subset of the Pubs database from microsoft. I am only interested and publishers and books, not publishers and employees, but there is a foreign key constraint between the publishers and emoloyees tables. When I remove the employees entity from my model, the model won't validate because of the foreign key constraint.

How do I create a model for a subset of a database when that subset links to other tabes with foreign key constraints?

Because this is for a demo, I deleted the offending tables and constraints from the database, but this won't work in production.

[A]
Not sure what I'm missing here, but your
```
filesize
```
being -1 seems to be your problem.  The
API docs
clearly state that
```
expectedContentLength
```
may not be available and that
```
NSURLResponseUnknownLength
```
is returned in these cases.
```
NSURLResponseUnknownLength
```
is defined as:
```
```
#define NSURLResponseUnknownLength ((long long)-1)
```
```
In these cases, you cannot get an accurate progress.  You'll need to handle this and display an indeterminate progress meter of some sort.


q:
I have a very simple model. I want to add a send email routine to on of the methods for the model:

$this->Email->delivery = 'smtp';
$this->Email->template = 'default';
$this->Email->sendAs = 'text';
$this->Email->from    = 'email';
$this->Email->to      = 'email';
$this->Email->subject = 'Error';

I've tried putting

App::import('Component', 'Email');

at the top, to no avail. The error I get is:

Fatal error: Call to undefined method stdClass::send() in E:\xampp\htdocs8080\app\models\debug.php on line 23

Any ideas?

I'm running CakePHP 1.2

[A]
Components are supposed to be used in controllers, not models.
In your controller use
```
```
var $components = array('Email');
```
```
There is no need to use App::import();
Without knowing your app and reasons for wanting to use it in a model, I might suggest you re-think your system architecture and move this logic to your controller.
If you definitely need it in your mode, your code included something like...
```
```
$this->Email->delivery = ...
```
```
Have you put created a new instance of the component and set it to a property of your model called Email? (No idea if this will work mind.)
The error you are getting is because you are calling the send() method on a the stdClass object i.e. not an instance of the EmailComponent.


q:
My scenario should be simple... the type I want to convert FROM is ALWAYS 'string'. What I want to convert to... could be many things - ints, DateTimes, ... strings, etc.

This would be easy:

string valueToConvertFrom = "123";

int blah = Convert.ToInt32(valueToConvertFrom);

However... I don't know (until runtime) that the value I need to convert to is an 'Int' (or whatever). I have tried this:

string valueToConvertFrom = "123";

Type convertToType = typeof(int);

object blah = Convert.ChangeType(valueToConvertFrom, convertToType);

But that gives me the following error: "Object must implement IConvertible."

I don't want to have to do a switch statement and call "Convert.ToBlah" based on the type name... any suggestions?

[A]
String class implements IConvertible, this code simply SHOULD work. Which version of .NET are you aiming?
```
```
object o = Convert.ChangeType( str, convertToType );
```
```
Besides, most of the types you mentioned implement Parse method, so your best shot might be something like this.
```
```
Type convertToType = ...;
MethodInfo mi = convertToType.GetMethod("Parse", BindingFlags.Static);
object blah;
if(mi != null)
{
    blah = mi.Invoke(null, new object[]{valueToConvertFrom});
}
else
{
    // the type doesn't implement the Parse method, handle it another way :/
}
```
```


q:
I put together a sample scenario of my issue and I hope its enough for someone to point me in the right direction.

I have two tables

Products

Product Meta

I need a result set of the following

[A]
```
```
Select a.ProductId
  ,a.Name
  ,(Select c.MetaValue
    From [Product Meta] c
    Where c.ProductId = a.ProductId
    And c.MetaKey = 'A') As 'A'
   ,(Select d.MetaValue
    From [Product Meta] d
    Where d.ProductId = a.ProductId
    And d.MetaKey = 'B') As 'B'
   ,(Select e.MetaValue
      From [Product Meta] e
      Where e.ProductId = a.ProductId
      And e.MetaKey = 'C') As 'C'
From Products a
Order By a.ProductId Asc
```
```


q:
Situation: you've got a .swf embedded in an html page, and when you click on something in the .swf, it needs to popup a chromeless window. Normally this would be fairly easy - but consider Safari, which completely disables all 'window.open' functionality while its popup-blocker is enabled (it makes an exception if the function is triggered onclick, but it doesn't count clicks in flash). How can you create something which gracefully degrades (provides an alternate and roughly equivalent experience) for browsers that won't execute window.open?

(note: this is AS3, and Safari 3 for PC or Mac we're talking about - but more broadly, any browser that doesn't support or refuses to allow the javascript window.open function.)

[A]
If your SWF is loaded using
```
wmode='opaque'
```
or
```
wmode='transparent'
```
, then you could have the SWF output JavaScript code that would create an empty
```
<div>
```
that's positioned over the SWF area.  That
```
<div>
```
could then handle the
```
onclick
```
event and create the popup window rather than the Flash code.


q:
On a more abstract level then a previous question, in my experience there are 3 ways to call a javascript function on an html page from an embedded .swf using AS3: ExternalInterface, fscommand, and navigateToURL.

Let's compare and contrast these methods (and maybe others I haven't listed) and talk about the pros and cons of each - right now, ExternalInterface seems like the way to go in terms of flexibility, but is it right for all situations? Are there concrete benefits in terms of execution speed or anything like that? I'm curious - what do we think?

[A] ExternalInferface was created to make communication between JS and Flash easier, so it doens't really make sense to use anything else. Common practice is to check if its available first by evaluating the value of the ExternalInterface.available property before making a call to some JS. This property tells you if the SWF in which you want to call some JS from is inside a container that offers an external interface. In otherwords, if using ExternalInterface will work. If its not available then just use flash.net.sendToUrl. Never use fscommand() as it uses VBScript and can cause conflicts with other VBScript on a page. Additionally, you can only send one argument string with fscommand and have to split it on the JS side.


q: Can someone explain in simple terms the "signals and slots" pattern?

[A]
Signals and slots are a way of decoupling a sender (the signal) and zero or more receivers (the slots). Let's say you a system which has events that you want to make available to any other part of the system interested in those events. Rather than hard-wiring the code that generates event to the code that wants to know about those events, you would use a signals and slots pattern.
When the sender signals an event (usually by calling the function associated with that event/signal) all the receivers for that event are automatically called. This allows you to connect and disconnect receivers as necessary during the lifetime of the program.
Since this question was tagged C++, here is a link to the
Boost.Signals
library which has a much more thorough explanation.


q: Unit tests are cheaper to write and maintain, but they don't cover all scenarios. What is the right balance between them?

[A]
On the app I am working on at the moment, there are probably 10:1 unit to functional tests. The unit test work simply things like retrieving entities from DB, error handling tests for db/network connectivity etc. These things run quick - minutes or less and are run by devs daily.
functional tests while fewer tend to be kitchen sink approach - can user complete order etc. tend to cover the business domain end of things are run by business analsyts and operations - sadly for us, often by hand. These things take weeks to run and usually to finalize a release cycle.


q:
Given a list of sets:

S_1 : [ 1, 2, 3, 4 ]

S_2 : [ 3, 4, 5, 6, 7 ]

S_3 : [ 8, 9, 10, 11 ]

S_4 : [ 1, 8, 12, 13 ]

S_5 : [ 6, 7, 14, 15, 16, 17 ]

What the most efficient way to merge all sets that share at least 2 elements?  I suppose this is similar to a connected components problem.  So the result would be:

[ 1, 2, 3, 4, 5, 6, 7, 14, 15, 16, 17] (S_1 UNION S_2 UNION S_5)

[ 8, 9, 10, 11 ]

[ 1, 8, 12, 13 ] (S_4 shares 1 with S_1, and 8 with S_3, but not merged because they only share one element in each)

The naive implementation is O(N^2), where N is the number of sets, which is unworkable for us.  This would need to be efficient for millions of sets.

[A]
If you can order the elements in the set, you can look into using
Mergesort
on the sets. The only modification needed is to check for duplicates during the merge phase. If one is found, just discard the duplicate. Since mergesort is O(n*log(n)), this will offer imrpoved speed when compared to the naive O(n^2) algorithm.
However, to really be effective, you should maintain a sorted set and keep it sorted, so that  you can skip the sort phase and go straight to the merge phase.


q: As the title says really. Does the virtual keyword cause a performance hit?

[A]
First off, in Actionscript you don't need to explicitly mark a method to be overridden as virtual as you do in C#, the compiler will do this for you. This is why the keyword doesn't show up in any docs because it is irrelevant from the developers perspective.
To answer your question though, which is whether overriding a method makes it slower, the answer is no as long as your class is sealed, meaning you don't use the 'dynamic' keyword when defining the class.
The reason why is that when constructing a sealed class, you're going to have explicit markers to every method for that object, when overriding a method you get a marker directly to the new function, the class does not have to look it up at runtime like in a dynamic class.


q: Is there a good Silverlight Design Architecture?

[A]
There is
Prism
it was originally designed for WPF but there is now a Silverlight release.


q:
Is there a way to use these operators to input and output binary data? The reason I want to do this is that it makes the code readable.
Ex: infile >> filedecrypter >> metadataparser >> audiodecoder >> effects >> soundplayer;

[A]
Indeed that can be done, if the library or your code provides the overloads for
```
operator<<
```
and
```
operator>>
```
for it to work. Simple example on how one could do it:
```
```
class transformer {
    public:
    virtual std::iostream& transform(std::iostream&) = 0;
};

class noise : public transformer {
    public:
    virtual std::iostream& transform(std::iostream&) {
         /* extract, change and put into again */
    }
};

class echo : public transformer {
    public:
    virtual std::iostream& transform(std::iostream&) {
         /* extract, change and put into again */
    }
};

std::iostream& operator>>(std::iostream& io, transformer& ts) {
    return ts.transform(io);
}

int main() {
    std::stringstream data;
    std::ifstream file("sound.wav");

    noise n; echo e;

    data << file.rdbuf();
    data >> n >> e;
    /* pipelined data now ready to be played back */
}
```
```
The problem with using a pure
```
std::istream
```
is that you would read, but then you wouldn't have a way to put the transformed data back for the next step in the pipeline. Thus i'm using
```
std::iostream
```
here. This approach doesn't seem to be efficient, as every operator>> call would extract the whole data, and put into again.
To have a more performant way to stream this would be to create an
```
expression template
```
. This means, while
```
operator>>
```
is called, you don't do the transforming yet, but you return expression types that will record the chain of operations within its type:
```
```
typedef transform< echo< noise< istream > > > pipeline;
std::ifstream file("file.wav");
pipeline pipe(file);
int byte = pipe.get();
```
```
would be an example of such a type. The pipelines' structure is decoded into the type itself. Therefore, no virtual functions are needed anymore in the pipeline. It's not constructed on-demand, but using typedef here, to show the principle. Programming such a system is not easy. So you probably should look into existing systems, like Boost.Iostreams (see below). To give you an idea how it would look like, here is an example i just coded up for you :) :
```
```
#include <iostream>

template<typename T>
struct transformer {
    int get() {
        return static_cast<T*>(this)->read();
    }
};

struct echot {
    template<typename Chain>
    struct chain : transformer< chain<Chain> > {
        Chain c;

        int read() {
            return c.get() + 1;
        }

        chain(Chain const& c):c(c) { }
    };
} echo;

struct noiset {
    template<typename Chain>
    struct chain : transformer< chain<Chain> > {
        Chain c;

        int read() {
            return c.get() * 2;
        }

        chain(Chain c):c(c) { }
    };
} noise;

template<typename T>
typename T::template chain<std::istream&> operator>>(std::istream& is, T) {
    return typename T::template chain<std::istream&>(is);
}

template<typename T, typename U>
typename U::template chain<T> operator>>(T t, U u) {
    return typename U::template chain<T>(t);
}

int main() {
    std::cout << (std::cin >> echo >> noise).get() << std::endl;
}
```
```
Entering 0 yields the ASCII code 48 here, which is added 1, and multiplied by 2, yielding a value of 98, which is also finally output. I think you agree this is not some code a starter would want to write. So maybe look into boost.
Boost has an sophisticated iostreams library, which can do many things. I'm sure you would find something fitting to this.
Boost.Iostreams


q:
I am trying to fade in a
 on mouseover and fade out on mouseout:

  $("p.follow").mouseover(function(){
        $(this).fadeTo("slow", 1.00);
})
$("p.follow").mouseout(function(){
        $(this).fadeTo("fast", 0.50);
})

If you go to ryancoughlin.com and on the right side, if you go over it you will see what I mean, it is almost as if it is stuck and keeps fading in.

Any ideas?

[A]
Try this:
```
```
$("p.follow").hover(function()
   {
      $(this).stop().fadeTo("slow", 1.00);
   },
   function()
   {
      $(this).stop().fadeTo("fast", 0.50);
   });
```
```
Two key differences: I use the jQuery
```
hover
```
event to associate mouseover and mouseout event handlers such that child elements won't result in confusing behavior, and i use the
```
stop()
```
function to prevent animations from overlapping and canceling each other out.


q:
I have configured a simple LAMP stack on Debian and I am experiencing some problems with the Apache web server.

Each 3-4 hours the web server is entering a deadlock and all the requests that hit the database block. The server is creating a new child for each request. The number of processes increases very quickly. After a few seconds Monit notices something is wrong and restarts the Apache server.

I suspect this problem is generated by the way PHP handles database connection pooling because the server is still able to answer static content requests. Have you experienced this kind of behavior? What should I try to do?

Update: Problem solved. It seems it's a bad idea to use APC for opcode caching and user data. I am now using Memcache for storing user data and APC only for code. I still get some segmentation faults from time to time but the server is most of the time stable.

[A]
Why don't you have a look at the logs?
```
/var/log/apache2/*
```
is a good place to start. What is requested just before the server dies? From there on, you can probably deduce what's going wrong. As php scripts are terminated after 30 seconds by default, the mistake needs to be quite massive to cause something like that.


q:
I would like to do something like the following but can't seem to get the syntax for the Do method quite right.

var sqr = new _mocks.CreateRenderer<ShapeRenderer>();
Expect.Call(sqr.CanRender(null)).IgnoreArguments().Do(x =>x.GetType() == typeof(Square)).Repeat.Any();

So basically, I would like to set up the sqr.CanRender() method to return true if the input is of type Square and false otherwise.

[A]
Are you looking for this?
```
```
Expect.Call(sqr.CanRender(null)).IgnoreArguments()
    .Do((Func<Shape, bool>) delegate(Agent x){return x.GetType() == typeof(Square);})
    .Repeat.Any();
```
```
EDIT: The answer was correct in spirit bu the original syntax did not quite work.


q:
I've been frustrated by this for the entire weekend, plus a day or two, so any help would be significantly appreciated.

I'm trying to write a program that can programmatically go into a SharePoint 2007 doc library, open a file, change the contents of the file, then put the file back. I've gotten all but the last part of this down. The reason Office Open XML is involved is that that's how I'm opening the document and modifying it - through the Office Open XML SDK. My question is: How do I get it from the document back into the library?

The problem as I see it is that there's no save function on the WordprocessingDocument object itself. This prevents me from saving it into the SPFile's SaveBinary function.

[A]
Yesterday I saw a webcast with Andrew Connell where he opened a doc from a doc library, added a watermark and saved the file again. It sure sounds like you should have a look at that webcast:
https://msevents.microsoft.com/CUI/WebCastRegistrationConfirmation.aspx?culture=en-US&RegistrationID=1299758384&Validate=false
btw I found that all 10 of the web casts in that serie were very good.


q:
This fails with 'X.m is not a function'...

var Y = function () {
    this.m = function () {
        alert('this is m');
    };
};

var X = new function () { };

X.prototype = new Y();
X.m();

It would certainly work if I skipped the new keyword in the X definition and then instantiated X before calling m() on it. Why can't I do it this way?

[A]
No you cannot set the prototype and have that change effect previously existing instances.  You can however, modify the prototype object to have the desired effect.  But not the way you have attempted.  This is because your instance X is an object, not a class.  (This is because you used the "new" operator before the definition of your class.)
Simple test:
```
```
var X = new function () { };
alert(X.prototype);  // displays "undefined" because X is an
                     // object not a class
```
```
So when you set the "prototype" attribute on X you are not storing the template object in a class, you are merely creating a new attribute on object X with the name "prototype" so, if you did this:
```
```
var Y = function () {
    this.m = function () {
        alert('this is m');
    };
};

var X = new function () { };
X.prototype = new  Y();
X.prototype.m();  // displays "this is m"
```
```
Then you get the output you expected previously.
Even though you created X as an instance of an anonymous class, you can still access that class through the "constructor" property.  Once you have that reference, you can then modify the prototype object.  Like this:
```
```
X.constructor.prototype.m = new Y().m;
X.m();  // displays "this is m"
```
```
You should note however, that this will not work:
```
```
X.constructor.prototype = new Y();
X.m();  // fails
```
```
Because changing the entire prototype object only effects instances created in the future.


q:
There are several people about (myself being one of them) who have been developing RIA for a while now using Flex and AJAX.  However Silverlight is now on the scene and worth picking up.

Question is, as someone who has never looked at .NET before, should I just dive in Silverlight and try and make up the bits I'm missing, or start somewhere else in .NET in order to get a foundation first?

[A]
I firmly believe in learning foundations first. I would start off by writing console apps - get the hang of collections, IO, the language itself (whether that's VB or C#, or even something else).
It's probably worth learning a bit of "normal" WPF after that, on the grounds that it may well be easier to experiment that way than with Silverlight itself. (I can't say I've written any Silverlight myself yet.)
If you dive straight into Silverlight, when you run into problems you won't know whether it's because you're unfamiliar with the language, the core platform, or Silverlight itself. You'll take a while longer to get going with my suggestion above, but once you've got going it'll be a much smoother ride, in my view.


q:
How do I expose the ActualWidth property of one of the components of my user control to users?

I have found plenty of examples of how to expose a normal property by creating a new dependency property and binding, but none on how to expose a read-only property like ActualWidth.

[A]
```
ActualWidth
```
is a public readonly property (coming from
```
FrameworkElement
```
) and is exposed by default. What is the case that you are trying to achieve?


q:
From the .net 4.0 previews I have read until now there has been lots of talk on how the next .net version will handle and use cpus with multiple cores. We will have additions like plinq that will help us make use of multiple cores. My question is why should I have to bother my mind with handling multiple cores when all I want is to make my application run faster. Why can't there be a kind of virtual cpu layer that exposes all cores as 1 core to my application?

Edit:
I would like to rephrase my question to avoid misunderstanding,
Could there be made a software that would expose a virtual thread to my application that would be 10 times faster because underlaying it was using 10 cores. I do not want to have different threads doing things in paralell, I just want my one thread running faster. I guess this is not a big problem today but soon we'll have 80 core processors to play with and then I would feel a bit shorthanded only using 1 of them.

[A]
You are misunderstanding the point of multiple cores in the first place.
With more than one core, you can perform two or more different operations in parallel (at the same time).  This is called threading.
This can't be done automatically because the "normal" programs you write are linear.  You can't easily convert one series of instructions into several series of instructions without taking into consideration side effects.
GPU's (specialized CPU's on graphics cards), for example, may contain hundreds of "cores" (stream processors) which operate in parallel to render the pixels on your screen.  With only one processor, you'd have to render pixel-by-pixel on a super-fast processor to achieve the same effect.
The reason CPU manufacturers moved to more than one core was because manufacturing a single core at higher speeds was getting more difficult and expensive, and that a single core would suck up more power and produce more heat than two cores at half the speed (basically; this isn't true in all cases).


q:
In my specific case, I have two kinds of "messages" that I need to retrive and paginate.

Let's omit the details, and just say that the first kind is in a model called Msg1 and the other is called Msg2

The fields of these two models are completely different, the only fields that are common to the two models are "date" and "title" (and of course, id).

I can get Msg1.objects.all() and Msg2.objects.all() but can I combine these two queries into one query, sort it by date, and paginate it?

I need to preserve the lazy nature of the query.

The trivial solution is to list(query) both queries and combine them in a python list. but this is inefficient for obvious reasons.

I looked through the django references on models and dp-api, but it doesn't seem that there is a way to combine queries of different models/tables into one.

[A]
"combine these two queries into one query, sort it by date, and paginate it?"
That's the SQL union.   Leave the Django ORM and use a SQL union.  It's not brilliantly fast because SQL has to create a temporary result, which it sorts.
Create the temporary result, which can be sorted.  Since a list has a sort method, you'll have to merge the two results into one list.
Write a merge algorithm that accepts two query sets, paginating the results.
Edit.  Here's a merge algorithm.
```
```
def merge( qs1, qs2 ):
    iqs1= iter(qs1)
    iqs2= iter(qs2)
    k1= iqs1.next()
    k2= iqs2.next()
    k1_data, k2_data = True, True
    while k1_data or k2_data:
        if not k2_data:
            yield k1
            try:
                k1= iqs1.next()
            except StopIteration:
                k1_data= False
        elif not k1_data:
            yield k2
            try:
                k2= iqs2.next()
            except StopIteration:
                k2_data= False
        elif k1.key <= k2.key:
            yield k1
            try:
                k1= iqs1.next()
            except StopIteration:
                k1_data= False
        elif k2.key < k1.key: # or define __cmp__.
            yield k2
            try:
                k2= iqs2.next()
            except StopIteration:
                k2_data= False
        else:
            raise Exception( "Wow..." )
```
```
You can fold in pagination:
```
```
def paginate( qs1, qs2, start=0, size=20 ):
    count= 0
    for row in merge( qs1, qs2 ):
        if start <= count < start+size:
            yield row
        count += 1
        if count == start+size:
            break
```
```


q:
Why whenever I compile and run the following code in Visual Studio 2008:

double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2;
Console::WriteLine(whole_number);

I get an incorrect value of 26 while the answer is 25.

However when I use static casts on the doubles, I get the right answer which is 25.

How can the wrong output be explained?

[A]
It's absolutely right.
```
```
double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2; // int whole_number = 26.0;
Console::WriteLine(whole_number);
```
```
What would you expect instead? The compiler first evaluates the right side, and then implicitly converts to the int. Thus,
```
26.0
```
becomes
```
26
```
When you cast before you add, then you are going to add
```
10
```
and
```
15
```
, which results in
```
25
```
:)


q:
I've worked on a number of CMS systems using the .NET platform (the CMS management system is in ASP.NET, and the site which renders the content is both ASP.NET and PHP).

I've traditionally stored the generated content in classes that serialize to XML, which is stored in MSSQL 2005/2008 in a varchar(max) field.  This has made it convenient structuarally for different consumers of the content to work with, and it can be bound to classes (for re-opening the CMS record and editing it, or for the consuming website).

However, I've been wondering what type of storage mechanism is popular with other CMS shops, and if anyone likes or has serious issue with the approach I'm most familiar with.

Good, bad, ugly?  What would you do?

[A]
I personally treat the data as any other data that would be stored in the system, for example I have a module built for DNN that stores collection of text data, I have the following collection of columns in a table for it.
EntryId
UpdatedBy
UpdatedDate
CreatedBy
CreatedDate
SortOrder
Content (NTEXT)
Hidden (Bit)
I find that this keeps the data easy to find, and it is easy to manipulate regardless of the caller.


q: I am working on a project using rails 2.1.1.  With the new release of 2.2.2 I want to migrate to the new version.  Is there anything I need to change to migrate my 2.1.1 controllers, views, and models?

[A]
There aren't any major changes in the way things are done.  Here is the list of
deprecations
Of course the best way to quickly discover changes is to have a good test suite in place.  If you don't have that, I suggest dropping 2.2 into vendor/rails and clicking around the site by hand.


q:
We have a large MS Access project that requires GUI functionality that is difficult / impossible to do in the VBA / access forms environment.

Over time, we wish to re-write / migrate to a managed C# environment with WPF as the presentation layer.

The only practical way for us to do this is over a longer period of time - converting some of the VBA forms first (that would give the best productivity benefit), and then over the course of 12-24 months convert the entire system.

What do you believe is the best approach. Can MS Access host the WPF forms as we convert them?

[A]
What if you look into Visual Studio Tools for Office (VSTO) ?
You can write managed .NET addins for Office in C#, that will integrate as ribbons with office.
Now, the problem is that Access add-ins are not supported in VSTO AFAIK.
But, take a look
here
, it seems to be not that impossible.
So, if you happen to be lucky, you could
Write a C# ribbon for Access which would have all the advanced GUI you need
Write services in C# that could be accessed from Access to encapsulate important business logic for instance, so that you could gradually move not only GUI, but build proper domain object model in C#.
If you decide to try it out, let me know how it turned out :)
Good luck anyway.
PS something else which maybe is helpful?
Access 2007 Developer Extensions (ADE)


q: I know FireBug with YSlow has to be by far my personal favourite. I also use IE developer toolbar when forced to test pages in IE. Is there any other jewels out there hiding??

[A]
I use the
Web Developer Extension
for Firefox, has tons of useful options.
(source:
mozilla.org
)
Also like the
Live HTTP Headers
Extension.


q: What's the coolest mashup you've built?  What APIs did you use?  How was the mashup better than the sum of its parts?

[A] Although probably not a true mashup, I created a script hat would read the Apple Movie Trailer RSS feed, and then visit the links in the feed to download the HTML of the pages linked to in the RSS feed. From there, it would download the container .mov files, and parse out the actual URL to the movie you can actually download.  SO while all the information was coming from Apple, the script would download multiple things, from different parts of their site, to piece together a final RSS feed that would contain links to .mov files that actually contained the movie trailer.


q:
I have code like this to move the player in my game left, right, up, and down:

keysSetRepeat(20, 5);

while (lives) {
    scanKeys();

    if (keysDownRepeat() & (KEY_LEFT | KEY_RIGHT | KEY_UP | KEY_DOWN)) {
        u8 new_x = x;
        u8 new_y = y;

        if (keysDownRepeat() & KEY_LEFT) {
            new_x--;
        } else if (keysDownRepeat() & KEY_RIGHT) {
            new_x++;
        } else if (keysDownRepeat() & KEY_DOWN) {
            new_y++;
        } else if (keysDownRepeat() & KEY_UP) {
            new_y--;
        }

        // ...
    }

    // ...

    swiWaitForVBlank();
}

Why are the keys not being detected? If I replace keysDownRepeat() with keysDown() it works (without the repeat rate, of course). The documentation is no help here.

[A]
I had to find the libnds source code to figure this out. Look at the implementation of keysDownRepeat():
```
```
uint32 keysDownRepeat(void) {
    uint32 tmp = keysrepeat;

    keysrepeat = 0;

    return tmp;
}
```
```
It actually returns the keys then resets them back to 0. This wasn't documented. I solved this by storing the result of
```
keysDownRepeat()
```
into a variable and using the variable to check the keys:
```
```
keysSetRepeat(20, 5);

while (lives) {
    scanKeys();
    u32 keys_down_repeat = keysDownRepeat();

    if (keys_down_repeat & (KEY_LEFT | KEY_RIGHT | KEY_UP | KEY_DOWN)) {
        u8 new_x = x;
        u8 new_y = y;

        if (keys_down_repeat & KEY_LEFT) {
            new_x--;
        } else if (keys_down_repeat & KEY_RIGHT) {
            new_x++;
        } else if (keys_down_repeat & KEY_DOWN) {
            new_y++;
        } else if (keys_down_repeat & KEY_UP) {
            new_y--;
        }

        // ...
    }

    // ...

    swiWaitForVBlank();
}
```
```


q:
Is it possible to migrate a VB.NET Winform solution to a 3.5 WPF solution.  If so, any suggestions how to do it?

Thanks in advance!
JFV

[A]
Microsoft is doing everything for us so that we have to throw away everything we've written 2 years ago.
According to Josh Smith,
Is there a way to convert Winforms application to a WPF application?
No.  Those two UI platforms are very different and there is no app which converts a WinForms app to a WPF app.  Of course, this will not prevent you from reusing any business/DAL/logging/Ioc/etc libraries you use in WinForms.
However, you might want to check out
this
, quite basic but functional WinForms->XAML converter, written by Rob Relyea from WPF & Xaml Language Team.
According to him, "We (Microsoft) haven't built a real converter because we think most people will not just move over controls, but often will rethink their application as they move it.  We'd love feedback..."
Also, you might want to check out
Guidance for migrating an app from Windows Forms to WPF
, also by Rob Relyea.


q:
I know I can configure command line arguments in the Run configuration but I want to run a java file multiple times with different command line arguments. It's a pain to change the Run Configuration every time.

Is there a way I can make Eclipse prompt me for command line arguments every time I run the program?

[A]
Add
```
string_prompt
```
as a
```
Program Argument
```
in the
```
Run
```
configuration.
```
```
${string_prompt}
```
```
There are also a
```
file_prompt
```
and a
```
folder_prompt
```
if you want specifically files\folders.
These are available through the
```
Variables
```
button on the
```
(x)= Arguments
```
tab of the Run Configuration dialog.