q:
Is there a way to take a class name and convert it to a string in C#?

As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be able to have compile-time safety when referencing this class.

Thus, is there a way that I could do this:

class Foo
{
}

tblBar.Include ( Foo.GetType().ToString() );

I don't think I can do GetType() without an instance. Any ideas?

[A]
You can't use
```
.GetType()
```
without an instance because
```
GetType
```
is a method.
You can get the name from the type though like this:
```
```
typeof(Foo).Name
```
```
And as pointed out by Chris, if you need the assembly qualified name you can use
```
```
typeof(Foo).AssemblyQualifiedName
```
```


q:
Can anybody recommend a good method for determining the Rect of some wrapped text on an iPhone?  I've tried all the built-in methods for NSString in the 2.1 SDK to no avail.  The size methods never return sizes that allow me to completely fit wrapped text in my custom view.

I'm drawing some user customizable text that should always be as big as possible within the limits of my custom view.  If I can determine the rect needed to completely enclose wrapped text for a given max width and font size, I can raise or lower the font size until the text is just big enough to completely fill the custom view without being clipped.

Any help is much appreciated!

[A]
NSString's sizeWithFont:constrainedToSize: method might be useful:
```
```
CGSize sizeForText = [theText sizeWithFont:theFont constrainedToSize:CGSizeMake(myMaxWidth, 9999)];
```
```
You say you've tried all the size methods, but based on your description, it sounds like what you're looking for.

s: huggingface

c: devops

d: intermediate


q: How can you change the href attribute (link target) for a hyperlink using jQuery?

[A]
Using
```
```
$("a").attr("href", "http://www.google.com/")
```
```
will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:
```
```

The CodeProject
```
```
...Then you probably don't want to accidentally add
```
href
```
attributes to them. For safety then, we can specify that our selector will only match
```
<a>
```
tags with an existing
```
href
```
attribute:
```
```
$("a[href]") //...
```
```
Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing
```
href
```
, you might use something like this:
```
```
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
```
```
This will find links where the
```
href
```
exactly matches the string
```
http://www.google.com/
```
. A more involved task might be matching, then updating only part of the
```
href
```
:
```
```
$("a[href^='http://stackoverflow.com']")
   .each(function()
   {
      this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
         "http://stackoverflow.com");
   });
```
```
The first part selects only links where the href
starts
with
```
http://stackoverflow.com
```
. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.


q:
I have a series of datetime objects and would like to calculate the average delta between them.

For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes.

Any suggestions on how to calculate this using Python?

[A]
As far as algorithms go, that's an easy one.  Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at.
If you have an array a of datetimes, you can do:
```
```
mx = max(a)
mn = min(a)
avg = (mx-mn)/(len(a)-1)
```
```
to get back the average difference.
EDIT:  fixed the off-by-one error


q:
By that I mean, what do I need to do to have useful assertions in my code?

MFC is quite easy, i just use ASSERT(something).

What's the non-MFC way?

Edit: Is it possible to stop assert breaking in assert.c rather than than my file which called assert()?

Edit: What's the difference between <assert.h> & <cassert>?

Accepted Answer: Loads of great answers in this post, I wish I could accept more than one answer (or someone would combine them all). So answer gets awarded to Ferruccio (for first answer).

[A]
```
```
#include <cassert>

assert(something);
```
```
and for compile-time checking, Boost's static asserts are pretty useful:
```
```
#include <boost/static_assert.hpp>

BOOST_STATIC_ASSERT(sizeof(int) == 4);  // compile fails if ints aren't 32-bit
```
```


q:
A few questions on MS Access databases -

Size: Are there limits to the size of an access database?  The reason i ask is that we have an access database that has a few simple tables. The size of the db is about 1GB.  When I do a query on it, i see it taking over 10 minutes to run.

With proper indexing, should MS Access be able to handle this or are there fundamental limitations to the technology.

This is MS Access XP.

Also, does MS Access support db transactions, commit and rollback?

[A]
You will get many varied answers here, but in MY OPINION access is just not there as a scalable solution.  It doesn't handle multi-user situations very well, as you start to approach 1Gb in size, stability starts to become a MAJOR concern, and in reality it just doesn't have the performance.
In regards to transaction support, please see
this Microsoft Artic
le.
Also, here is a article that actually points out a good majority of
limitations of access
.


q:
In Visual Source Safe 6.0, you could "reset" a working folder by setting it to a blank string.  This meant that the working folder would be determined by the working folder of the parent.

How do I do this in Visual Source Safe 2005?

[A]
This can't be done in the normal VSS 2005 "Set Working Folder" dialog.
However, if you
hold the shift key while invoking the "Set Working Folder" dialog
, it shows the old VSS 6.0 dialog.  Here you can reset the working folder by deleting the string and pressing OK.


q:
I have a multi-timezone web application that stores all of the datetime values in UTC in the database, when actions happen on the server, I can easily convert the time into UTC.

However, when a client enters a time or time span, what is the best way to detect and store it?

I am currently doing the following:

Get the value of Date.getTimezoneOffset() (javascript)

Post that to the server-side code via the ICallbackEventHandler on Page.

Store that value in the session

On any subsequent request, calculate the output/input datetime value using the client's timezone.

Regardless of the actual implementation, this seems like an in-elegant solution.  Does anyone have a better method?

[A]
I was doing something very similar, but I now think I prefer to use
javascript
to convert all times to local on the client-side. The server will give all times in UTC in the generated page, and the
javascript
will convert it once the page loads.
This eliminates confusion on the server-side code, as I always know what time it is (UTC). On the client-side, I'm using
jquery
and the
```
each()
```
function to format all the time values at once. I write out each of the times as a
Unix
time in a hidden field to make this easy to process with
jquery
.
The only problems I see with this method is that:
a) I don't have a really good date/time formatting routine yet in
javascript
, and
b) if the user has
javascript
turned off, then it doesn't work.


q: Basically, I'm trying to selectively copy a table from one database to another. I have two different [Oracle] databases (e.g., running on different hosts) with the same schema. I'm interested in a efficient way to load Table A in DB1 with the result of running a select on Table A in DB2. I'm using JDBC, if that's relevant.

[A]
Use a database link, and use create table as select.
```
```
create database link other_db connect to remote_user identified by remote_passwd using remote_tnsname;

create table a as select * from a@other_db;
```
```


q: Many Java Apps don't use anti-aliased fonts by default, despite the capability of Swing to provide them.  How can you coerce an arbitrary java application to use AA fonts?  (both for applications I'm running, and applications I'm developing)

[A]
If you have access to the source, you can do this in the main method:
```
```
// enable anti-aliased text:
  System.setProperty("awt.useSystemAAFontSettings","on");
```
```
or, (and if you do not have access to the source, or if this is easier) you can simply pass the system properties above into the jvm by adding these options to the command line:
```
```
-Dawt.useSystemAAFontSettings=on
```
```


q:
We are migrating our test report data (unit, regression, integration, etc..) from an XML format to a database format for better analysis. Right now the majority of our test analysis is done using the CruiseControl.NET dashboard, but this is limited to primarily the most recent test data. Older test data can be accessed but not easily compared to new test data. We want to pin point problem components and better narrow down bugs. With the onset of tons of information brought on by our newly implemented regression and integration testing I would like to see some better metrics generated (possibly performance and the like). Have you worked with any business intelligence systems that will provide a framework for accurately and easily implementing some sort of analysis and reporting?

I have looked into JasperReports and Pentaho but I'm struggling with implemetation of Pentaho at the moment. Should I continue my fight with the system? Is this what I'm looking for?

