q: Is it possible to cache database connections when using PHP like you would in a J2EE container?  If so, how?

[A]
You cannot instantiate connection pools manually.
But you can use the "built in" connection pooling with the
mysql_pconnect
function.


q:
From a web developer point of view, what changes are expected in the development arena when Google Chrome is released?

Are the developments powerful enough to make another revolution in the web? Will the way we see web programming change?

Or is it just another web browser?

[A]
I think this is just another web browser. The most impact I expect to be improved Javascript performance, and the usability perspective. The first will benefit developers, especially when using Google Gears. I think the users will benefit the most from an enhanced user experience, the safety features, and ease of use.
I can only hope other browser vendors (MS) will follow Mozilla and Google to create a faster Javascript implementation, since this is the only thing that can truly impact web development.

s: huggingface

c: devops

d: intermediate


q: Things like $log$ and $version$ which add data upon check-in to the file. I'm interested in seeing the other ones and what information they can provide, but I can't get much info unless I know what they are called.

[A]
Both Subversion and CVS call them
```
Keywords
```
.
Have a look in the SVN manual here
(scroll down to
svn:keywords
) or
here for CVS
.


q:
Is a GUID unique 100% of the time?

Will it stay unique over multiple threads?

[A]
While each generated GUID is not
guaranteed to be unique, the total
number of unique keys (2
128
or
3.4×10
38
) is so large that the probability of the same number being
generated twice is very small. For
example, consider the observable
universe, which contains about 5×10
22
stars; every star could then have
6.8×10
15
universally unique GUIDs.
From
Wikipedia
.
These are some good articles on how a GUID is made (for .NET) and how you could get the same guid in the right situation.
https://ericlippert.com/2012/04/24/guid-guide-part-one/
https://ericlippert.com/2012/04/30/guid-guide-part-two/
https://ericlippert.com/2012/05/07/guid-guide-part-three/


q: Here's my scenario - I have an SSIS job that depends on another prior SSIS job to run. I need to be able to check the first job's status before I kick off the second one. It's not feasible to add the 2nd job into the workflow of the first one, as it is already way too complex. I want to be able to check the first job's status (Failed, Successful, Currently Executing) from the second one's, and use this as a condition to decide whether the second one should run, or wait for a retry. I know this can be done by querying the MSDB database on the SQL Server running the job. I'm wondering of there is an easier way, such as possibly using the WMI Data Reader Task? Anyone had this experience?

[A]
You may want to create a third package the runs packageA and then packageB.  The third package would only contain two execute package tasks.
http://msdn.microsoft.com/en-us/library/ms137609.aspx
@Craig
A status table is an option but you will have to keep monitoring it.
Here is an article about events in SSIS for you original question.
http://www.databasejournal.com/features/mssql/article.php/3558006


q:
I have an SQL query that takes the following form:

UPDATE foo
SET flag=true
WHERE id=?

I also have a PHP array which has a list of IDs. What is the best way to accomplish this other than with parsing, as follows, ...

foreach($list as $item){
    $querycondition = $querycondition . " OR " . $item;
}

... and using the output in the WHERE clause?

[A]
You should be able to use the IN clause (assuming your database supports it):
```
UPDATE foo
SET flag=true
WHERE id in (1, 2, 3, 5, 6)
```


q:
I have an actionscript file that defines a class that I would like to use inside a Flex application.

I have defined some custom controls in a actionscript file and then import them via the application tag:

<mx:Application
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:scorecard="com.apterasoftware.scorecard.controls.*"
...
</mx:Application>

but this code is not a flex component, rather it is a library for performing math routines, how do I import this class?

[A]
You'd need to import the class inside a script tag.
```
```
<mx:Application
  xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Script>
    import com.apterasoftware.scorecard.controls.*;
    // Other imports go here

    // Functions and other code go here
  </mx:Script>

  <!-- Components and other MXML stuff go here -->
  <mx:VBox>
    <!-- Just a sample -->
  </mx:VBox>
</mx:Application>
```
```
Then you'll be able to reference that class anywhere else in your script tag.  Depending on how the class is written you may not be able to use binding within the MXML, but you could define your own code to handle that.
Namespace declarations are only used to import other MXML components.  AS classes are imported using the import statement either within a Script block or another AS file.


q: What data structures would you use to represent a chessboard for a computer chess program?

[A]
The simple approach is to use an 8x8 integer array. Use 0 for empty squares and assign values for the pieces:
```
```
1 white pawns
2 white knights
3 white bishops
4 white rooks
5 white queens
6 white king

Black pieces use negative values
-1 black pawn
-2 black knight
etc

8| -4 -2 -3 -5 -6 -3 -2 -4
7| -1 -1 -1 -1 -1 -1 -1 -1
6|  0  0  0  0  0  0  0  0
5|  0  0  0  0  0  0  0  0
4|  0  0  0  0  0  0  0  0
3|  0  0  0  0  0  0  0  0
2|  1  1  1  1  1  1  1  1
1|  4  2  3  5  6  3  2  4
  -------------------------
   1  2  3  4  5  6  7  8
```
```
Piece moves can be calculated by using the array indexes. For example the white pawns move by increasing the row index by 1, or by 2 if it's the pawn's first move. So the white pawn on [2][1] could move to [3][1] or [4][1].
However this simple 8x8 array representation of has chessboard has several problems. Most notably when you're moving 'sliding' pieces like rooks, bishops and queens you need to constantly be checking the indexes to see if the piece has moved off the board.
Most chessprograms today, especially those that run on a 64 bit CPU, use a bitmapped approach to represent a chessboard and generate moves. x88 is an alternate board model for machines without 64 bit CPUs.


q:
The IE Developer Toolbar is a plugin that can dock or separate from the browser. I understand its much more difficult to do this in IE than in Firefox.

How does one create an IE plugin?

What languages are available for this task?

How can I make a Hello World plugin?

[A]
Here are a few resources that might help you in your quest to create browser helper objects (BHO).
http://petesearch.com/wiki/ (archived)
http://www.hackszine.com/blog/archive/2007/06/howto_port_firefox_extensions.html
http://msdn.microsoft.com/en-us/library/ms182554(VS.80).aspx
http://www.codeplex.com/TeamTestPlugins


q: I want to use the  MultipleLookupField control in a web page that will run in the context of SharePoint. I was wondering if anyone would help me with an example, which shows step by step how to use the control two display two SPField Collections.

[A]
I'm not entirely sure I understand your question, especially the bit about displaying two SPField collections. Sorry if this turns out to be the answer to a completely different question!
Anyway here's a quick demo walkthrough of using the MultipleLookupField in a web part.
Create a team site. Add a few tasks to the task list. Also put a document in the Shared Documents library. Create a new column in the Shared Documents library; call it "Related", have it be a Lookup into the Title field of the Tasks list, and allow multiple values.
Now create a web part, do all the usual boilerplate and then add this:
```
```
Label l;
MultipleLookupField mlf;

protected override void CreateChildControls()
{
    base.CreateChildControls();
    SPList list = SPContext.Current.Web.Lists["Shared Documents"];
    if (list != null && list.Items.Count > 0)
    {
        LiteralControl lit = new LiteralControl("Associate tasks to " +
                             list.Items[0].Name);
        this.Controls.Add(lit);

        mlf = new MultipleLookupField();
        mlf.ControlMode = SPControlMode.Edit;
        mlf.FieldName = "Related";
        mlf.ItemId = list.Items[0].ID;
        mlf.ListId = list.ID;
        mlf.ID = "Related";
        this.Controls.Add(mlf);

        Button b = new Button();
        b.Text = "Change";
        b.Click += new EventHandler(bClick);
        this.Controls.Add(b);

        l = new Label();
        this.Controls.Add(l);
    }

}

void bClick(object sender, EventArgs e)
{
    l.Text = "";
    foreach (SPFieldLookupValue val in (SPFieldLookupValueCollection)mlf.Value)
    {
        l.Text += val.LookupValue.ToString() + " ";
    }
    SPListItem listitem = mlf.List.Items[0];
    listitem["Related"] = mlf.Value;
    listitem.Update();
    mlf.Value = listitem["Related"];
}

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    EnsureChildControls();
}
```
```
Granted, this is borderline ridiculous -- everything is hard-coded, there is no error-handling at all, and it serves no useful purpose -- but it's only meant as a quick demo. Now build and deploy this web part and add an instance of it to your team site's homepage; it should allow you to get and set the tasks which are associated with the first document in the library.
The strange bit towards the end of the button Click handler, where we read a value from mlf.Value and then write it back again, appears to be required if you want the UI to stay in sync with the actual list values. Try omitting the last line of bClick to see what I mean. This has been driving me nuts for the last hour or so, and I'm hoping another commenter can come up with a better approach...


q: I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.

