q:
In Google groups and some other web sites, there is a 5-star rating component which is pretty neat, such as in this url:
http://groups.google.com/group/Google-Picasa-Data-API/browse_thread/thread/b5a346e6429a70a7?hl=en

I am wondering whether there is an existing 5-star rating component in the iPhone environment. Or if there is not, if anyone has clue where to start?

Thanks

[A]
I don't know of any free/available components off the top of my head, but if nobody offers one up and/or you can't find one you like, it should be fairly trivial to roll your own. In the simplest terms, you would only have to:
Create/Find a star icon - one outline (unselected), one filled
Create a UIButton and set the icons for the selected/unselected states
Create a container view that held your x stars and when one was selected, the container could set the selected state on any button to the left of the touched button.
Shouldn't take long at all to build...


q: how good to use 3 point technique for risk assessment.

[A]
Is this what you mean?
http://www.aof.mod.uk/aofcontent/tactical/risk/content/tpe.htm?zoom_highlight=simulation
If so, it looks like that site's a pretty good overview and analysis.

s: huggingface

c: devops

d: intermediate


q: I'm pretty green with web services and WCF, and I'm using Windows integrated authentication - how do I get the username on the server-side interface? I believe that I'm supposed to implement a custom Behavior, or perhaps something with WCF Sessions? Any clues would be super-handy.

[A]
have you tried
```
WindowsIdentity.GetCurrent();
```
?


q: Trying to create a random string, x characters in length using 0-9 and a-z/A-Z and can't seem to find a good example, any ideas?

[A]
I forgot all my VB6 (thank God) but in pseudocode it's pretty easy:
```
all_chars = an array of all the valid chars
    seed random number generator
    for i = 1 to x do
        random_index = get a random number between 1 and length of all_chars
        'I remember how to concat and comment in VB6 :-)
        string = string & all_chars[random_index]
    end for

    done!
```
So it's just a matter of finding out how to create an array and fill it with characters, how to get the length of the array and how to get a
random number
between the first and last indexes of said array.
Well, all that and looping of course.


q:
I'm a simple soul with simple needs, and I'm trying to configure a form.  I detest forms.

It needs to have JavaScript to transfer the data, it needs to send an e-mail with the data to an e-mail address, and it needs to redirect visitors to a pdf.  CGI has always been confusing to me, and I don't know much JavaScript.

I've already done the html, but the post action and the JavaScript is killing me.  It's been 4 hours of searching.  Stick a fork in me.  I'm done.

[A]
OK, first thing's first, we need to clarify you're wording.  JavaScript and Java are two significantly different languages.
In order to send mail, you need to use whichever language you're using in conjunction with an SMTP server, which is what would have to be what actually sends the e-mail, not JavaScript which is client-side.
An example of using JavaScript to post to an SMTP server can be found here (though I wouldn't recommend this method as ActiveX is IE exclusive):
http://www.ostrosoft.com/smtp_component/smtp_javascript.asp
Ultimately with JavaScript, the best method you'd use would just be posting to a non-SMTP server that then sends the data to the SMTP server.
If you're actually using Java, there's an optional library you can add called JavaMail to make it much easier to send mail, though again, you need to communicate with an SMTP server.
An example of JavaMail can be found here:
http://www.javapractices.com/topic/TopicAction.do?Id=144


q: What are the coolest new features that you guys are looking for, or that you've heard are releasing in c# 4.0.

[A]
the dynamic keyword looks like it can bridge the gap between dynamic languages like IronRuby or IronPython quite nicely, which will probably help its adoption in the Microsoft monoculture... that excites me.
While I'm intrigued by it, I'm also worried that it will be overused, like Generics and LINQ, SQLCLR, etc :)


q:
I read through the Wikipedia article Existential types. I gathered that they're called existential types because of the existential operator (∃). I'm not sure what the point of it is, though. What's the difference between

T = ∃X { X a; int f(X); }

and

T = ∀x { X a; int f(X); }

?

[A]
As I understand it's a math way to describe interfaces/abstract class.
As for T = ∃X { X a; int f(X); }
For C# it would translate to a generic abstract type:
```
```
abstract class MyType<T>{
    private T a;

    public abstract int f(T x);
}
```
```
"Existential" just means that there is some type that obey to the rules defined here.


q: I have a function which gets a key from the user and generates a Hashtable (on a pattern specified by the key). After creating a Hashtable, I would like to populate a JTable so that each each column represents a key and every rows represents the values associated with the key. I tried everything but couldn't get this work. I'm not creating the table from within the constructor as I need to get input from the user.

[A]
See
How to Use Tables: Creating a Table Model
.
The JTable constructor used by
  SimpleTableDemo creates its table
  model with code like this:
```
```
new AbstractTableModel() {
    public String getColumnName(int col) {
        return columnNames[col].toString();
    }
    public int getRowCount() { return rowData.length; }
    public int getColumnCount() { return columnNames.length; }
    public Object getValueAt(int row, int col) {
        return rowData[row][col];
    }
    public boolean isCellEditable(int row, int col)
        { return true; }
    public void setValueAt(Object value, int row, int col) {
        rowData[row][col] = value;
        fireTableCellUpdated(row, col);
    }
}
```
```
You basically have to wrap your hashtable in the above manner. Here's an example.
```
```
package eed3si9n.hashtabletable;

import java.awt.BorderLayout;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.JButton;
import java.awt.Dimension;

public class MainForm extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;  //  @jve:decl-index=0:visual-constraint="23,38"
    private JScrollPane m_scrollPane = null;
    private JTable m_table = null;
    private Hashtable<String, String> m_hash = null;
    private JButton m_btnAdd = null;

    /**
     * This is the default constructor
     */
    public MainForm() {
        super();
        initialize();
        m_hash = new Hashtable<String, String>();
        m_hash.put("Dog", "Bow");
    }

    private void onButtonPressed() {
        m_hash.put("Cow", "Moo");
        m_table.revalidate();
    }

    /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(409, 290);
        this.setTitle("JFrame");
        this.setContentPane(getJContentPane());
    }

    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.setSize(new Dimension(500, 500));
            jContentPane.setPreferredSize(new Dimension(500, 500));
            jContentPane.add(getM_scrollPane(), BorderLayout.NORTH);
            jContentPane.add(getM_btnAdd(), BorderLayout.SOUTH);
        }
        return jContentPane;
    }

    /**
     * This method initializes m_scrollPane
     *
     * @return javax.swing.JScrollPane
     */
    private JScrollPane getM_scrollPane() {
        if (m_scrollPane == null) {
            m_scrollPane = new JScrollPane();
            m_scrollPane.setViewportView(getM_table());
        }
        return m_scrollPane;
    }

    /**
     * This method initializes m_table
     *
     * @return javax.swing.JTable
     */
    private JTable getM_table() {
        if (m_table == null) {
            m_table = new JTable();
            m_table.setModel(new AbstractTableModel(){
    private static final long serialVersionUID = 1L;

    public int getColumnCount() {
        return 2;
    }

    public int getRowCount() {
        return m_hash.size();
    }

    public String getColumnName(int column) {
        if (column == 0) {
            return "Animal";
        } else {
            return "Sound";
        }
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        if (columnIndex == 0) {
            return getKey(rowIndex);
        } else {
            return m_hash.get(getKey(rowIndex));
        } // if-else

    }

    private String getKey(int a_index) {
        String retval = "";
        Enumeration<String> e = m_hash.keys();
        for (int i = 0; i < a_index + 1; i++) {
            retval = e.nextElement();
        } // for

        return retval;
    }

            });
        }
        return m_table;
    }

    /**
     * This method initializes m_btnAdd
     *
     * @return javax.swing.JButton
     */
    private JButton getM_btnAdd() {
        if (m_btnAdd == null) {
            m_btnAdd = new JButton();
            m_btnAdd.setPreferredSize(new Dimension(34, 30));
            m_btnAdd.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    onButtonPressed();
                }
            });
        }
        return m_btnAdd;
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MainForm frame = new MainForm();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(500, 500);
                frame.setVisible(true);
            }
        });
    }
}  //  @jve:decl-index=0:visual-constraint="10,10"
```
```


q: How do I select the unique elements from the list {0, 1, 2, 2, 2, 3, 4, 4, 5} so that I get {0, 1, 3, 5}, effectively removing all instances of the repeated elements {2, 4}?

[A]
```
```
var nums = new int{ 0...4,4,5};
var distinct = nums.Distinct();
```
```
make sure you're using Linq and .NET framework 3.5.


q:
I always see the code like this in the blogs:

$.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "WebService.asmx/HelloWorld",
                    data: "{}",
                    dataType: "json",
                    success: function(msg) {
                        alert(msg.d);
                    }
                });

But I think this is run only with asp.net 3.5. I couldn't run it with 2.0. How can I use such these codes in my Applications?

[A]
I already know this article, but It couldn't help me.
In my sample app, I use these codes:
my Jquery code:
```
```
$(document).ready(function() {
        $('#clKaydet').click(function() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebService.asmx/HelloWorld",
                data: "{}",
                dataType: "json",
                success: function(msg) {
                    alert(msg);
                }
            });

        });

    });
```
```
My Html Code:
```
```
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server" />
    <div>

        <input type="button" id="clKaydet" runat="server" value="Kayıt" onclick="Kayit()" />
    </div>

    </div>
    </form>
```
```
My Webservise Code:
```
```
<WebMethod()> _
Public Function HelloWorld() As String
    Dim sText As String = "Hello"
    Return sText
End Function
```
```
Is there any mistake?


q:
We are currently working with Flex creating a web application. We are having trouble taking Arabic text from the user and displaying correctly (like in a chat feature). While presumably Flash 10 will solve this problem, we don't want to force our users to upgrade.

Flash flips the order of the sentence's words. so if I wrote something like "Hello World" in the text field, it will appear as "World Hello" in the chat area.

Is there a standard way to work with Right to Left languages in Flash?

*We currently flip the order of the words with a function, but it things get messed up when using English or special characters in the chat like :) or :D *

[A]
This would appear to be a Unicode issue, and so a quick talaash via Google gave me
Unicode in Flash
, but probably more to the point is
Flash: RTL (right-to-left)
, seeing as it mentions Arabic (along with other RTL languages) as well as
RTL text output class for Flash
.
HTH