[A]
You could try looking at rolling your own (if you know what you're looking for) using
Processing
written by Ben Fry.  It's best accompanied by his book "
Visualizing Data
".
The tool is free and I guess you can get a free 45 day trial of O'Reilly Books Online to get a head start and see if its right for you.  I do know there are chapters on reading and crunching data from all kinds of sources (including XML and databases) and then making meaningful and useful visualisations from them.
I'm currently using it to get my head round the dependency complexities of an inherited code base and its been massively useful.


q: I am in a situation where I must update an existing database structure from varchar to nvarchar using a script.  Since this script is run everytime a configuration application is run, I would rather determine if a column has already been changed to nvarchar and not perform an alter on the table.  The databases which I must support are SQL Server 2000, 2005 and 2008.

[A]
The following query should get you what you need:
```
```
IF EXISTS
  (SELECT *
   FROM sysobjects syo
   JOIN syscolumns syc ON
     syc.id = syo.id
   JOIN systypes syt ON
     syt.xtype = syc.xtype
   WHERE
     syt.name = 'nvarchar' AND
     syo.name = 'MY TABLE NAME' AND
     syc.name = 'MY COLUMN NAME')
BEGIN
   ALTER ...
END
```
```


q:
I would like a code sample for a function that takes a tDateTime and an integer as input and sets the system time using setlocaltime after advancing that tDateTime by (int) months. The time should stay the same.

pseudo code example

SetNewTime(NOW,2);

The issues I'm running into are rather frustrating.  I cannot use incmonth or similar with a tDateTime, only a tDate, etc.

[A]
Below is a complete command-line program that works for me.  Tested in Delphi 5 and 2007.  Why do you say
IncMonth
does not work for TDateTime?
```
```
program OneMonth;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Windows,
  Messages;

procedure SetLocalSystemTime(settotime: TDateTime);
var
  SystemTime : TSystemTime;
begin
  DateTimeToSystemTime(settotime,SystemTime);
  SetLocalTime(SystemTime);
  //tell windows that the time changed
  PostMessage(HWND_BROADCAST,WM_TIMECHANGE,0,0);
end;

begin
  try
    SetLocalSystemTime(IncMonth(Now,1));
  except on E:Exception do
    Writeln(E.Classname, ': ', E.Message);
  end;
end.
```
```


q:
This Linq to SQL query ...

    Return (From t In Db.Concessions Where t.Country = "ga" Select t.ConcessionID, t.Title, t.Country)

... is generating this SQL:

SELECT [t0].[ConcessionID], [t0].[Title], [t0].[Country]
FROM [dbo].[Concessions] AS [t0]
WHERE [t0].[Country] = ga

... when what I want is

WHERE [t0].[Country] = 'ga'

Any ideas why?

[A]
the select should be
```
```
Select New With {t.ConcessionID, t.Title, t.Country}
```
```
rather than
```
```
Select t.ConcessionID, t.Title, t.Country
```
```
you need to create a new instance of an anonymous type to contain the fields.


q:
Right now, I have a SQL Query like this one:

SELECT X, Y FROM POINTS

It returns results like so:

X    Y
----------
12   3
15   2
18   12
20   29

I'd like to return results all in one row, like this (suitable for using in an HTML <AREA> tag):

XYLIST
----------
12,3,15,2,18,12,20,29

Is there a way to do this using just SQL?

[A]
```
```
DECLARE @s VarChar(8000)
SET @s = ''

SELECT @s = @s + ',' + CAST(X AS VarChar) + ',' + CAST(Y AS VarChar)
FROM POINTS

SELECT @s
```
```
Just get rid of the leading comma


q:
Is it possible to check out subdirectories of a repository in Git?

Imagine I am setting up a new WordPress installation. I will create two new directories for my plugin and theme customization:

wordpress/wp-content/plugins/myplugins/

wordpress/wp-content/themes/mytheme/

I want to maintain these directories via Git. In Subversion, I would accomplish this by having trunk/myplugins/ and trunk/mytheme/ directories and checking out subdirectories. Does Git have a way to accomplish the same task using a single repository?

I could just be missing the boat on some Git paradigm, as a long time SVN user with little exposure to Git.

Edit: Multiple branches storing different content is an interesting way to handle this.

[A]
There is no real way to do that in git. And if you won’t be making changes that affect both trees at once as a single work unit, there is no good reason to use a single repository for both. I thought I would miss this Subversion feature, but I found that creating repositories has so little administrative mental overhead (simply due to the fact that repositories are stored right next to their working copy, rather than requiring me to explicitly pick some place outside of the working copy) that I got used to just making lots of small single-purpose repositories.
If you insist (or really need it), though, you could make a git repository with just
```
mytheme
```
and
```
myplugins
```
directories and symlink those from within the WordPress install.
MDCore wrote:
making a commit to, e.g.,
mytheme
will increment the revision number for
myplugin
Note that this is not a concern for git, if you do decide to put both directories in a single repository, because git does away entirely with the concept of monotonically increasing revision numbers of any form.
The sole criterion for what things to put together in a single  repository in git is whether it constitutes a single unit, ie. in your case whether there are changes where it does not make sense to look at the edits in each directory in isolation. If you have changes where you need to edit files in both directories at once and the edits belong together, they should be one repository. If not, then don’t glom them together.
Git really really wants you to use separate repositories for separate entities.
submodules
Submodules do not address the desire to keep both directories in one repository, because they would actually
enforce
having a separate repository for each directory, which are then brought together in
another
repository using submodules. Worse, since the directories inside the WordPress install are not direct subdirectories of the same directory and are also part of a hierarchy with many other files, using the per-directory repositories as submodules in a unified repository would offer no benefit whatsoever, because the unified repository would not reflect any use case/need.


q:
I've written a simple multi-threaded game server in python that creates a new thread for each client connection.  I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error.  I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present.

What is a good way to deal with this?  My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program.

PS: This question/answer deals with the problem in a generic way; how specifically should I solve it?

[A]
Read up on the try: statement.
```
```
try:
    # do something
except socket.error, e:
    # A socket error
except IOError, e:
    if e.errno == errno.EPIPE:
        # EPIPE error
    else:
        # Other error
```
```


q:
I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document. What is correct way (if any) to set the title of the document?

<script type="text/javascript">
$(document).ready(function() {

    // ???

});
</script>

[A]
Like this:
```
```
$(document).ready(function ()
{
    document.title = "Hello World!";
});
```
```
Be sure to set a default-title if you want your site to be properly indexed by search-engines.
A little tip:
```
```
$(function ()
{
    // this is a shorthand for the whole document-ready thing
    // In my opinion, it's more readable
});
```
```


q: Is there an easy way to generate a PDF report from an RDL that's been uploaded to Report Manager and put that file somewhere on the server's disk? I already have a location on disk to put the file, I just need to know how to programmatically generate the PDF. This is for SQL Server 2005 Reporting Services. Code in either VB or C# is fine.

[A]
This
article
will show you how you can generate PDF report from reporting service, without using report viewer. Only change you have to do is to write the result byte array into a file stream instead of sending it to response stream as shown in that example. The above mentioned example is using the web services provided by SQL reporting service to generate report.


q:
How do I get a method's execution time?

Is there a Timer utility class for things like timing how long a task takes, etc?

Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.

[A]
This probably isn't what you wanted me to say, but this is a good use of AOP. Whip an proxy interceptor around your method, and do the timing in there.
The what, why and how of AOP is rather beyond the scope of this answer, sadly, but that's how I'd likely do it.
Edit:
Here's a link
to Spring AOP to get you started, if you're keen. This is the most accessible implementation of AOP that Iive come across for java.
Also, given everyone else's very simple suggestions, I should add that AOP is for when you don't want stuff like timing to invade your code. But in many cases, that sort of simple and easy approach is fine.


q:
Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++?

MyObject  object;  // ok - default ctor
MyObject  object(blah); // ok

MyObject  object();  // error

I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?

[A]
The same syntax is used for function declaration - e.g. the function
```
object
```
, taking no parameters and returning
```
MyObject
```


q:
To make click-able divs, I do:

<div class="clickable" url="http://google.com">
    blah blah
</div>

and then

$("div.clickable").click(
function()
{
    window.location = $(this).attr("url");
});

I don't know if this is the best way, but it works perfectly with me, except for one issue:
If the div contains a click-able element, such as
    <a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called

This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function AND follows the link in the 'url' attribute of the div.

Anyway around this?

[A]
```
$("div.clickable").click(
function(event)
{
    window.location = $(this).attr("url");
    event.preventDefault();
});
```


q:
Does WebSphere offer an HTTP input filter / firewall like mod_security?

I know that it's possible to have Apache be the HTTP server front-end to WebSphere, but that type of configuration is beyond my influence.  We're stuck using just what WebSphere itself can do.

EDIT - To clarify, I am not looking for authentication, authorization, or non-repudiation aspects of security here.  I want a rule-based HTTP firewall like mod_security that works on WebSphere.

Also, I know that in version 1.x, there was a partial implementation of mod_security in Java.  We currently have a custom, in-house solution that is a work-alike, but less arbitrarily configurable.  Thanks!

[A]
J2EE has a
standard
way of
securing
it's apps.  I recommend using this.  If what you are trying to do is oddball, you could look at
Custom User Registries (IBM specific)
, or implement a custom system all together with
Servlet Filters
.


q:
We are making a Ruby On Rails webapp where every customer gets their own database.

The database needs to be created after they fill out a form on our website.

We have a template database that has all of the tables and columns that we need to copy.  How can I do this in programatically from ruby on rails?

[A]
From any controller, you can define the following method.
```
```
def copy_template_database
        template_name = "customerdb1" # Database to copy from
        new_name = "temp" #database to create & copy to

        #connect to template database to copy.  Note that this will override any previous
        #connections for all Models that inherit from ActiveRecord::Base
        ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => template_name, :host => "olddev",
        :username => "root", :password => "password" })

        sql_connection = ActiveRecord::Base.connection
        sql_connection.execute("CREATE DATABASE #{new_name} CHARACTER SET latin1 COLLATE latin1_general_ci")
        tables = sql_connection.select_all("Show Tables")
        #the results are an array of hashes, ie:
        # [{"table_from_customerdb1" => "customers"},{"table_from_customerdb1" => "employees},...]
        table_names = Array.new
        tables.each { |hash| hash.each_value { |name| table_names << name }}

        table_names.each { |name|
            sql_connection.execute("CREATE TABLE #{new_name}.#{name} LIKE #{template_name}.#{name}")
            sql_connection.execute("INSERT INTO #{new_name}.#{name} SELECT * FROM #{template_name}.#{name}")
        }
        #This statement is optional.  It connects ActiveRecord to the new database
        ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
        :username => "root", :password => "password" })
    end
```
```
Note that I do not know for sure if this will keep foriegn key integrity.  I think it depends a lot on how the template Database is created.


q:
I have a memory of talking to people who have got so far in using Ruby on Rails and then had to abandon it when they have hit limits, or found it was ultimately too rigid.  I forget the details but it may have had to do with using more than one database.

So what I'd like is to know is what features/requirements fall outside of Ruby on Rails, or at least requires such contortions that it is better to use another more flexible framework, even though you may have to lose some elegance or write extra boilerplate code.

[A]
Ruby on Rails does not support two-phase commits out of the box, which maybe required if your database-backed application needs to guarantee immediate consistency AND you need to use two or more database schemas.
For many web applications, I would venture that this is not a common use-case. One can perfectly well support eventual consistency with two or more databases. Or one could support immediate consistency with one database schema. The former case is a great problem to have if your app has to support a mondo amount of transactions (note the technical term :). The latter case is more typical, and Rails does just fine.
Frankly, I wouldn't worry about limits to using Ruby on Rails (or any framework) until you hit real scalability problems. Build a
killer
app
first
, and then worry about scalability.
CLARIFICATION: I'm thinking of things that Rails would have a hard-time supporting because it might require a fundamental shift in its architecture. I'll be generous and include some things that are part of the gem/plugin ecosystem such as foreign key enforcement or SOAP services.
By two-phase commits, I mean attempting to make two commits to physically distinct servers within one transactional context.
Use case #1 for a two-phase commit: you've clustered your database, so that you have 2 or more database servers and your schema is spread across both servers. You may want to commit to both servers, because you want to allow ActiveRecord think do a "foreign key map" that traverses across the different servers.
Use case #2 for a two-phase commit: you're attempting to implement a messaging solution (sorry, I'm J2EE developer by day). The message producer commits to the messaging broker (one server) and to the database (a different server).