[A]
Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove the elements.
Documentation links
std::remove
http://www.cppreference.com/cppalgorithm/remove.html
std::vector.erase
http://www.cppreference.com/cppvector/erase.html
```
```
std::vector<int> v;
v.push_back(1);
v.push_back(2);

//Vector should contain the elements 1, 2

//Find new end iterator
std::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);

//Erase the "removed" elements.
v.erase(newEnd, v.end());

//Vector should now only contain 2
```
```
Thanks to Jim Buck for pointing out my error.


q: Windows has a feature that allows an administrator to perform auto-logon whenever it is started. How can this feature be activated?

[A]
Based on the advice, moved the answer to the answers section:
There are tools out there that give you a GUI for setting this easily, but you can also do it relatively easily by editing the registry.
Under the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
Add the following values:
DefaultDomainName     String  < domain-name >
DefaultUserName   String  < username >
DefaultPassword   String  < password >
AutoAdminLogon    String  1
Important: Using auto-logon is insecure and should, in general, never be used for standard computer configurations. The problem is not only that your computer is accessible to anyone with physical access to it, but also that the password is saved in plain-text in a well known location in your registry. This is usually used for test environments or for special setups. This is even more important to notice if you intend to perform auto-logon as an administrator.


q: I'm getting a Connection Busy With Results From Another Command error from a SQLServer Native Client driver when a SSIS package is running. Only when talking to SQLServer 2000. A different part that talks to SQLServer 2005 seems to always run fine. Any thoughts?

[A]
Microsoft KB article 822668
is relevant here:
FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query
Symptoms
Under stress conditions, you may receive the following error message when you perform linked server activity:
```
```
Server: Msg 7399, Level 16, State 1, Procedure <storedProcedureName>, Line 18 OLE DB provider 'SQLOLEDB' reported an error.
OLE/DB Provider 'SQLOLEDB' ::GetSchemaLock returned 0x80004005:

OLE DB provider SQLOLEDB supported the Schema Lock interface, but returned 0x80004005 for GetSchemaLock .].
OLE/DB provider returned message: Connection is busy with results for another command
OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ::CreateSession returned 0x80004005.
```
```
Note
The OLE DB source of the error may vary. However, all variations of the error message include the text "Connection is busy with results for another command".
Resolution
To resolve this problem, obtain the latest service pack for Microsoft SQL Server 2000.
As noted there, the problem was first corrected in SQL Server 2000 Service Pack 4.
This blog post
by Mark Meyerovich, a Senior Software Engineer at RDA Corp, also provides some insight (now archived, because the original link went dead):
SQL Server service pack upgrade
A quick search on Google turns up the following article (
http://support.microsoft.com/kb/822668
):
  FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query.
It basically implies the issue is a bug and recommends an upgrade to Service Pack 4. We have started out with SQL Server 2000 SP3 and we do have some linked servers in the equation, so we give it a try. After the upgrade to SP4 – same result.


q:
I'm trying to boil down the concepts of coupling and cohesion to a concise definition. Can someone give me a short and understandable explanation (shorter than the definitions on Wikipedia here and here)? How do they interact?

Thanks.

Anybody have a good, short example?

[A]
Coupling - A measure of how much a module (package, class, method) relies on other modules. It is desirable to reduce coupling, or reduce the amount that a given module relies on the other modules of a system.
Cohesion - A measure of how closely related the members (classes, methods, functionality within a method) of a module are to the other members of the same module. It is desirable to increase cohesion as that indicates that a module has a very specific task and does only that task.


q:
In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals().  Is there some equivalent way of doing this in Javascript?  For instance, I would like to do something like the following:

var foo = function(){ alert('foo'); };
var bar = function(){ alert('bar'); };

var s = 'foo';
locals()[s](); // alerts 'foo'

Is this at all possible, or should I just be using a local object for the lookup?

[A]
Well, I don't think that there is something like that in js. You can always use eval instead of locals(). Like this:
```
```
eval(s+"()");
```
```
You just have to know that actually function
foo
exists.
Edit:
Don't use eval:) Use:
```
```
var functionName="myFunctionName";
window[functionName]();
```
```


q:
I know how to use tags in subversion. I create a tag every time I get to a release milestone.

What I don't quite understand is how they work.

Is a tag just a copy, made from what ever revision I specify? Or is a tag more like a reference, where internally subversion just says GO TO /trunk/project/ Revision 5 or whatever.

The command to create a tag (svn copy) seems to imply that it's a copy, but I've seen other people write that subversion doesn't really copy anything.

Say I dump just the HEAD revision of a repository. I don't care about any history except the tags. Are those tags dumped along with the rest of the Head revision?

Finally, is all this just programming magic that I don't really want to know.

[A]
Right, a tag is just a copy:
```
```
svn copy trunk tags/BLAH
```
```
When people say SVN doesn't really copy anything, they mean that the repository doesn't need to duplicate the data. It uses something akin to symbolic links to keep track of the copies.


q: How do I create a new webpage in the Documentum front end Webtop?

[A]
Why WebTop?  You should use Web Publisher which is built on WebTop with the specific purpose of managing web content. Is this an OOTB installation?  Web Publisher / WebTop requires significant amount of customization in order to start being useful.  Do you have templates defined?  If so, then just go to File New and select your template.
http://www.dmdeveloper.com/
Is a good site with some very good how-to's.


q: As the title says, is there a way to run the same Adobe AIR app more than once?  I have a little widget I wrote that shows thumbnails from a couple of photo streams, and I'd like to fix it so I can look at more than  one stream at a time.  Thanks!

[A]
It seems that this is not possible. From the
documentation
:
Only one instance of an AIR application is started. When an already running application is invoked again, AIR dispatches a new invoke event to the running instance.
It also gives a possible workaround:
It is the responsibility of an AIR to respond to an invoke event and take the appropriate action (such as opening a new document window).
There is
already a bug
related to this on the bugtracker, but it is marked closed with no explicit resolution given...


q:
How can I create a new database from my C# application?

I'm assuming once I create it, I can simply generate a connection string on the fly and connect to it, and the issue all the  CREATE TABLE statements.

[A]
KB307283
explains how to create a database using ADO.NET.
From the article:
```
```
String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");

str = "CREATE DATABASE MyDatabase ON PRIMARY " +
    "(NAME = MyDatabase_Data, " +
    "FILENAME = 'C:\\MyDatabaseData.mdf', " +
    "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
    "LOG ON (NAME = MyDatabase_Log, " +
    "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
    "SIZE = 1MB, " +
    "MAXSIZE = 5MB, " +
    "FILEGROWTH = 10%)";

SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
    myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
    if (myConn.State == ConnectionState.Open)
    {
        myConn.Close();
    }
}
```
```


q:
Code below does not run correctly and throws InvalidOperationExcepiton.

public void Foo()
{
 DataContext context = new DataContext();
 LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ;
 context.LinqEntities.Attach(item, true);
}

[A]
I'm not sure what you mean by disconnected from the database.
It appears that you are trying to insert a new row into the LinqEntities table -- is that correct?
If that is the case you'll want to do
```
```
context.LinqEntities.InsertOnSubmit(item);
context.Submit();
```
```


q:
I am writing a few extensions to mimic the map and reduce functions in Lisp.

public delegate R ReduceFunction<T,R>(T t, R previous);
public delegate void TransformFunction<T>(T t, params object[] args);

public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial)
{
     var aggregate = initial;
     foreach(var t in list)
         aggregate = r(t,aggregate);

     return aggregate;
}
public static void Transform<T>(this List<T> list, TransformFunction<T> f, params object [] args)
{
    foreach(var t in list)
         f(t,args);
}

The transform function will cut down on cruft like:

foreach(var t in list)
    if(conditions && moreconditions)
        //do work etc

Does this make sense? Could it be better?

[A]
I would use the built in Func delegates instead.  This same code would work on any IEnumerable.  Your code would turn into:
```
```
public static R Reduce<T,R>(this IEnumerable<T> list, Func<T,R> r, R initial)
{
     var aggregate = initial;
     foreach(var t in list)
         aggregate = r(t,aggregate);

     return aggregate;
}
public static void Transform<T>(this IEnumerable<T> list, Func<T> f)
{
    foreach(var t in list)
             f(t);
}
```
```


q:
Is it true that the only way to handle default function arguments is through function overloading?

For example, in PHP I can do this:

function foo($x, $y=0)
{
}

Would the best way to handle it in C# be this?

void foo(int x)
{
  foo(x, 0);
}

void foo(int x, int y)
{
}

Example lifted from here

Edit

Made the C# example into actual C# (Thanks Blair Conrad)

[A]
Yes, that'd be best
, except you'd omit the
```
$
```
s on the parameter names
, as others have pointed out. For those interested in the rationale behind the lack of default parameter values, see @Giovanni Galbo's explanation.