q:
A few years ago client Java was unsuitable for web development because a remarkable part of web users did not have Java installed. ( I don't remember exact numbers, more than 10%).

Now I see the Google Analytics stats for a big site and it tells that >98% of users have Java installed.

Is these stats very biased by Javascript usage? As I understand Google Analytics measure only users that has Javascript.

Is the picture similar on other big sites?

Does client Java have really "stopper" drawbacks compared to Flash?

EDIT: I mean java applets mainly, java WebStart seems to be not suitable for average user.

I mention Javascript only to describe the way Google Analytics works.

[A]
When I wrote my diploma project, I had to choose between Flash and Java Applets. Here are some pros and cons:
Java Applets:
[plus] you program in Java, which is mature and stable
[plus] you can use the Java GUI frameworks that pack a lot of punch
[minus] the first time the user hits the page with the applet, the JVM must be initialized and this can take up to a few minutes even on a fast computer
[minus] Applets are not meant to be used as animation media; sure, you can do stuff, but it is like programming in C - you do everything from scratch
example: i needed to show a data packet as it moved between two routers. The packet must be a control of some sort, like a button or smth. This animation can be defined in 1 line of code in Flash, where all objects derive from some base object that can be animated. I could not find a suitable solution in Java.
Flash:
[plus] really really focused on animations;
[plus] ActionScript is actually an OO language
[minus] ActionScript is sloppy, bughish and has only a few supporters. If you are stuck, be prepared to search obscure Japanese forums for solutions
[minus] ActionSCript may be OO, but it lacks a lot of features, like Enums, fully fledged interfaces, threads (!!!!) etc.
[minus] Flash was designed to be used by non-tech people - they just use the authoring tool; I wrote code for everything and it worked, but it was a pain.
My conclusion:
I eagerly await a programming paradigm for animations and rich client interfaces.
ps: Silverlight seems to be a disappointment so far, maybe Microsoft will inject some $ into it.


q:
I want to decode a string that has been encoded using the java.net.URLEncoder.encode() method.

I tried using the unescape() function in javascript, but a problem occurs for blank spaces because java.net.URLEncoder.encode() converts a blank space
to '+' but unescape() won't convert '+' to a blank space.


q:
I recently wrote a class for an assignment in which I had to store names in an ArrayList (in java). I initialized the ArrayList as an instance variable private ArrayList<String> names. Later when I checked my work against the solution, I noticed that they had initialized their ArrayList in the run() method instead.

I thought about this for a bit and I kind of feel it might be a matter of taste, but in general how does one choose in situations like this? Does one take up less memory or something?

PS I like the instance variables in Ruby that start with an @ symbol: they are lovelier.

(meta-question: What would be a better title for this question?)

[A]
In the words of the great Knuth "Premature optimization is the root of all evil".
Just worry that your program functions correctly and that it does not have bugs. This is far more important than an obscure optimization that will be hard to debug later on.
But to answer your question - if you initialize in the class member, the memory will be allocated the first time a mention of your class is done in the code (i.e. when you call a method from it). If you initialize in a method, the memory allocation occurs later, when you call this specific method.
So it is only a question of initializing later... this is called lazy initialization in the industry.


q:
I have a number of user permissions that are tested throughout my ASP.NET application. These permission values are referenced in an Enum so that I can conveniently test permissions like so:

btnCreate.Enabled = PermissionManager.TestPermission(Permission.AllowCreate);

However, I also have these permissions stored in the database because I need hold more info about them than just their Id. But this creates a horrible dependency between the enum values and those in the database, an ill considered change to either and I have problems throughout my application. Is there a better way around this issue? Has anyone dealt with this before?

[A]
I do not know what the best solution is, I would like to hear that.
Our solution is to explicitly type the enum like
```
```
public enum MyEnum : int
{
   None =0,
   Value = 1,
   AnotherValue =2
}
```
```
And save the integer value to the database. When for instance the Value 1 is removed, you will still be able to use the enumeration and AnotherValue still has the value 2 in the database.


q:
I want to discard all remaining characters in a string as soon as one of several unwanted characters is encountered.

As soon as a blacklisted character is encountered, the string before that point should be returned.

For instance, if I have an array:

$chars = array("a", "b", "c");

How would I go through the following string...

log dog hat bat

...and end up with:

log dog h

[A]
The
strcspn
function is what you are looking for.
```
```
<?php

$mask = "abc";

$string = "log dog hat bat";

$result = substr($string,0,strcspn($string,$mask));

var_dump($result);

?>
```
```


q:
This follows on from this question where I was getting a few answers assuming I was using files for storing my HTML templates.

Before recently I've always saved 'compiled' templates as html files in a directory (above the root). My templates usually have two types of variable - 'static' variables which are not replaced on every usage but are used across the site - basically for ease of maintenanceif I decide to change the site name for example; and dynamic vars that change on every page load.

I always used to save these as files on the server - but my friend pointed out something I'd overlooked: why have 5-10 filesystem calls when you can have one database call?

What I want to know is which is more efficient? Calling several HTML files from the system or calling several rows of templates from the database (in one query/call).

[A]
Don't Store Editable HTML In the database
Seriously, because the maintenance overhead for mere changes becomes exhaustive once you realise you can no longer just pop open a text editor.
I worked on many projects which had HTML content in the database, and it was a constant nightmare of "find that row the content is on" and I really would liked to have
shot
the person whom made it.
Also,
DON'T PREMATURELY OPTIMISE
. If you find it a problem thats slowing the project down, then change it. Because making the code exhaustively less maintainable to save a millisecond. But design the code well enough that should you need to change where the content comes from later it should be easy to do.
Surely that can be resolved by having
  a suitable web interface for editing
  the templates?
Erm, really not, unless you're only trying to compete with notepad. Syntax highlighting and all the other full host of features you can get in a standard editor just make your developers suicidal when they find themselves editing web pages by hacking at an undersized text area with awful white on black ( not to mention the extra fun you get with having to worry about entity encoding etc, for instance, try editing html with in a text area where the html content contains a text area element! )
On FileIO
While File IO can be a bottleneck, keep in mind that if you have a proper linux install, and plenty of memory, a handy thing known as "disk-cache" takes effect, which in effect, keeps files used in memory, so file IO becomes mere memcpy.
On the contrary, in real stress tests on any of the code I have used, the biggest slowdowns have been in the database!, primarily the nice slow CONNECT string, query parse time, extra php<->mysql interactions.  You're not really looking at gaining anything. Filesystem lookup is close to database index lookup, and you don't have any unknowns other than "you need to stream it from a disk", no table locking stuff to worry about!
You should probably try something like a caching library, X-Cache comes highly recommended, thats more  likely to give you visible performance gains.


q:
The MS source server technology uses an initialization file named srcsrv.ini. One of the values identifies the source server location(s), e.g.,

MYSERVER=\\machine\foobar

The docs leave much unanswered about this value. To start with, I haven't been able to find the significance of the value name, i.e., what's on the left side--and I don't see it used anywhere else. Hewardt & Pravat in Advanced Windows Debugging say "The left side ... represents the project name", but that doesn't seem to jibe with MS's "MYSERVER" example.

What is the significance of the left side? Where else is it used? Does the value reference a server or a project, and is there one per server, or one per project?

[A]
For anyone looking into this in the future, I received the following information from MS:
The name on the left side is the logical name of a version
  control server. The name is also used in the source-indexed symbol files
  (pdb). For example, a symbol file may contain this string value:
MYSERVER=mymachine1.sys-mygroup.corp.microsoft.com:2003
and the source files are referenced like this in pdb:
*MYSERVER*/base/myfolder/mycode.c
When SrcSrv starts, it looks at Srcsrv.ini for values; these values override the information contained in the .pdb file:
"MYSERVER=mymachine.sys-mygroup.corp.microsoft.com:1666" overrides
"MYSERVER=mymachine1.sys-mygroup.corp.microsoft.com:2003"
This enables users to configure a debugger to use an alternative source control server at debug time. The info is documented at
http://msdn.microsoft.com/en-us/library/ms680641.aspx
.
So, it is a logical name for a source server, and its value can be changed at debug time to reference a different server than the one originally used when the PDBs were created.


q:
I would like such empty span tags (filled with &nbsp; and space) to be removed:

<span> &nbsp; &nbsp; &nbsp; </span>

I've tried with this regex, but it needs adjusting:

(<span>(&nbsp;|\s)*</span>)

preg_replace('#<span>(&nbsp;|\s)*</span>#si','<\\1>',$encoded);

[A]
.
```
```
qr{<span[^>]*(/>|>\s*?</span>)}
```
```
Should get the gist of them. ( Including XML style-self closing tags ie:  )
But you
really
shouldn't use regex for HTML processing.
Answer only relevant to the context of the question that was visible before the formatting errors were corrected


q:
Just that... I get a string which contains a path to a file plus some arguments. How can I recognize the path? I thought about the index of the '.' in the file... but I don't like it.

What about using regular expressions? Can anyone point me in the right direction?

Regards

Edit: Theses are valid entries...

somefile.msi /a

C:\MyFolder\SomeFile.exe -i -d

I don't care much about the arguments cause once I have the path I'll assume the rest are arguments

[A]
Well, before you tackle finding the path in the string, you need to outline a set of rules for what a path in this context
This is, for the operating system, a valid filename: a
Since no directory information is specified, the
current directory
will be used. The file has no extension.
But is still a filename.
Is this a
path
in your context? Or do you mean something that has directory information as well?
Examples of what you need to handle would be useful.


q:
I have seen the ASP.NET community buzzing about MVC. I know the basics of its origin, and that there are many sites (unless I am mistaken, stack overflow itself) based on ASP.NET MVC.

From everything I have heard and read about MVC it seems to be the future of ASP.NET development. But since I don't usually dabble in .NET web development I am left wondering the following: when is it appropriate to use MVC and when is it not, and why? Examples of great (and terrible) use of MVC would be fascinating.

Though I realize there are other implementations of MVC view other languages like RoR I am more interested on its impact for .NET programmers.

If this has already been gone over, my apologies!

[A]
Here are my 2 cents about MVC for web applications.  For the sort of GUI apps for which MVC was originally intended, "listener" code was required, so that the UI could be updated when events altered the model data.
In MVC for the web this is unnecessary, you get your listener for free: the web server, and the HTTP request IS the event.  So really MVC for the web should be even simpler.  Indeed, it could be boiled down to the Mediator pattern, where the Controller mediates between the model and the view.
There are two things that there is a lot of confusion about.  Regardless of conventional "wisdom":
Frameworks != MVC
Database Data != "Model"
"Full stack" web development frameworks typically add lots of features, and may or may not be MVC-oriented at their core.  One of the features many frameworks add is database access or object relational mapping functionality, and because frameworks and MVC get confused, subsequently database data and the model facet of MVC also get confused.  The model can generally be viewed as the underlying data for the application, but it does NOT have to come from a database.  A good example might be a wiki, where the underlying model/data consists of file revision data, for instance, from RCS.
Hope this helps and I'm sure others will have plenty to add.


q: How can I draw a concave corner rectangle in WPF?

[A]
```
```
do you mean a rectangle with concave corners?, ie:
     ____________________
    |                    |
  __|                    |__
 |                          |
 |                          |
 |                          |
 |__                      __|
    |                    |
    |____________________|
```
```
Given a rectangle of dimension
```
w x h
```
with corner radius
```
r
```
There are 4 corners:
```
```
A :  0,0
B :  w,0
C :  w,h
D :  0,h
```
```
There is an implicit minimum size of
```
```
w = 2r
h = 2r
```
```
There are 4 Circle Centers,
```
A,B,C,D
```
And there's thus a grid of edge points:
```
```
(0,0)--(0+r,0)---(w-r,0)---(w,0)
|                              |
(0,0+r)                  (w,0+r)
|                              |
|                              |
(0,h-r)                  (w,h-r)
|                              |
(0,h)--(0+r,h)---(w-r,h)---(w,h)
```
```
Then its merely a case of computing the arc from one point to another.


q: As the question says, how do I set the value of a DropDownList control using jQuery?

[A]
```
```
$("#mydropdownlist").val("thevalue");
```
```
just make sure the value in the options tags matches the value in the val method.


q:
I have a page that spits out db data in long horizontal tables.

I need to print it nicely so it does not cut off. Any tips ?

[A]
If it doesn't fit on the paper in a readable font, it just doesn't.. In my opinion, huge horizontal tables (be it a HTML table or an Excel sheet with many columns) don't lend well to printing. For that matter, they don't lend well to viewing on a screen either. Remember vertical scrolling is much easier for your users than horizontal scrolling - all thanks to that little wheel on your mouse.
Worst case, you might need to write a seperate print version which uses a vertical layout.


q:
Using only MySQL, I'm seeing if it's possible run an insert statement ONLY if the table is new. I successfully created a user variable to see if the table exists. The problem is that you can't use "WHERE" along with an insert statement. Any ideas on how to get this working?

// See if the "country" table exists -- saving the result to a variable
SELECT
    @table_exists := COUNT(*)
FROM
    information_schema.TABLES
WHERE
    TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'country';

// Create the table if it doesn't exist
CREATE TABLE IF NOT EXISTS country (
    id INT unsigned auto_increment primary key,
    name VARCHAR(64)
);

// Insert data into the table if @table_exists > 0
INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands') WHERE 0 < @table_exists;

[A]
```
```
IF @TableExists > 0 THEN
   BEGIN
       INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands');
   END
```
```


q:
Unlike C++, in C# you can't overload the assignment operator.

I'm doing a custom Number class for arithmetic operations with very large numbers and I want it to have the look-and-feel of the built-in numerical types like int, decimal, etc. I've overloaded the arithmetic operators, but the assignment remains...

Here's an example:

Number a = new Number(55);
Number b = a; //I want to copy the value, not the reference

Is there a workaround for that issue?

[A]
You won't be able to work around it having the C++ look, since a = b; has other semantics in C++ than in C#. In C#, a = b; makes a point to the same object like b. In C++, a = b changes the content of a. Both has their ups and downs. It's like you do
```
```
MyType * a = new MyType();
MyType * b = new MyType();
a = b; /* only exchange pointers. will not change any content */
```
```
In C++ (it will lose the reference to the first object, and create a memory leak. But let's ignore that here). You cannot overload the assign operator in C++ for that either.
The workaround is easy:
```
```
MyType a = new MyType();
MyType b = new MyType();

// instead of a = b
a.Assign(b);
```
```
Disclaimer
: I'm not a C# developer
You could create a write-only-property like this. then do a.Self = b; above.
```
```
public MyType Self {
    set {
        /* copy content of value to this */
        this.Assign(value);
    }
}
```
```
Now, this is
not
good. Since it violates the principle-of-least-surprise (POLS). One wouldn't expect a to change if one does a.Self = b;


q: Except perhaps at bigger (or better) shops, the development UI is done by the developers.  In your experience, how much has this impacted the final product, and how much time should we spend getting the development UI right?

[A]
The interface you're building and showing to your customers is basically all they will ever see. You can sit down with them and talk for hours about what the product is supposed to do, but the number one best method to have the users spot problems or missing functionality, is to show them the interface as it will look like in the final product. You can do this with a prototype or the actual interface as it is being built.
So I would say the interface should look pretty much like what you will be delivering at the end during development. This will guarantee that you get the right feedback, and that the user knows what he is getting. Of course, you can build an interface which doesn't exactly have the style of the final product (colors, window styles, fonts, etc...), but the functionality of the product you're building should be clear as early on as possible.


q:
In my master pages I have <form ... action="" ...>, in pre SP1, if I viewed the source the action attribute would be an empty string.  In SP1 the action attribute is overridden "MyPage.aspx?MyParams", unfortunately, this causes my postbacks to fail as I have additional pathinfo in the URL (ie. MyPage.aspx\CustomerData?MyParams). I have checked the action attribute in the OnLoad event and it is still blank at this time, so somewhere SP1 is overriding this :(.

Sorry, I just realized that part of my post was missing since I did not use the markdown correctly.

[A]
Maybe you can find the solution here in
this ASP.NET Forum post
(Known Issues / Breaking Changes for ASP.NET in .NET 3.5 Service Pack 1).
Issue
The HtmlForm action attribute is now honored when defined in declarative markup.
Reason
3.5 SP1 added a settable Action property to the HtmlForm type.  This new feature makes it much easier for developers to explicitly set the form’s action attribute for scenarios where a developer wants to use a different Url than the normal postback-generated Url.  However this change also means that if the action attribute has been set in an .aspx page’s declarative markup, ASP.NET will use the setting from the markup when rendering a
```
<form />
```
element.
Workaround
Previous versions of ASP.NET always ignored the action attribute if it was present in the declarative markup for a
```
<form />
```
element.  Developers should remove the action attribute from their declarative markup to return to the original behavior where ASP.NET renders the postback Url.
Example
Before (the action attribute was ignored by ASP.NET as dead code):
```
```
<form name="form1" method="post" runat="server" action="test.aspx"></form>
```
```
3.5 SP1 (remove the action attribute to have ASP.NET render the postback Url):
```
```
<form name="form1" method="post" runat="server"></form>
```
```


q:
I am trying to animate an object, let's say its a car. I want it go from point

x1,y1,z1

to point x2,y2,z2 . It moves to those points, but it appears to be drifting rather than pointing in the direction of motion. So my question is: how can I solve this issue in my updateframe() event? Could you point me in the direction of some good resources?

Thanks.

[A]
You need to work out the initial orientation of the car, and the final orientation of the car at its destination, then interpolate between them to determine the orientation in between for the current timestep.
This
article describes the mathematics behind doing the interpolation, as well as some other things to do with rotating objects that may be of use to you. gamasutra.com in general is an excellent resource for this sort of thing.


q:
When I create a graph after using range.copy and range.paste it leaves the paste range selected, and then when I create a graph a few lines later, it uses the selection as the first series in the plot.  I can delete the series, but is there a more elegant way to do this?  I tried

Set selection = nothing

but it won't let me set selection.  I also tried selection.clear, but that just cleared the last cells that were selected, and still added an extra series to the plot.

[A]
I do not think that this can be done. Here is some code copied with no modifications from Chip Pearson's site:
http://www.cpearson.com/excel/UnSelect.aspx
.
UnSelectActiveCell
This procedure will remove the Active Cell from the Selection.
```
```
Sub UnSelectActiveCell()
    Dim R As Range
    Dim RR As Range
    For Each R In Selection.Cells
        If StrComp(R.Address, ActiveCell.Address, vbBinaryCompare) <> 0 Then
            If RR Is Nothing Then
                Set RR = R
            Else
                Set RR = Application.Union(RR, R)
            End If
        End If
    Next R
    If Not RR Is Nothing Then
        RR.Select
    End If
End Sub
```
```
UnSelectCurrentArea
This procedure will remove the Area containing the Active Cell from the Selection.
```
```
Sub UnSelectCurrentArea()
    Dim Area As Range
    Dim RR As Range

    For Each Area In Selection.Areas
        If Application.Intersect(Area, ActiveCell) Is Nothing Then
            If RR Is Nothing Then
                Set RR = Area
            Else
                Set RR = Application.Union(RR, Area)
            End If
        End If
    Next Area
    If Not RR Is Nothing Then
        RR.Select
    End If
End Sub
```
```


q: I can get simple examples to work fine as long as there's no master page involved. All I want to do is click a button and have it say "hello world" with the javascript in a .js file, using a master page. Any help very much appreciated :)

[A]
Just move the
```
<script type="text/javascript" src="jquery.js" />
```
tag into the head tag in the master page. Then you can use jquery in all content pages.
There is no magic about using master pages with jQuery.


q: I have a few ASP.Net database front-end websites where MS Access is the back-end.  I am trying to use ASP.Net dynamic data website.  Should I change this database to SQL Server Express or something else to make it easier or should this work from with MS Access.

[A]
Pick SQL Express for these reasons:
Scaling
: MS Access will never scale.  Once you get over about 10 concurrent connections you will start to see trouble.  SQL Express will scale.  You can always move SQL Express up to a full-blow SQL Server installation.  While this is somewhat true of Access, some of your SQL statements and data types may not transfer cleanly.
Security
: SQL Server has a much better security model than Access.  You can lock down the schema in your db per user.  You can also better administrate user access (think dev user vs test user vs production user).
Performance
: This is similar to scaling.  If you see a traffic spike to your web site, Access may not handle it while SQL Server Express probably will.
Tools
: Tools and libraries like LINQ are always going to be targeted at SQL Server.  You will get better support and better documentation using them this way.


q:
I have a Java SOAP data service which sits on top of a Sybase database which, for reasons out of my control, has unreliable performance. The database is part of a vendor package which has been modified by an internal team and most of the issues are caused by slow response times at certain times of the day.

The SOAP service provides data to a calculation grid and when I request data, I need the response time to be both fast and consistent.  The service provides basic CRUD functionality, but the ratio of reads to writes is approximately 100:1.

What is the best strategy to isolate myself from the database's unreliable performance and ensure that the SOAP service is fast and reliable?

[A]
I have seen this issue a few times, normally with a vendor database.
If this is on Windows, you could create a Windows service as an intermediary between the SOAP service and the database. Then put a message queue (either MSMQ or a JMS implementation such as MQ Series) between the SOAP service and Windows service for asynchronous communications. In this way the database performance issues will no longer affect the SOAP service. This solution does, however, come at the cost of increased complexity.
Note that a .NET web service can be called by, and respond asynchronously to, its clients. I'm not sure if that's possible with a Java SOAP service.
If this is on some flavour of Unix, I assume it has similar functionality to a Windows service - maybe a daemon.


q:
I am trying to insert a new row into my table which holds the same data as the one I am trying to select from the same table but with a different user_id and without a fixed value for auto_id since that is an auto_increment field, and setting ti to NOW(). Below is my mockup query where '1' is the new user_id. I have been trying many variations but am still stuck, anyone who can help me with turning this into a working query.

INSERT INTO `lins` ( `user_id` , `ad` , `ke` , `se` , `la` , `ra` , `ty` , `en` , `si` , `mo` , `ti` , `de` , `re` , `ti` ) (

SELECT '1', `ad` , `ke` , `se` , `la` , `ra` , `ty` , `en` , `si` , `mo` , `ti` , `de` , `re` , NOW( )
FROM `lins`
WHERE autoid = '4'
AND user_id = '2'
)

Thank you for taking the time to help me out!

[A]
I think you need to explicitly match the line terminators, as well as handle spaces better as others have suggested.  Assuming the user can choose between \r and \n, try
```
```
@"(?<select>\Aselect .+)[\n\r]" +
@"(?<from>\s*from .+)[\n\r]" +
@"(?<where>\s*where .+)[\n\r]" +
@"(?<groupBy>\s*group by .+)[\n\r]" +
@"(?<having>\s*having .+)[\n\r]"
```
```
As long as you are using regular expressions, you probably want to do a bit better:
```
```
@"\Aselect (?<select>.+)[\n\r]" +
@"\s*from (?<from>.+)[\n\r]" +
@"\s*where (?<where>.+)[\n\r]" +
@"\s*group by (?<groupBy>.+)[\n\r]" +
@"\s*having (?<having>.+)[\n\r]"
```
```
My biggest problem with regular expressions for this sort of use is that the only error message you can give is that things failed.  You can't give the user any further information about what they did wrong.


q: What type of client is likely to support XP (Extreme Programming) practices?

[A]
If your team achieves great results with a proven track-record, then companies desiring a successful result.  If the converse is true, only companies who are wandering blindly will be interested.
There is the
odd
case where the client will want a certain practices followed. Like a experienced dev manager outsourcing a project to an external firm, or potentially a client who has heard that XP is good in passing but has no real knowledge or experience with it. In the former the experienced consumer will know what he wants and if you do not provide those services they will go elsewhere.  If you try to fake it, they will know and be most displeased.  The later, it doesn't matter so much as long as they get good results and think it was their own wisdom that brought them forth from the ground.
Either way, it is results that matter.
Now begins my diatribe which so far has inspired much ire:
Would you jeopardize your good practices just to suit a client? If you are staunchly in favour of XP, sell it! If they want you to use a methodology that you strongly disagree with. Tell them that. If you can't come to a consensus, there should be no deal.
Do I tell a baker what grain to use? How hot to have the ovens? Hell no.  If I say I want poppy seeds on the buns I don't care how they are put there so long as they are there. Dp I select a baker based on his methods, or on how damn tasty the bread is? Letting a non programmer tell you how to do your craft is just plain bad.
If you are trying to extol the virtues of XP then be upfront, pitch the cost-benefits and ROI.  Show them why it is better for them in terms of developer efficiency and defect reduction.  If you are working for non-programmers, you are the expert, take the reigns and give advice.
If your team excels at XP and has great results you will have no problem selling any potential client on your practices.  Results matter to clients; if you can prove that you consistently produce high quality products within consistent timelines you should have no problem selling your methodology. (with some exceptions that absolutely require waterfall).


q:
Based on their work, how do you distinguish a great SQL developer?

Examples might include:

Seldom uses CURSORs, and tries to refactor them away.

Seldom uses temporary tables, and tries to refactor them away.

Handles NULL values in OUTER JOINs with confidence.

Avoids SQL extensions that are not widely implemented.
Knows how to indent with elegance.

[A]
I don't think that cursors, temporary tables or other SQL practices are inherently bad or that their usage is a clear sign of how good a database programmer is.
I think there is the right tool for every type of problem. Sure, if you only have a hammer, everything looks like a nail. I think a great SQL programmer or database developer is a person who knows which tool is the right one in a specific situation. IMHO you can't generalize excluding specific patterns.
But a rule of thumb may be: a great database developer will find a more
short and elegant solution
for complex situations than the average programmer.


q: Does anyone know because all the places I've tried seem to timeout!

[A]
You can download JSTL 1.1
here
and JSTL 1.2
here
.
See also:
JSTL wiki page


q:
which one of the two is more spread? I want to read out the version number from http://freshmeat.net/projects-xml/mysql/mysql.xml?branch_id=46519 but I want to use the one which more people have.

If you know another way to get the latest stable version number from mysql please tell me ;)

[A]
For this kind of task, reading the document into a
```
DomDocument
```
and using
```
DomXPath
```
is probably more suitable.
To answer your question, both libraries (as well as
```
DomDocument
```
+
```
DomXPath
```
) are standard outfit with PHP5, so they would be equally fine choices.


q: Well, what is one?

[A]
It's a
Universally Unique Identifier


q:
I need to allow the vertical scrollbar in a multiselect listbox (VB6) however, when the control is disabled, I can't scroll.

I would think there is an API to allow this, but my favorite VB6 site (MVPS VB.NET) does not have a way.

I toyed with pretending it was disabled, and ignore the clicks... but to do that with VB6 code is really ugly... so if this is a solution, I need an API to ignore the clicks.

Thanks for your help.

[A]
Rather than looking for the API to ignore clicks, can't you just ignore the events? (i.e. just don't do when the user clicks/selects something).
And, I think there is a
```
SelectionMode
```
property to disable multiselect and make it single select.
If you don't want the user to be able to select anything at all, you can try hooking into the
```
SelectionIndexChanged
```
event and set the
```
SelectionIndex
```
to -1.
My VB6 is a bit rustly, so sorry if the event/property name don't match exactly.


q:
can you set SO_RCVTIMEO and SO_SNDTIMEO socket options in boost asio?

If so how?

Note I know you can use timers instead, but I'd like to know about these socket options in particular.

[A]
It doesn't appear to be built into Boost.Asio (as of current Boost SVN), but, if you're willing to write your own classes to simulate the
```
boost::asio::detail::socket_option
```
ones, you can always follow the examples in
```
boost/asio/socket_base.hpp
```
and do the following:
```
```
typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_SNDTIMEO>
    send_timeout;
typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_RCVTIMEO>
    receive_timeout;
```
```
(Obviously, I'm not suggesting you inject the
```
timeval
```
class into the
```
boost::asio::detail::socket_option
```
namespace, but I can't think of a good one to use at the moment. :-P)
Edit: My sample implementation of
```
socket_option::timeval
```
, based on
```
socket_option::integer
```
:
```
```
// Helper template for implementing timeval options.
template <int Level, int Name>
class timeval
{
public:
  // Default constructor.
  timeval()
    : value_(zero_timeval())
  {
  }

  // Construct with a specific option value.
  explicit timeval(::timeval v)
    : value_(v)
  {
  }

  // Set the value of the timeval option.
  timeval& operator=(::timeval v)
  {
    value_ = v;
    return *this;
  }

  // Get the current value of the timeval option.
  ::timeval value() const
  {
    return value_;
  }

  // Get the level of the socket option.
  template <typename Protocol>
  int level(const Protocol&) const
  {
    return Level;
  }

  // Get the name of the socket option.
  template <typename Protocol>
  int name(const Protocol&) const
  {
    return Name;
  }

  // Get the address of the timeval data.
  template <typename Protocol>
  ::timeval* data(const Protocol&)
  {
    return &value_;
  }

  // Get the address of the timeval data.
  template <typename Protocol>
  const ::timeval* data(const Protocol&) const
  {
    return &value_;
  }

  // Get the size of the timeval data.
  template <typename Protocol>
  std::size_t size(const Protocol&) const
  {
    return sizeof(value_);
  }

  // Set the size of the timeval data.
  template <typename Protocol>
  void resize(const Protocol&, std::size_t s)
  {
    if (s != sizeof(value_))
      throw std::length_error("timeval socket option resize");
  }

private:
  static ::timeval zero_timeval()
  {
    ::timeval result = {};
    return result;
  }

  ::timeval value_;
};
```
```


q: Do I need a UUID to program for the iPhone? I was told I need this, how can I get a UUID


q:
I need an algorithm to determine if a sentence, paragraph or article is negative or positive in tone... or better yet, how negative or positive.

For instance:

Jason is the worst SO user I have ever witnessed (-10)

Jason is an SO user (0)

Jason is the best SO user I have ever seen (+10)

Jason is the best at sucking with SO (-10)

While, okay at SO, Jason is the worst at doing bad (+10)

Not easy, huh? :)

I don't expect somebody to explain this algorithm to me, but I assume there is already much work on something like this in academia somewhere. If you can point me to some articles or research, I would love it.

Thanks.

[A]
This falls under the umbrella of
Natural Language Processing
, and so reading about that is probably a good place to start.
If you don't want to get in to a very complicated problem, you can just create lists of "positive" and "negative" words (and weight them if you want) and do word counts on sections of text.  Obviously this isn't a "smart" solution, but it gets you some information with very little work, where doing serious NLP would be very time consuming.
One of your examples would potentially be marked positive when it was in fact negative using this approach ("Jason is the best at sucking with SO") unless you happen to weight "sucking" more than "best"....  But also this is a small text sample, if you're looking at paragraphs or more of text, then weighting becomes more reliable unless you have someone purposefully trying to fool your algorithm.


q:
Many products/services we are interact with (including our own) uses XML-over-HTTP or derivatives (like OMA IMPS IM/presence protocol).

I am looking for some tool that will "listen" to a traffic and produce client/server stubs for simulation/testing.

Thanks.

[A]
That sounds like a good idea for a project.
This is not a solution, but your first step should be to at least support know webservice descriptors.
To do that should sniff the traffic using wireshark or something similar and see the URL's that are being accessed.  If you are lucky these services would be webservices with a retrievable descriptor or schema for the interface.  Check for .xsd, .wsdl, .asmx
Here are some examples:
http://www.webservicex.net/CurrencyConvertor.asmx
http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl
http://www.weather.gov/forecasts/xml/DWMLgen/schema/DWML.xsd
There are Microsoft tools available that come packaged with the SDL that can provide stubs for these.
I don't know of any drop in solution for you but my approach to solving this problem would be:
- use wireshark to record http conversations for specific webservices.
- parse (or look at) these files to extract the URLs that are invoked and track the message passing + xml documents.
- Create stubs based on what appear to be the parameters.
- Start by creating some simple pattern matchers and transforms (xml + xsl can = code or some page for debug).
You may also need to consider
- communication may not be 2 way xml- it could be HTTP posts with query string one way and xml responses back.
- The XML documents may not be properly formatted XML- test parse each message before trying to generate anything.


q: Is there any persistence solution for Common Lisp, such as Elephant, that allows function persistence? Currently my app stores an identifier on the db and later searches in a function table which it is, but this method does not allow dynamically created functions to be stored.

[A]
Functions are opaque objects, so you won't have much luck storing them in files or something like that.  You can, however, store lists and
compile
them upon retrieval from the database.
This won't help you store closures, of course.  That would entail storing the lexical environment along with the code, neither of which you have (portable) access to.  Code that you compile from stored lists will have to rely entirely on global data or data stored in the database.
By the way, note that you can
funcall
symbols, so you don't need a function table for global functions.


q:
I think I'm pretty good at using semantic markup on my pages but I still have a handful of classes like this:

/**** Aligns ****/
.right_align  { text-align: right; }
.left_align   { text-align: left; }
.center_align { text-align: center; }

Which, technically, is a no-no. But when you just want to position some text in a table, how crazy am I supposed to get with the semantic markup?

[A]
Semantic markup is an admirable goal, but in the real world, you sometimes have to make compromises. In some cases, the only sensible way to do something is to break semantics and just throw in a
```
right_align
```
.
Edit: People seem to be misunderstanding my point in this. You should use semantic markup where possible. However, there are cases where it really is just a stylistic choice and there is nothing inherent to the data that you can use to describe or classify it. This is most typically true with large sections of tabular data, especially if it is dynamically generated.
I've had cases where clients want to be able to dynamically control what columns appear in data grid. There's no way to know ahead of time what type of data they're going to choose to show. If they want a way to center or right align a dynamically generated column, it's better to have center and right align classes available for them to use than to have them sticking
```
style
```
attributes everywhere.


q: I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance

[A]
Perhaps with
```
java -jar archive.jar
```
?
Of course, it supposes the manifest points to the right class...
You should give the exact message you got, it might shed more light.
EDIT:  See
Working with Manifest Files: The Basics
for information on setting the application entry point (Main class) in your jar manifest file.


q:
Let's say I have a line of text like this

Small   0.0..20.0   0.00    1.49    25.71   41.05   12.31   0.00    80.56

I want to capture the last six numbers and ignore the Small and the first two groups of numbers.

For this exercise, let's ignore the fact that it might be easier to just do some sort of string-split instead of a regular expression.

I have this regex that works but is kind of horrible looking

^(Small).*?[0-9.]+.*?[0-9.]+.*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+)