q:
I have a number of child tables that have a foreign key to a parent table.

How do I add an entry in the parent table and get the primary key of that entry, so that I can then enter rows in the child tables that point to the entry in the parent table?

I'm doing this in a MS Access Database from a C# application.

[A]
Microsoft Access 2000 or later does support the @@IDENTITY property to retrieve the value of an Autonumber field after an INSERT. (
msdn
)
Edit:
This
is the link to a similar article for .NET 3.5


q:
I've been programming in C++ for a few years, and I've used STL quite a bit and have created my own template classes a few times to see how it's done.

Now I'm trying to integrate templates deeper into my OO design, and a nagging thought keeps coming back to me: They're just a macros, really... You could implement (rather UGLY) auto_ptrs using #defines, if you really wanted to.

This way of thinking about templates helps me understand how my code will actually work, but I feel that I must be missing the point somehow. Macros are meant evil incarnate, yet "template metaprogramming" is all the rage.

So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like

Inscrutable compiler errors in
places where you don't expect them?

Code bloat?

Difficulty in tracing code?

Setting Debugger Breakpoints?

[A]
They are parsed by the
compiler
and not by a preprocessor that runs
before
the compiler.
Here's what MSDN says about it:
http://msdn.microsoft.com/en-us/library/aa903548(VS.71).aspx
Here are some problems with the macro:
There is no way for the compiler to verify that the macro parameters are of compatible types.
The macro is expanded without any special type checking.
The i and j parameters are evaluated twice. For example, if either parameter has a postincremented variable, the increment is performed two times.
Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging.
If that's not enough for you, I don't know what is.


q:
I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later.

Can anybody tell me how to obtain the file path from the save dialog box to use it later?

[A]
Here is a sample code I just wrote very fast... instead of Console.Write you can simply store the path in a variable and use it later.
```
```
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 1;

if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    Console.WriteLine(saveFileDialog1.FileName);//Do what you want here
}
```
```


q:
In our program, each customer gets their own database.  We e-mail them a link that connects them to their database.  The link contains a GUID that lets the program know which database to connect to.

How do I dynamically and programatically connect ActiveRecord to the right db?

[A]
you can change the connection to ActiveRecord at any time by calling ActiveRecord::Base.establish_connection(...)
IE:
```
```
ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
    :username => "root", :password => "password" })
```
```


q:
Is there any way instead of a JS hack where I can post from an iframe to another page outside the iframe?

the iframe is posting data to a 3rd party and then just responding back with a URL which is the redirection URl thus we cannot set the form target. We are PCI compliant and thus we cannot use window.parent.location = url;

[A]
```
<form>
```
accepts a target parameter, e.g. target="_parent"


q:
I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition.

How about these examples:

int* test;

int *test;

int * test;

int* test,test2;

int *test,test2;

int * test,test2;

Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one.

The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a "real" int. What about case 6? Same as case 5?

[A]
4, 5, and 6 are the same thing, only
test
is a pointer. If you want two pointers, you should use:
```
```
int *test, *test2;
```
```
Or, even better (to make everything clear):
```
```
int* test;
int* test2;
```
```


q:
I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16.

var users = from u in dc.Users
            where ((u.UserRolesBitmask & 1) == 1)
               || ((u.UserRolesBitmask & 4) == 4)
               || ((u.UserRolesBitmask & 16) == 16)
            select u;

I'd like to rewrite this into the method below to returns all the users from the given roles so I can reuse it:

private List<User> GetUsersFromRoles(uint[] UserRoles) {}

Any pointers on how to dynamically build my query? Thanks

[A]
Assuming your UserRoles values are themselves bitmasks, would something like this work?
```
```
private List<User> GetUsersFromRoles(uint[] UserRoles) {
    uint roleMask = 0;
    for (var i = 0; i < UserRoles.Length;i++) roleMask= roleMask| UserRoles[i];
    // roleMasknow contains the OR'ed bitfields of the roles we're looking for

    return (from u in dc.Users where (u.UserRolesBitmask & roleMask) > 0) select u);
}
```
```
There's probably a nice LINQ syntax that'll work in place of the loops, but the concept should be the same.


q: Classes that use other classes (as members, or as arguments to methods) need instances that behave properly for unit test. If you have these classes available and they introduce no additional dependencies, isn't it better to use the real thing instead of a mock?

[A]
It is fine to use the "real thing" as long as you have absolute control over the object.  For example if you have an object that just has properties and accessors you're probably fine.  If there is logic in the object you want to use, you could run into problems.
If a unit test for class a uses an instance of class b and an change introduced to b breaks b, then the tests for class a are also broken.  This is where you can run into problems where as with a mock object you could always return the correct value.  Using "the real thing"  Can kind of convolute tests and hide the real problem.
Mocks can have downsides too, I think there is a balance with some mocks and some real objects you will have to find for yourself.


q: I'm looking for a similar control to the InputFormSection control in Sharepoint that I want to use in a regular web page that doesn't run in the context of Sharepoint. Here's how the inputformsection looks like : http://graegert.com/wp-content/uploads/2008/01/moss_adminarea_page_structure1.png

[A]
So do I understand your question correctly? You want to have a control that looks and behave like the InputFormSection control of SharePoint, but it should be able to run outside the context of a SharePoint site?
If so, one approach that you could take is to rip out the generated HTML and use it in your own user control. The IE Developer Toolbar can be of great help to retrieve all other the information (
http://www.microsoft.com/en-us/download/details.aspx?id=18359
).


q:
I'm refactoring some PHP code and discovered that certain nested combinations of

if () :

and

if () {

generate syntax errors.  Not that I would normally mix the two, but I like to do frequent syntax checks as I'm writing code and I kept getting a syntax error because of this.

Example - generates syntax error:

if ( $test == 1 ) :
  if ( $test2 == 'a' ) {
    if ( $test3 == 'A' ) {
    } else {
    }
  }
else :
  echo 'test2';
endif;

Example - does NOT generate syntax error:

if ( $test == 1 ) :
  if ( $test2 == 'a' ) :
    if ( $test3 == 'A' ) :
    else :
    endif;
  endif;
else :
  echo 'test2';
endif;

Could someone please explain to me why the first block of code is generating an error?

[A]
This is a wild guess since I am not familiar with the grammar of PHP. But here goes:
The problem is the second
```
else
```
. The parser can't see if this
```
else
```
is belonging to the first or the second if (counting from the beginning). In your second example there is an
```
endif
```
making the second
```
if
```
-block be terminated so there it can do the parse. Perhaps this is the famous 'dangling-else' problem in disguise?


q:
I have roughly the following code. Could this be made nicer or more efficient? Perhaps using std::remove_if? Can you remove items from the map while traversing it? Can we avoid using the temporary map?

typedef std::map<Action, What> Actions;
static Actions _actions;

bool expired(const Actions::value_type &action)
{
  return <something>;
}

void bar(const Actions::value_type &action)
{
  // do some stuff
}

void foo()
{
  // loop the actions finding expired items
  Actions actions;
  BOOST_FOREACH(Actions::value_type &action, _actions)
  {
    if (expired(action))
      bar(action);
    else
      actions[action.first]=action.second;
    }
  }
  actions.swap(_actions);
}

[A]
If the idea is to remove expired items, why not use
map::erase
? This way you only have to remove elements you don't need anymore, not rebuild an entire copy with all the elements that you want to keep.
The way you would do this is to save off the iterators pointing to the elements you want to erase, then erase them all after the iteration is over.
Or, you can save off the element that you visited, move to the next element, and then erase the temporary. The loop bounds get messed up in your case though, so you have to fine tune the iteration yourself.
Depending on how expired() is implemented, there may be other better ways. For example if you are keeping track of a timestamp as the key to the map (as expired() implies?), you can do upper_bound on the current timestamp, and all elements in the range [ begin(), upper_bound() ) need to be processed and erased.


q:
I've just discovered that Oracle lets you do the following:

SELECT foo.a, (SELECT c
               FROM bar
               WHERE foo.a = bar.a)
from foo

As long as only one row in bar matches any row in foo.

The explain plan I get from PL/SQL developer is this:

SELECT STATEMENT, GOAL = ALL_ROWS
 TABLE ACCESS FULL  BAR
 TABLE ACCESS FULL  FOO

This doesn't actually specify how the tables are joined.  A colleague asserted that this is more efficient than doing a regular join.  Is that true? What is the join strategy on such a select statement, and why doesn't it show up in the explain plan?

Thanks.

[A]
The plan you have there does not provide much information at all.
Use SQL*Plus and use dbms_xplan to get a more detailed plan.  Look for a script called utlxpls.sql.
This gives a bit more information:-
```
```
--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |  1837 | 23881 |     3   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| BAR  |    18 |   468 |     2   (0)| 00:00:01 |
|   2 |  TABLE ACCESS FULL| FOO  |  1837 | 23881 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("BAR"."A"=:B1)

Note
-----
   - dynamic sampling used for this statement

18 rows selected.
```
```
I didn't create any indexes or foreign keys or collect statistics on the tables, which would change the plan and the join mechanism choosen.  Oracle is actually doing a NESTED LOOPS type join here.  Step 1, your inline sub-select, is performed for every row returned from FOO.
This way of performing a SELECT is not quicker.  It could be the same or slower.  In general try and join everything in the main WHERE clause unless it becomes horribly unreadable.