q:
I've got an MS-Access app (1/10th MS-Acccess, 9/10ths MS-SQL) that needs to display photographs of some assets along with their specifications. Currently the images are stored in an MS-Access table as an OLE Object (and copy-n-pasted into the field by the users).

For various reasons, I would like to do is store the original .jpgs in a folder on the network drive, and reference them from the application portion. I have considered moving into MS-SQL's image data type (and its replacement varbinary), but I think my user population will more easily grasp the concept of the network folder.

How can I get MS Access to display the contents of a .jpg?

[A]
The easiest way is probably to plop an Internet Explorer onto one of your forms. Check out this site:
http://www.acky.net/tutorials/vb/wbrowser/
Since you can reference that object in Access, you will only need to point the webbrowser control to the path of the .jpg (NavigateTo() if I remember correctly).
EDIT:
The above link was just googled and picked from the results (first one that opened quickly). I do not think it is a very good tutorial, it just has all the pointers you need... Check out msdn etc. if you need more information!


q:
How do I get it to work with my project?

http://ajax.asp.net/

http://www.codeplex.com/AjaxControlToolkit/

[A]
Install the ASP.NET AJAX Control Toolkit
Download the ZIP file
AjaxControlToolkit-Framework3.5SP1-DllOnly.zip
from the
ASP.NET AJAX Control
Toolkit Releases
page of the
CodePlex web site.
Copy the contents of this zip file
directly into the bin directory of
your web site.
Update web.config
Put this in your web.config under the <controls> section:
```
```
<?xml version="1.0"?>
<configuration>
    ...
    <system.web>
        ...
        <pages>
            ...
            <controls>
                ...
                <add tagPrefix="ajaxtoolkit"
                    namespace="AjaxControlToolkit"
                    assembly="AjaxControlToolKit"/>
            </controls>
        </pages>
        ...
    </system.web>
    ...
</configuration>
```
```
Setup Visual Studio
Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"
Inside that tab, right-click on the Toolbox and select "Choose Items..."
When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.
You can now use the controls in your web sites!


q:
I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu.

My quesion then is: Does anyone have any sample code that will do this?

[A]
Having never developed one myself, I'm not certain how this is typically done in Firefox plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request:
```
```
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);

xmlhttp.onreadystatechange = function() {
    if(this.readyState == 4) { // Done loading?
        if(this.status == 200) { // Everything okay?
            // read content from this.responseXML or this.responseText
        } else { // Error occurred; handle it
            alert("Error " + this.status + ":\n" + this.statusText);
        }
    }
};

xmlhttp.send(null);
```
```
A couple of notes on this code:
You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found
here
.
You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time.
You may want to do things when earlier readyStates are received.
This page
documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful.


q:
I have a very strange problem. Under some elusive circumstances I fail to apply any jQuery selector on my pages under IE. It's OK under Firefox though. The jQuery function simply returns empty array.

Any suggestions?

Page is too complex to post it here. Practically any selector, except "#id" selectors, returns a zero element array. The jQuery version is 1.2.3

[A]
What version(s) of IE is it failing under? Is it failing for a specific complex selector? I think we need an example.
Edit: Does the problem go away if you upgrade to 1.2.6? 1.2.6 is primarily a bug-fix release according to
this page
.
Failing that, the best way to find the problem is to create a minimum page that can reproduce the bug. Without that, it's just about impossible to troubleshoot.


q:
Does C# have built-in support for parsing strings of page numbers?  By page numbers, I mean the format you might enter into a print dialog that's a mixture of comma and dash-delimited.

Something like this:

1,3,5-10,12

What would be really nice is a solution that gave me back some kind of list of all page numbers represented by the string.  In the above example, getting a list back like this would be nice:

1,3,5,6,7,8,9,10,12

I just want to avoid rolling my own if there's an easy way to do it.

[A]
It doesn't have a built-in way to do this, but it would be trivial to do using String.Split.
Simply split on ',' then you have a series of strings that represent either page numbers or ranges. Iterate over that series and do a String.Split of '-'. If there isn't a result, it's a plain page number, so stick it in your list of pages. If there is a result, take the left and right of the '-' as the bounds and use a simple for loop to add each page number to your final list over that range.
Can't take but 5 minutes to do, then maybe another 10 to add in some sanity checks to throw errors when the user tries to input invalid data (like "1-2-3" or something.)


q:
I infrequently (monthly/quarterly) generate hundreds of Crystal Reports reports using Microsoft SQL Server 2005 database views.  Are those views wasting CPU cycles and RAM during all the time that I am not reading from them?  Should I instead use stored procedures, temporary tables, or short-lived normal tables since I rarely read from my views?

I'm not a DBA so I don't know what's going on behind the scenes inside the database server.

Is it possible to have too many database views?  What's considered best practice?

[A]
For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT * FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 views.
However, from a people-perspective, trying to manage and figure out what "hundreds" of views are doing is probably impossible, so you likely have a lot of duplicated code in there. What happens if some business rules change that are embedded in these redundant views?
The main point of views is to encapsulate business logic into a pseudo table (so you may have a person table, but then a view called "active_persons" which does some magic). Creating a view for each report is kind of silly unless each report is so isolated and unique that there is no ability to re-use.


q:
The ASP page gets data uses that to draw a graph, I then need to save the image created to JPEG to be displayed on the browser and also used in PDF and other format. What is the best way to compress the image? I am currently porting a JPEG compression library to ASP but I think it will be too slow on this ARM device running Windows CE 6.0.

So, the ASP page, running in Windows CE webservers, gets data, renders it into a bitmap image than then needs to be delivered to the browser accessing that ASP page. The same image is also used in PDF and one other proprietary format that can contain JPEG streams.

Edit:
What I am looking for is to way to create an array representing a bitmap and then compressing it to JPEG with ASP in Windows CE's IIS which has quite limited ASP implementation.

[A]
I'm confused...
The images from ASP would be compressed on the server side--not client side.
I'm sure your web server is not running on Windows CE, so I don't think your concern is warranted.
EDIT:
Seems as though you can run a web server on Windows CE:
http://www.microsoft.com/windows/embedded/products/windowsce/default.mspx
.  I'll keep my thoughts to myself from now on. :-x


q:
I've got to get a directory listing that contains about 2 million files, but when I do an ls command on it nothing comes back. I've waited 3 hours. I've tried ls | tee directory.txt, but that seems to hang forever.

I assume the server is doing a lot of inode sorting. Is there any way to speed up the ls command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time.

[A]
How about
```
find ./ -type f
```
(which will find all files in the currently directory)?  Take off the
```
-type f
```
to find everything.


q:
I have a flag enum below.

[Flags]
public enum FlagTest
{
    None = 0x0,
    Flag1 = 0x1,
    Flag2 = 0x2,
    Flag3 = 0x4
}

I cannot make the if statement evaluate to true.

FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;

if (testItem == FlagTest.Flag1)
{
    // Do something,
    // however This is never true.
}

How can I make this true?

[A]
For bit operations, you need to use bitwise operators.
This should do the trick:
```
```
if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)
{
    // Do something,
    // however This is never true.
}
```
```
Edit:
Fixed my if check - I slipped back into my C/C++ ways (thanks to Ryan Farley for pointing it out)


q:
Is there an easy way to find the storage card's path on a Windows Mobile device
when there is a storage card and a bluetooth ftp connection?

[A]
On Windows CE 5 (which is the base for Windows Mobile 6) the storage cards get mounted at the root file system as "Storage Card\", "Storage Card2\", etc.
To find out if it's mounted call GetFileAttributes (or the remote version CeGetFileAttributes I believe) passing in the full path ("\Storage Card\"). If it returns INVALID_FILE_ATTRIBUTES then it's not mounted, otherwise check to make sure it's a directory before returning true.


q:
A client of mine has asked me to integrate a 3rd party API into their Rails app.  The only problem is that the API uses SOAP.  Ruby has basically dropped SOAP in favor of REST.  They provide a Java adapter that apparently works with the Java-Ruby bridge, but we'd like to keep it all in Ruby, if possible.  I looked into soap4r, but it seems to have a slightly bad reputation.

So what's the best way to integrate SOAP calls into a Rails app?

[A]
Try
SOAP4R
SOAP4R
Getting Started with SOAP4R
And I just heard about this on the Rails Envy Podcast (ep 31):
WS-Deathstar SOAP walkthrough


q:
I have an NFS-mounted directory on a Linux machine that has hung. I've tried to force an unmount, but it doesn't seem to work:

$ umount -f /mnt/data
$ umount2: Device or resource busy
$ umount: /mnt/data: device is busy

If I type "mount", it appears that the directory is no longer mounted, but it hangs if I do "ls /mnt/data", and if I try to remove the mountpoint, I get:

$ rmdir /mnt/data
rmdir: /mnt/data: Device or resource busy

Is there anything I can do other than reboot the machine?

[A]
You might try a lazy unmount:
```
```
umount -l
```
```


q: I am a member of all the roles (Browser, Content Manager, My Reports, Publisher, Report Builder). If I login with a Local Administrator account, I can see and use it fine. Any ideas?

[A]
The first thing I would check is to make sure that your normal login is mapped to a role with the correct system-level permissions.  The item-level role definitions don't make a difference for the "Report Builder" button.
From the browser-based report manager interface:
Click "site settings"
In the Security section, click "Configure system-level role definitions"
Click the Role that you want to have this ability (e.g. "System Administrator" and "System User" are the default roles, but I believe that you can create your own if you want to).
Make sure that the "Execute Report Definitions" task is checked/selected.  This is the permission that controls whether or not the "Report Builder" button is displayed.
Click "OK" and then return to the "Site Settings" page.
In the Security section, click "Configure site-wide security"
Click "New Role Assignment" and then map your login (or an AD group to which your login belongs might be even better) to the system-level role you edited in the previous steps.
The forms are pretty straightforward, and I'd guess that your login just isn't mapped to the proper system-level role since you can see the button with the local administrator login.  If that doesn't work, you might check your IIS security settings for the report service to make sure that they're configured to use windows authentication (assuming that's what you're using in the first place).


q: And why would I use one over the other in my code?

[A]
Caution: This answer appears to be out of date.
It was posted before .NET 4 became available, which apparently introduced some optimizations regarding
```
Type
```
and thus rendered the information in this answer obsolete. See
this more recent answer
for details.
According to
this blog post (from 2006) by Vance Morrison
,
```
RuntimeTypeHandle
```
is a value type (
```
struct
```
) that wraps an unmanaged pointer, so
```
Type.GetTypeHandle(obj).Equals(anotherHandle)
```
is faster to use for strict "is exactly the same type" comparisons than
```
obj.GetType().Equals(anotherType)
```
— the latter creates
```
System.Type
```
instances which are, apparently, heavier.
However, it's also less obvious, and definitely falls under the category "micro-optimization" so if you're wondering when you need one over the other, you should probably just use System.Type.


q:
Is it possible to handle POSIX signals within the Java Virtual Machine?

At least SIGINT and SIGKILL should be quite platform independent.

[A]
Perhaps
Runtime#addShutdownHook
?


q: I need to empty an LDF file before sending to a colleague.  How do I force SQL Server to truncate the log?

[A]
In management studio:
Don't do this on a live environment, but to ensure you shrink your dev db as much as you can:
Right-click the database, choose
```
Properties
```
, then
```
Options
```
.
Make sure "Recovery model" is set to "Simple", not "Full"
Click OK
Right-click the database again, choose
```
Tasks
```
->
```
Shrink
```
->
```
Files
```
Change file type to "Log"
Click OK.
Alternatively, the SQL to do it:
```
```
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
 DBCC SHRINKFILE (mydatabase_Log, 1)
```
```
Ref:
http://msdn.microsoft.com/en-us/library/ms189493.aspx


q:
I have a List of Foo.

Foo has a string property named Bar.

I'd like to use LINQ to get a string[] of distinct values for Foo.Bar in List of Foo.

How can I do this?

[A]
Try this:
```
```
var distinctFooBars = (from foo in foos
                       select foo.Bar).Distinct().ToArray();
```
```


q:
I always thought Java uses pass-by-reference.

However, I've seen a blog post that claims that Java uses pass-by-value.

I don't think I understand the distinction they're making.

What is the explanation?

[A]
Java is always pass by value, with no exceptions,
ever
.
So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java
never
provides direct access to the values of
objects themselves
, in
any
circumstances. The only access to objects is through a
reference
to that object. Because Java objects are
always
accessed through a reference, rather than directly, it is common to talk about fields and variables
and method arguments
as being
objects
, when pedantically they are only
references to objects
.
The confusion stems from this (strictly speaking, incorrect) change in nomenclature.
So, when calling a method
For primitive arguments (
```
int
```
,
```
long
```
, etc.), the pass by value is
the actual value
of the primitive (for example, 3).
For objects, the pass by value is the value of
the reference to the object
.
So if you have
```
doSomething(foo)
```
and
```
public void doSomething(Foo foo) { .. }
```
the two Foos have copied
references
that point to the same objects.
Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.


q:
As the title already states, I'm trying to declare a nested function and return a pointer to that function. I want this function 'not' to return a new function pointer which will return the negation of whatever the original function was.

Here is what I have:

someType not( someType original ) {
    int isNot( ListEntry* entry ) {
        return !original( entry );
    }

    someType resultFunc = calloc( 1024, 1 );
    memcpy( resultFunc, &isNot, 1024 );

    return resultFunc;
}

someType is defined as:

typedef int(*someType)(ListEntry* entry)

[A]
I'm using GCC.
You can turn on nested functions by using the flag:
```
```
-fnested-functions
```
```
when you compile.


q:
I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example:

//Function Declarations
function parentFunction()
{
    function callMe()
    {
     textField.text = "lawl";
    }
}

Now, how do I call the "callMe()" function in a different part of the code, like an onRelease function?

on(release)
{
callMe(); //doesn't work
parentFunction().callMe(); //doesn't work
parentFunction.callMe(); //doesn't work
}

ActionScript 2.0 is just so wonky! Any ideas?

[A]
Are you forced to declare callMe inside of parentFunction?  I assume so because otherwise you would just do
function parent()  { }
function callMe()  { }
To be clear, a function can't own another function unless you provide some scope for that function to live in.
So in JavaScript, you would do this by using the prototype object to declare the callMe function as a method of the object that parentFunction returned.
http://www.howtocreate.co.uk/tutorials/javascript/objects
For ActionScript, read this article on Adobe's website:
http://www.adobe.com/devnet/flex/articles/as_collections_03.html
EDIT: After some more reading it appears the way you did things, you are actually declaring callMe as a
private
function.  See this article which should make the whole
private/public javascript issue
a lot more understandable.


q:
Extreme Programming, Scrum and Test Driven Development definitely seem to be the most popular Agile methods at the moment. But someone recently suggested that I take a look at Feature Driven Development.

Have you ever used this method with any success? What are the advantages of using it?

[A]
FDD is an older methodology. It has lot's of the ideas of other agile methodologies and misses some of them. Like Scrum it's a bit management-focussed and I think you need some elements from XP for practical implementations.
FDD is certainly interesting to look into. But just like Scrum and XP I think you have to understand the mechanics and not just implement the practices to be succesful. If you just "do FDD" or "do Scrum" you're not as adaptive as you should be.
The things I would look into if you want to understand agile would be
Scrum or FDD to understand what management can get out of agile.
XP to understand how enable agile from a technology perspective.
Crystal Clear to understand the communications aspects.
Lean Agile to get a completely different perspective on agile methodologies
I wouldn't call TDD an agile methodology by the way. It's an practice from XP but not a complete methodology per se.


q: I need to determine if I'm on a particular view.  My use case is that I'd like to decorate navigation elements with an "on" class for the current view.  Is there a built in way of doing this?

[A]
My current solution is with extension methods:
```
```
public static class UrlHelperExtensions
{
    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    /// <param name="helper">Url Helper</param>
    /// <param name="action">The action to check.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller
    {
        MethodCallExpression call = action.Body as MethodCallExpression;
        if (call == null)
        {
            throw new ArgumentException("Expression must be a method call", "action");
        }

        return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&
                typeof(TController) == helper.ViewContext.Controller.GetType());
    }

    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <param name="helper">Url Helper</param>
    /// <param name="actionName">Name of the action.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction(this UrlHelper helper, string actionName)
    {
        if (String.IsNullOrEmpty(actionName))
        {
            throw new ArgumentException("Please specify the name of the action", "actionName");
        }
        string controllerName = helper.ViewContext.RouteData.GetRequiredString("controller");
        return IsAction(helper, actionName, controllerName);
    }

    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <param name="helper">Url Helper</param>
    /// <param name="actionName">Name of the action.</param>
    /// <param name="controllerName">Name of the controller.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)
    {
        if (String.IsNullOrEmpty(actionName))
        {
            throw new ArgumentException("Please specify the name of the action", "actionName");
        }
        if (String.IsNullOrEmpty(controllerName))
        {
            throw new ArgumentException("Please specify the name of the controller", "controllerName");
        }

        if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
        {
            controllerName = controllerName + "Controller";
        }

        bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);
        return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
    }
}
```
```


q:
Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number.

For example, in Prototype this works:

$$('li')[5].addClassName('active');

But this will not work no matter how I try to cast the variable as a number or integer:

$$('li')[currentPage].addClassName('active');