Is there some way to compact that?

For example, is it possible to combine the check for the last 6 numbers into a single statement that still stores the results as 6 separate group matches?

[A]
If you want to keep each match in a separate backreference, you have no choice but to "spell it out" - if you use repetition, you can either catch all six groups "as one" or only the last one, depending on where you put the capturing parentheses. So no, it's not possible to compact the regex and still keep all six individual matches.
A somewhat more efficient (though not beautiful) regex would be:
```
```
^Small\s+[0-9.]+\s+[0-9.]+\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)
```
```
since it matches the spaces explicitly. Your regex will result in a lot of backtracking. My regex matches in 28 steps, yours in 106.
Just as an aside: In Python, you could simply do a
```
```
>>> pieces = "Small   0.0..20.0   0.00    1.49    25.71   41.05   12.31   0.00    80.56".split()[-6:]
>>> print pieces
['1.49', '25.71', '41.05', '12.31', '0.00', '80.56']
```
```


q:
I'm relatively new to .NET programming (and OOP in general) and I want to make sure I'm not developing bad beginner habits when designing my applications.

If you were hiring a new .NET developer and had to get him up to speed relatively quickly, but also wanted to make sure he adopts best practices (e.g., single responsibility principle, unit testing, separation of concerns), what would be your recommended learning path?