q:
Being an aspiring Apple developer, I want to get the opinions of the community if it is better to learn C first before moving into Objective-C and ultimately the Cocoa Framework?

My gut says learn C, which will give me a good foundation.

[A]
Better, I don't know, even less as I am not familiar with Objective-C.
But bases of C aren't so hard to learn, it isn't a very complex language (in terms of syntax, not in terms of mastering!), so go for it, it won't be wasted time.
Personally, I think it is always a good idea to learn C, it gives a good insight of how computer works. After all, most languages and systems are still written in C. Then move on! :-)
PS.: By "move on", I didn't mean "drop it", just "learn more, learn different". Once you know C, you might never drop it: Java uses JNI to call C routines for low level stuff, Python, Lua, etc. are often extended with C code (Lua reference even just assumes some C knowledge for some functions which are just a thin wrapper to the C function behind), and so on.


q:
I'd like to bold the text for a tab page under certain conditions (not, necessarily, GotFocus).  Is it true the only 'er easiest way to do this is by overriding the DrawItem event for the tab control?

http://www.vbforums.com/showthread.php?t=355093

It seems like there should be an easier way.

Like ...

tabControl.TabPages(index).Font = New Font(Me.Font, FontStyle.Bold)

That doesn't work, obviously.

[A]
When you set the Font property on a TabPage, you are setting the default font for all controls on that tab page. You are not setting it for the header, however.
When you execute the following code:
```
```
tabControl.TabPages(index).Font = New Font(Me.Font, FontStyle.Bold)
```
```
Any controls on that page will now be bold by default, which is not (I'm assuming) what you want.
The header's font (that is, the tab itself) is controlled by the TabControl's Font property. If you were to change your code to:
```
```
tabControl.Font = New Font(Me.Font, FontStyle.Bold)
```
```
You will see that in action. However, it changes the font for
all
the tabs on display, which is also not, I'm assuming, what you want.
So, using the default WinForms tab control, you are (I believe) limited to the technique in the link you've posted. Alternatively, you can begin looking at 3rd-party controls, such as those discussed in
these
questions
on
StackOverflow
.


q: I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values.  How do I convert this into a "regular" string that I can echo to the screen?


q: I am hoping to find a resource for lining up input elements in a HTML page. I find it difficult to get a select element and a text box to be the same width even when using the width style attribute, and it is even more difficult across browsers. Finally, file inputs seem impossible to get to the same width cross browser. Are there any good guides or tips for accomplishing this? Perhaps there are some default CSS attributes I should be setting.

[A] I usually put them inside a div or table cell (horrors! I know) of the width I want, then set the select and input style:width to 100% so they fill the div / cell they are in.


q:
When 'val' below is not a bool I get an exception, I believe I can use TryParse but I'm not sure how best to use it with my code below. Can anyone help?

checkBox.Checked = Convert.ToBoolean(val);

Thanks

[A]
The code is as follows to determine whether the string
```
val
```
is a valid Boolean value and use it to set the
```
Checked
```
property if so. You need to decide what action you would take if it does not represent a valid value.
```
```
bool result;
if (bool.TryParse(val, out result))
{
    // val does represent a Boolean
    checkBox.Checked = result;
}
else
{
    // val does not represent a Boolean
}
```
```


q:
I heard Microsoft allows use of commercially available Office UI controls, with the exception of competing products, such as a word processor or spreadsheet app, etc.

How true is that?

Also, if it is not true, do you know of any free Ribbon controls?

[A]
You should look at
Jensen Harris' blog entry about licensing the Office user interface
which explains it in great detail. However I believe the relevant point here is:
There's only one limitation: if you
  are building a program which directly
  competes with Word, Excel, PowerPoint,
  Outlook, or Access (the Microsoft
  applications with the new UI), you
  can't obtain the royalty-free license.


q:
So, I'm working under the assumption that we have typed languages because we make a lot of mistakes... so typing is one way to have the compiler do a lot of checks for us and help us out a bit (please let me know if it is my assumptions that's incorrect).

However, if we introduce casting to a typed language, don't we re-introduce most the problems we had when were not able to type variables?

I'm also aware that my assumption isn't the only reason why we type variables. Please share some of the other reasons why we have typed languages.

[A]
so typing is one way to have the
  compiler do a lot of checks for us and
  help us out a bit
Yes.
However, if we introduce casting to a
  typed language, don't we re-introduce
  most the problems we had when were not
  able to type variables?
Yes.
You should avoid it to the extent possible, but sometimes you still need to do dirty work.
Of course, there are plenty of languages that do not enforce strict typing, and plenty of people who like them and get useful work done with them.


q:
I'm using a vendor API to obtain a JDBC connection to the application's database. The API works when running in the application server or when running in a stand-alone mode. I want to run a series of SQL statements in a single transaction. I'm fine with them occurring in the context of the JTA transaction if it exists. However, if it doesn't then I need to use the JDBC transaction demarcation methods. (Calling these methods on a JDBC connection that is participating in a JTA transaction causes a SQLException.)

So I need to be able to determine whether the Connection came from the JTA enabled DataSource or if it's just a straight JDBC connection.

Is there a straight forward way to make this determination?

Thanks!