In jQuery I get similar weirdness. This will work:

jQuery('li').eq(5).addClass("active");

But this will not work again even though the value of currentPage is 5 and its type is number:

jQuery('li').eq(currentPage).addClass("active");

I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.

[A]
Are you certain that
```
currentPage
```
is an integer? Try something like:
```
```
var currentPage = 5;
jQuery('li').eq(currentPage);
```
```
as a simple sanity check. If that works, you should try casting to
```
Integer
```
.


q:
I've been using PHP for too long, but I'm new to JavaScript integration in some places.

I'm trying to find the fastest way to pass database information into a page where it can be modified and displayed dynamically in JavaScript.

Right now, I'm looking at loading a JSON with PHP echo statements because it's fast and effective, but I saw that I could use PHP's JSON library (PHP 5.2).

Has anybody tried the new JSON library, and is it better than my earlier method?

[A] Use the library. If you try to generate it manually, I predict with 99% certainty that the resulting text will be invalid in some way. Especially with more esoteric features like Unicode strings or exponential notation.


q:
What are they and what are they good for?

I do not have a CS degree and my background is VB6 -> ASP -> ASP.NET/C#. Can anyone explain it in a clear and concise manner?

[A]
Imagine if every single line in your program was a separate function. Each accepts, as a parameter, the next line/function to execute.
Using this model, you can "pause" execution at any line and continue it later. You can also do inventive things like temporarily hop up the execution stack to retrieve a value, or save the current execution state to a database to retrieve later.


q:
I'm building an excel template (*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer).  How do I do this?

Update: I should have added that I would prefer not to use any vba (macro).  If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button.

[A]
You can edit the default template for excel -
There is a file called
```
Book.xlt
```
in the
```
XLSTART
```
directory, normally located at
```
C:\Program Files\Microsoft Office\Office\XLStart\
```
You should be able to add a macro called Workbook_Open
```
```
Private Sub Workbook_Open()
    If ActiveWorkBook.Sheets(1).Range("A1") = "" Then
        ActiveWorkBook.Sheets(1).Range("A1") = Now
    End If
End Sub
```
```
My VBA is a little rusty, but you might find something like this works.


q: I've inherited a large VB6 app at my current workplace. I'm kinda learning VB6 on the job and there are a number of problems I'm having. The major issue at the moment is I can't figure out how to check if a key exists in a Collection object. Can anyone help?

[A]
I've always done it with a function like this:
```
```
public function keyExists(myCollection as collection, sKey as string) as Boolean
  on error goto handleerror:

  dim val as variant

  val = myCollection(sKey)
  keyExists = true
  exit sub
handleerror:
  keyExists = false
end function
```
```


q:
I'm trying to find a way to validate a large XML file against an XSD. I saw the question ...best way to validate an XML... but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException.

Are there any other tools,libraries, strategies for validating a larger than normal XML file?

EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation  outside of java.

[A]
Instead of using a DOMParser, use a SAXParser.  This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory.
```
```
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);

SAXParser parser = factory.newSAXParser();

XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new SimpleErrorHandler());
reader.parse(new InputSource(new FileReader ("document.xml")));
```
```


q:
I'm maintaining some code that uses a *= operator in a query to a Sybase database and I can't find documentation on it.  Does anyone know what *= does?  I assume that it is some sort of a join.

select * from a, b where a.id *= b.id

I can't figure out how this is different from:

select * from a, b where a.id = b.id

[A]
It means outer join, a simple = means inner join.
```
```
*= is LEFT JOIN and =* is RIGHT JOIN.
```
```
(or vice versa, I keep forgetting since I'm not using it any more, and Google isn't helpful when searching for *=)


q: After test driving Google Chrome for 30 minutes or so, I like it, even if it seems bare-bones at the moment.  The obvious way to add a few things I can't live without would be through plugins.  Does anyone have any links to resources on how to get started building a plugin/addon for Chrome?  Thanks.