I've been listening to the Polymorphic Podcast lately and, while listening to discussion of best practices is helpful, I'm finding a lack of screencasts and code examples aimed at providing an introduction to these best practices.

[A]
If, as in your hypothetical example, I was hiring a new .NET developer and wanted to make sure they adopted best practices, I would start by making them look through my current code base.
Then I would recommend they read the following:
The Pragmatic Programmer
Code Complete
Head First Design Patterns
Refactoring
Test-Driven Development by Example
That should give anyone a pretty solid foundation in best OOP practices.


q:
I'm attempting to create a Wizard type control in VB6 and have run into a stumbling block.

I'd like to allow users of the control to be able to add and manage CWizardPage(s) to the design time control using a property page.

The first approach I used was to add the Wizard pages to the OCX directly using a Collection, however I ran into two problems in that the Collection class is not persistable (and I couldn't find an easy way to make it so) and that VB6 seems very limited in it's ability to instantiate controls at run time - so it would seem to be a struggle to actually re-instantiate them.

My next thought was to just allow the users to draw the wizard pages at design time. This sort of works, however it's far too easy to draw one of the wizard pages inside another wizard page instead of inside the CWizardContainer.

So can anyone please tell me how to add controls to a form at design time without using drag 'n' drop?

[A]
You can dynamically add controls to a form or other container (such as a UserControl) using the
```
Add
```
method of the container's
```
Controls
```
collection. For example, to add a TextBox named
```
myTextBox
```
to a form called frmMyForm, you could do this:
```
frmMyForm.Controls.Add "VB.TextBox", "myTextBox"
```
Here is a snippet from the VB6 help file:
Add Method (Controls Collection)
Adds a control to the
Controls
collection and returns a reference to
  the control.
Syntax
object
.
Add
(***ProgID, name, container*
)**
The
Add
method syntax has these parts:
object
(Required)
An object expression that evaluates to
  an object in the
Applies To
list.
ProgID
(Required)
A string that
  identifies the control. The ProgID of
  most controls can be determined by
  viewing the Object Browser. The ProgID
  is composed of the Library and Class
  of the control. For example, the
  CommandButton control's ProgID is
  VB.CommandButton. In cases where the
  ProgID differs from that shown in the
  Object Browser, Visual Basic displays
  an error message that contains the
  correct ProgId.
name
(Required)
A string that identifies the member of
  the collection.
container
(Optional)
An object reference that specifies a
  container of the control. If not
  specified or NULL, defaults to the
  container to which the Controls
  collection belongs. You can put a
  control in any existing container
  control (such as the Frame control) by
  specifying this argument. A user
  control or an ActiveX document can
  also be a container.


q: Suppose I have an interval (a,b), and a number of subintervals {(ai,bi)}i whose union is all of (a,b).  Is there an efficient way to choose a minimal-cardinality subset of these subintervals which still covers (a,b)?

[A]
Sounds like dynamic programming.
Here's an illustration of the algorithm (assume intervals are in a list sorted by ending time):
```
```
//works backwards from the end
int minCard(int current, int must_end_after)
{
    if (current < 0)
        if (must_end_after == 0)
            return 0; //no more intervals needed
        else
            return infinity; //doesn't cover (a,b)

    if (intervals[current].end < must_end_after)
        return infinity; //doesn't cover (a,b)

    return min( 1 + minCard(current - 1, intervals[current].start),
                    minCard(current - 1, must_end_after) );
    //include current interval or not?
}
```
```
But it should also involve caching (memoisation).


q: I need to build full-text search functionality into our knowledge base system using C#. How do I start?

[A]
For example from Lucene:
http://lucene.apache.org/java/docs/
C# port is here
http://incubator.apache.org/lucene.net/
You should also read something about the the information retrieval, and you can start with this one :
http://www.amazon.com/Modern-Information-Retrieval-Ricardo-Baeza-Yates/dp/020139829X


q:
I have a custom WinForms control (inherits from control, i.e. without user interface jsut as Timer) to which I want to add a custom command add design time.

This could be similar to the "right click and choose 'Edit Items...'" of a menu.

Is this posisble? How?

Also, could you recommend some general reading (online) about improving the design time experience of custom controls?

[A]
First here is a link to the relevant MSDN doco on the subject
http://msdn.microsoft.com/en-us/library/ms171567(VS.80).aspx
and more specifically
http://msdn.microsoft.com/en-us/library/system.componentmodel.design.menucommand(VS.80).aspx
As for a book that covers this,
Chris Sells Winforms book
is probably the best, however to be honest, I don't think that any of the books out there (on-line or otherwise) cover design time features in the sort of depth that I personally would like.


q:
I've read a lot about the pros and cons of sizing with either relative or absolute font sizes. Fixed sizes don't zoom in IE6 but that's not much of an issue these days. Accessibility is important, but I assume that all good accessibility software is built to deal with these issues?

I guess it mainly comes down to whether you want to be able to change all font sizes with one rule (i.e. the default font size you set) or whether you want to be able to change a font size somewhere without affecting nested elements (this is the thing that frustrates me most!).

Anyone have any tips?

[A]
The only big reason valid is that a lot of people is still using IE6. Just this.
Probably could be a good thing, at the end of 2008, to give no more attention at IE6. But is difficult to ignore IE6. I work as web designer/devolper for a big company in Italy, and many of ours employes  or clients, in their work computers, are browsing the internet with IE6 right now.
Why? They don't have administrator rights and can't install anithing in their machines, and the system admistrators are always too busy to upgrade the computers of every office. May be this people will upgrade to IE7 (something like  Firefox is a dream) when their hard disks will need to be changed.
Is possible that this sort of things happens only in Italy. But I would not bet on this.


q:
The "core" .NET languages are integrated into VS2008 - C#, VB.NET, and C++. I'm not sure about current support for J# and JScript.

But there are a number of other .NET languages out there - A#, Boo, Oxygene, F#, IronLisp/IronScheme, IronPython, IronRuby, Nemerle, Phalanger, P#, PowerShell, and more. Of these, I have only found VS support for F# (which is made by Microsoft, so no surprise there), Oxygene, A# (but only VS2005 support), and IronPython (only with external projects designed for this purpose).

But what about the other languages? Since they target the .NET runtime, I figure that it only makes sense that there would be a way to use those languages inside VS. Is there some limitation(s) of Visual Studio that prevent this? Is there a way to "force" VS to compile these languages?

[A]
I suspect it's pretty simple: IDE integration is no simple task, if you want to do it well. I would guess that most of these languages are done in spare time rather than having commercial funding. The amount of effort required is just prohibitively expensive - and not necessarily due to Visual Studio making things particularly hard, but due to it fundamentally being a difficult thing to achieve well.
That's not to say it can't be done, of course - just that it's hard, and "hobby" projects aren't likely to get that level of commitment unless they're really popular.
For Boo, by the way, you should look at
BooLangStudio
.


q:
Basically I'm about to start work on a site and I'd like something that I can add into my .htaccess file (or elsewhere) that'll work like this pseudo code: (my ip will be in place of 127.0.0.1)

if (visitors_ip <> 127.0.0.1)
    redirectmatch ^(.*)$ http://www.example.com/under-construction.html

Hopefully that makes sense...

[A]
That would be
something like
:
```
```
RewriteEngine On
RewriteBase /
RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1

RewriteCond %{REQUEST_URI} !/mypage\.html$

RewriteRule .* http://www.anothersite.com/mypage.html [R=302,L]
```
```
As
Andrew
points out, the %{REQUEST_URI} condition avoids infinite loop if you redirect to the same domain.
As
Xorax
comments
almost 9 years later
:
You should not use
```
REMOTE_HOST
```
, it will fail in many case. You should use
```
REMOTE_ADDR
```
.
Cf "
difference between
```
REMOTE_HOST
```
and
```
REMOTE_ADDR
```
"


q:
I have a Rails app with some basic models. The website displays data retrieved from other sources. So I need to write a Ruby script that creates new instances in my database. I know I can do that with the test hooks, but I'm not sure that makes sense here.

I'm not sure what this task should look like, how I can invoke it, or where it should go in my source tree (lib\tasks?).

For example, here's my first try:

require 'active_record'
require '../app/models/mymodel.rb'

test = MyModel.new
test.name = 'test'
test.save

This fails because it can't get a connection to the database. This makes sense in a vague way to my newbie brain, since presumably Rails is doing all the magic work behind the scenes to set all that stuff up. So how do I set up my little script?

[A]
You can open a connection in your scripts as such:
```
```
ActiveRecord::Base.establish_connection(
    :adapter  => "mysql",
    :username => "root",
    :host     => "localhost",
    :password => "******",
    :database => "******"
)
```
```
I'm sure there is a more elegant way to do it, so that it grabs the info from your database.yml.


q:
What's the best method to pass parameters to SQLCommand? You can do:

cmd.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = "Bob";

or

cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = "Bob";

or

cmd.Parameters.Add("@Name").Value = "Bob";

It seems like the first one might be somehow "better" either performance-wise or error checking-wise. But I would like to know more definitively.

[A]
You can also use
```
AddWithValue()
```
, but be aware of the possibility of the wrong implicit type conversion.
```
```
cmd.Parameters.AddWithValue("@Name", "Bob");
```
```


q:
I am making a little GUI frontend for a app at the moment using wxPython.

I am using wx.StaticText() to create a place to hold some text, code below:

content = wx.StaticText(panel, -1, "Text Here", style=wx.ALIGN_CENTRE)

I have a button when clicked retrieves data from MySQL, I am wanting to change the value of the StaticText() to the MySQL data or what else could I use the hold the data.

I have tried using the below method:

contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL)
content.SetValue("New Text")