[A]
You could try to check the Connection's autoCommit flag to see if it is in a transaction (regardless of where it came from).
(Apparently, see the accepted answer, this does not work too well. I am not deleting this answer because the following still stands: )
But I think you should really modify your API to depend on external transactions exclusively. If you still want to support plain JDBC, wrap it into a separate API that just starts the transaction.
Update: Just re-read your question and saw that you are not providing an API, but want to use a container-managed connection. But still, can you just mandate (as part of your application's requirements) that JTA be in effect? If not, you could provide a configuration option to fall back to manually managed transactions. For such a critical feature it seems reasonable to require the proper configuration (as opposed to try to guess what would be appropriate).


q:
How do you iterate over each file in a directory with a .bat or .cmd file?

For simplicity please provide an answer that just echoes the filename or file path.

[A]
Command line usage:
```
```
for /f %f in ('dir /b c:\') do echo %f
```
```
Batch file usage:
```
```
for /f %%f in ('dir /b c:\') do echo %%f
```
```
Update
: if the directory contains files with space in the names, you need to change the delimiter the
```
for /f
```
command is using. for example, you can use the pipe char.
```
```
for /f "delims=|" %%f in ('dir /b c:\') do echo %%f
```
```
Update 2
: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the
```
usebackq
```
option on the
```
for
```
:
```
```
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f
```
```
And if you need to use output redirection or command piping, use the escape char (
```
^
```
):
```
```
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f
```
```


q:
I have an upcoming project which will have to be able to print simple reports from its data. It'll be WPF-based, and I'm wondering which way to go.

I know that WPF introduces its own printing technology (based on XPS) which looks quite easy to use. However, part of me wonders whether it would just be easier to use the ReportViewer control and embed it in a Windows Forms host control, since that will give users the ability to export to a variety of formats as well as print.

Has anyone had any experience with printing/reporting from WPF? Which direction would you recommend?

[A]
I've reccently accomplished task of developing own reporting system, which basically consist on design enviroment and data Source manager. The first task was to develop WYSWIG-like design enviroment. I've done this using GDI+, without even bothering about printing, as it came out printing/generating print preview was easiest than i expected, In general it  only takes to draw all things on screen to graphics object of printing event.
I think that in case of WPF it would be similar, so all you should worry about is to display you report on screen and printing would be only few lines of code.


q:
Is there a way to take substrings of a string with .bat/.cmd files?

For example given the string "hello.txt" is there a way to strip the .txt?

EDIT: Also is there a more general way to do this, not under the assumption that it is a file name or file path?

[A]
If this is a file passed as a parameter, you can use %~n1, like this:
```
```
test.bat
----------
echo %~n1 %~n2

c:\> test.bat myfile.txt my.long.file.bat
  myfile my.long.file
```
```
If you know the length of the string you can use the substring operator:
```
```
echo %variable:0,4%   =>  "test.txt" => "test"
```
```
And to get everything EXCEPT the last 4 characters:
```
```
echo %variable:~0,-4%  => "file...name.txt" => "file...name"
```
```
BatchFiles Website (kind advanced)
Decent forum post
Another Good Post


q: What are the best free resources for learning advanced batch-file usage?

[A]
Tried
Wikipedia's batch file entry
? ...or any of
the multitude of answers google gives on advanced batch file usage
?


q: I have a ListBox which displays items of variable height. I want to show as many items as will fit in the available space, without showing a vertical scrollbar. Other than surgery on the ListBox item template, is there a way to only show the number of items which will fit without scrolling?

[A]
```
```
<ListBox ScrollViewer.VerticalScrollBarVisibility="Auto" />
```
```
the default is visible


q:
I have a servlet which is in the same web application as the JSF servlet.
How do I replace (rather than redirect) the servlet response with the JSF response?

[A]
Not sure I fully understand your question - but if you want to include the output from a JSF page in your servlet response, something like:
```
```
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        // Do stuff
        req.getRequestDispatcher("/blah.jsf").forward(req, res);
        // Do other stuff
}
```
```
Should do the trick


q:
Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface?

In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter the changed data. Using a better model structure would be one way of reducing the duplication of the data, but there may be situation where the duplicated data needs to be changed on an individual basis in the future.

[A]
You can
save as
by just enabling adding this to your ModelAdmin:
```
```
save_as = True
```
```
This replaces the "Save and add another" button with a "Save as" button.  "Save as" means the object will be saved as a new object (with a new ID), rather than the old object.


q:
Here are some gems:

Literals:

var obj = {}; // Object literal, equivalent to var obj = new Object();
var arr = []; // Array literal, equivalent to var arr = new Array();
var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something');

Defaults:

arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as:
arg = !!arg ? arg : 'default';

Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great:

(function() { ... })(); // Creates an anonymous function and executes it

Question: What other great syntactic sugar is available in javascript?

[A]
In Mozilla (and reportedly IE7) you can create an XML constant using:
```
var xml = <elem></elem>;
```
You can substitute variables as well:
```
var elem = "html";
var text = "Some text";
var xml = <{elem}>{text}</{elem}>;
```


q:
I'm the creator (and so far, only developer) of a CodePlex project.  I've writing it on my laptop, using a Subversion repository on my home network.

Submitting my changes to CodePlex via the TeamServer interface is driving me crazy, and I'd really like a simple way of syncing my svn repos with CodePlex via there new SVN interface.  svnsync or synmerge seem to be the way to go, but neither's instructions seem clear to a guy who's only ever used TortoiseSVN. And they seem to also seem need local access to the destination server (which clearly for CodePlex, is impossible)

So, could someone give simple instructions how to do this?

[A]
As you'll find in the
documentation
, svnsync requires exclusive (but not local) access to the destination server. This makes it unfit for your purpose, as it would render the CodePlex repository inaccessible for commits by other developers (when they come ;)).
You might consider the other way around though: always commit to the CodePlex repo, and use svnsync to keep a local (and read-only) mirror of that.


q:
How would you reference the models (Accord, CRV, Prius, etc) in this structure?
Is this a bad structure to be able to extract the makes...then use a make to get the models...then use the model to get the options?

var cars = [
    {
        "makes"   : "Honda",
        "models"   : [
            {'Accord' : ["2dr","4dr"]} ,
            {'CRV'    : ["2dr","Hatchback"]} ,
            {'Pilot'  : ["base","superDuper"] }
        ]
    },
    {
        "makes"   : "Toyota",
        "models"  : [
            {'Prius'   : ["green","reallyGreen"]} ,
            {'Camry'   : ["sporty","square"]} ,
            {'Corolla' : ["cheap","superFly"] }
        ]
    }
];

Thanks

[A]
cars[0].models.Accord
    cars[0].models.CRV
    cars[0].models.Pilot
(See
olliej
's answer)
Though, it may be easier to use the following access concept:
```
```
cars.Honda.Accord
cars.Toyota.Prius
```
```
...using...
```
```
var cars = {
  Honda : {
    Accord : ["2dr", "4dr"],
    CRV    : ["2dr", "Hatchback"],
    Pilot  : ["base", "superDuper"]
  },
  Toyota : {
    Prius : ["green", "reallyGreen"],
    Camry : ["sporty", "square"],
    Corolla : ["cheap", "superFly"]
  }
};
```
```


q:
What is the maximum length for the text string contained in a CEdit control in MFC? I get a beep when trying to add a character after the character 30001 is this documented anywhere? Can I display longer texts in a CEdit? Should I use another control?

As "Windows programmer" says down below, the text length limit is not the same when the user types as when we programatically set the text using SetWindowText. The limit for setting a text programatically is not mentioned anywhere. The default text lentgth limit for the user typing is wrong. (see my own post below).

I'm guessing that after I call pEdit->SetLimitText(0) the limit for both programatically and user input text length is 7FFFFFFE bytes. Am I right?

In vista, when pasting text longer than 40000 characters into a CEdit, it becomes unresponsive. It does not matter if I called SetLimitText(100000) previously.

[A]
You can find out what the maximum is for your control by calling
CEdit::GetLimitText()
on your control.  This returns the maximum size for character data in bytes.  You can change the maximum size using the
CEdit::SetLimitText()
function.
The SetLimitText() function is equivalent to sending an
EM_SETLIMITTEXT
message.  The documentation for that message gives the maximum sizes that can be used, but since these are MSDN links that will probably be broken by tomorrow, I'll copy the relevant information :)
The UINT parameter is interpreted as:
The maximum number of TCHARs the user
  can enter. For ANSI text, this is the
  number of bytes; for Unicode text,
  this is the number of characters. This
  number does not include the
  terminating null character. Rich edit
  controls: If this parameter is zero,
  the text length is set to 64,000
  characters.
Edit controls on Windows NT/2000/XP:
  If this parameter is zero, the text
  length is set to 0x7FFFFFFE characters
  for single-line edit controls or –1
  for multiline edit controls.
Edit controls on Windows 95/98/Me: If
  this parameter is zero, the text
  length is set to 0x7FFE characters for
  single-line edit controls or 0xFFFF
  for multiline edit controls.
Also, from the Remarks section:
Before EM_SETLIMITTEXT is called, the
  default limit for the amount of text a
  user can enter in an edit control is
  32,767 characters.
Edit controls on Windows NT/2000/XP:
  For single-line edit controls, the
  text limit is either 0x7FFFFFFE bytes
  or the value of the wParam parameter,
  whichever is smaller. For multiline
  edit controls, this value is either –1
  bytes or the value of the wParam
  parameter, whichever is smaller.
Edit controls on Windows 95/98/Me: For
  single-line edit controls, the text
  limit is either 0x7FFE bytes or the
  value of the wParam parameter,
  whichever is smaller. For multiline
  edit controls, this value is either
  0xFFFF bytes or the value of the
  wParam parameter, whichever is
  smaller.
I assume they meant 0xFFFFFFFF instead of -1 in the second paragraph there...


q: If a file is set to read only mode, how do I change it to write mode and vice versa from within Emacs?

[A]
M-x read-only-mode
in very old versions of Emacs, the command was:
M-x toggle-read-only
On my Windows box, that amounts to Alt-x to bring up the meta prompt and typing "read-only-mode" to call the correct elisp function.
If you are using the default keyboard bindings,
C-x C-q
(which you read aloud as "Control-X Control-Q") will have the same effect.  Remember, however, given that emacs is essentially infinitely re-configurable, your mileage may vary.
Following up from the commentary:
you should note that the writeable status of the buffer does not change the writeable permission of the file.  If you try to write out to a read only
file
, you'll see a confirmation message.  However, if you own the file, you can write out your changes
without
changing the permissions on the file.
This is very convenient if you'd like to make a quick change to a file without having to go through the multiple steps of add write permission, write out changes, remove write permission.  I tend to forget that last step, leaving potentially critical files open for accidental changes later on.


q: Working in Eclipse on a Dynamic Web Project (using Tomcat (v5.5) as the app server), is there some way I can configure things so Tomcat will start with security turned on (i.e. as if I ran catalina.sh start -security)?

[A]
I'm assuming that you're using Tomcat 5.5.x
after looking at catalina.bat/catalina.sh, all the -security flag does is to set
-Djava.security.policy=="%CATALINA_BASE%\conf\catalina.policy"
Most people have CATALINA_BASE set to TOMCAT_HOME or CATALINA_HOME
So, if you have installed tomcat in the directoryc:\tomcat, then all you need to do is to set an option in the tomcat plugin to include the above policy.
i.e, add this to JAVA_OPTIONS : -Djava.security.policy=="c:\tomcat\conf\catalina.policy".
That's all and restart.


q:
I want to programmatically create a new column in an MS Access table.  I've tried many permutations of ALTER TABLE MyTable Add  MyField DECIMAL (9,4) NULL; and got:

Syntax Error in Field Definition

I can easily create a number field that goes to a Double type, but I want decimal.  I would very strongly prefer to do this in a single ALTER TABLE statement and not have to create a field and then alter it.

I am using Access 2003.

[A]
The ALTER TABLE syntax is only supported in Jet 4.0/ACE while in
ANSI-92 Query Mode. Try an ADO connection e.g.
CurrentProject.Connection.Execute "ALTER TABLE myTbl ADD COLUMN myColumn DECIMAL(9,4)"


q:
I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call.

Given this data:

var data = new List<string>();
data.Add("One");
data.Add("Two");
data.Add("Three");

And this code: ** Which is not correct and is what needs to be fixed!! **

var shaped = data.Select(c =>
    new { c = c }
).ToList();

serializer.Serialize(shaped,sb);
string desiredResult = sb.ToString();

I would like desiredResult to be:

{
    "One": "One",
    "Two": "Two",
    "Three": "Three"
}

but it is currently:

{ "c" : "One" },{ "c" : "Two" }, etc.

One problem is that on the left side of the object initializer I want the value of c, not c itself...


q: Is there a freely available Base64 decoding code snippet in C++?

[A]
See
Encoding and decoding base 64 with C++
.
Here is the implementation from that page:
```
```
/*
   base64.cpp and base64.h

   Copyright (C) 2004-2008 René Nyffenegger

   This source code is provided 'as-is', without any express or implied
   warranty. In no event will the author be held liable for any damages
   arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose,
   including commercial applications, and to alter it and redistribute it
   freely, subject to the following restrictions:

   1. The origin of this source code must not be misrepresented; you must not
      claim that you wrote the original source code. If you use this source code
      in a product, an acknowledgment in the product documentation would be
      appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and must not be
      misrepresented as being the original source code.

   3. This notice may not be removed or altered from any source distribution.

   René Nyffenegger rene.nyffenegger@adp-gmbh.ch

*/

static const std::string base64_chars =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";

static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}
std::string base64_decode(std::string const& encoded_string) {
  int in_len = encoded_string.size();
  int i = 0;
  int j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = base64_chars.find(char_array_4[i]);

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = base64_chars.find(char_array_4[j]);

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}
```
```


q: Just updated build server with rc0 and surprise no chiron.  Wondering how you package up a xap file without chiron.

[A]
Hey Brian, you can get chiron from
http://www.codeplex.com/sdlsdk
-- it was decided to be removed from the SL SDK core tools, but is still a part of the DLR SDK which is available.


q:
I have many years of experience in Java including Swing, Servlet and JDBC, but have never programmed for a Java EE server.

Many job advertisements from large companies are specifically asking for Java EE experience.  Are there specific skills or development environments that I should learn to qualify for these kinds of jobs?

[A]
Those jobs are most likely asking that you have experience with one or more of the major app server vendors, i.e. WebLogic, WebSphere, or JBoss. It's a bit different from what you're used to with servlets & JDBC, but it's still just Java. Typically you have to deal with things like JNDI lookups, dependency injection, messaging queues, maintaining application state between transactions, object/relational mapping, etc.
I have found that for most Java EE projects, it's more about knowing how components and systems are configured and how they work together than it is about any specific programming skill. And you also spend a lot more time waiting for the server to start up ;);


q:
I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly.

Lets say that I am trying to shuffle the randomizer array.

int[] randomizer = new int[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));

For some reason the elements stay sorted exactly the same whether or not I call the shuffle method.  Any ideas?

[A]
```
Arrays.asList
```
cannot be used with arrays of primitives. Use this instead:
```
```
Integer[] randomizer = new Integer[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
```
```
The same rule applies to most classes in the collections framework, in that you can't use primitive types.
The original code (with
```
int[]
```
) compiled fine, but did not work as intended, because of the behaviour of the variadic method
```
asList
```
: it just makes a one-element list, with the
```
int
```
array as its only member.


q: Why does tempuri.org exist?  Why does each XML Webservice require its own namespace, unique from any other on the web?

[A]
Unfortunately the
```
tempuri.org
```
URL now just redirects to Bing.
You can see what it used to render via
```
archive.org
```
:
https://web.archive.org/web/20090304024056/http://tempuri.org/
To quote:
Each XML Web Service needs a unique namespace in order for client
  applications to distinguish it from other services on the Web.  By
  default, ASP.Net Web Services use
http://tempuri.org/
for this
  purpose.  While this suitable for XML Web Services under development,
  published services should use a unique, permanent namespace.
Your XML Web Service should be identified by a namespace that you
  control.  For example, you can use your company's Internet domain name
  as part of the namespace.  Although many namespaces look like URLs,
  they need not point to actual resources on the Web.
For XML Web Services creating[sic] using ASP.NET, the default namespace can
  be changed using the WebService attribute's Namespace property.  The
  WebService attribute is applied to the class that contains the XML Web
  Service methods.  Below is a code example that sets the namespace to
  "
http://microsoft.com/webservices/
":
C#
```
```
[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
   // implementation
}
```
```
Visual Basic.NET
```
```
<WebService(Namespace:="http://microsoft.com/webservices/")> Public Class MyWebService
    ' implementation
End Class
```
```
Visual J#.NET
```
```
/**@attribute WebService(Namespace="http://microsoft.com/webservices/")*/
public class MyWebService {
    // implementation
}
```
```
It's also worth reading section 'A 1.3 Generating URIs' at:
http://www.w3.org/TR/wsdl#_Toc492291092


q:
What is the difference between the search() and match() functions in the Python re module?

I've read the Python 2 documentation (Python 3 documentation), but I never seem to remember it.  I keep having to look it up and re-learn it.  I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head.  Or at least I'll have a better place to return with my question and it will take less time to re-learn it.

[A]
```
re.match
```
is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using
```
^
```
in the pattern.
As the
re.match documentation
says:
If zero or more characters at the
beginning of string
match the regular expression pattern, return a
  corresponding
```
MatchObject
```
instance.
  Return
```
None
```
if the string does not
  match the pattern; note that this is
  different from a zero-length match.
Note: If you want to locate a match
  anywhere in string, use
```
search()
```
instead.
```
re.search
```
searches the entire string, as
the documentation says
:
Scan through string
looking for a
  location where the regular expression
  pattern produces a match, and return a
  corresponding
```
MatchObject
```
instance.
  Return
```
None
```
if no position in the
  string matches the pattern; note that
  this is different from finding a
  zero-length match at some point in the
  string.
So if you need to match at the beginning of the string, or to match the entire string use
```
match
```
. It is faster. Otherwise use
```
search
```
.
The documentation has a
specific section for
```
match
```
vs.
```
search
```
that also covers multiline strings:
Python offers two different primitive
  operations based on regular
  expressions:
```
match
```
checks for a match
only at the beginning
of the string,
  while
```
search
```
checks for a match
anywhere
in the string (this is what
  Perl does by default).
Note that
```
match
```
may differ from
```
search
```
even when using a regular expression
  beginning with
```
'^'
```
:
```
'^'
```
matches only
  at the start of the string, or in
```
MULTILINE
```
mode also immediately
  following a newline. The “
```
match
```
”
  operation succeeds
only if the pattern
  matches at the
start
of the string
regardless of mode, or at the starting
  position given by the optional
```
pos
```
argument regardless of whether a
  newline precedes it.
Now, enough talk. Time to see some example code:
```
```
# example code:
string_with_newlines = """something
someotherthing"""

import re

print re.match('some', string_with_newlines) # matches
print re.match('someother',
               string_with_newlines) # won't match
print re.match('^someother', string_with_newlines,
               re.MULTILINE) # also won't match
print re.search('someother',
                string_with_newlines) # finds something
print re.search('^someother', string_with_newlines,
                re.MULTILINE) # also finds something

m = re.compile('thing$', re.MULTILINE)

print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines,
               re.MULTILINE) # also matches
```
```


q: My application has no forms. It runs by calling Application.Run();

[A]
Call
```
```
System.Windows.Forms.Application.Exit();
```
```


q: Has anyone been able to implement the JQuery grid plugin, jqGrid? I'm trying to implement the JSON paging, and I feel like I'm getting close, but that I am also being swamped by inconsequential details. If anyone could post some sample code, I would greatly appreciate it.

[A]
I'm just floundering trying to pull everything together. My first concern is simply generating a correct JSON response. My returned class appears to be serialised as a property named 'd' - is this a JQuery thing, or ASP.Net web method convention? I'm afraid that jqGrid will be looking for the data to be top-level, whereas asp.net will put it in a property called 'd':
```
```
[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static object GetData() {
        TestClass tc = new TestClass() { One = "Hello", Two = "World" };
        return tc;
    }

        $("#divResults").click(function() {
            $.ajax({
                type: "POST",
                url: "GridData_bak.aspx/GetData",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(test) {
                    // Replace the div's content with the page method's return.
                    $("#divResults").text(test.d.One);
                },
                error: function(msg) {
                    $("#divResults").text(msg);
                }
            });
        });
```
```


q:
I installed Ruby and Ruby on Rails yesterday on Vista 32bit using the directions on this site: http://rubyonrails.org/down

So I downloaded the installer, then Gems, then I downloaded rails with Gems.

Now I can't use the Gem or Ruby commands in the command line... so I assume there's something wrong with the environment variables, but I hav eno idea how to set them up in Vista or what to put.

Can anyone help me with this?

[A]
In the command line window type
```
PATH
```
then hit return, do you see
```
ruby.exe
```
on the
```
PATH
```
environment variable?
If you installed ruby to say
```
c:\ruby
```
then it'll be
```
c:\ruby\bin\
```
.
Looks like it may be missing from the path.


q:
I am trying to learn some of the basic and advanced features of visual studio, Anyone find sites that have this type of information ?

I see this:

https://stackoverflow.com/questions/86355/best-way-to-learn-visual-studio-power-features

But it seems more related to tips and advanced features.

All three versions ( 2003, 2005, 2008 )


q:
With very large amounts of ram these days I was wondering, it is possible to allocate a single chunk of memory that is larger than 4GB? Or would I need to allocate a bunch of smaller chunks and handle switching between them?

Why???
I'm working on processing some openstreetmap xml data and these files are huge. I'm currently streaming them in since I can't load them all in one chunk but I just got curious about the upper limits on malloc or new.

[A]
it depends on which C compiler you're using, and on what platform (of course) but there's no fundamental reason why you cannot allocate the largest chunk of contiguously available memory - which may be less than you need. And of course you may have to be using a 64-bit system to address than much RAM...
see
Malloc
for history and details
call
HeapMax
in alloc.h to get the largest available block size


q:
I would like to extract from a general HTML page, all the text (displayed or not).

I would like to remove

any HTML tags

Any javascript

Any CSS styles

Is there a regular expression (one or more) that will achieve that?

[A]
Using perl syntax for defining the regexes, a start might be:
```
```
!<body.*?>(.*)</body>!smi
```
```
Then applying the following replace to the result of that group:
```
```
!<script.*?</script>!!smi
!<[^>]+/[ \t]*>!!smi
!</?([a-z]+).*?>!!smi
/<!--.*?-->//smi
```
```
This of course won't format things nicely as a text file, but it strip out all the HTML (mostly, there's a few cases where it might not work quite right). A better idea though is to use an XML parser in whatever language you are using to parse the HTML properly and extract the text out of that.


q:
I wanted to do something like this:

<asp:Label ID="lblMyLabel" onclick="lblMyLabel_Click" runat="server">My Label</asp:Label>

I know that in Javascript I can do:

<span onclick="foo();">My Label</span>

So I'm wondering why I can't do that with a Label object.

[A]
You can use Attributes to add onclick client side callback.
I didn't know you can do this on span tags, but if it works you can add 'onclick' by
```
lblMyLabel.Attributes.Add("onclick", "foo();");
```
But
```
foo();
```
would need to be a client side javascript function.
```
System.Web.UI.WebControls.Label
```
does NOT have OnClick server event. You could look into using AJAX if you want server callback with example above.
You could also use
```
LinkButton
```
like other say. You can make it not look like a link by using CSS, if it is just that underline you are concerned about.
ASPX:
```
```
<asp:LinkButton ID="LinkButton1" runat="server"
    CssClass="imjusttext" OnClick="LinkButton1_Click">
LinkButton
</asp:LinkButton>
```
```
CSS:
```
```
a.imjusttext{ color: #000000; text-decoration: none; }
a.imjusttext:hover { text-decoration: none; }
```
```


q:
I have a text file with multiple records. I want to search a name and date, for example if I typed JULIUS CESAR as name then the whole data about JULIUS will be extracted. What if I want only to extract information?

Record number: 1
Date: 08-Oct-08
Time: 23:45:01
Name: JULIUS CESAR
Address: BAGUIO CITY, Philippines
Information:
I lived in Peza Loakan, Bagiou City
A Computer Engineering student
An OJT at TIPI.
23 years old.

Record number: 2
Date: 09-Oct-08
Time: 23:45:01
Name: JOHN Castro
Address: BAGUIO CITY, Philippines
Information:
I lived in Peza Loakan, Bagiou City
A Electronics Comm. Engineering Student at SLU.
An OJT at TIPI.
My Hobby is Programming.

Record number: 3
Date: 08-Oct-08
Time: 23:45:01
Name: CESAR JOSE
Address: BAGUIO CITY, Philippines
Information:
Hi,,
I lived Manila City
A Computer Engineering student
Working at TIPI.

[A]
If it is one line per entry, you could use a regular expression such as:
```
```
$name = "JULIUS CESAR";
```
```
Then use:
```
```
/$name/i
```
```
to test if each line is about "JULIUS CESAR." Then you simply have to use the following regex to extract the information (once you find the line):
```
```
/Record number: (\d+) Date: (\d+)-(\w+)-(\d+) Time: (\d+):(\d+):(\d+) Name: $name Address: ([\w\s]+), ([\w\s]+?) Information: (.+?)$/i
```
```
$1 = record number
$2-$4 = date
$5-$7 = time
$6 = address
$7 = comments
I would write a code example, but my perl is rusty. I hope this helps :)


q:
i have a databound GridView in asp.net 2.0 with a row-selection link. When a row is selected, I want to programmatically add a table row below the selected row, in order to nest another grid et al.

I am researching this for a client and for an article, and i think my google-fu is not strong tonight. Any suggestions?

EDIT: I actually had a working solution but Visual Studio was nutted up somehow; closing and re-opening VS and rebuilding everything fixed the problem ;-)