[A]
Chrome does support the netscape plugin api, but that is for displaying certain kinds of content.
You seem to be after a extention api, really firefox is the only major browser to encourage and support third party extentions to browsing capability (that aren't simply new toolbars)
Nothing in the developer documentation points to a browser enhancing api - google seem to want to keep a tight reign on the look and feel of the application.
You might find a more conclusive answer on the development site:
dev.chromium.org, and some of the developers might be on irc on #chromium on freenode.


q:
Is it possible to create a REST web service using ASP.NET 2.0?  The articles and blog entries I am finding all seem to indicate that ASP.NET 3.5 with WCF is required to create REST web services with ASP.NET.

If it is possible to create REST web services in ASP.NET 2.0 can you provide an example.

Thanks!

[A] I'm only just beginning to use them, but from what I've seen 2.0 pretty assumes SOAP.


q: It will be important for developers wanting to develop for the chrome browser to be able to review existing bugs (to avoid too much pulling-out of hair), and to add new ones (to improve the thing).  Yet I can't seem to find the bug tracking for this project.  It is open source, right?

[A]
From the
Google Site
Click the Page menu page menu.
Select Report a bug or broken website.
Choose an issue type from the drop-down menu. The web address of the webpage you're on is recorded automatically.
If possible, add key details in the 'Description' field, including steps to reproduce the issue you're experiencing.
Keep 'Send source of current page' and 'Send screenshot of current page' checkboxes selected.
Click the Send report button to report a Google Chrome bug.
I don't see any reference to public bug tracking...


q:
Although the general case is undecidable, many people still do solve problems that are equivilent well enough for day to day use.

In cohen's phd thesis on computer viruses, he showed how virus scanning is equivilent to the halting problem, yet we have an entire industry based around this challenge.

I also have seen microsoft's terminator project -  http://research.microsoft.com/Terminator/

Which leads me to ask - is the halting problem overrated - do we need to worry about the general case?

Will types become turing complete over time - dependant types do seem like a good development?

Or, to look the other way, will we begin to use non turing complete languages to gain the benefits of static analysis ?

[A]
The Halting Problem is really only interesting if you look at it in the general case, since if the Halting problem were decidable, all other undecidable problems would also be decidable via reduction.
So, my opinion on this question is, no, it is not easy in the cases that matter.  That said, in the real world, it may not be such a big deal.
See also:
http://en.wikipedia.org/wiki/Halting_problem#Importance_and_consequences


q:
How do you give a C# auto-property an initial value?

I either use the constructor, or revert to the old syntax.

 Using the Constructor:

class Person
{
    public Person()
    {
        Name = "Initial Name";
    }
    public string Name { get; set; }
}

Using normal property syntax  (with an initial value)

private string name = "Initial Name";
public string Name
{
    get
    {
        return name;
    }
    set
    {
        name = value;
    }
}

Is there a better way?

[A]
Have you tried using the
DefaultValueAttribute
or
ShouldSerialize and Reset methods
in conjunction with the constructor?  I feel like one of these two methods is necessary if you're making a class that might show up on the designer surface or in a property grid.


q:
I am setting the .Content value of a Label to a string that contains underscores; the first underscore is being interpreted as an accelerator key.

Without changing the underlying string (by replacing all _ with __), is there a way to disable the accelerator for Labels?

[A]
You could override the RecognizesAccessKey property of the ContentPresenter that is in the default template for the label. For example:
```
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid>
    <Grid.Resources>
      <Style x:Key="{x:Type Label}" BasedOn="{StaticResource {x:Type Label}}" TargetType="Label">
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="Label">
              <Border>
                <ContentPresenter
                  HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                  RecognizesAccessKey="False" />
              </Border>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style>
    </Grid.Resources>
    <Label>_This is a test</Label>
  </Grid>
</Page>
```
```


q: In this question someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere...

[A]
I guess there are a couple of options:
For a pure CLI solution, use something like gnuplot. See
here
for example usage. I haven't used gnuplot since my student days :-)
Not really a pure CLI solution, but download something like
JFreeChart
and write a simple Java app that reads stdin and creates your chart.
Hope this helps.


q:
Are all of these equal?  Under what circumstances should I choose each over the others?

var.ToString()

CStr(var)

CType(var, String)

DirectCast(var, String)

EDIT: Suggestion from NotMyself…

TryCast(var, String)

[A]
I prefer the following syntax:
```
```
Dim number As Integer = 1
Dim str As String = String.TryCast(number)

If str IsNot Nothing Then
```
```
Hah you can tell I typically write code in C#. 8)
The reason I prefer TryCast is you do not have to mess with the overhead of casting exceptions. Your cast either succeeds or your variable is initialized to null and you deal with that accordingly.


q:
How do I determine the (local-) path for the "Program Files" directory on a remote computer? There does not appear to any version of SHGetFolderPath (or related function) that takes the name of a remote computer as a parameter.

I guess I could try to query HKLM\Software\Microsoft\Windows\CurrentVersion\ProgramFilesDir using remote-registry, but I was hoping there would be "documented" way of doing it.


q:
I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile.

How would I go about doing this using the regular Windows command line?

I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well.

[A]
It would be an new shell (but I think it is worth it), but from PowerShell it would be
```
```
[int](get-content counter.txt) + 1 | out-file counter.txt
```
```


q:
If I have an HTML helper like so:

Name:<br />
<%=Html.TextBox("txtName",20) %><br />

How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?

[A]
You can pass it into the TextBox call as a parameter.
```
```
Name:<br/>
<%= Html.TextBox("txtName", "20", new { @class = "hello" }) %>
```
```
This line will create a text box with the value 20 and assign the class attribute with the value hello.  I put the @ character in front of the class, because class is a reserved keyword.  If you want to add other attributes, just separate the key/value pairs with commas.


q: Is there an IDE that I can load on a Blackberry, E71, or an iPhone?

[A] Not that I know of, typically you'll develop apps on a desktop machine (PC/MAC whatever) and download/control the application on the phone. Also I don't think Java is available on a standard (non-cracked) iPhone.


q:
What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?

I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?

[A]
Here is an example of sending back a pdf.
```
```
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);
```
```
@Swish
I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type?
Also in the PHP manual
Hayley Watson
posted:
If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).
Also according
IANA
there is no registered application/force-download type.


q: Do you know if it's possible to build an application for the LinkedIn platform?

[A]
Yes, Linkedin has an API:
http://www.programmableweb.com/api/linkedin
http://blog.linkedin.com/blog/2007/12/the-intelligent.html
So you could build an application that uses it.
Update:
(
from second link
)
We’ll be phasing all of this in over the coming months and to get involved with the Intelligent Application Platform either for APIs, widgets, or hosted applications, send us an e-mail to
developers@linkedin.com
telling us what you want to build and what you need to build it.
Since there are published Mashups using LinkedIn I would assume that means you can use the API even if the documentation isn't readily available.
As a tip, in the future include links to what you found that didn't work, so we know not to give it to you again.
I poked around a bit more and I found some
more on their widgets
which appears to be the main focus of their API.


q: Grails makes it very easy to configure datasources for different environments (development, test, production) in its DataSources.groovy file, but there seems to be no facility for configuring multiple datasources in one environment. What to I do if I need to access several databases from the same Grails application?

[A]
The following post seems to be the best source of information on the subject:
How to get mutli-dataSource in grails
It boils down to:
Define datasource1 in DevelopmentDataSource
Define datasource2 in resources.xml
Write a DAO for CRUD of the domain objects using datasource2
In hibernate.cfg.xml, list all domain objects.
Only the first datasource will have dynamic finder methods.
If its a really simple query you are after and don't mind not having the ORM features you could use Groovy SQL or the native SQL features of Hibernate.


q:
I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string.  In my situation it would be used as a unique session/key identifier that would "likely" be unique over 500K+ generation (my needs don't really require anything much more sophisticated).

Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like "AEYGF7K0DM1X".

[A]
Algorithm
To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.
Implementation
Here's some fairly simple and very flexible code for generating random identifiers.
Read the information that follows
for important application notes.
```
```
public class RandomString {

    /**
     * Generate a random string.
     */
    public String nextString() {
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)];
        return new String(buf);
    }

    public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String lower = upper.toLowerCase(Locale.ROOT);

    public static final String digits = "0123456789";

    public static final String alphanum = upper + lower + digits;

    private final Random random;

    private final char[] symbols;

    private final char[] buf;

    public RandomString(int length, Random random, String symbols) {
        if (length < 1) throw new IllegalArgumentException();
        if (symbols.length() < 2) throw new IllegalArgumentException();
        this.random = Objects.requireNonNull(random);
        this.symbols = symbols.toCharArray();
        this.buf = new char[length];
    }

    /**
     * Create an alphanumeric string generator.
     */
    public RandomString(int length, Random random) {
        this(length, random, alphanum);
    }

    /**
     * Create an alphanumeric strings from a secure generator.
     */
    public RandomString(int length) {
        this(length, new SecureRandom());
    }

    /**
     * Create session identifiers.
     */
    public RandomString() {
        this(21);
    }

}
```
```
Usage examples
Create an insecure generator for 8-character identifiers:
```
```
RandomString gen = new RandomString(8, ThreadLocalRandom.current());
```
```
Create a secure generator for session identifiers:
```
```
RandomString session = new RandomString();
```
```
Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:
```
```
String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);
```
```
Use as session identifiers
Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.
There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.
The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.
Use as object identifiers
Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.
Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.
Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox."
The probability of a collision,
p
, is approximately n
2
/(2q
x
), where
n
is the number of identifiers actually generated,
q
is the number of distinct symbols in the alphabet, and
x
is the length of the identifiers. This should be a very small number, like 2
‑50
or less.
Working this out shows that the chance of collision among 500k 15-character identifiers is about 2
‑52
, which is probably less likely than undetected errors from cosmic rays, etc.
Comparison with UUIDs
According to their specification,
UUIDs
are not designed to be unpredictable, and
should not
be used as session identifiers.
UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.
UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.


q:
In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation.

I've got my interface set up with the ServiceContract and OperationContract:

    [OperationContract]
    void FileUpload(UploadedFile file);

Along with the actual method:

    public void FileUpload(UploadedFile file) {};

To access the Service I enter http://localhost/project/myService.svc/FileUpload
but I get the "Method not Allowed" error

Am I missing something?

[A]
The basic intrinsic types (e.g.
```
byte
```
,
```
int
```
,
```
string
```
, and arrays) will be serialized automatically by WCF. Custom classes, like your UploadedFile, won't be.
So, a silly question (but I have to ask it...): is UploadedFile marked as a
```
[DataContract]
```
? If not, you'll need to make sure that it is, and that each of the members in the class that you want to send are marked with [DataMember].
Unlike remoting, where marking a class with [XmlSerializable] allowed you to serialize the whole class without bothering to mark the members that you wanted serialized, WCF needs you to mark up each member. (I believe this is changing in .NET 3.5 SP1...)
A tremendous resource for WCF development is what we know in our shop as "the fish book":
Programming WCF Services
by Juval Lowy. Unlike some of the other WCF books around, which are a bit dry and academic, this one takes a practical approach to building WCF services and is actually useful. Thoroughly recommended.


q:
Given the following:

List<List<Option>> optionLists;

what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value.

So we should end up with List<Option> where each item appears only once.

[A]
Ok, this will find the list of Option objects that have a Value appearing in
every
list.
```
```
var x = from list in optionLists
        from option in list
        where optionLists.All(l => l.Any(o => o.Value == option.Value))
        orderby option.Value
        select option;
```
```
It doesn't do a "distinct" select so it'll return multiple Option objects, some of them with the same Value.


q:
Suppose someone worked for a company that put up an HTTP proxy preventing internet access without password authentication (NTLM, I think). Also suppose that this password rotated on a daily basis, which added very little security, but mostly served to annoy the employees. How would one get started writing a Firefox add-on that automatically entered these rotating passwords?

To clarify: This add-on would not just submit the password; the add-on would programmatically generate it with some knowledge of the password rotation scheme.

[A]
This is built into Firefox. Open up about:config, search for 'ntlm'
The setting you're looking for is called network.automatic-ntlm-auth.trusted-uris and accepts a comma-space delimited list of your proxy server uris.
This will make FireFox automatically send hashed copies of your windows password to the proxy, which is disabled by default for obvious reasons. IE can do this automatically because it can use security zones to figure out whether a proxy server is trusted or not.
Blog post discussing this


q:
I have a number of users with multi-megabyte files that need to be processed before they can be uploaded. I am trying to find a way to do this without having to install any executable software on their machines.

If every machine shipped with, say, Python it would be easy. I could have a Python script do everything. The only scripting language I can think of that's on every machine is JavaScript. However I know there are security restrictions that prevent reading and writing local files from web browsers.

Is there any way to use this extremely pervasive scripting language for general purpose computing tasks?

EDIT: To clarify the requirements, this needs to be a cross platform, cross browser solution. I believe that HTA is an Internet Explorer only technology (or that the Firefox equivalent is broken).

[A]
The application that I maintain and develop for work is an
HTML Application
or
HTA
, linked with a SQL Server 2005 backend. This allows various security restrictions to be "avoided". All the client-side components in the application are done with javascript, including writing files to locally mapped network drives and loading data into screens/pages in an AJAXy way.
Perhaps HTA could be helpful for your situation.


q:
How can I get an image to stretch the height of a DIV class?

Currently it looks like this:

However, I would like the DIV to be stretched so the image fits properly, but I do not want to resize the `image.

Here is the CSS for the DIV (the grey box):

.product1 {
    width: 100%;
    padding: 5px;
    margin: 0px 0px 15px -5px;
    background: #ADA19A;
    color: #000000;
    min-height: 100px;
}

The CSS being applied on the image:

.product{
    display: inline;
    float: left;
}

So, how can I fix this?

[A]
```
```
display:inline
float:left
```
```
is your problem
Floating makes the parents width not be stretched by the child, try placing the image without the float. If you take the float off, it should give you the desired effect.
Another approach would be to make sure you are clearing your floats at the end of the parent element so that they don't scope creep.
Update:
After viewing your link Your height issue as displayed, is because the floats are not being cleared.


q:
Is there a fast and clean way of returning a JSON hash back from any node in a Ruby on Rails' acts_as_nested_set without using recursion?

Here's the recursive solution for reference:

class Node < ActiveRecord::Base
  has_many :products
  def json_hash
    if children.size > 0
      children.collect { |node| { node.name => node.json_hash }.to_json
    else
      { node.name => node.products.find(:all).collect(&:name) }.to_json
    end
  end
end

[A]
There is a
wikipedia article
on tree traversal which shows different alternatives to the recursive solution you are using.  It may be tricky to use them in your specific case, but it should be possible.
However, my question to you is, is there a specific reason you want to use iteration instead of recursion?  I don't think any of the iterative solutions will be nearly as clean.  Are your trees so big that you are running out of stack space (they would have to be pretty big)?  Otherwise, I'm not so sure an iterative solution will really be faster.
I see one potential for improvement though, if you are seeing performance issues... but I don't know rails, so I'm not sure if it is accurate:
Does the find method return a new array?  If so, you probably want to invoke .collect! instead of .collect, because if find creates an array, you are just creating an array and then throwing it away to the call to collect (which also creates an array), which surely is not going to be very efficient and may slow you down a lot if you have a big tree there.
So
```
```
{ node.name => node.products.find(:all).collect(&:name) }.to_json
```
```
might become
```
```
{ node.name => node.products.find(:all).collect!(&:name) }.to_json
```
```
EDIT: Also, it may be more efficient to create your hash of hashes, and then convert the whole thing to json in 1 fell swoop, rather than converting it piecemail like you are doing.
So
```
```
class Node < ActiveRecord::Base
  has_many :products
  def json_hash
    if children.size > 0
      children.collect { |node| { node.name => node.json_hash }.to_json
    else
      { node.name => node.products.find(:all).collect!(&:name) }.to_json
    end
  end
end
```
```
might become
```
```
class Node < ActiveRecord::Base
  has_many :products
  def json_hash
    to_hash.to_json
  end

  def to_hash
    if children.size > 0
      children.collect { |node| { node.name => node.to_hash }
    else
      { node.name => node.products.find(:all).collect!(&:name) }
    end
  end
end
```
```
Whether this works and is more efficient I leave as an exercise for you ;-)


q:
I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I could configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer.

Thanks

[A]
There doesn't seem to be an easier way,
unless you're willing to buy MAMP Pro
.
As far as I know, the only way to use SSL with MAMP is to
configure mod_ssl for Apache
. mod_ssl is bundled with MAMP, and I found configuration to be pretty straightforward. Note that you'll probably have to start Apache from the command line to use it:
```
```
/Applications/MAMP/bin/apache2/bin$ ./apachectl stop
/Applications/MAMP/bin/apache2/bin$ sudo ./apachectl startssl
```
```


q: I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a SQL-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only works on IQueryable<T>. Is there any way to get this functionality on IEnumerable<T>?

[A]
I guess it would work to use reflection to get whatever property you want to sort on:
```
```
IEnumerable<T> myEnumerables
var query=from enumerable in myenumerables
          where some criteria
          orderby GetPropertyValue(enumerable,"SomeProperty")
          select enumerable

private static object GetPropertyValue(object obj, string property)
{
    System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);
    return propertyInfo.GetValue(obj, null);
}
```
```
Note that using reflection is considerably slower than accessing the property directly, so the performance would have to be investigated.


q:
I assumed there were only bug fixes/(no new types) in .NET 2.0 SP1 until I came across few posts which were mentioning DateTimeOffset structure, that was added in .NET 2.0 SP1.

Is there a full listing of the newly added types in .NET 2.0 SP1?

[A]
Here's what you're looking for:
Full Article:
http://www.hanselman.com/blog/CatchingRedBitsDifferencesInNET20AndNET20SP1.aspx
This may also be helpful:
Full Article:
http://www.hanselman.com/blog/ChangesInTheNETBCLBetween20And35.aspx


q:
How do you run Emacs in Windows?

What is the best flavor of Emacs to use in Windows, and where can I download it? And where is the .emacs file located?

[A]
Well, I personally really like what I have been using since I started with Emacs, which is GNU Emacs.  It looks like it is built for
windows too
.  That link also answers your
.emacs file question
.
Here is a place you can download it
.  You should probably get version 22.2 (the latest).
If this is your first time, I hope you enjoy it!  I know I absolutely love emacs!


q:
Has anybody got any kind of experience with dynamic programming using WCF. By dynamic programming I mean runtime consumption of WSDL's.
I have found one blog entry/tool:
http://blogs.msdn.com/vipulmodi/archive/2006/11/16/dynamic-programming-with-wcf.aspx

Has anybody here found good tools for this?

[A]
I have done this a long time ago with SOAP web services. There was a tool on GotDotNet which I think has become
Web Services Studio Express
, that had code which inspected/parsed a WSDL file and allowed you to call it.
I think the assumption is that the WSDL is known at the time of client creation, and you don't need to be hooked up at runtime. If you inspect the WSDL at runtime you still need to have some sort of logic to decide how to generate the proxy. Why would can you not consume the WSDL before runtime? Web Services are supposed to be fairly static with an interface that doesn't change once published.
You can use .NET CodeDom to generate code to execute and use the web service described by the WSDL. The WSDL can be parsed using the standard .NET XML classes.


q: What do search engine bots use as a starting point? Is it DNS look-up or do they start with some fixed list of well-know sites? Any guesses or suggestions?

[A]
You can submit your site to search engines using their
site submission forms
- this will get you into their system. When you actually get crawled after that is impossible to say - from experience it's usually about a week or so for an initial crawl (homepage, couple of other pages 1-link deep from there). You can increase how many of your pages get crawled and indexed using clear semantic link structure and submitting a
sitemap
- these allow you to list all of your pages, and weight them relative to one another, which helps the search engines understand how important you view each part of site relative to the others.
If your site is linked from other crawled websites, then your site will also be crawled, starting with the page linked, and eventually spreading to the rest of your site. This can take a long time, and depends on the crawl frequency of the linking sites, so the url submission is the quickest way to let google know about you!
One tool I can't recommend highly enough is the
Google Webmaster Tool
. It allows you to see how often you've been crawled, any errors the googlebot has stumbled across (broken links, etc) and has a host of other useful tools in there.


q:
I'm looking for a tool to generate a JavaScript stub from a WSDL.

Although I usually prefer to use REST services with JSON or XML, there are some tools I am currently integrating that works only using SOAP.

I already created a first version of the client in JavaScript but I'm parsing the SOAP envelope by hand and I doubt that my code can survive a service upgrade for example, seeing how complex the SOAP envelope specification is.

So is there any tool to automatically generate fully SOAP compliant stubs for JavaScript from the WSDL so I can be more confident on the future of my client code.

More: The web service I try to use is RPC encoded, not document literal.

[A]
I had to do this myself in the past and I found this
CodeProject article
.  I changed it up some, but it gave me a good foundation to implement everything I needed.  One of the main features it already has is generating the SOAP client based off the WSDL.  It also has built in caching of the WSDL for multiple calls.
This article also has a custom implementation of XmlHttpRequest for Ajax calls.  This is the part that I didn't use.  During that time, I think I was using
Prototype
javascript library and modified the code in this article to use it's Ajax functions instead.  I just felt more comfortable using Prototype for the ajax calls, because it was widely used and had been tested on all the browsers.


q:
I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality:

The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database.

Although I am mainly interested in doing this in php, I also have some Java implementation ideas for this. I believe it could also help if the answer was as much language-agnostic as possible.

[A]
I haven't tried it, but take a look at
isbndb
API Description: Introduction
ISBNdb.com's remote access application programming interface (API) is designed to allow other websites and standalone applications use the vast collection of data collected by ISBNdb.com since 2003. As of this writing, in July 2005, the data includes nearly 1,800,000 books; almost 3,000,000 million library records; close to a million subjects; hundreds of thousands of author and publisher records parsed out of library data; more than 10,000,000 records of actual and historic prices.
Some ideas of how the API can be used include:
```
```
- Cataloguing home book collections
- Building and verifying bookstores' inventories
- Empowering forums and online communities with more useful book references
- Automated cross-merchant price lookups over messaging devices or phones
```
```
Using the API you can look up information by keywords, by ISBN, by authors or publishers, etc. In most situations the API is fast enough to be used in interactive applications.
The data is heavily cross-linked -- starting at a book you can retrieve information about its authors, then other books of these authors, then their publishers, etc.
The API is primarily intended for use by programmers. The interface strives to be platform and programming language independent by employing open standard protocols and message formats.


q:
Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default!

/EDIT: Without having source to the object itself

[A]
I don't use VB, but here it goes.
I found
Using the Value of a Control
, but it's not a programmatic solution.
If you have access to the code, look for
```
```
Attribute Value.VB_UserMemId = 0
```
```
using Notepad.


q:
In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, static int MYINT = 3; causes the serialVersionUID to change. In this example, it makes sense because different versions of the class would get different initial values. Why does any initialization change the serialVersionUID? For example, static String MYSTRING = System.getProperty("foo"); also causes the serialVersionUID to change.

To be specific, my question is why does initialization with a method cause the serialVersionUID to change. The problem I hit is that I added a new static field that was initialized with a system property value (getProperty). That change caused a serialization exception on a remote call.

[A]
If I read the spec correctly the automatic
```
serialVersionUID
```
shouldn't change if you change the value of a static of transient field. Take a look at
Chapter 5.6
of the Spec.
However
, if you think about this a bit - you start by serializing an object that has
```
static int MYINT = 3
```
, when you then deserialize the class you expect to get the same object back, that is, with
```
MYINT = 3
```
. So, if you change the static initialization you would expect the
```
serialVersionUID
```
to change because you can't get the same object back again.
Anyways
, keep this in all your serializable classes and you can control the
```
serialVersionUID
```
:
```
```
private static final long serialVersionUID = 7526472295622776147L;
```
```


q:
Is there any way to use this kind of format in .Net (C#)?
I want to use the same skin format that uTorrent uses in my app, but i can't get the transparent background.
Any ideas?
Thanks for your time.

[A]
The PixelFormat enumeration lists the formats of 'bitmaps' you can create in .Net, so you'd want PixelFormat.Format32bppArgb:
http://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat.aspx
http://msdn.microsoft.com/en-us/library/3z132tat.aspx
However I'm not entirely sure that the BMP file format supports transparency - so you would have to save the file as perhaps a PNG file instead.


q: I am going to be using Subversion for source control on a new J2EE web application. What directory structure will you recommend for organizing code, tests and documentation?

[A]
I usually have
```
Project Directory
  src - actual source
  doc - documentation
  lib - libraries referenced from source
  dep - installation files for dependencies that don't fit in lib
  db  - database installation script
```
In work with Visual Studio, I'm not sure if this works the same in the java world. But i usually put stuff in different project folders in src. For each source project there's a separate test project. Build files go in the main project directory. I usually put a README there too documenting how to setup the project if it needs more than just checking out.
EDIT: This is the structure for a single working checkout of the project. It will be duplicated for each branch/tag in your revision control system (remember, in most SVN system, copies are cheap). The above example under Subversion would look like:
```
```
/project
    /trunk
        /src
        /doc
        /...
    /branches
        /feature1
            /src
            /doc
            /...
        /feature2
            /src
            /doc
            /...
```
```


q:
If not, what are the significant differences?

Edit: Daren Thomas asks:

which ones?

I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me...

By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts.

[A]
which ones?
I use
```
gvim
```
on Windows and
```
MacVim
```
on the mac. Seem similar enough to be the same to me...


q:
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.

In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?

Or will I have to make my own custom shortcuts to setup the context properly?

[A]
If you can hook your authentication into the
Django authentication scheme
you'll be able to use
```
request.user
```
.
I think this should just be a case of calling
```
authenticate()
```
and
```
login()
```
based on the contents of your Cookie.
Edit: @Staale - I always use the
```
locals()
```
trick
for my context so all my templates can see
```
request
```
and so
```
request.user
```
.  If you're not then I guess it wouldn't be so straightforward.


q: I'm trying to understand how namespaces work in XML. When I have an element like foo:bar, the attributes will often not have namespaces on them. But sometimes they will. Are the attribute in the namespace of the element, even when the default namespace has been declared? Looking over the xsd for xhtml it seems the attributes are part of the schema and should be in the namespace for xhtml, but they are never presented that way...

[A]
Read up at
6.1 Namespace Scoping
and
6.2 Namespace Defaulting
on w3c.
Basically:
The scope of a namespace declaration declaring a prefix extends from the beginning of the start-tag in which it appears to the end of the corresponding end-tag
However, the text here doesn't seem to explain if  means a is foo:a or the default namespace in the context. I would assume that it does not refer to foo:a, but rather the documents default namespace a. Considering this quote at least:
Such a namespace declaration applies to all element and attribute names within its scope whose prefix matches that specified in the declaration.
Ie. the namespace "foo:" only applies to elements prefixed with foo:


q:
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.

How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?

[A]
Namespaces are packages essentially. They can be used like this:
```
```
namespace MyNamespace
{
  class MyClass
  {
  };
}
```
```
Then in code:
```
```
MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
```
```
Or, if you want to always use a specific namespace, you can do this:
```
```
using namespace MyNamespace;

MyClass* pClass = new MyClass();
```
```
Edit:
Following what
bernhardrusch
has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).
And as you asked
below
, you can use as many namespaces as you like.


q:
I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.

I know that's possible by using keyword system like that :

#!/usr/bin/env ruby
directory = '/home/paulgreg/'
system 'ls ' + directory

but is that possible by using the "backquotes or backticks syntax" ?
(I mean by using that syntax : ls)

[A]
No, that will just concatenate the output from
```
ls
```
and the contents of
```
directory
```
.
But you can do this:
```
```
#!/usr/bin/env ruby
directory = '/home/paulgreg/'
`ls #{directory}`
```
```


q: Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?

[A]
You can try:
```
```
Bitmap.InterpolationMode = InterpolationMode.HighQualityBicubic;
```
```
and
```
```
Bitmap.CompositingQuality = CompositingQuality.HighQuality;
```
```
Which does keep the quality fairly high, but not the highest possible.


q:
In Visual Studio you can create a template XML document from an existing schema. The new XML Schema Explorer in VS2008 SP1 takes this a stage further and can create a sample XML document complete with data.
Is there a class library in .NET to do this automatically without having to use Visual Studio? I found the XmlSampleGenerator  article on MSDN but it was written in 2004 so maybe there is something already included in .NET to do this now?

[A]
Directly, none that I can think of, other than third party add-ons. You could utilize the
xsd schema definition tool
to take your XSD and create a .NET object/class, once you have that, you could, to quote the linked page:
XSD to Classes: Generates runtime classes from an XSD schema file. The generated classes can be used in conjunction with
System.Xml.Serialization.XmlSerializer
to read and write XML code that follows the schema.


q:
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)

For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this:
(jobId, label, username) = job

I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?

Here are my two best guesses:
(jobId, label, username) = (job[0], job[1], job[2])
...but that doesn't scale nicely when you have 15...20 fields

or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)