This displays the data fine but after the data is loaded you can edit the data and I do not want this.

Hope you guys understand what I am trying to do, I am new to Python :)

Cheers

[A]
```
wx.TextCtrl
```
has a style called
```
wx.TE_READONLY
```
. Use that to make it read-only.
As a sidenode, you can use the
C++ wxWidgets Manual
for wxPython aswell. Where special handling for wxPython or other ports is required, the manual often points out the difference.


q:
I have an owner-drawn UserControl where I've implemented double-buffering.  In order to get double-buffering to work without flicker, I have to override the OnPaintBackground event like so:

protected override void OnPaintBackground(PaintEventArgs e)
{
    // don't even have to do anything else
}

This works great at runtime.  The problem is that when I have an instance of the control on a form at design time, it becomes a black hole that shows trails of whatever windows are dragged over it (because the override of the OnPaintBackground event also governs design-time appearance).  It's just a cosmetic problem, but it's visually jarring and it always leads new developers on the project to assume something has gone horribly wrong.

Is there any way to have an overridden method like this not be overridden at design time, or is there another solution?

[A]
```
```
if (this.DesignMode)
{
    return;    //or call base.OnPaintBackground()
}
```
```


q:
Method chaining is the only way I know to build fluent interfaces.

Here's an example in C#:

John john = new JohnBuilder()
    .AddSmartCode("c#")
    .WithfluentInterface("Please")
    .ButHow("Dunno");

Assert.IsNotNull(john);

  [Test]
    public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
    {
        DateTime now = DateTime.Now;

        IInvoice invoice = new InvoiceBuilder()
            .IssuedOn(now)
            .WithInvoiceNumber(40)
            .WithPaymentTerms(PaymentTerms.SevenDays)
            .Generate();

        Assert.IsTrue(invoice.DateDue == now.AddDays(7));
    }

So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?

[A]
Fluent interface is achieved in object oriented programming by always returning from your methods the same interface that contains the method. Consequently you can achieve this effect in java, javascript and your other favorite object oriented languages, regardless of version.
I have found this technique easiest to accomplish through the use of interfaces:
```
```
public interface IFoo
{
    IFoo SetBar(string s);
    IFoo DoStuff();
    IFoo SetColor(Color c);
}
```
```
In this way, any concrete class that implements the interface, gets the fluent method chaining capabilities.  FWIW.. I wrote the above code in C# 1.1
You will find this technique littered throughout the jQuery API


q:
Open  App.Path & "\Folder\" & str(0) For Output

Seems to get a path not found however if directly before that I do

MsgBox App.Path & "\Folder\" & str(0)

It Provides the correct directory/filename that I want

and if I replace that string with the direct path in quotes it works fine however that won't be very good for other users of my app :(  Anyone know why this doesn't work?

[A]
You can open a file that doesn't exist. I tried it with:
```
```
Open "c:\temp\test.txt" & Str(0) For Output As #1
  Close #1
```
```
When it ran it created c:\temp\test.txt 0
Note that I added "As #1" to the Open statement, and taht Str(0) adds a leading space for the optional minus sign (CStr(0) doens't add a leading space)


q:
On a site where 90% of the pages use the same libraries, should you just load the libraries all the time or only load them when needed? The other pages would be ajax or simple pages that don't have any real functionality.

Also, should you only load the code when needed? If part way down a page you need a library, should you load it then or just load it at the top. Maybe it's possible it may never get there before of an error or wrong data. (Loading at the top makes it somewhat easier to understand, but may result in extra code not needed.)

I'm also wondering if I should make the libraries more specific so I'm not say loading the code to edit at the same time as viewing?

Basically, how much should I worry about loading code or not loading code?

[A]
I would always try to give a file, class, and method a
single responsibility
. Because of that, separating the displaying from the editing code could be a good idea in either case.
As for loading libraries, I believe that the performance loss of including non required libraries could be quite irrelevant in a lot of cases. However,
```
include
```
,
```
require
```
,
```
include_once
```
, and
```
require_once
```
are relatively slow as they (obviously) access the file system. If the libraries you do not use on each occasion are quite big and usually include a lot of different files themselves, removing unnecessary includes could help reducing the time spent there. Nonetheless, this cost could also be reduced drastically by using an efficient caching system.
Given you are on PHP5 and your libraries are nicely split up into classes, you could leverage PHP's
auto loading functionality
which includes required classes as the PHP script needs them. That would pretty effectively avoid a lot of non used code to be included.
Finally, if you make any of those changes which could affect your website's performance, run some benchmarks and profile the gain or loss in performance. That way, you do not run into the risk of doing some possibly cool optimization which just costs too much time to fully implement or even degrades performance.


q:
I'm just starting out writing trying to write a simple program in C and I am using Visual Studios to do so. I heard that it does compile C as well as C++. And I know that it does because it says it compiles. The only problem is that when I go to the output directory, there isn't a .exe file in the directory! It has the following:

BuildLog.html

mt.dep

test1.obj

vc90.idb

vc90.pdb

But that is all! No EXE. I've looked through all the options and made sure that it is set to compile to an exe and i checked the output file. That is $(OutDir)\$(ProjectName).exe. But alas, no exe appears. Any ideas?

Also when i try to hit f5 and run with debut i get an error that says

This application has failed to start
  because MSVCR90.DLL was not found.
  Re-installing the application may fix
  this problem

[A]
is it a C/C++ console application?
did you use the project wizard to create it?
do you have a function like
```
```
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    printf("Hello, world!\n");
    return 0;
}
```
```
in a .c module, typically main.c?
what happens when you hit F5 to run-with-debug?
what does your build log look like?