My solution is posted below, please tell me how to make it better if possible. Thanks!

[A]
I think I figured it out. Here is a solution that seems to work. It could be improved using user controls but this is the gist of it:
```
```
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow &&
        (e.Row.RowState & DataControlRowState.Selected) > 0)
    {
        Table tbl = (Table)e.Row.Parent;
        GridViewRow tr = new GridViewRow(e.Row.RowIndex + 1, -1,
            DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
        TableCell tc = new TableCell();
        tc.ColumnSpan = GridView1.Columns.Count;
        tc.Controls.Add(
            makeChildGrid(Convert.ToInt32(
                ((DataRowView)e.Row.DataItem)["ROW_ID_FIELD"])));
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);
    }
}

protected GridView makeChildGrid(int id)
{
    GridView gv = new GridView();
    SqlDataSource sqlds = new SqlDataSource();
    sqlds.DataSourceMode = SqlDataSourceMode.DataSet;
    sqlds.ConnectionString = SqlDataSource1.ConnectionString;
    sqlds.SelectCommand = "SELECT * from MY_TABLE_NAME " +
        "WHERE KEY_FIELD = " + id.ToString();
    DataView dv = (DataView)sqlds.Select(DataSourceSelectArguments.Empty);
    gv.DataSource = dv;
    gv.DataBind();    //not sure this is necessary...?
    return gv;
}
```
```