[A]
I'd say that a dictionary is definitely the best way to do it.  It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries.  If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.
For example:
```
```
job={}
job['jobid'], job['label'], job['username']=<querycode>
```
```


q:
As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?

I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site.

[A]
Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence.
So start with MVC, and you will easily be able to move in to WebForms if needed.


q:
I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen Ayende's blog posts and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider.

If you've got some background using these things, any chance you could put it in real laymans terms:

What exactly building DSLs means?

What languages are you using?

Where using a DSL makes sense?

What is the benefit of using DSLs?

[A]
DSL
stands for
Domain Specific Language
i.e. language designed specifically for solving problems in given area.
For example, Markdown (markup language used to edit posts on SO) can be considered as a DSL.
Personally I find a place for DSL almost in every large project I'm working on. Most often I need some kind of SQL-like query language. Another common usage is rule-based systems, you need some kind of language to specify rules\conditions.
DSL makes sense in context where it's difficult to describe\solve problem by traditional means.


q: What is the best way to calculate Age using Flex?

[A]
I found an answer at
the bottom of this page in comments section (which is now offline)
.
jpwrunyan said on Apr 30, 2007 at 10:10 PM :
By the way, here is how to calculate age in years (only) from DOB without needing to account for leap years:
With a slight correction by
Fine-Wei Lin
, the code reads
```
```
private function getYearsOld(dob:Date):uint {
    var now:Date = new Date();
    var yearsOld:uint = Number(now.fullYear) - Number(dob.fullYear);
    if (dob.month > now.month || (dob.month == now.month && dob.date > now.date))
    {
       yearsOld--;
    }
    return yearsOld;
}
```
```
This handles most situations where you need to calculate age.