q:
PHP provides a mechanism to register a shutdown function:

register_shutdown_function('shutdown_func');

The problem is that in the recent versions of PHP, this function is still executed DURING the request.

I have a platform (in Zend Framework if that matters) where any piece of code throughout the request can register an entry to be logged into the database.  Rather than have tons of individual insert statements throughout the request, slowing the page down, I queue them up to be insert at the end of the request.  I would like to be able to do this after the HTTP request is complete with the user so the length of time to log or do any other cleanup tasks doesn't affect the user's perceived load time of the page.

Is there a built in method in PHP to do this?  Or do I need to configure some kind of shared memory space scheme with an external process and signal that process to do the logging?

[A]
Aside from register_shutdown_function() there aren't built in methods for determining when a script has exited. However, the Zend Framework has several hooks for running code at specific points in the dispatch process.
For your requirements the most relevant would be the action controller's
post-dispatch hook
which takes place just after an action has been dispatched, and the
dispatchLoopShutdown event
for the controller plugin broker.
You should read the manual to determine which will be a better fit for you.
EDIT: I guess I didn't understand completely. From those hooks you could fork the current process in some form or another.
PHP has several ways to fork processes as you can read in the manual under
program execution
. I would suggest going over the pcntl extension - read
this blog post
to see an example of forking child processes to run in the background.


q:
I know a question like this was already asked, but the situation is a little different, and all the answers on that problem didn't work for me.

I'm trying to compile some C code in VS2008 and it doesn't create an exe. Also, when I try to run it with f5, I get:

This application has failed to start
  because MSVCR90.DLL was not found.

I did some googling and it said that this was because my c++ redistributable package wasnt installed. So I installed that, restarted everything and tried again. But alas, I still get the same error. Does anyone have any clue how to fix this?