q:
I was wondering if you know somewhere where I can find information on how to build a signature file for docuement retrieval.

Do you know if there is some code out there that I can use or look at?

I have to create a signature file in C++ under linux platform.

UPDATE: Sorry, I appreciatte the help but I was refering to signature files not as a way to validate documents but as a way of indexing documents.

http://en.wikipedia.org/wiki/Signature_files

Any help will be greatly appreciated.

Thanks,

[A]
md5sum
might be what you are looking for. Source code for generating md5 signatures is available if you Google around.
From Wikipedia:
Because almost any change to a file
  will cause its MD5 hash to also
  change, the MD5 hash is commonly used
  to verify the integrity of files
  (i.e., to verify that a file has not
  changed as a result of file transfer,
  disk error, meddling, etc.). The
  md5sum program is installed by default
  in most Unix, Linux, and Unix-like
  operating systems or compatibility
  layers. BSD variants (including Mac OS
  X) have a similar utility called md5.
  Versions for Microsoft Windows do
  exist.


q:
In VB.NET I often Catch…When:

Try
    …
Catch e As ArgumentNullException When e.ParamName.ToUpper() = "SAMPLES"
    …
End Try

Is there a C# equivalent to Catch…When?

I don't want to resort to using an if statement inside a catch if possible.

[A]
There's no equivalent to
```
Catch…When
```
in C#. You will really have to resort to an
```
if
```
statement inside your
```
catch
```
, then rethrow if your condition isn't fulfilled:
```
```
try
{
    …
}
catch (ArgumentNullException e)
{
    if ("SAMPLES" == e.ParamName.ToUpper())
    {
        … // handle exception
    }
    else
    {
        throw;  // condition not fulfilled, let someone else handle the exception
    }
}
```
```


q:
I have an asp.net text form that contains numerous decimal fields that are optional. I want to selectively update the database but not inserting a "0" for fields that do not have data (maintaining the null status).

Typically, I would create multiple functions, each with a different signature to handle this. However, I am inserting the data through a webservice which does not allow a function with the same name to have multiple signatures. I can think of a couple ways to work around this, but none "pragmatically".

[A]
You could use the
DBNull class
to represent a null value on your web service code.
While you would still have to use a surrogate value (e.g., 0 or -1), and then just evaluate that value to convert it into the
```
DBNull
```
object.


q:
Is there anyway to build a solution to target 64 bit environment in vs2003? My solution is native c++ not visual c++. Any help would be greatly appreciated.

cheers,

RWendi

[A]
This page on 2003's lack of 64-bit targeting seems to address your issue:
http://www.toymaker.info/Games/html/64_bit.html
.
The first step was to set up my development environment for 64 bit development. I use Visual Studio 2003 which has little built in support for 64 bit development.
In order to create 64 bit applications you need to install the latest Platform SDK from Microsoft (Microsoft Platform SDK for Windows Server 2003). The SDK, as well as having libraries for 32 bit programming, has 64 bit versions for AMD64 and IA64 (Intel) development.
Getting the correct library and header file paths set up in Visual Studio proved surprisingly difficult. I wanted the choice of developing 32 bit or 64 bit projects. While the platform SDK comes with command files to set up the correct paths they wipe out any other paths. Since T2 uses DirectX I also needed the DirectX paths setting correctly.
Upgrading to a newer edition of Visual Studio looks like the safer, non-hackish solution, if possible.


q:
Implementing a file upload under html is fairly simple, but I just noticed that there is an 'accept' attribute that can be added to the <input type="file" ...> tag.

Is this attribute useful as a way of limiting file uploads to images, etc? What is the best way to use it?

Alternatively, is there a way to limit file types, preferably in the file dialog, for an html file input tag?

[A]
Accept attribute was introduced in the
RFC 1867
, intending to enable file-type filtering based on MIME type for the file-select control. But as of 2008, most, if not all, browsers make no use of this attribute. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).
Other solutions for advanced file uploading require Flash movies like
SWFUpload
or Java Applets like
JUpload
.


q: I am using an authentication attribute on some of my actions in an asp.net mvc page to refer people to a login screen if they have not authenticated.  My problem is returning them to the referring page after they have logged in.  I was just keeping track of the referring action and referring controller but that becomes problematic when I also need to keep track of some parameters.  Is there some nifty built in trick about which I don't know?

[A]
What I did to achieve that result might be overdoing it, and I'd like to see some other methods as well. However, here's my code.
Please note it's using Moq to mock a context... And, I haven't done anything with the querystring yet (my routes don't contain any querystrings).
```
```
var urlReferrer = Request.UrlReferrer;
if (urlReferrer != null)
{
    var url = "~" + Server.UrlDecode(urlReferrer.PathAndQuery);

    // get routecollection
    var routeCollection = new RouteCollection();
    GlobalApplication.RegisterRoutes(routeCollection);

    // mcok context
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    context.Expect(ctx => ctx.Request).Returns(request.Object);

    // mock request
    // TODO: convert querystring to namevaluecollection
    // now it's just stripped
    if (url.IndexOf('?') > 0)
    {
        url = url.Substring(0, url.IndexOf('?'));
    }

    var mock = Mock.Get(context.Object.Request);

    // TODO: insert namevaluecollection of querystring
    mock.Expect(req => req.QueryString).Returns(new NameValueCollection());
    mock.Expect(req => req.AppRelativeCurrentExecutionFilePath).Returns(url);
    mock.Expect(req => req.PathInfo).Returns(string.Empty);

    // get routedata with mocked context
    var routeData = routeCollection.GetRouteData(context.Object);
    var values = routeData.Values;

    return RedirectToAction(routeData.Values["action"].ToString(), values);
}
```
```
As I said, it's maybe a bit overcomplicated :)


q:
If I have a style defined

.style1
{
   width: 140px;
}

can I reference it from a second style?

.style2
{
   ref: .style1;
}

Or is there a way via javascript/jQuery?

--- Edit

To clarify the problem, I am trying to apply whatever style is defined for a #x and #c to .x and .c without altering the CSS as the CSS is going to have updates that are out of my control.

I used width but really the style would be something more complex with font, border and other style elements being specified.

Specifying multiple class names does work when the style is being applied to a class so I'll mark existing responses as answers, but I need to take the style being applied to an id and also apply it to a class style ... if that makes any sense.

[A]
There's no way to do it with CSS -- it's an oft-requested feature, but not included in the spec yet. You also can't do it directly with JS, but there's sort of a hacky workaround:
```
```
$('.style2').addClass ('style1');
```
```


q:
I have a simple iphone app that's based on the CrashLanding sample app.  So basically you tap the title screen and do some stuff... all on the same "view".  I want to add an "options" screen/page/view whatever with a few UISwitches.  What's the easiest way to do this?

Cheers!

[A]
Dunno if this will help I'm a bit new to objective-c and iPhone api.
Maybe u can do something like this:
Use the interface builder: just type "Interface Builder" on the Spotlight (top right corner) to generate like "myOptions.xib"
And then just implement it: like
```
```
@implementation myOptions

-(void)awakeFromNib
{
...
```
```
You can take a look at the QuartzDemo under the iPhone API to see how to load the interface list of objects. In the previous view controller you just need to add it to the object list.
It will look something like this:
```
```
@implementation previousController
-(void)awakeFromNib
{
    menuList = [[NSMutableArray alloc] init];
    QuartzViewController *controller;

    controller = [[QuartzViewController alloc] initWithTitle:@"Options"];
    controller.quartzViewDelegate = [[[myOptions alloc] init] autorelease];
    [menuList addObject:controller];
    [controller release];
```
```
Hope it helps


q:
How does TCP/IP report errors when packet delivery fails permanently? All Socket.write() APIs I've seen simply pass bytes to the underlying TCP/IP output buffer and transfer the data asynchronously. How then is TCP/IP supposed to notify the developer if packet delivery fails permanently (i.e. the destination host is no longer reachable)?

Any protocol that requires the sender to wait for confirmation from the remote end will get an error message. But what happens for protocols where a sender doesn't have to read any bytes from the destination? Does TCP/IP just fail silently? Perhaps Socket.close() will return an error? Does the TCP/IP specification say anything about this?

[A]
The sockets API has no way of informing the writer exactly how many bytes have been received as acknowledged by the peer.  There are no guarantees made by the presence of a successful
```
shutdown
```
or
```
close
```
either.
The TCP/IP specification says nothing about the application interface (which is nearly always the sockets API).
SCTP
is an alternative to TCP which attempts to address these shortcomings, among others.


q:
Is it a problem if you use the global keyword on variables you don't end up using? Compare:

function foo() {
    global $fu;
    global $bah;
    if (something()) {
        $fu->doSomething();
    } else {
        $bah->doSomething();
    }
}

function bar() {
    if (something()) {
        global $fu;
        $fu->doSomething();
    } else {
        global $bah;
        $bah->doSomething();
    }
}

I'm quite aware that using the second method makes maintaining this code much harder, and that it's generally preferred to put all your globals at the start of functions, so: Ignoring the difference in maintainability and code-styling of the two functions, is there a difference between these two in terms of overhead?

[A]
If there is, it won't be (humanly) measurable, unless you are literally calling this function millions of times. And even if it was a recursive function with that property, I still wouldn't use your second method for the maintainability aspects you already brought up.
Edit:
For arguments sake, I actually went and benchmarked this, and
```
bar()
```
ended up slower by 0.1s over one million calls. Which means performance wise, you still have a reason to use the cleaner version.


q: I've installed Oracle XE with APEX, but forgot to write down the URL to access it.  How may I determine the URL?

[A]
The default is
http://127.0.0.1:8080/apex
If you happen to be on Windows, there will also be an entry in the Start menu (Programs > Oracle XE > Database homepage )


q:
What is the best way to automatically install an MSI file or installer .exe? We want to do some automated testing from our build system on the installed copy of the product. Our installer has the usual license acceptance screen, install location, etc.

As FryHard pointed out there are two options in particular that seem handy:

"/quiet" - no use interaction

"/passive" - process bar only, unattended mode

[A]
If you head over to one of your MSI packages in the command prompt and run a:
```
```
Myproduct.MSI /?
```
```
A screen will pop up with all the details of command line parameters that you can pass to the MSI. I am sure that in this way you could install your application via a command prompt and in this way automate it.


q: Have you refactored from an ActiveRecord to a DataMapper pattern? What conditions prompted the switch? I'm primarily interested in web based applications, but would like to know the challenges that accompany such a move in any environment.

[A]
I really do like the ActiveRecord pattern for its simplicity.  However, I have been moving away from it for larger web apps.  I find that as an ActiveRecord based project becomes more complex the ActiveRecord objects become large and laden with too much code.
By introducing a Repository pattern (essentially a Data Mapper) the domain model classes become simpler and the data mapping / data access logic is kept separate.
Also, it is quite difficult (impossible?) to mock ActiveRecord objects because of their user of static methods.


q:
I have been using Ruby for a while now and I find, for bigger projects, it can take up a fair amount of memory.  What are some best practices for reducing memory usage in Ruby?

Please, let each answer have one "best practice" and let the community vote it up.

[A]
Beware of C extensions which allocate large chunks of memory themselves.
As an example, when you load an image using RMagick, the entire bitmap gets loaded into memory inside the ruby process. This may be 30 meg or so depending on the size of the image.
However
, most of this memory has been allocated by RMagick itself. All ruby knows about is a wrapper object, which is tiny(1).
Ruby only thinks it's holding onto a tiny amount of memory, so it won't bother running the GC. In actual fact it's holding onto 30 meg.
If you loop over a say 10 images, you can run yourself out of memory really fast.
The preferred solution is to manually tell the C library to clean up the memory itself - RMagick has a destroy! method which does this. If your library doesn't however, you may need to forcibly run the GC yourself, even though this is generally discouraged.
(1): Ruby C extensions have callbacks which will get run when the ruby runtime decides to free them, so the memory will eventually be successfully freed at some point, just perhaps not soon enough.


q: What is the best way to write bytes in the middle of a file using Java?

[A]
Use
```
RandomAccessFile
```
Tutorial
Javadocs


q:
I'm making a Stored Procedure that basically concatenates a long string with data from many records.

I want to do:

set @output = @output + 'aaa' + LINEBREAK

How do I specify that line break?

[A]
```
```
DECLARE @LINEBREAK AS varchar(2)
SET @LINEBREAK = CHAR(13) + CHAR(10)
```
```


q:
The new awesome Ctrl + . keyboard shortcut to show smart tags has suddenly stopped working, a week or so after I discovered it :(

I am missing it badly, having had to revert back to Ctrl + Alt + F10, which really just isn't the same.

I recently installed F# CTP 1.9.6.2

Has anyone else

installed this CTP and still has Ctrl + .

Lost Ctrl + . without installing F#

Even better, found how to get it back again?

EDIT In attempting John Sheehan recommendation, I have noticed that my available mapping schemes only include Visual C# 2005, should I not have a 2008?

Also the mapped shortcut to this is

OtherContextMenus.FSIConsoleContext.CancelEvaluation

[A]
From the
documentation
:
Use of NSCalendarDate strongly
  discouraged. It is not deprecated yet,
  however it may be in the next major OS
  release after Mac OS X v10.5. For
  calendrical calculations, you should
  use suitable combinations of
  NSCalendar, NSDate, and
  NSDateComponents, as described in
  Calendars in
Dates and Times
  Programming Topics for Cocoa
.
Following that advice:
```
```
NSDate *today = [NSDate date];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];

NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
components = [gregorian components:unitFlags fromDate:tomorrow];
components.hour = 0;
components.minute = 0;

NSDate *tomorrowMidnight = [gregorian dateFromComponents:components];

[gregorian release];
[components release];
```
```
(I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.)
Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although
```
dateFromComponents:
```
may
tolerate out-of-bounds values, it's not guaranteed to.  You're strongly encouraged not to rely on it.


q: I need to sort tuples according to the second element of each tuple but apparently usort/1 only works with the first element. So I have to swap the elements, usort them and swap back.Is there an easier way?Also is there a way to sort in descending order (I know sorting and reversing can be done, but just want to know).

[A]
It shouldn't be too hard to write your own sort function (adapted from a common example):
```
```
qsort([]) -> [];
qsort([Pivot|Tail]) ->
    {PivotFirst, PivotSecond} = Pivot,
    qsort([{FirstElement, SecondElement} || {FirstElement,SecondElement} <- Tail, SecondElement < PivotSecond])
        ++ [Pivot] ++
        qsort([{FirstElement, SecondElement} || {FirstElement,SecondElement} <- Tail, SecondElement >= PivotSecond]).
```
```


q:
Sometimes I break long conditions in ifs onto several lines. The most obvious way to do this is:

  if (cond1 == 'val1' and cond2 == 'val2' and
      cond3 == 'val3' and cond4 == 'val4'):
      do_something

Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.

For the moment I'm using:

  if (    cond1 == 'val1' and cond2 == 'val2' and
          cond3 == 'val3' and cond4 == 'val4'):
      do_something

But this isn't very pretty. :-)

Can you recommend an alternative way?

[A]
This doesn't improve so much but...
```
```
allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and
                 cond3 == 'val3' and cond4 == 'val4')

if allCondsAreOK:
   do_something
```
```


q:
I have a text string value that I'd like to persist from one web page to another without using query strings or the session/view states.  I've been trying to get the ASP http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx">HiddenField control to pass information from one web form to a different form.

All the hiddenfield control examples that I've seen is to preserve round trips from the client to the server for the same form.

Is there way for a form to access the ASP controls (and their values) from the previously-rendered form?  Or is the initial form simply disposed of in memory by the time the second form executes it's OnLoad method?

[A]
I would presume that the Response.Redirect() sends a Location: HTTP header to do a redirect.
As HTTP is stateless, I'd also presume that these variables are inaccessible.
There are however, solutions.
Print a form with hidden fields, and use javascript to submit it
Redirect in the code internally (load up the thing it needs to get to manually)
Store the data in some temporary database table somewhere, and pass along a unique ID
However, from my experience, I can't understand why you might need to do this (other than re-submitting a form after a user authentication - which hopefully you should be able to use method 2 for