[A]
It sounds like either a problem with your VS2008 installation, or something wrong with your DLL search path. MSVCR90.DLL is installed when you install VS2008, you shouldn't have to install any additional redistributable packages.
First I would check your PATH environment variable and make sure there is no gobbledydook in it that will break some of the entries, and if you don't find a problem there, then I would uninstall and reinstall Visual Studio.
You could also try searching for MSVCR90.DLL (and other DLLs like it), and move them to your Windows/System32 folder.
If you just want to get going now, another thing you could do is change your project to statically link to the runtime libraries, and then it wont even try to load that DLL. Go to your Project settings, Configuration Properties->C/C++->Code Generation and change Runtime Library from Multi-Threaded DLL to just Multi-Threaded (or any of the options that doesn't end with DLL).


q:
Does Lucene QueryParser.parse(string) still work?
If it is deprecated, what is the new syntax?

Query query = QueryParser.parse("Ophelia");

Thanks
Tatyana

[A]
Not sure of the exact API, but it's changed to an instance object. All QueryParsers are now instance objects.
```
```
var qp = new QueryParser(new StandardAnalyzer(),fields);
qp.Parse(inputString,fields);
```
```


q:
How can I pad a string with spaces on the left when using printf?

For example, I want to print "Hello" with 40 spaces preceding it.

Also, the string I want to print consists of multiple lines.  Do I need to print each line separately?

EDIT: Just to be clear, I want exactly 40 spaces printed before every line.

[A]
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.
```
```
char *ptr = "Hello";
printf("%40s\n", ptr);
```
```
That will give you 35 spaces, then the word "Hello".  This is how you format stuff when you know how wide you want the column, but the data changes (well, it's
one
way you can do it).
If you know you want exactly 40 spaces then some text, save the 40 spaces in a constant and print them.  If you need to print multiple lines, either use multiple
```
printf
```
statements like the one above, or do it in a loop, changing the value of
```
ptr
```
each time.


q:
I'm writing a simple program that's going to parse a logfile of a packet dump from wireshark into a more readable form. I'm doing this with python.

Currently I'm stuck on this part:

for i in range(len(linelist)):
if '### SERVER' in linelist[i]:
    #do server parsing stuff

    packet = linelist[i:find("\n\n", i, len(linelist))]

linelist is a list created using the readlines() method, so every line in the file is an element in the list. I'm iterating through it for all occurances of "### SERVER", then grabbing all lines after it until the next empty line(which signifies the end of the packet). I must be doing something wrong, because not only is find() not working, but I have a feeling there's a better way to grab everything between ### SERVER and the next occurance of a blank line.

Any ideas?

[A]
Looking at the
file.readlines()
doc:
file.readlines([sizehint])
Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.
and the
file.readline()
doc:
file.readline([size])
Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately.
```
A trailing newline character is kept in the string
```
- means that each line in
```
linelist
```
will contain at most
one
newline. That is why you cannot find a
```
"\n\n"
```
substring in any of the lines - look for
a whole blank line
(or an empty one at EOF):
```
```
if myline in ("\n", ""):
    handle_empty_line()
```
```
Note: I tried to explain
```
find
```
behavior, but a pythonic solution looks very different from your code snippet.


q:
I wonder what are the main challenges to porting those emulator engines.

Could there been any sucess without having to rewrite all the code? Any conversion tools available that can help?

[A]
Some people have tried but it seems they
gave up
:
scummvmxna
Other route could be the approach taken by
Cibyl
.


q:
I have a dropdown box and a literal tag inside an Update Panel.  On the selection change event of the dropdown up requery the database and repopulate the literal tag and then call UPdatePanel.Update().

below, is there are way i can avoid having to create a new Oledbconnection each time as this seems slow.  Can i reuse and store:

The Datasource

The connection in the page.

if so, how do i keep this state between calls from the GUI to the server?  Here is my selection change code below

protected void cboPeople_SelectedIndexChanged(object sender, EventArgs e)
{
    string dataSource = ConfigurationSettings.AppSettings["contactsDB"];
    var objConn = new OleDbConnection(dataSource);
    string id = People[cboPeople.Text];
    UpdateLiteral(objConn, id);
}

[A]
You need to recreate this for each request.  You have a a state less server.  you never know when or if your client will call back. You do not want to keep an open connection to the database nor could you simply service multiply clients while maintaining one database connection.
To deploy high-performance
  applications, you must use connection
  pooling. When you use the .NET
  Framework Data Provider for OLE DB,
  you do not have to enable connection
  pooling because the provider manages
  this automatically. For more
  information about how to use
  connection pooling with the .NET
  Framework Data Provider for OLE DB,
  see OLE DB, ODBC, and Oracle
  Connection Pooling (ADO.NET).
  From
OleDbConnection Class


q:
I am trying to send a user to another page using a Javascript Function:

<input type="button" name="confirm" value="nextpage" onClick="message()">

And my JavaScript:

function message() {
    ConfirmStatus = confirm("Install a Virus?");

    if (ConfirmStatus == true) {
        //Send user to another page
    }
}

Does anyone know how to send a user to another specific page?

[A]
I believe
```
window.location.href = "newpage.html";
```
will work.


q:
Is there a PHP version of JavaScript's confirm() function?

If not, what are my other options or how do I make something similar to the confirm()?

[A]
Because PHP is a server-side language (all the PHP code is executed on the server, and the output of the code is sent to the client), you'd have to make an HTML form with OK/Cancel buttons that would submit to your PHP page. Something like this:
confirm.php:
```
```

Are you sure you want to do this?

<form action="page2.php" method="post">
    <input type="submit" name="ok" value="OK" />
    <input type="submit" name="cancel" value="Cancel" />
</form>
```
```
page2.php:
```
```
<?php

if (isset($_POST['ok'])) {
    // They pressed OK
}

if (isset($_POST['cancel'])) {
    // They pressed Cancel
}

?>
```
```


q:
For example if I put "C:\docs" in address bar of Firefox, it shows all files in the directory. Is it possible to customize this page with CSS?

Apache 2.2 allows us to do it using IndexStyleSheet directive, so I wondered if Firefox can do it.

[A]
Firefox has a file userContent.css for each profile (found in the profile's settings folder). That file defines the standard CSS, why may then be overwritten by a website. So they also apply to directory listings.
You should have a look at the actual HTML code Firefox is creating for the directory listing to see how to do the CSS definitions right. You will find extensive documentation about userContent.css on the web.
http://www.mozilla.org/unix/customizing.html#userContent


q:
I would like to make apps that can run in a flash enabled browser and decided flex would be best for me so I started to learn that. AFAIK flex has a GC but how that GC works compared to the ones in other languages I've seen may be a bit different. I have found this but apparently there is (or were) huge memory leaks that could not be prevented and a lot worse when run in IE.

Is flex safe to trust now. Have any leak that were there been fixed?

[A]
A couple resources you can have a look at are :
Flex Bug Tracking
which you could peruse for memory leak bugs that have been fixed/logged. Also in the Flex Builder IDE you can use the Profiler to monitor memory/CPU usage etc. I cant specifically answer your question. I think that part of the responsibility here is on you, the developer, and how you have designed and managed your code. Apart from that, I have noticed using the Flex 3 framework (or ASVM2 in general) that it has done a good job of managing the GC for me. Keep in mind as well that Flex 4 is around the corner.


q:
What are the basic steps for Agile software development?

And how you start a new project with agile methodology?

[A]
have a look at "Agile Software Development, Principles, Patterns, and Practices" by robert marin. there is a java and a c# version.
http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445


q:
I have a ASP.NET project and when building the project it is showing build suceessfull. But when I am building the deployment project, it is showing build failed with an error message

Error    5    "aspnet_compiler.exe" exited with code 1

I rechecked my project and found that when i am removing the line <!--#include file="admin/topstyle.asp"-->, it is working fine. If I use this line, I am getting error building web deployment project to create my dll.

topstyle.asp is a file which render some common styles for the page like heading image and all.

Can anyone tell me how to get rid of this problem?

[A]
Does it work successfully on other pages? Also is the Topstyle.asp page a ASP.NET page? If not it will not work as you can't mix the two technologies like that.
In ASP.NET the include syntax is discouraged. Try using a user control instead, or the <%= Globals.MyConstantThatContainsTheStyles %>.
If you are using ASP 2.0 look at using Master Pages, but that might be a big change for your app.


q:
I'm writing a file that requires dates to be in decimal format:

2007-04-24T13:18:09 becomes 39196.554270833331000

Does anyone have a time formatter that will do this (Decimal time is what VB/Office, etc. use)?

Basic code goes like follows:

final DateTime date = new DateTime(2007, 04, 24, 13, 18, 9, 0, DateTimeZone.UTC);
double decimalTime = (double) date.plusYears(70).plusDays(1).getMillis() / (Days.ONE.toStandardDuration().getMillis())); //=39196.554270833331000.

For the example above.

(I started on a DateTimePrinter that would do this, but it's too hard for now (I don't have the joda source linked, so I can't get ideas easily)).

Note: Decimal time is the number of days since 1900 - the . represents partial days.  2.6666666 would be 4pm on January 2, 1900

[A]
What's wrong with the
getTime()
method?


q:
I'd like to rank my stories based on "controversy" quotient. For example, reddit.com currently has "controversial" section: http://www.reddit.com/controversial/

When a story has a lot of up and a lot of down votes, it's controversial even though the total score is 0 (for example). How should I calculate this quotient score so that when there's a lot of people voting up and down, I can capture this somehow.

Thanks!!!

Nick

[A]
The easiest method is to count the number of upvote/downvote pairings for a given comment within the timeframe (e.g. 1 week, 48 hours etc), and have comments with the most parings appear first.  Anything more complex requires trial-and-error or experimentation on the best algorithm - as always, it varies on the content of the site and how you want it weighted.
Overall, it's not much different than a hotness algorithm, which works by detecting the most upvotes or views within a timeframe.


q:
I would like to know what kinds of builds (i.e for example and learning) does one have.

I currently set up nightly build triggered on changes..

Should I have a different server for ci builds or different config blocks???

Please give ideas or samples on how you maintain CI and nightly build in config

[A]
We use one build machine (a slightly older desktop pc at the moment, going to be in the server rack soon), with multiple project blocks in the configuration.
We have several main projects:
Debug (triggered automatically every hour)
Test(integration & unit tests) (triggered once a day)
Release (manually triggered, also does the integration and unit tests)
this seems to work well for our team of 12, however it would depend on your team size, release frequency and whether you do nightly builds for beta users.


q:
is it possible to use the ajaxComplete or ajaxStop features of jQuery to decide whether or not the callback gets called?

Essentially I want to be able to take basic error checking code that is currently in most of my callbacks, and add it to a sort of global callback.

[A]
Sort answer: No.
Long answer: Both
```
ajaxComplete
```
and
```
ajaxStop
```
are jQuery AJAX events. You cannot prevent events from happening - and "event" means nothing else as "execute every callback function that has been registered". Callbacks get called regardless, if you want or not.
What you
can
do is program your callback so that it does
nothing
when certain requirements are (or are not) met. In effect this is exactly what you asked for. If you edit your question to explain what you're up to exactly, people can show you how to do it.


q:
A few weeks back I was using std::ifstream to read in some files and it was failing immediately on open because the file was larger than 4GB. At the time I couldnt find a decent answer as to why it was limited to 32 bit files sizes, so I wrote my own using native OS API.

So, my question then: Is there a way to handle files greater than 4GB in size using std::ifstream/std::ostream (IE: standard c++)

EDIT: Using the STL implementation from the VC 9 compiler (Visual Studio 2008).
EDIT2: Surely there has to be standard way to support file sizes larger than 4GB.

[A]
Apparently it depends on how
```
off_t
```
is implemented by the library.
```
```
#include <streambuf>
__int64_t temp=std::numeric_limits<std::streamsize>::max();
```
```
gives you what the current max is.
STLport
supports larger files.


q:
I am getting the following error when an event (Add/Edit/Delete) occurs on my databound control.

Invalid postback or callback argument.
  Event validation is enabled using in
  configuration or <%@ Page
  EnableEventValidation="true" %> in a
  page. For security purposes, this
  feature verifies that arguments to
  postback or callback events originate
  from the server control that
  originally rendered them. If the data
  is valid and expected, use the
  ClientScriptManager.RegisterForEventValidation
  method in order to register the
  postback or callback data for
  validation.

I am using a custom DataList control, but this problem also occurs with GridView, DetailsView, FormView and Repeater control (and maybe with other databound controls).

The answers I can find tell me to turn off the validation in the config file or page, but that does not sound like it is the best solution. What am I doing wrong?

[A]
The problem is loading the data for the control in the page Load event and calling the  DataBind() method. However it appears that if the DataBind() method is called before the events are raised the above exception is generated as the control naming has changed.
The solution is to change this to if(!IsPostback) DataBind() and then call the DataBind() method at the end of the event handler. You would need to call it most of the time anyway at the end of the handler to affect the changes.
If this is not your problem, and you are modifying controls client side using JavaScript, check out
this article
.
This is a self answered post as I was getting a lot of responses on my blog to this issue and thought I might share it further.


q:
i need a Regular Expression to convert a a string to a link.i wrote something but it doesnt work in asp.net.i couldnt solve and i am new in Regular Expression.This function converts (bkz: string) to (bkz: show.aspx?td=string)

Dim pattern As String = "&lt;bkz[a-z0-9$-$&-&.-.ö-öı-ış-şç-çğ-ğü-ü\s]+)&gt;"
Dim regex As New Regex(pattern, RegexOptions.IgnoreCase)
str = regex.Replace(str, "<a href=""show.aspx?td=$1""><font color=""#CC0000"">$1</font></a>")

[A]
Your regexp is in trouble because of a ')' without '('
Would:
```
```
<bkz:\s+((?:.(?!>))+?.)>
```
```
work better ?
The first group would capture what you are after.


q: How can I make Emacs show blank spaces (like a space, a tab, a line-jump, etc). Many other editors like Kate and Eclipse have this feature and I find it very useful to see when code is indent-broken because of mix of spaces and tabs (particularly Python).

[A]
All the possible settings to do that seem to be
summarized here (blank-mode)
and here
and here (ShowWhiteSpace)
also:
```
```
(if (>= emacs-major-version 22)
  (progn
    ;; Mode to use with Emacs 22
    ;; http://emacswiki.org/cgi-bin/wiki/BlankMode
    (require 'blank-mode)
    ;; Mode not active by default: let's activate it
    (global-blank-mode t)
    ;; ... activate it when text mode where color syntax is not active by default
    (add-hook 'text-mode-hook 'blank-mode-on)
    ;; All invisible chars are shown, except newline char.
    (setq blank-chars '(tabs spaces trailing lines space-before-tab))
    ;; Show only for one color, no mark inserted
    (setq blank-style '(color))
    ;; Use for normal space (not shown)
    (set-face-background 'blank-space-face nil)
    (set-face-foreground 'blank-space-face "black")
    ;; used for non breakable space
    (set-face-background 'blank-hspace-face "PaleGreen")
    (set-face-foreground 'blank-hspace-face "black")
    ;; Used for spaces left of a tab
    (set-face-background 'blank-space-before-tab-face "orange")
    (set-face-foreground 'blank-space-before-tab-face "black")
    ;; Used for tab
    (set-face-background 'blank-tab-face "lemonchiffon")
    (set-face-foreground 'blank-tab-face "black")
    ;; used for extra space at the end of a line
    (set-face-background 'blank-trailing-face "gold")
    (set-face-foreground 'blank-trailing-face "black")
    ;; Used for line too long
    (set-face-background 'blank-line-face "snow2")
    (set-face-foreground 'blank-line-face "black")
  )
  (progn
    ;; For older Emacs prior to version 22.
    ;; http://www.emacswiki.org/cgi-bin/wiki/show-wspace.el
    (require 'show-wspace)
    (add-hook 'font-lock-mode-hook 'show-ws-highlight-tabs)
    (add-hook 'font-lock-mode-hook 'show-ws-highlight-hard-spaces)
    (add-hook 'font-lock-mode-hook 'show-ws-highlight-trailing-whitespace)
  )
)
```
```


q:
I can't directly add ChartFrame object to my Jframe object with .add(Component) method. And it's not possible to cast from ChartFrame to JComponent. Casting ChartFrame to Component from java.awt library is also impossible.

How can I add ChartFrame to JFrame the other way?

[A]
That would mean inserting a JFrame within another JFrame.
A possible solution would be to use a
JDesktopPane
```
```
JDesktopPane desktop = ...
JFrame frame = ...

frame.setContentPane(desktop);

JInternalFrame internalFrame = ...
desktop.add(internalFrame);
```
```


q:
With wxWidgets I use the following code:

HWND main_window = ...
...
wxWindow *w = new wxWindow();
wxWindow *window = w->CreateWindowFromHWND(0, (WXHWND) main_window);

How do I do the same thing in Qt? The HWND is the handle of the window I want as the parent window for the new QtWidget.

[A]
Have you tried the
```
QWinWidget
```
class from the
Qt/MFC Migration Framework
?


q:
Is there a way to get the amount of free diskspace of a disk or a folder in a CMD
without having to install some thirdparty applications?

I have a CMD that copies a big file to a given directory and could of course use
the errorlevel return from the copy command, but then I have to wait for the time
it takes to copy the file (eg...to that then the disk is full and the copy operation fails).

I would like to know before I start the copy if it is any idea at all. Tried the DU.EXE utility from Sysinternals, but that show occupied space only.

[A]
If you run "
```
dir c:\
```
", the last line will give you the free disk space.
Edit:
Better solution: "
```
fsutil volume diskfree c:
```
"