q:
I'm trying to read a file to produce a DOM Document, but the file has whitespace and newlines and I'm trying to ignore them, but I couldn't:

DocumentBuilderFactory docfactory=DocumentBuilderFactory.newInstance();
docfactory.setIgnoringElementContentWhitespace(true);

I see in Javadoc that setIgnoringElementContentWhitespace method operates only when the validating flag is enabled, but I haven't the DTD or XML Schema for the document.

What can I do?

Update

I don't like the idea of introduce mySelf < !ELEMENT... declarations and i have tried the
solution proposed in the forum pointed by Tomalak, but it doesn't work, i have used java 1.6 in an linux environment. I think if no more is proposed i will make a few methods to ignore whitespace text nodes

[A]
‘IgnoringElementContentWhitespace’ is not about removing
all
pure-whitespace text nodes, only whitespace nodes whose parents are described in the schema as having ELEMENT content — that is to say, they only contain other elements and never text.
If you don't have a schema (DTD or XSD) in use, element content defaults to MIXED, so this parameter will never have any effect. (Unless the parser provides a non-standard DOM extension to treat all unknown elements as containing ELEMENT content, which as far as I know the ones available for Java do not.)
You could hack the document on the way into the parser to include the schema information, for example by adding an internal subset to the < !DOCTYPE ... [...] > declaration containing < !ELEMENT ... > declarations, then use the IgnoringElementContentWhitespace parameter.
Or, possibly easier, you could just strip out the whitespace nodes, either in a post-process, or as they come in using an LSParserFilter.


q:
I m just starting using gwt and so far so good, however after reading some sample code I wonder is it necesary to have a high level of test coverage? (I can see that most code is declarative and then add some attributes I can see the sense in checking so me particular attributes are there but not all)

Also i would be interested to know anything about what are the gotchas in TDDing with GWT

I m using eclipse so also if you are really happy with some particualrs add ins for GWT I would be happy to hear about that
Thanks for the input

edit: maybe I m asking a very wide question, but even little pieces of information will help
I come from having nvelocity views with jquery/extJs/prototype/scriptaculous and this is a bit different

[A]
I think you asked a pretty broad question, which is part of the reason why you didn't get a reply for a while.
Compared to traditional AJAX web development, one could argue a GWT application requires less testing.  Because the GWT team has worked so hard to make sure that its widgets work consistently across all web browsers, you don't have to worry about cross-browser compatibility nearly as much for your own application.
That frees you up to focus on your own application.  Create a separate test case for each of your own custom widgets and test that they behave as you expect, and then write higher-level tests for each module.  Take the extra step to make your tests fully automatable - that way every time you make a change or are about to release, it's easy to run all of your tests.
http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=DevGuideJUnitIntegration

s: huggingface

c: devops

d: intermediate


q:
I have a String which I would like to modify in some way. For example: reverse it or upcase it.

I have discovered that the fastest way to do this is by using a unsafe block and pointers.

For example:

        unsafe
        {
            fixed (char* str = text)
            {
                *str = 'X';
            }
        }

Are there any reasons why I should never ever do this?

[A]
The .Net framework requires strings to be immutable. Due to this requirement it is able to optimise all sorts of operations.
String interning
is one great example of this requirement is leveraged heavily. To speed up some string comparisons (and reduce memory consumption) the .Net framework maintains a Dictionary of pointers, all pre-defined strings will live in this dictionary or any strings where you call the
```
String.intern
```
method on. When the IL instruction ldstr is called it will check the interned dictionary and avoid memory allocation if we already have the string allocated, note:
String.Concat
will not check for interned strings.
This property of the .net framework means that if you start mucking around directly with strings you can corrupt your intern table and in turn corrupt other references to the same string.
For example:
```
```
// these strings get interned
        string hello = "hello";
        string hello2 = "hello";

        string helloworld, helloworld2;

        helloworld = hello;
        helloworld += " world";

        helloworld2 = hello;
        helloworld2 += " world";

        unsafe
        {
            // very bad, this changes an interned string which affects
            // all app domains.
            fixed (char* str = hello2)
            {
                *str = 'X';
            }

            fixed (char* str = helloworld2)
            {
                *str = 'X';
            }

        }

        Console.WriteLine("hello = {0} , hello2 = {1}", hello, hello2);
        // output: hello = Xello , hello2 = Xello

        Console.WriteLine("helloworld = {0} , helloworld2 = {1}", helloworld, helloworld2);
        // output : helloworld = hello world , helloworld2 = Xello world
```
```


q:
I am using Python to extract the filename from a link using rfind like below:

url = "http://www.google.com/test.php"

print url[url.rfind("/") +1 : ]

This works ok with links without a / at the end of them and returns "test.php".  I have encountered links with / at the end like so "http://www.google.com/test.php/".  I am have trouble getting the page name when there is a "/" at the end, can anyone help?

Cheers

[A]
You could use
```
```
print url[url.rstrip("/").rfind("/") +1 : ]
```
```


q:
In my main page (call it index.aspx) I call

<%Html.RenderPartial("_PowerSearch", ViewData.Model);%>

Here the viewdata.model != null
When I arrive at my partial:

<%=ViewData.Model%>

Says viewdata.model == null

What gives?!

[A]
Have you tried just passing in ViewData instead of ViewData.Model? This is an abridged version what I use in my helpers (shamelessly stolen from the Storefront series):
```
```
/// <summary>
    /// Renders a LoggingWeb user control.
    /// </summary>
    /// <param name="helper">Helper to extend.</param>
    /// <param name="control">Type of control.</param>
    /// <param name="data">ViewData to pass in.</param>
    public static void RenderLoggingControl(this System.Web.Mvc.HtmlHelper helper, LoggingControls control, object data)
    {
        string controlName = string.Format("{0}.ascx", control);
        string controlPath = string.Format("~/Controls/{0}", controlName);
        string absControlPath = VirtualPathUtility.ToAbsolute(controlPath);
        if (data == null)
        {
            helper.RenderPartial(absControlPath, helper.ViewContext.ViewData);
        }
        else
        {
            helper.RenderPartial(absControlPath, data, helper.ViewContext.ViewData);
        }
    }
```
```
Note that I pass in the current ViewData and not the Model.


q:
I have an Office 2007 (specifically Outlook 2007) add in created in Visual Studio 2008.

When I uncheck the "Sign the ClickOnce manifests" option, and then publish, it rechecks that option automatically.

I have a regular Windows Forms project in the same solution that allows me to publish with this unchecked.

Why isn't it allowing me to uncheck the sign option?

[A]
You are not required to sign EXE files, but you need to sign DLL files for deployment. Your Office add-in is in the form of a DLL file, so it must be signed. Your Windows Forms project is linked into an EXE file, hence it does not need to be signed.
See the relevant MSDN page,
ClickOnce Manifest Signing and Strong-Name Assembly Signing Using Visual Studio Project Designer's Signing Page
, sub section
Signing Assemblies
.


q:
I've made a custom DataGridViewCell that displays a custom control instead of the cell; but if the DataGridView uses shared rows, then the custom control instance is also shared, so you get strange behaviour (for example, hovering over buttons highlights all the buttons).  Also, I can't access the DataGridViewCell.Selected property, so I don't know what colour to paint the row.

How do I prevent a DataGridView from sharing rows?  I know I can add the rows using the Rows.Add(object[]) override, but then the first row is still shared (i.e. has index -1) so the problem with colours still applies.

I need to be able to tell the DataGridView not to share a row containing a custom cell.  Can that be done with attributes?  Can it be done at all?

[A]
Try to set a Tooltip Text in one cell of the Row
A row cannot be shared in any of the following situations:
 The row contains a single selected cell that is not in a selected column.
 The row contains a cell with its ToolTipText or ContextMenuStrip properties set.
 The row contains a DataGridViewComboBoxCell with its Items property set.
or read
http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspx
for more Information


q:
I have a string in Bash:

string="My string"

How can I test if it contains another string?

if [ $string ?? 'foo' ]; then
  echo "It's there!"
fi

Where ?? is my unknown operator. Do I use echo and grep?

if echo "$string" | grep 'foo'; then
  echo "It's there!"
fi

That looks a bit clumsy.

[A]
I am not sure about using an if statement, but you can get a similar effect with a case statement:
```
```
case "$string" in
  *foo*)
    # Do stuff
    ;;
esac
```
```


q:
The Mutex class is very misunderstood, and Global mutexes even more so.

What is good, safe pattern to use when creating Global mutexes?

One that will work

Regardless of the locale my machine is in

Is guaranteed to release the mutex properly

Optionally does not hang forever if the mutex is not acquired

Deals with cases where other processes abandon the mutex

[A]
I want to make sure this is out there, because it's so hard to get right:
```
```
using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly
using System.Threading;                 //Mutex
using System.Security.AccessControl;    //MutexAccessRule
using System.Security.Principal;        //SecurityIdentifier

static void Main(string[] args)
{
    // get application GUID as defined in AssemblyInfo.cs
    string appGuid =
        ((GuidAttribute)Assembly.GetExecutingAssembly().
            GetCustomAttributes(typeof(GuidAttribute), false).
                GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

    // Need a place to store a return value in Mutex() constructor call
    bool createdNew;

    // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
    // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
    var allowEveryoneRule =
        new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
                                                   , null)
                           , MutexRights.FullControl
                           , AccessControlType.Allow
                           );
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

   // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
    using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
    {
        // edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                // edited by acidzombie24
                // mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access");
            }
            catch (AbandonedMutexException)
            {
                // Log the fact that the mutex was abandoned in another process,
                // it will still get acquired
                hasHandle = true;
            }

            // Perform your work here.
        }
        finally
        {
            // edited by acidzombie24, added if statement
            if(hasHandle)
                mutex.ReleaseMutex();
        }
    }
}
```
```


q:
does anybody know how to refresh the Internet Explorer (like by pressingthe F5 key) but using some "backdoor" like PostMessage or SendMessage? The internet Explorer Window is not active so I can't use the keyboard.

Thanks

(Language doesnt matter)

[A]
If you can identify what is to be replaced through a regular expression, I recommend using the optional task
replaceregexp
. Here's the doc:
http://ant.apache.org/manual/Tasks/replaceregexp.html
You can call it twice, one for the start tag and other for the end tag.
The regexp for replacing your
can be a bit cumbersome, since you say you do not want to replace all
tags, but I think this is the easiest way.
Another option would be to create a custom ant task to do what you want.


q:
I am working on a stored procedure with several optional parameters.  Some of these parameters are single values and it's easy enough to use a WHERE clause like:

WHERE (@parameter IS NULL OR column = @parameter)

However, in some instances, the WHERE condition is more complicated:

WHERE (@NewGroupId IS NULL OR si.SiteId IN (SELECT gs.SiteId
FROM [UtilityWeb].[dbo].[GroupSites] AS gs
WHERE gs.GroupId = @NewGroupId))

When I uncomment these complicated WHERE clauses, the query execution time doubles and the execution plan becomes remarkably more complicated. While the execution plan doesn't bother me, doubling the execution time of a query is a definite problem.

Is there a best practice or pattern that others have found for working with optional parameters in their stored procedures?

Is this one of those instances where dynamic SQL would be a better solution?

[A]
I would create separate queries for the parameter being available or not.
This will create simpler SQL, and the optimizer will do a better job.
Like this:
```
```
if (@parameter IS NULL) then begin
   select * from foo
end
else begin
   select * from foo where value = @parameter
end
```
```
In you have to many parameters to redesign like this, and you go for the dynamic sql solution, then also always use parameters, you might get bitten by the
SQL-Injection
bug.
A combination is also possible. The most likely used query/queries you code in full, and get precompiled. All other combinations are created dynamically.


q:
<input type="submit"/>

<style>
input {
  background: url(tick.png) bottom left no-repeat;
  padding-left: 18px;
}
</style>

But the bevel goes away, how can I add an icon to submit button and keep the bevel?

Edit: I want it to look like the browser default.

[A]
Use border.  For example:
```
```
INPUT.button {
    BORDER-RIGHT: #999999 1px solid;
    BORDER-TOP: #999999 1px solid;
    FONT-SIZE: 11px;
    BACKGROUND: url(tick.png) bottom left no-repeat;
    BORDER-LEFT: #999999 1px solid;
    CURSOR: pointer;
    COLOR: #333333;
    BORDER-BOTTOM: #999999 1px solid
}

<input type="submit" class="button" />
```
```


q:
In a C program (p1), how to launch a dynamically constructed command (and its arguments) that reads its standard input from p1's standard output?

Note that:

A method other than this stdout -->
stdin piping is also OK provided
it is PORTABLE across Windows and
Linux.

I cannot use C++, Java, Perl, Ruby,
Python, etc here.

Also, will this have a MinGW dependency for its Windows build?

REOPENED: The question below answers it for Linux, but this question wants a portable method.
Execute program from within a C program

[A]
It's not 100% clear to me what you're trying to achieve exactly to be honest.
But as I understand it, you could take a look at
Boost.Process
You can do things like
```
```
bp::child cs = p.start();
 bp::postream& os = cs.get_stdin();
```
```
And then use the
os
as any stream to dump stuff in the standard input of your child process.
Anyway, an awful lot can be achieved with the library w.r.t. pipe redirecting and chaining.


q:
Following on from a previous question, I am creating a symbolic link on a Server 2008 from a Vista machine using UNC paths. I can create the link just fine. I can go to the Server 2008 box and double click on the link in explorer to open the target file. What I cannot do though is use FileCreateW to get a handle to the UNC path link (from the Vista box). When I try it, it fails and GetLastError() returns error code 1463 (0x5B7), which is:

The symbolic link cannot be followed because its type is disabled.

How to enable its "type" in Server 2008 (assuming the error means what it says)?

[A]
Well I found the answer, though to describe it as badly documented is an understatement!
First of all,
this TechEd article
highlights the fact that users can "enable or disable any of the four evaluations that are available in symbolic links". Those four "evaluations" include remote to local and local to remote. It doesn't give any clue as to how to do this.
However a further search revealed
this fsutil help page
, which does actually document how to "enable or disable any of the four evaluations that are available in symbolic links". So to fix the problem I was having, I need to issue the following command
on the Vista box
:
```
```
fsutil behavior set SymlinkEvaluation L2L:1 R2R:1 L2R:1 R2L:1
```
```
in order to allow full access to where symlinks are pointing on both local and remote machines.


q:
I read the following in a review of Knuth's "The Art of Computer Programming":

"The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the behavior of most other languages which implement a for loop."

(http://www.amazon.com/review/R9OVJAJQCP78N/ref=cm_cr_pr_viewpnt#R9OVJAJQCP78N)

What is this guy talking about?  How could you implement a for loop that wasn't just syntactic sugar for a while loop?

[A]
He probably refers to for loops like
```
for i:=0 to N
```
and for-each loops that iterate over the elements of a set. I suspect all languages that have a C-style for loop actually got it from C.


q: I'd like to create a basic "Hello World" style application for the IPhone using Java - can anyone tell me how?

[A]
You can't code in Java for iPhone. The iPhone only supports C/C++/Objective-C - Cocoa.
However, under the current license you can use translation tools that generate such code.
There are several solutions that do exactly that:
Codename One
- focuses on building applications using Java with visual tools and simulators. Open source with a SaaS backend that removes the need for a Mac.
XMLVM
- a translator to convert Java bytecode to C/Objective-C. Open source, but requires writing iOS specific code at the moment.
There are also several proprietary solutions but I have no experience with them. E.g. Software AG has a tool called web objects.


q:
I have a rails application that I am running with Vista,IIS7 and SQL 2005. For some reason the CSS is not being rendered. The CSS works fine when I use Webrick.

Any ideas how to get CSS working correctly with IIS7. I have uninstalled and reinstalled windows components "Common Http Features" with no luck.

[A]
Can you use Firebug or something to check that IIS7 is sending the correct MIME type with your stylesheets? Some browsers will ignore CSS unless the server explicitly sends
```
```
Content-Type: text/css
```
```
in the HTTP response headers, and with dynamic content or non-standard file extensions you may find that IIS7 isn't configured to do this "out of the box"


q:
I'm looking for an abstract representation of a grid in Java (grid as in that thing with columns and rows of data).  Do such things exist?  I want to be able to sort, filter, keep track of rows, set column properties etc.  I'll then be realising the grid on the web.

To be clear: I've already decided on the ultimate view technology (client side).  The thing I'm looking for will hold all the records and offer them up as the view demands.

[A]
JTable
is what you are looking for.


q:
How do the timeouts work in WCF? I know for example that you can configure sendTimeout and receiveTimeout for a clients binding. But how do they work?

MSDN describes sendTimeout as:

A TimeSpan value that specifies the interval of time provided for a
  send operation to complete. This value should be greater than or equal
  to Zero. The default is 00:01:00.

What are send operations/receive operations?

[A]
Client side:
SendTimeout is used to initialize the OperationTimeout, which governs the whole interaction for sending a message (including receiving a reply message in a request-reply case).  This timeout also applies when sending reply messages from a CallbackContract method.
OpenTimeout and CloseTimeout are used when opening and closing channels (when no explicit timeout value is passed).
ReceiveTimeout is not used.
Server side:
Send, Open, and Close Timeout same as on client (for Callbacks).
ReceiveTimeout is used by ServiceFramework layer to initialize the session-idle timeout.
The source is
Brian McNamara on MSDN forums
.


q:
In cleaning up this answer I learnt a bit about TRIGGERs and stored procedures in MySQL, but was stunned that, while BEFORE INSERT and BEFORE UPDATE triggers could modify data, they seemingly couldn't cause the insert/update to fail (ie. validation). In this particular case I was able to get this to work by manipulating the data in such a way as to cause a primary key duplicate, which in this particular case made sense, but doesn't necessarily make sense in a general sense.

Is this sort of functionality possible in MySQL? In any other RDBMS (my experience is limited to MySQL sadly)? Perhaps a THROW EXCEPTION style syntax?

[A]
From this
blog post
MySQL Triggers: How do you abort an INSERT, UPDATE or DELETE with a
  trigger? On EfNet’s #mysql someone
  asked:
How do I make a trigger abort the operation if my business rule fails?
In MySQL 5.0 and 5.1 you need to
  resort to some trickery to make a
  trigger fail and deliver a meaningful
  error message. The MySQL Stored
  Procedure FAQ says this about error
  handling:
SP 11. Do SPs have a “raise” statement to “raise application errors”? Sorry, not at present. The SQL standard SIGNAL and RESIGNAL statements are on the TODO.
Perhaps MySQL 5.2 will include SIGNAL
  statement which will make this hack
  stolen straight from MySQL Stored
  Procedure Programming obsolete. What
  is the hack? You’re going to force
  MySQL to attempt to use a column that
  does not exist. Ugly? Yes. Does it
  work? Sure.
```
```
CREATE TRIGGER mytabletriggerexample
BEFORE INSERT
FOR EACH ROW BEGIN
IF(NEW.important_value) < (fancy * dancy * calculation) THEN
    DECLARE dummy INT;

    SELECT Your meaningful error message goes here INTO dummy
        FROM mytable
      WHERE mytable.id=new.id
END IF; END;
```
```


q:
Ok, there are a million regexes out there for validating an email address, but how about some basic email validation that can be integrated into a TSQL query for Sql Server 2005?

I don't want to use a CLR procedure or function.  Just straight TSQL.

Has anybody tackled this already?

[A]
Very
basic would be:
```
```
SELECT
  EmailAddress,
  CASE WHEN EmailAddress LIKE '%_@_%_.__%'
            AND EmailAddress NOT LIKE '%[any obviously invalid characters]%'
  THEN 'Could be'
  ELSE 'Nope'
  END Validates
FROM
  Table
```
```
This matches everything with an @ in the middle, preceded by at least one character, followed by at least two, a dot and at least two for the TLD.
You can write more
```
LIKE
```
patterns that do more specific things, but you will never be able to match everything that could be an e-mail address while not letting slip through things that are not. Even with regular expressions you have a hard time doing it right. Additionally, even matching according to the very letters of the RFC matches address constructs that will not be accepted/used by most emailing systems.
Doing this on the database level is maybe the wrong approach anyway, so a basic sanity check as indicated above may be the best you can get performance-wise, and doing it in an application will provide you with far greater flexibility.


q:
I'm trying to create a form that has an expandable widget. The problem is that when the widget is open, The form extends outside the limit in the content box, and it looks bad.

I tried using overflow:scroll but it creates 2 ugly scrollbars that do not disappear even if the content is smaller then the content box. I only need one vertical scrollbar.

Visual Studio also alerted that overflow-y is not available in CSS.

[A]
Change your overflow to
```
auto
```
and define the height and/or width of the element.


q:
I'm using Lawrence Philips Double-Metaphone algorithm with great success, but I have found the odd "unexpected result" for some combinations.

Does anyone else have additions or changes to the algorithm for other parts of it they wouldn't mind sharing, or just the combinations that they've found that do not work as expected.

eg. I had issues between:

Peashill and Bushley. (both match with PXL)

Rockliffe and Rockcliffe (RKLF and RKKL)

[A]
All Soundex, Metaphone and variant schemes are occasionally going to give results that aren't identical to what you expect.  This is unavoidable - they can be regarded as more or less simple hash algorithms with special information preserving properties, and will sometimes produce collisions when you'd rather they didn't, and will sometimes produce differences when you'd rather they didn't.
One possible way of improving things is using 'synonym rings'.  This basically produces lists of words that should be regarded as synonyms, independent of the spelling.  I encountered them in the context of name matching.  For example, variants on Chaudri
included:
CHAUDARY
CHAUDERI
CHAUDERY
CHAUDHARY
CHAUDHERI
CHAUDHERY
CHAUDHRI
CHAUDHRY
CHAUDHURI
CHAUDHURY
CHAUDHY
CHAUDREY
CHAUDRI
CHAUDRY
CHAUDURI
CHAWDHARY
CHAWDHRY
CHAWDHURY
CHDRY
CHODARY
CHODHARI
CHODHOURY
CHODHRY
CHODREY
CHODRY
CHODURY
CHOUDARI
CHOUDARY
CHOUDERY
CHOUDHARI
CHOUDHARY
CHOUDHERY
CHOUDHOURY
CHOUDHRI
CHOUDHRY
CHOUDHURI
CHOUDHURY
CHOUDREY
CHOUDRI
CHOUDRY
CHOUDURY
CHOUWDHRY
CHOWDARI
CHOWDARY
CHOWDHARY
CHOWDHERY
CHOWDHRI
CHOWDHRY
CHOWDHURI
CHOWDHURRYY
CHOWDHURY
CHOWDORY
CHOWDRAY
CHOWDREY
CHOWDRI
CHOWDRURY
CHOWDRY
CHOWDURI
CHOWDURY
CHUDARY
CHUDHRY
CHUDORY
COWDHURY


q: As a developer who spent many years working within Visual C++ 6, I'm used to working with the String Table resource to store unicode strings for localization. Is there a resource within Visual Studio 2005 that provides the same? Are there any third party libraries or tools?

[A]
ResourceManager
is your friend - and yes, Visual Studio still has support for it all in the editor. You might also want to read "
Encoding and Localization
". If you're really keen, I can thoroughly recommend
Guy Smith-Ferrier's book on .NET i18n
.


q:
What is the best way to save enums into a database?

I know Java provides name() and valueOf() methods to convert enum values into a String and back. But are there any other (flexible) options to store these values?

Is there a smart way to make enums into unique numbers (ordinal() is not safe to use)?

Update

Thanks for all awesome and fast answers! It was as I suspected.

However, a note to toolkit: That is one way. The problem is that I would have to add the same methods to each enum type that I create. That's a lot of duplicated code and, at the moment, Java does not support any solutions for this (a Java enum cannot extend other classes).

[A]
I would argue that the only safe mechanism here is to use the String
```
name()
```
value. When writing to the DB, you
could
use a sproc to insert the value and when reading, use a View. In this manner, if the enums change, there is a level of indirection in the sproc/view to be able to present the data as the enum value without "imposing" this on the DB.


q:
I have some simple .doc files I made in Word 2007 where I changed the text color and used highlights to compare some similar texts. What I'd like to do is change any instances of green text or gray highlighting to different respective colors for each.

I'm sure there is a simple way to do this with VBA but any other sort of answers are also welcome.

EDIT: While I do appreciate answers, one that allows me to keep the .doc files as .docs is preferred.

[A]
You can always save the file as HTML, and replace colors there. Color is represented with
```
```
...
```
```
and highlight is
```
```
...
```
```
Should be easy to manipulate if your document is simple enough.
Edit that answers the edit in the question: After you are done, re-open the file and save the file back as .doc.


q: I have a gridview containing some data from db, and after a check I want to see a small cross/tick image in each row, due to the result of the check.How can I change the image url dynamically?

[A]
```
```
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:Image ID="check" runat="server" ImageUrl='<%#If(Eval("check") = 1,"images/checked.gif","images/unchceked.gif") %>' />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
```
```


q:
Anyone point my at a utility for syncing sql server logins after restoring a database to a different server?

I know I can do it with scripts, but I've been using a wonderful little utility - 'Db Maint Sync SQL Logins' (http://www.dbmaint.com/SyncSqlLogins.asp) to do it on sql server 2000 which unfortunately doesn't support 2005 and I'm loath to go back to actually thinking :-)

[A]
```
sp_change_users_login
```
with the
```
Update_One
```
action can map a login in a database to a user on a new server.


q:
I have heard mixed opinions over the amount of memory that a byte takes up in a java program.

I am aware you can store no more than +127 in a java byte, and the documentation says that a byte is only 8 bits but here I am told that it actually takes up the same amount of memory as an int, and therefore is just a Type that helps in code comprehension and not efficiency.

Can anyone clear this up, and would this be an implementation specific issue?

[A]
Java is never implementation or platform specific (at least as far as
primitive type sizes
are concerned).  They primitive types are always guaranteed to stay the same no matter what platform you're on.  This differs from (and was considered an improvement on) C and C++, where some of the primitive types were platform specific.
Since it's faster for the underlying operating system to address four (or eight, in a 64-bit system) bytes at a time, the JVM may allocate more bytes to store a primitive byte, but you can still only store values from -128 to 127 in it.


q: Can a flash front end talk to a .net backend?

[A]
Yes.
We use
Adobe Flex
to talk to .Net XML web services.
Be careful with complex serialised .Net types (for instance DataSets) - ActionScript can't handle them.
Instead produce simple XML with primitive types.
See also:
Flex and ADO.NET Data Services...anyone done it?
```
```
<mx:WebService id="myDataService" showBusyCursor="true">
    <mx:operation name="WebMethodName" resultFormat="object" result="functionFiredOnComplete();"></mx:operation>
</mx:WebService>

public function load():void
{
    myDataService.loadWSDL( "web method's wsdl" );
    myDataService.WebMethodName.send( params );
}

public function functionFiredOnComplete():void
{
    // get data
    var myData:Object = myDataService.WebMethodName.lastResult;
    ...
```
```


q:
What are the dangerous characters that should be replaced in user input when the users' input will be inserted in a MySQL query? I know about quotes, double quotes, \r and \n. Are there others?
(I don't have the option of using a smart connector that accepts parameters so I have to build the query myself and this will be implemented in multiple programming languages, including some obscure ones so solutions such as mysql_real_escape_string in PHP are not valid)

[A]
What languages do you need to support? It is much better to use a language's built-in sanitization than to write your own.
Edit: Looking at
```
mysql_real_escape_string
```
on php.net:
```
mysql_real_escape_string()
```
calls MySQL's library function
```
mysql_real_escape_string
```
, which prepends backslashes to the following characters:
```
\x00
```
,
```
\n
```
,
```
\r
```
,
```
\
```
,
```
'
```
,
```
"
```
and
```
\x1a
```
.


q:
Using the following code I get a nice formatted string:

Request.QueryString.ToString

Gives me something like: &hello=world&microsoft=sucks

But when I use this code to clone the collection to another object (of the same type) I get the Type() back from the ToString() method instead.

System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
    variables.Remove("sid");
Response.Write(variables.ToString());

Is there a tidier way to output it rather than looking and building the string manually?

[A]
Why do you want to copy the QueryString collection into a new NameValueCollection?
```
```
if (!string.IsNullOrEmpty(Request.QueryString["sid"]))
        Request.QueryString.Remove("sid");
```
```
Yes indeed, i am wrong, it is read only. So the essence is to use the Remove Method on your NameValuecollection:
```
```
System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
    variables.Remove("sid");
```
```


q: Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?

[A]
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
Have a hidden input in your form, such as
```
<input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />
```
. This will then be available in the servlet as a request parameter.
Put it in the session (see
```
request.getSession()
```
- in a JSP this is available as simply
```
session
```
)
I recommend using the Session as it's easier to manage.


q: How would I reset the primary key counter on a sql table and update each row with a new primary key?

[A]
I would add another column to the table first, populate that with the new PK.
Then I'd use update statements to update the new fk fields in all related tables.
Then you can drop the old PK and old fk fields.
EDIT:
Yes, as Ian says you will have to drop and then recreate all foreign key constraints.


q:
I am currently in the process of searching for a rules engine that works in .NET.  Our logic is pretty simple, +, -, *, /, and, or, basic order of operations stuff.  However we are going to need to store this information in the database and then generate the rules file when a new version is pulled from the database.  So the common UI editors are going to be useless to us, unless one of them has a web version UI editor.

So my question is, given what I have said, which is going to be the best rules engine for us in terms of programmatic configuration and integration with ASP.NET.

[A]
My experience with WWF has been pretty bad.  Its great for developing a workflow that you know is going to exist (such as "this document goes to a person's manager, then to HR, if its invalid it goes back to the submitter") but a real pain if you want dynamic configuration.  As you can tell we tried to use it for a fully configurable system, something that BizTalk does really well, and it looks like MS isn't keen on letting developers replace BizTalk so cheaply.
We also looked at using the
Acumen rules engine and tools
which looked like a great fit for what we needed though we never got the time to remove WWF and replace it.
I would strongly recommend that if your rules are going to be relatively simple that you either use a rules engine you have the source code to or write it yourself.
Justin Etheredge
has a
two
part
article about performing domain validation through custom rules using the pattern identified in
Domain-Driven Designs
(Evans).
I've implemented a similar system in my current project following the same guidelines and I serialize/deserialize rules from the database.  I will have to take a look at
Drools.NET
.


q:
On our Scrum board, tasks start at 'To Do', go to 'In Progress', and when you're done with a task, they move to 'To Verify' before ending up in 'Done'. The 'To Verify' column is when you're done with a task and someone else can have a look at it, test it, and comment on it.

This has proven helpful for errors, better code, etc.

To people who have a similar practice: after the developer has addressed the comments/errors, do you verify it again, or do you assume the issues have been addressed and move the task to 'Done'?

I hope this is clear, and would like to hear your thoughts.

[A] In my expirence the fixing of bugs have a 50 - 75% chance of introducing new bugs, especially if the code if not covered by test cases. I would certainly verify it again.


q: How do you find out the length/size of the data in an ntext column in SQL? - It's longer than 8000 bytes so I can't cast it to a varchar. Thanks.

[A]
Use
DataLength()
```
```
SELECT * FROM YourTable WHERE DataLength(NTextFieldName) > 0
```
```


q: We use Grid Control 10.2.0.4, with a catalog repository database also at 10.2.0.4. It seems that after a week or two of being up, the response time of the web interface gets very poor (20+ seconds to navigate to a new page, when normally 2-3 seconds is seen). The only thing we've found to overcome it is a restart of the catalog database and the GC/OMS. No errors reported in the alert log, just unbearable slowness. Are there any Oracle DBA's using GC out there who have seen this (and hopefully found a solution)?


q: Related to this question, how to save many different csv files into one excel workbook with one sheet per csv ? I would like to know how to do this programmatically in Java.

[A]
You'll need some form of library for accessing Excel from Java. A Google search turned this one up:
http://j-integra.intrinsyc.com/support/com/doc/excel_example.html
An alternative is to use the XML Excel format that came into being with Office 2003. You'll end up with a XML file, but you can open it in Excel and see the different sheets.
http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-officeml.html


q:
We are moving from regular 2.0 webforms with no testing to TDD MVC

I'm looking to find out all the requirements for making the jump from 2.0 to 3.5 MVC.

Does SQL Server 2000 work with .net 3.5?

Does the MVC Framework come with .net 3.5?

How does AJAX work with all this stuff?

Is visual studios team suite worth the time/money?

[A]
ASP.NET MVC is an extension of ASP.NET 3.5, it is still in beta and voices says that it will be available before the end of the year.
For your other questions:
- .NET 3.5 works well on SQL Server 2000
- The MVC framework is not part of .NET 3.5
- For using AJAX with ASP.NET MVC it's better if you take a look at JQuery (or other frameworks). The support for ASP.NET Ajax is not fully available.
IMHO the real advantanges of ASP.NET MVC are:
Testability
Testability :-)
The ability to generate the HTML that you really want! No viewstate! No other noise! :-)
BTW the jump to TDD with MVC is not simple...it needs time.
HTH


q:
I am trying to manipulate a string using Jython, I have included below an example string:

This would be a title for a website :: SiteName

This would be a title for a website :: SiteName :: SiteName

How to remove all instances of ":: Sitename" or ":: SiteName :: SiteName"?

[A]
No different from regular Python:
```
```
>>> str="This would be a title for a website :: SiteName"
>>> str.replace(":: SiteName","")
'This would be a title for a website '
>>> str="This would be a title for a website :: SiteName :: SiteName"
>>> str.replace(":: SiteName","")
'This would be a title for a website '
```
```


q: What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?

[A]
From .NET 4.5 on, there is the
```
Stream.CopyToAsync
```
method
```
```
input.CopyToAsync(output);
```
```
This will return a
```
Task
```
that can be continued on when completed, like so:
```
```
await input.CopyToAsync(output)

// Code from here on will be run in a continuation.
```
```
Note that depending on where the call to
```
CopyToAsync
```
is made, the code that follows may or may not continue on the same thread that called it.
The
```
SynchronizationContext
```
that was captured when calling
```
await
```
will determine what thread the continuation will be executed on.
Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).
From .NET 4.0 on, there's is the
```
Stream.CopyTo
```
method
```
```
input.CopyTo(output);
```
```
For .NET 3.5 and before
There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:
```
```
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}
```
```
Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not
```
input.Length
```
? Because that Length may not be available! From the
docs
:
If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.


q:
I've been experimenting with fulltext search lately and am curious about the meaning of the Score value. For example I have the following query:

SELECT table. * ,
MATCH (
col1, col2, col3
)
AGAINST (
'+(Term1) +(Term1)'
) AS Score
FROM table
WHERE MATCH (
col1, col2, col3
)
AGAINST (
'+(Term1) +(Term1)'
)

In the results for Score I've seen results, for one query, between 0.4667041301727 to 11.166275978088. I get that it's MySQLs idea of relevance (the higher the more weight).

What I don't get is how MySQL comes up with that score. Why is the number not returned as a decimal or something besides ?

How come if I run a query "IN BOOLEAN MODE" does the score always return a 1 or a 0 ? Wouldn't all the results be a 1?

Just hoping for some enlightenment. Thanks.

[A]
Generally relevance is based on how many matches each row has to the words given to the search.  The exact value will depend on many things, but it really only matters for comparing to other relevance values in the same query.
If you really want the math behind it, you can find it at the
internals manual
.


q: I have a table that was imported as all UPPER CASE and I would like to turn it into Proper Case. What script have any of you used to complete this?

[A]
Here's a UDF that will do the trick...
```
```
create function ProperCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
  declare @Reset bit;
  declare @Ret varchar(8000);
  declare @i int;
  declare @c char(1);

  if @Text is null
    return null;

  select @Reset = 1, @i = 1, @Ret = '';

  while (@i <= len(@Text))
    select @c = substring(@Text, @i, 1),
      @Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,
      @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
      @i = @i + 1
  return @Ret
end
```
```
You will still have to use it to update your data though.


q:
I am trying to aid another programmer with a page called Default.aspx with a code-behind section, and unfortunately I am at a bit of a loss.

 Partial Class _Default
 Inherits OverheadClass
 'A bunch of global variables here'

 Private Sub page_load(ByVal sender As Object, ByVal e As System.Eventarts) Handles Me.Load
 'Function goes here'

And in the OverheadClass we have

 Public Sub Sub_OverheadClass_Load(ByVal sender As Object, ByVal e as System.EventArgs) Handles MyClass.Load

The desired effect is when the OverheadClass is inherited, we want its load to run before the load event on the page runs.  There is probably a very simple answer to this that I am missing.

Edit: I forgot to note that we write in VB, and not C# as many of you are used to for ASP.

[A]
You should be able to override the OnLoad and call the base class's OnLoad first, then your class, for example:
C# Version
```
```
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    // Do some stuff here
}
```
```
VB Version
```
```
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)

    MyBase.OnLoad(e)

    ' Do some stuff here

End Sub
```
```


q: I know that you can run almost all Java in Dalvik's VM that you can in Java's VM but the limitations are not very clear.  Has anyone run into any major stumbling blocks?  Any major libraries having trouble?  Any languages that compile to Java byte code (Scala, Jython etc...) not work as expected?

[A]
There is a number of things that Dalvik will not handle or will not handle quite the same way as standard Java bytecode, though most of them are quite advanced.
The
most severe example is runtime bytecode generation
and custom class loading. Let's say you would like to create some bytecode and then use classloader to load it for you, if that trick works on your normal machine, it is guaranteed to not work on Dalvik, unless you change your bytecode generation.
That prevents you from using certain dependency injection frameworks, most known example being Google Guice (though I am sure some people work on that). On the other hand AspectJ should work as it uses bytecode instrumentation as a compilation step (though I don't know if anyone tried).
As to other jvm languages -- anything that in the end compiles to standard bytecode and does not use bytecode instrumentation at runtime can be converted to Dalvik and should work. I know people did run Jython on Android and it worked ok.
Other thing to be aware of is that there is
no just in time compilation
. This is not strictly Dalviks problem (you can always compile any bytecode on the fly if you wish) but that Android does not support that and is unlikely to do so. In the effect while microbenchmarking for standard Java was useless -- components had different runtime characterstics in tests than as parts of larger systems -- microbenchmarks for Android phones totally make sense.


q:
I have a page that is supposed to launch the Print Preview page onload.

I found this:

var OLECMDID = 7;
/* OLECMDID values:
* 6 - print
* 7 - print preview
* 1 - open window
* 4 - Save As
*/
var PROMPT = 1; // 2 DONTPROMPTUSER
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(OLECMDID, PROMPT);
WebBrowser1.outerHTML = "";

But...

it does not work in FireFox.

it's kind of ugly.

Is there a better way for IE or a way that works for FireFox?

[A]
You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.
That's why your example uses Active X, which bypasses the JavaScript security issues.
So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.
Read
Alist Apart: Going to Print
for a good article on the subject of print stylesheets.


q:
near the top of the code i see things like,

btn_dropdown._visible = false;
mcMenuBkg._visible = false;

but I can't find these assets anywhere in the library or in any code, how does this make any sense?

The movie clips in the library that look the same have different names and I can delete them entirely and they still show up when I compile and run, or I can add trace statements into their code and they never get called.

where on earth are these assets defined?

[A]
You can create movie clips with code dynamically.
This means that you may not have them in your assets if you are unable to find them.
You can create any type of symbol using a constructor out of thin air with actionscript alone.
I would search the code for one of these
```
```
var mybutton:SimpleButton=new SimpleButton();
```
```


q: Should the "visibility" for the __destruct() function be public or something else? I'm trying to write a standards doc for my group and this question came up.

[A]
I think it would need to be public in the case where a subclass needs to explicitly call the
__destruct
method of the parent class.
Something like this would throw an error:
```
```
<?php
class MyParent
{
    private function __destruct()
    {
        echo 'Parent::__destruct';
    }
}

class MyChild extends MyParent
{
    function __destruct()
    {
        echo 'Child::__destruct';
        parent::__destruct();
    }
}

$myChild = new MyChild();
?>
```
```


q:
Exception is:
'Country' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country");
Country.DataSource = dsCountry.tblDropDownValues;
Country.DataTextField = "AttrValue";
Country.DataValueField = "Id";
Country.DataBind();

The values held within dsCountry.tblDropDownValues are:

Id                                      AttrValue       AttrName
aefa28e0-a118-11dd-ad8b-080c210c9a66    PLEASE SELECT   Country
213a743e-ea0b-419c-bd44-03b1c35241b3    USA         Country
eefa1387-8dc0-11d8-975f-13da67a41a5d    CANADA          Country

[A]
Try binding the data on postback.  It sounds like when the event handler is accessing the DropDownList, it hasn't been repopulated with the values you are initially binding to the DropDownList.
Also, remember to bind early enough so that it is bound before the event handler starts its processing.  OnInit or OnLoad should be good enough.
Otherwise, might need some more details:
When is the exception occurring? During the rendering, or on the postback in the event handler?
Do you have a stack trace on the error that might point to the point in the code where the selected value is accessed?
When are you binding the data?


q: Has Java 1.6 SDK been released for mac? I can't seem to find it...

[A]
Yes, but only for 64-bit Intel-based Macs, i.e. Macs using Core 2 (duo or solo) or Xeon chips. The original Core chip is not supported, nor is any PPC chip. Also, Java 6 is currently Leopard-only. The update should appear in Software Update, if you have a compatible Mac and recent-enough OS version.
Here are the release notes for the
first update
. And here are the
second update
's release notes.


q:
Using Vim, I'm trying to pipe text selected in visual mode to a UNIX command and have the output appended to the end of the current file. For example, say we have a SQL command such as:

SELECT * FROM mytable;

I want to do something like the following:

<ESC>
V                 " select text
:'<,'>!mysql -uuser -ppass mydb

But instead of having the output overwrite the currently selected text, I would like to have the output appended to the end of the file. You probably see where this is going. I'm working on using Vim as a simple SQL editor. That way, I don't have to leave Vim to edit, tweak, test SQL code.

[A]
How about copying the selected text to the end of the file, select the copy and run the command? If you do not want to repeat the same commands over and over again, you can record the sequence by using
```
q
```
or add a new command. I have tried the latter as follows:
```
```
:com -range C <line1>,<line2>yank | $ | put | .,$ !rev
```
```
With it you can select some lines and then type
```
:C
```
. This will first yank the selection, then go to the end of the file, paste the yanked text and run the command (
```
rev
```
in this case) over the new text.


q:
I am trying to get center of parent form, not center of screen behavior.
Passing in the parent form seems to only control the ownership of the window.
These classes are sealed, so I do not see how I can do any WinProc tricks.
Rewriting the classes is not an appealing option.
Any other ideas?

[A]
I do not know much about the dialogs or message boxes but, you can position a new Form as you are looking for with its StartPosition property.
```
```
System.Windows.Forms.Form f = new Form();
f.StartPosition = FormStartPosition.CenterParent;
```
```


q:
I'm making another app's window topmost to ensure that a click in my app brings the other's dialog into views. The problem I'm having is that I don't get focus back to my app after the call. If the other app has more windows one of them ends up with focus, and otherwise no window (looking at the taskbar only) gets focus. Where should I start investigating the issue?

My code for making the other app topmost is:

Process p = Process.GetProcessById(trackedProcessID);
IntPtr h = p.MainWindowHandle;
uint TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS;
SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

with constants as

public static readonly uint SWP_NOMOVE = 0x0002;
public static readonly uint SWP_NOSIZE = 0x0001;
public static readonly uint SWP_ASYNCWINDOWPOS = 0x4000;
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);

[A]
Related:
Unexpected behaviour of Process.MainWindowHandle
Basically MainWindowHandle gives you the current top-most window of the process despite what the documentation says.
That explains why the main window of your other process doesn't necessarily get focus.
Your other problem is because you are not returning focus to your app after giving it away.
Actually, the correct term for what you are doing is establishing
z-order
.
Instead of trying to control z-order - which cannot be guaranteed - you might be better off sending messages to the other process.


q: When I am creating a new database table, what factors should I take into account for selecting the primary key's data type?

[A]
If using a numeric key, make sure the datatype is giong to be large enough to hold the number of rows you might expect the table to grow to.
If using a guid, does the extra space needed to store the guid need to be considered?  Will coding against guid PKs be a pain for developers or users of the application.
If using composite keys, are you sure that the combined columns will always be unique?


q:
The print functionality of Excel (using VBA) is extremely slow. I'm hoping someone has a way of speeding the printing up (without using the Excel 4 Macro trick).  Here's how I do it now:

Application.ScreenUpdating = False

With ActiveSheet.PageSetup

  -various setup statements which I've already minimized-

End With
ActiveSheet.PrintOut

Application.ScreenUpdating = True

[A]
Yes, the PageSetup properties are very slow when you set them.
You have already set
```
Application.ScreenUpdating = False
```
, which is good, but an equally (or more) important step in this case is to set
```
Application.Calculation = xlCalculationManual
```
. (It is best if you save these settings and then restore them to the original at the end.)
Additionally, the property get for each PageSetup property is very fast, while it is only the property set that is so slow. Therefore, you should test the new property setting to make sure it isn't already the same as the existing property value in order to prevent an unnecessary (and expensive) call.
With all this in mind, you should be able to use code that looks something like the following:
```
```
Dim origScreenUpdating As Boolean
origScreenUpdating = Application.ScreenUpdating
Application.ScreenUpdating = False

Dim origCalcMode As xlCalculation
origCalcMode =  Application.Calculation
Application.Calculation = xlCalculationManual

With ActiveSheet.PageSetup
    If .PrintHeadings <> False Then .PrintHeadings = False
    If .PrintGridlines <> False Then .PrintGridlines = False
    If .PrintComments <> xlPrintNoComments Then .PrintComments = xlPrintNoComments
    ' Etc...
End With

Application.ScreenUpdating = origScreenUpdating
Application.Calculation = origCalcMode
```
```
Edit: A couple of updates:
For Excel 2010 and above you can make use of the 'Application.PrintCommunication' property, while for Excel 2007 and below, you can make use of 'ExecuteExcel4Macro'. For more details, see
Migrating Excel 4 Macros to VBA
.
For Excel 2007 and below, another interesting trick is to temporarily assign the printer driver to the 'Microsoft XPS Document Writer' and then set it back. Printing speed can improve by 3x. See:
Slow Excel PageSetup Methods
.
Hope this helps...


q:
I am new to jmock and trying to mock an HttpSession. I am getting:

java.lang.AssertionError: unexpected invocation: httpServletRequest.getSession()
no expectations specified: did you...
 - forget to start an expectation with a cardinality clause?
 - call a mocked method to specify the parameter of an expectation?

the test method:

@Test

public void testDoAuthorization(){

    final HttpServletRequest request = context.mock(HttpServletRequest.class);
    final HttpSession session = request.getSession();

    context.checking(new Expectations(){{
       one(request).getSession(true); will(returnValue(session));
   }});

    assertTrue(dwnLoadCel.doAuthorization(session));
}

I have done a bit of searching and it isn't clear to me still how this is done. Feels like I am missing some small piece. Anyone with experience in this can just point me in the right direction.
thanks

[A]
I think you need to tell the JMock context how many times you expect the method to be called before you actually go ahead and call it.
```
```
final HttpServletRequest request = context.mock(HttpServletRequest.class);

context.checking(new Expectations(){{
  one(request).getSession(true); will(returnValue(session));
}});

final HttpSession session = request.getSession();
```
```
I'm not super familiar with JMock but do you actually care in your
```
dwnLoadCel
```
unit test how many times certain methods in the mocked object are called? Or are you just trying to test your class that depends on a HttpSession without an actual Session? If it's the latter than I think that JMock is overkill for you.
You might want to look into either creating a class that implements the
```
HttpSession
```
interface yourself for the purposes of unit testing only (a stub), and running your tests off of that, or you should take a look at
```
dwnLoadCel
```
and determine if it
really
needs to have a reference to the HttpSession, or if it just needs some properties within the HttpSession. Refactor
```
dwnLoadCel
```
to only depend on what it actually needs (a
```
Map
```
or a certain parameter value within the Session object) - this will make your unit test easier (the dependency on the servlet container goes bye-bye).
I think that you have some level of dependency injection in your class being tested already, but you might be dependent on too broad of an object.
The Google Test Blog
has had
a lot
of excellent
articles
on DI lately that you might find useful (I sure have).


q: I am writing a DB upgrade script that will check to see if an index has the right two columns defined.  If it doesn't, or if it only has one of them, then I will DROP it (is there a way to ALTER an index?) and then recreate it with both.

[A]
I don't have a database immediately on-hand to test this, but you should be able to see if a column exists in an index by using the following IF EXISTS statement.
I'm not sure whether you can alter an index on the fly.
```
```
IF EXISTS
(
   SELECT MyIndex.Name AS IndexName,
          Columns.name AS ColumnName
   FROM sys.indexes MyIndex
   INNER JOIN sys.index_columns IndexColumns
      ON  MyIndex.index_id = IndexColumns.index_id
      AND MyIndex.object_id = IndexColumns.object_id
   INNER JOIN sys.columns Columns
      ON  Columns.column_id = IndexColumns.column_id
      AND IndexColumns.object_id = Columns.object_id
   WHERE Columns.name = 'ColumnName'
   AND MyIndex.Name='IX_MyIndexName'
)
```
```


q: I'm trying to use jQuery to get data from an ASP.NET web service (SharePoint Server 2007 lists.asmx), but any call to a web service will really help as a first step in that direction.

[A]
Here is an example to call your webservice using jQuery.get:
```
```
$.get("http://domain.com/webservice.asmx", { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  });
```
```
In the example above, we call "webservice.asmx", passing two parameters: name and time. Then, getting the service output in the call back function.


q: I'm looking for the equivalent of right clicking on the drive in windows and seeing the disk space used and remaining info.

[A]
Look for the commands
```
du
```
(disk usage) and
```
df
```
(disk free)


q:
In my eternal saga to insert 1.4 million rows of data from a SQL script, I've written a basic WinForms app that takes each line of the script and executes it individually.

However, because the original script contained

SET IDENTITY_INSERT [Table] OFF

and SET is a session-wide command, this setting is getting lost on every SQL call, meaning that each line is failing.  Is there a way to set IDENTITY_INSERT off for the whole table, database-wide just so I can make these individual calls without them failing?  Or perhaps I can tell it to ignore the identity specification by appending a command to each line?

[A]
BULK INSERT
won't work for you?  Or the SQL Server Import/Export Wizard (
here
or
here
)?  I know import/export can turn off identity insert for the whole import.  I'm reasonably certain you can do it just prior to BULK INSERT


q:
I want yo use the EXSLT - DYN:EVALUATE in a style sheet. I have added the names pace but I don't know where the .xsl file I need to import is. I don't believe I have XALAN installed to point the import to. How would I install this? Once installed and I point it to the .xsl will it pick up the function and apply it? I am running Windows. The XSLT file is included at the top of the XML document.

Thanks

Pete

[A]
Xalan has the EXSL dyn:evaluate function built-in, you don't need to import anything in order to use it. You just need to declare the namespace. I'll give a small example:
input.xml
:
```
```
<root>
<foo>I am foo</foo>
<bar>I am bar</bar>
</root>
```
```
dyn_evaluate.xsl
:
```
```
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:dyn="http://exslt.org/dynamic"
    extension-element-prefixes="dyn">

  <xsl:param name="path"/>

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:value-of select="dyn:evaluate($path)"/>
  </xsl:template>

</xsl:stylesheet>
```
```
Running
```
```
xalan.exe -p path '/root/foo' input.xml dyn_evaluate.xsl
```
```
gives
```
```
I am foo
```
```
Running
xalan.exe -p path '/root/bar' input.xml dyn_evaluate.xsl
gives
```
```
I am bar
```
```
Hope this helps.


q:
Looking to hear from people who are using WCF in an enterprise environment.

What were the major hurdles with the roll out?
Performance issues?
Any and all tips appreciated!

Please provide some general statistics and server configs if you can!

[A]
WCF can be
configuration hell
. Be sure to familiarize yourself with its
diagnostics and svcTraceViewer
, lest you get madenning cryptic, useless exceptions. And watch out for the generated client's
broken implementation of the disposable pattern
.


q:
What would be the best way to fill an array from user input?

Would a solution be showing a prompt message and then get the values from from the user?

[A]
```
```
string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
    answer[i]= Console.ReadLine();
}
```
```


q:
I've gone through most of the example code and I still need some help.  I want to make an uber-simple app:  show one screen at startup with a label and a button.  click the button and we slide over to another screen (I suppose these are called views) which has another label and the "back" button in the top menu bar.  I just want to click back and forth between the two screens.

How do I do this?

[A]
You'll need to use a UINavigationController to accomplish the "slide"/"back button" behavior you're talking about. It is as simple as you might think, as long as the app is setup correctly. Essentially, UINavigationControllers allow you to push and pop instances of UIViewController or subclasses thereof, and take care of the animation and view history tracking for you.
The best way to get started, by far, is just open XCode, choose "New Project", and start with the "Navigation-Based Application." Dig around that project for a while and I think you'll start to see clearly what needs to be done.


q:
I have a table with multiple rows. Each row is a form. I want to use JQuery to submit all the forms that have the check box checked. The form is posting to an IFrame so there is not much need for AJAX.

So far I have:

       $("form").submit();

which submits the form. but all forms. There is arbritary number of rows, could be 80-100.

[A]
This is kinda a guess since I'm not sure of your layout, but here goes....
```
```
$("td > input:checked > form").submit();
```
```


q: If not, is smoke testing still used?

[A]
It's sort of a Venn Diagram.  Some Automated tests are Smoke tests, and some smoke tests are Automated (inasfar as they are ran by a computer program).  A Smoke test is a take off (if I recall correctly) on the term "Where there's smoke, there's usually fire."  It's a set of preliminary tests that the program must pass to be considered for 'real' (viz. fire) testing.
A smoke test can be manual insomuch as a tester has a list of steps he follows, but these aren't automated with a computer program.
Smoke testing is still used -- in places I've worked, it's usually automated.


q:
Where are variables in C++ stored?

Inside the RAM or the processor's cache?

[A]
Variables can be held in a number of different places, sometimes in more than one place.  Most variables are placed in RAM when a program is loaded; sometimes variables which are declared
```
const
```
are instead placed in ROM.  Whenever a variable is accessed, if it is not in the processor's cache, a cache miss will result, and the processor will stall while the variable is copied from RAM/ROM into the cache.
If you have any halfway decent optimizing compiler, local variables will often instead be stored in a processor's register file.  Variables will move back and forth between RAM, the cache, and the register file as they are read and written, but they will generally always have a copy in RAM/ROM, unless the compiler decides that's not necessary.


q:
I am trying to sort a list using delegates but I am getting a signature match error. The compiler says I cannot convert from an 'anonymous method'

List<MyType> myList = GetMyList();
myList.Sort( delegate (MyType t1, MyType t2) { return (t1.ID < t2.ID); } );

What am I missing?

Here are some references I found and they do it the same way.

Developer Fusion Reference

Microsoft Reference

[A]
The Sort doesn't take a binary predicate, it takes a
```
Comparison<T>
```
delegate which returns an
```
int
```
not a
```
bool
```
.
The return values are
```
0
```
for when the items are equal,
```
<0
```
for when the first item is less than the second, and
```
>0
```
for when the first item is greater than the second.


q:
Assume that I set up an automatic nightly build.  What artifacts of the build should I save?

For example:

Input source code

output binaries

Also, how long should I save them, and where?

Do your answers change if I do Continuous Integration?

[A] We save the binaries, stripped and unstripped (so we have the exactly same binary, once with and once without debug symbols). Further we build everything twice, once with debug output enabled and once without (again, stripped and unstripped, so every build result in 4 binaries). The build is stored to a directory according to SVN revision number. That way we can always retain the source from the SVN repository by simply checking out this very revision (that way the source is archived as well).


q:
I am actually developing and application that has around 15 modules, all of them using the same database.

I am using Apache + Mongrel, I cannot use Passenger because I am working on Windows (please forgive me for this deadly sin!)

Which of the following is a better approach?

Deploy multiple small rails
applications using a virtual server
and a pair of mongrels for each
application.

Deploy only a big rails application

I am worried about the number of running mongrels and the memory/cpu load.

[A]
It depends on hwo many simultaneous clients you expect to have.  One mongrel, one client at a time (until Rails 2.2) since Rails isn't currently threaded.
Two is enough mongrels if you don't expect more than a few simultaneous users.  You can raise that number by using page caching to bypass mongrel for pages that don't have user-specific dynamic content.
The only way to be truly sure is to test the system.
In my experience you'll need at least 4 mongrels for a moderately active site of just a few users at a time.


q:
PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not.

Can we build similar feature for C/C++ (some kind of symbol table lookup)?

[A] Not really.  You can't dynamically create variables (though you can dynamically create storage with malloc() et al, or new et al. in C++) in C.  I suppose dynamically loaded libraries blur the picture, but even there, the way you establish whether the variable exists is by looking up its name.  If the name is not there, then, short of running a compiler to create a dynamically loaded module and then loading it, you are probably stuck.  The concept really doesn't apply to C or C++.


q:
I'd like a consistent and simple way to throw exceptions in JNI code; something that handles chained exceptions (implicitly from the env->ExceptionOccurred method, or explicitly by parameters, either way is good) and saves me looking up constructors every time I want to do this.  All of the above is preferably in C, although I could translate it from C++ at need.

Does anyone on SO have something like this that they can share?

[A]
We just code utility methods for each of the types of exceptions we want to throw.  Here are some examples:
```
```
jint throwNoClassDefError( JNIEnv *env, char *message )
{
    jclass exClass;
    char *className = "java/lang/NoClassDefFoundError";

    exClass = (*env)->FindClass( env, className);
    if (exClass == NULL) {
        return throwNoClassDefError( env, className );
    }

    return (*env)->ThrowNew( env, exClass, message );
}

jint throwNoSuchMethodError(
        JNIEnv *env, char *className, char *methodName, char *signature )
{

    jclass exClass;
    char *exClassName = "java/lang/NoSuchMethodError" ;
    LPTSTR msgBuf;
    jint retCode;
    size_t nMallocSize;

    exClass = (*env)->FindClass( env, exClassName );
    if ( exClass == NULL ) {
        return throwNoClassDefError( env, exClassName );
    }

    nMallocSize = strlen(className)
            + strlen(methodName)
            + strlen(signature) + 8;

    msgBuf = malloc( nMallocSize );
    if ( msgBuf == NULL ) {
        return throwOutOfMemoryError
                ( env, "throwNoSuchMethodError: allocating msgBuf" );
    }
    memset( msgBuf, 0, nMallocSize );

    strcpy( msgBuf, className );
    strcat( msgBuf, "." );
    strcat( msgBuf, methodName );
    strcat( msgBuf, "." );
    strcat( msgBuf, signature );

    retCode = (*env)->ThrowNew( env, exClass, msgBuf );
    free ( msgBuf );
    return retCode;
}

jint throwNoSuchFieldError( JNIEnv *env, char *message )
{
    jclass exClass;
    char *className = "java/lang/NoSuchFieldError" ;

    exClass = (*env)->FindClass( env, className );
    if ( exClass == NULL ) {
        return throwNoClassDefError( env, className );
    }

    return (*env)->ThrowNew( env, exClass, message );
}

jint throwOutOfMemoryError( JNIEnv *env, char *message )
{
    jclass exClass;
    char *className = "java/lang/OutOfMemoryError" ;

    exClass = (*env)->FindClass( env, className );
    if ( exClass == NULL ) {
        return throwNoClassDefError( env, className );
    }

    return (*env)->ThrowNew( env, exClass, message );
}
```
```
That way, it's easy to find them, your code-completion editor will help you to type them in, and you can pass simple parameters.
I'm sure you could expand this to handle chained exceptions, or other more complicated approaches.  This was enough to meet our needs.


q:
I'm using C# & .NEt 3.5.  What is the difference between the OptionA and OptionB ?

class MyClass
{
    private object m_Locker = new object();
    private Dicionary<string, object> m_Hash = new Dictionary<string, object>();

    public void OptionA()
    {
        lock(m_Locker){
          // Do something with the dictionary
        }
    }

    public void OptionB()
    {
        lock(m_Hash){
          // Do something with the dictionary
        }
    }
}

I'm starting to dabble in threading (primarly for creating a cache for a multi-threaded app, NOT using the HttpCache class, since it's not attached to a web site), and I see the OptionA syntax in a lot of the examples I see online, but I don't understand what, if any, reason that is done over OptionB.

[A]
It's not what you're "Locking", its the code that's contained between the lock { ... } thats important and that you're preventing from being executed.
If one thread takes out a lock() on any object, it prevents other threads from obtaining a lock on the same object, and hence prevents the second thread from executing the code between the braces.
So that's why most people just create a junk object to lock on, it prevents other threads from obtaining a lock on that same junk object.


q:
Is it possible for a generic interface's type to be based on a specific parent class?

For example:

public interface IGenericFace<T : BaseClass>
{
}

Obviously the above code doesn't work but if it did, what I'm trying to tell the compiler is that T must be a sub-class of BaseClass.  Can that be done, are there plans for it, etc.?

I think it would be useful in terms of a specific project, making sure a generic interface/class isn't used with unintended type(s) at compile time.  Or also to sort of self-document: show what kind of type is intended.

[A]
```
```
public interface IGenericFace<T> where T : SomeBaseClass
```
```


q: How do I force Python's print function to flush the buffered output to the screen?

[A]
In Python 3,
```
print
```
can take an optional
```
flush
```
argument:
```
```
print("Hello, World!", flush=True)
```
```
In Python 2, after calling
```
print
```
, do:
```
```
import sys
sys.stdout.flush()
```
```
By default,
```
print
```
prints to
```
sys.stdout
```
(see the documentation for more about
file objects
).


q:
I have a user control that is pretty basic. It contains several TextBox controls, a few DropDownList controls, a save Button and a cancel Button. I would like to use this control in two different modes. The first mode is in the normal postback mode to do the save and cancel actions. The second mode would use AJAX to do the save and cancel actions.

Is it possible to wrap the contents of the control in an UpdatePanel and then be able to turn on/off whether or not the UpdatePanel does AJAX or PostBack for the control events? Or would I be better served by just creating two new controls (1 with UpdatePanel, 1 without) to house the one old control?

[A]
The easiest way to just 'turn off' your UpdatePanel is to set EnablePartialRendering to false in the ScriptManager.  I'm not sure that this is the best solution.  I would recommend adding your controls to an update panel in your codebehind Page_Load event handler based on a boolean flag.
```
```
void Page_Load() {
    if(IsAjaxy) {
     upAnUpdatePanel.Controls.Add(tbSomeTextBox);
    }
    else {
     this.Controls.Add(tbSomeTextBox);
    }
```
```
Something along those lines should work just fine.


q:
I assume that most of the analyzing and tracking is done based on the data gathered from browser actions like page requests. Tools like AWStats, Google Analytics and Omniture take place in this.

But there is also good amount of data available in databases or service level logs. For example GWT based application might be a bit tricky to analyze. Or in case of a financial application customer might be interested in suspicious transfers.

So, please share your best practices:

What kind of approaches you have implemented for DB or log analysis?

Do you use some existing tools or your own in-house products?

Are you happy just to follow which functionality is the used most one and how fast it is processed?

Or do you actually store user action paths and use those to spot unusual patterns?


q:
I need to select from a table and filter on dates greater than a
specified date.

The problem I'm having is that the dates are stored as nchar(20) and I
can't seem to get it converted to date in the where clause.

SELECT CONVERT(DATETIME,log_time,20) from dbo.logs
where CONVERT(DATETIME,log_time,20) > '10/20/2008'

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting datetime from character string.

[A]
try this:
```
```
select convert(datetime, cast(trim(log_time), nvarchar)) from dbo.logs
where convert(datetime, cast(trim(log_time), nvarchar)) > '10/20/2008'
```
```
I think the trick is that you need to trim the string and cast to nvarchar


q:
I'm creating a table that looks something like this.

CREATE TABLE packages
(
  productCode char(2)
  , name nvarchar(100)
  , ...
)

How do I make sure the productCode is always one of two values XJ or XD?

[A]
```
```
ALTER TABLE packages
ADD CONSTRAINT constraintname CHECK (productCode in ('XJ', 'XD'))
```
```


q:
This is a winforms application.

In windows, I want the user to click and button, and then a popup should make the user select the path of where they want to save the file.

[A]
```
StringBuilder.ToString()
```
can be passed to the
```
TextStream.Write()
```
method after creating the file.
Using the
SaveFileDialog class
, you can let the user select path and file name - in a standard way. Detailed examples in the
doc
.


q:
The first one is definitely something that works, but which one below is the efficient way?

switch($type) {
    case 1:
        print 'success';
    break;

    case 2:
        print 'success';
    break;

    case 3:
        print 'success';
    break;

    case 4:
        print 'success for type 4';
    break;
}

Since 1, 2 and 3 print do the same, can I do this?

switch($type) {
    case 1, 2, 3:
        print 'success';
    break;

    case 4:
        print 'success for type 4';
    break;
}

or

switch($type) {
    case 1:
    case 2:
    case 3:
        print 'success';
    break;

    case 4:
        print 'success for type 4';
    break;
}

[A]
```
```
switch($type)
 {
     case 1:
     case 2:
     case 3:
         print 'success';
     break;
     case 4:
         print 'success for type 4';
     break;
 }
```
```
Is the way to go!


q:
I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:

import commands

commands.getoutput('server stop')

[A]
Should be able to pass it as a parameter.  something like:
```
```
commands.getoutput('server stop -p password')
```
```


q: As I've read somewhere it is advised to use !== and === instead.

[A]
"Use the strict equality operator (===) when you want to check that the two operands are of the same type and value. Use the regular equality operator (==) if you care only about the value and the type does not matter. If, for example, one operand is the number 5 and the other operand is the string "5", standard equality operator will return true, but, since they are not of the same type, a strict equality operator will return false."
http://www.webreference.com/js/column26/stricteq.html


q:
I saw a code snippet yesterday in one of the responses here on StackOverflow that intrigued me. It was something like this:

 List<string> myList = new List<string> {"aBc", "HELLO", "GoodBye"};

 myList.ForEach(d=>d.ToLower());

I was hoping I could use it to convert all items in myList to lowercase. However, it doesn't happen... after running this, the casing in myList is unchanged.

So my question is whether there IS a way, using LINQ and Lambda expressions to easily iterate through and modify the contents of a list in a manner similar to this.

Thanks,
Max

[A]
```
```
[TestMethod]
public void LinqStringTest()
{
    List<string> myList = new List<string> { "aBc", "HELLO", "GoodBye" };
    myList = (from s in myList select s.ToLower()).ToList();
    Assert.AreEqual(myList[0], "abc");
    Assert.AreEqual(myList[1], "hello");
    Assert.AreEqual(myList[2], "goodbye");
}
```
```


q:
I am attempting to disable SSL v2.0 protocol on IIS 7.

The following article refers to IIS v6:
http://support.microsoft.com/kb/187498

It doesn't seem to apply because the only protocol listed in the registry is SSL 2.0 (not all the others) and the setting "DisabledByDefault=1" is already in there, which would seem to imply that it is disabled.

However, the following article seems to suggest that it still applies and to turn off "DisabledByDefault" which seems strange.
http://forums.iis.net/t/1151822.aspx

I only need to disable SSL v2.0, but I want to be relatively confident I am doing the right thing.

[A] Add a DWORD named "Enabled" with value 0x0 (default) to the SSL 2.0 key


q:
I have a Delphi Web Server setup and running, publishing Web Services, and I want to know some stuff on the calls to the web services:

The IP address of the client who calls the web service.

Some SOAP information on the call, such as username and password.

How can I get this information from within the service code? My class is inheriting from TSoapDataModule, so I figure there's a way to get that info through it. Still, I can't find how.

TMyAppServerDataModule = class(TSoapDataModule, ITMyAppServerDataModule ,
            IAppServerSOAP, IAppServer, ITMySOAPWebService)
// ...my working components and methods... //
end;

[A]
You should be able to get a
TWebRequest
from the Request property of the TWebModule object you get from calling
GetSOAPWebModule
. TWebRequest will tell you lots of things about the request. Like RemoteAddr


q:
I make a request to an xml web service, and get back a response. This response, being a stream, is then saved to a string. The problem is, the response is full of tags, CDATA, etc (as you would expect). There is no line breaking either, as to be expected.

I want to take this string, which represents an xml document, and strip it of all its tags but keep the actual values, and also, make sure that each record is in one line, so:

<Record>
  <name>adam</name>
  <telephoneno>000</telephonenumber>
</Record>
<Record>
  <name>mike</name>
  <telephoneno>001</telephonenumber>
</Record>

Will be transformed to:

adam 000
mike 001

Headings is an easy issue, but how could I achieve this? I've tried datatables and datasets but I don't think they have great support for achieving what I am trying to do.

[A]
This is exactly what XSLT is for! It transforms XML files into a different output. In your case, you could use a relatively simple XSL transformation to output a list.
This might do it:
records.xml:
```
```
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<Records>
  <Record>
    <name>adam</name>
    <telephonenumber>000</telephonenumber>
  </Record>
  <Record>
    <name>mike</name>
    <telephonenumber>001</telephonenumber>
  </Record>
</Records>
```
```
style.xsl
```
```
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
  <xsl:template match="Record">
    <xsl:value-of select="name"/><xsl:text> </xsl:text><xsl:value-of select="telephonenumber"/>
  </xsl:template>
</xsl:stylesheet>
```
```
I tested it with
this tool
and it works.


q:
I am trying to include a value from a database table within the value element of an input field.

This is what I have, but it is not working:

?><input type="text" size="10" value="<?= date("Y-m-d",
strtotime($rowupd['upcoming_event_featured_date'])) ?>" name="upcoming_event_featured_date"
id="keys"/><?php

I have done this before, but I usually print it out like this:

print '<input type="text" size="10" value="'.date("Y-m-d",
strtotime($rowupd['upcoming_event_featured_date'])).'" name="upcoming_event_featured_date"
id="keys"/>';

What is the appropriate way of doing this without using print ''?

[A]
You can use the
short_open_tag
ini directive to turn on the <?= shortcut for printing.
If that is not available, you must use either print or echo to accomplish this.
You can try:
```
```
ini_set('short_open_tag', true);
```
```


q:
Is there any library function for this purpose, so I don't do it by hand and risk ending in TDWTF?

echo ceil(31497230840470473074370324734723042.6);

// Expected result
31497230840470473074370324734723043

// Prints
<garbage>

[A]
This will work for you:
```
```
$x = '31497230840470473074370324734723042.9';

bcscale(100);
var_dump(bcFloor($x));
var_dump(bcCeil($x));
var_dump(bcRound($x));

function bcFloor($x)
{
    $result = bcmul($x, '1', 0);
    if ((bccomp($result, '0', 0) == -1) && bccomp($x, $result, 1))
        $result = bcsub($result, 1, 0);

    return $result;
}

function bcCeil($x)
{
    $floor = bcFloor($x);
    return bcadd($floor, ceil(bcsub($x, $floor)), 0);
}

function bcRound($x)
{
    $floor = bcFloor($x);
    return bcadd($floor, round(bcsub($x, $floor)), 0);
}
```
```
Basically it finds the flooy by multiplying by one with zero precision.
Then it can do ceil / round by subtracting that from the total, calling the built in functions, then adding the result back on
Edit: fixed for -ve numbers


q:
I'd like a loop that uses a UInt16 (ushort) to loop through all of its values.  However, this doesn't do it:

for( ushort i = 0; i < UInt16.MaxValue; i++ )
{
    // do something
}

The problem is that the loop will quit when i == 0xFFFF and not "do something".
If I change the 'for' statement to "for(ushort i = 0; i <= UInt16.MaxValue; i++ )", then it becomes an infinite loop because i never gets to 0x10000 because ushorts only go to 0xFFFF.

I could make 'i' an int and cast it or assign it to a ushort variable in the loop.

Any suggestions?

[A]
Use a
```
do...while
```
loop
```
```
ushort i = 0;
do
{
    // do something
} while(i++ < UInt16.MaxValue);
```
```
There is an interesting discussion of testing loops at the top vs. the bottom
here
.


q: As a counterpart to C++ Coding Guideline 102, which of the 101 guidelines of Sutter & Alexandrescu do you violate or ignore most often, and why?

[A]
I'd say for me, it's probably 16. Avoid macros. I find there are a good number of things I can only do with macros (especially inlining __FILE__ and __LINE__ into expressions), and many cases where I need a compact expression which operates in the external function context (checking result codes and returning, for example). As a result, my code tends to be sprinkled liberally with assertions in the form of macros, for example, so I'd say this is one I ignore quite a bit.
That said, I would forgo most of my uses if the language allowed alternative similarly compact expressions of the same concepts, but since it does not, macros will be around for a long time.
I should add, it's not to say that I think the suggestion is bad, or it's bad to follow it when you have an alternative available. I just find that I end up using a lot of macros, usually because there's no alternative available.


q:
I am making a strong effort to discipline my projects and create a Vision/Scope document at the onset.  Included in this are the use case diagrams.  Just listing out the use cases has really helped me fully see all the requirements that the customer is asking for, and it has opened up dialog.

I am wondering about how detailed the use case should be.  If I am making a web application and the user will login to see a report, do I list all the columns on the report in the use case description?

If not, then when would I document those details?

[A]
the advantage of use-case diagrams is that they are simple and end-users can read and understand them
the columns to go on a report are part of a design or requirements specification (details of a feature, in agile terms) and do
not
belong on a use-case diagram
anything that clutters the use-case diagram belongs somewhere else
where? it doesn't matter, as long as it's a consistent place and you know where to find it ;-)
to remind people what a use-case diagram looks like - and why there is no room for spurious details -
(source:
agilemodeling.com
)


q: Ok simple question. I have a JSF application, containing a login page. The problem is if the user loads the login page, leaves it for a while, then tries to login the session expires and a ViewExpiredException is thrown. I could redirect back to the login when this happens, but that isn't very smooth. How can I allow this flow to properly login without an additional attempt?

[A]
Couple of slightly hacky solutions:
(Very hacky) use a
```
<meta http-equiv="refresh" content="5"/>
```
tag to automatically reload the page every so often.
Use a JavaScript function to periodically send a 'ping' request to the server to keep the session alive.
We use
IceFaces
at work which automatically detects when your session has expired and displays a pop-up alerting you to the fact. But we do still sometimes have problems on the login page for some reason.


q:
What's everyone take on tieing code enum's to row ID's in a database table? I'm really looking for a cleaner alternative. What if for example your static rows in a given table are ID's 1,2,3, and then that table gets filled with user transactional data using ID's 4-100, and then you later want to add a new row ID which in your local production database is row ID 4, but when that row goes to a customers database it will have to be 101...well that kinda breaks everything.

So how do you handle static locked rows in a table that also gets filled with transactional data?

Thanks,
MeshMan

[A]
Don't do that. ;-)
If you have static rows, values that never change, in a table that has user data that is transactional or at least mutable, then I'd say you have at least a normalization issue in the schema.
Reference data belongs in it's own table, usually.  If the table itself contains only the reference data, then assigning the IDs from the application or using generated IDs from the DB becomes a matter of preference.
I've often toyed with the idea of generating either a 'source code' Enum class from DB tables or filling DB tables with Enum class information at build/deployment time, but I've never 'gotten around to it'.


q:
I am on the way to build an ASP.NET MVC application with the latest beta release and I wonder if it is possible to change the default project Layout of

/Views/Home/Index.aspx
/Views/Home/About.aspx

to

/Blog/Views/Home/Index.aspx
/Blog/Views/Home/About.aspx

/Forum/Views/Home/Index.aspx
/Forum/Views/Home/About.aspx

The goal is to get some separation between "applications" within one single Web project, something like Thomas Owens asked already here: Under an MVC framework, which directory structure would be expected by other developers?

Of course this should include the Controllers as well, not only the Views.

[A]
Yes, it should be possible to do this.  I can think of one way; there may be others.
The first step is to modify the default route to include your application name:
```
```
routes.MapRoute("Default",
                "{applicationName}/{controller}/{action}/{id})",
                null, null);
```
```
I'm presuming that you're going to group the two "applications" into different namespaces within a single assembly. So you might have two namespaces like:
MyApp.Blog.Controllers
MyApp.Forum.Controllers
Next, you need to change the controller factory so that it instantiates the right controller. You can do this by subtyping the DefaultControllerFactory and overriding the GetControllerType method:
```
```
protected override System.Type GetControllerType(string controllerName)
    {
        string applicationName;
        if (RequestContext != null &&
           RequestContext.RouteData.Values.TryGetValue(
           "applicationName", out applicationName)) {
           // return controller type using app name to
           // look up namespace and controllerName argument
           return ...
        }

        // if no match, maybe it's a different controller/route
        return base.GetControllerType(controllerName);
    }
```
```
Finally, you need to tell MVC to use your ControllerFactory. In Global.asax.cs:
```
```
private void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
        ControllerBuilder.Current.SetControllerFactory(
            MyApp.MyControllerFactory());
    }
```
```
Locating views can be handled similarly.  In this case, you subtype WebFormViewEngine.


q:
I know enough to know that we need to get our application to deploy with a single user action. However, I don't know:

What are some good tools to use in a .NET shop?

How do you manage config changes for each of your environments?

Can someone point me to some good resources for continous integration. I'd like to see some theory as well as a step by step practical guide.

Edit:

I'm in need to automated a web deployment right now; however, I'd also like to learn how to do this for desktop apps.

[A]
Visual Build Pro
from Kinook is a pretty good tool for one-click deployment. It's easy to use and has a lot of capabilities. I have been using it for years.  Of course there's also NAnt, which I haven't used much.
As far as managing config changes, I manage multiple config files with extensions that indicate the deployment environment, and then just do a simple rename as a step within my build script.
For example, if I am deploying to Test, I might have a config file called Web.test.config, which gets automatically renamed to Web.config by the build script.


q:
I cant' figure out how to reference the current instance object defined by the XAML file in the XAML file.

I have a converter that I want to send in the current instance as the parameter object.

{Binding Path=<bindingObject>, Converter={x:Static namespace:Converter.Instance}, ConverterParameter=this}

In this code this is converted to a string instead of a reference to the current instance object.

Thanks

John

[A]
Have you tried using the
```
RelativeSource
```
markup extension
? You can use
```
Self
```
there.


q: Anyone know off the top of their heads how to convert a System.Xml.XmlNode to System.Xml.Linq.XNode?

[A]
I don't think there is, but why would you need to? Each is the lowest 'leaf' of the Xml structure for different ways of reading the document.
If you use Linq to Xml and XDocument you'll have all the linq-style syntax and new functionality, but really all that's about selecting a node.
Once you have the element that you're dealing with, why do you need to switch?


q:
I want to use the php simple HTML DOM parser to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?

I guess im wondering why I use this, and what does it do as I have never come across a callback function before!

[A]
Here's a basic callback function example:
```
```
<?php

function thisFuncTakesACallback($callbackFunc)
{
    echo "I'm going to call $callbackFunc!
";
    $callbackFunc();
}

function thisFuncGetsCalled()
{
    echo "I'm a callback function!
";
}

thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>
```
```
You can call a function that has its name stored in a variable like this:
$variable()
.
So, in the above example, we pass the name of the
thisFuncGetsCalled
function to
thisFuncTakesACallback()
which then calls the function passed in.


q:
In a project I am working on, Apache is set up to only forward requests that come in as /prefix/* to mongrel. How can I tell ruby on rails to generate all URLs with that prefix?

I have the routes set up for forward to the correct controller action by doing this:

map.connect 'sfc/:controller/:action'

but that doesn't seem to affect the way that the url writer generates the URLs.

Any ideas?

[A]
The
```
RAILS_RELATIVE_URL_ROOT
```
environment variable should do the trick, though I haven't tried it myself.


q:
I am using the ASP.Net plugin and control provided by reCAPTCHA. I can successfully get the control to work if the submit button on the web form is not in a validationgroup. There is no validationgroup attribute for the reCAPTCHA control.

Has anybody had any success with this or any solutions to get the reCAPTCHA control to work when there is a validationgroup on the web form?

[A]
The reCAPTCHA ASP.NET plug-in is written to be backward-compatible with ASP.NET 1.1, which means the
```
ValidationGroup
```
concept (which is new in ASP.NET 2.0) is not supported. But the plug-in comes with
downloadable source code
, so you can modify it yourself to support
```
ValidationGroup
```
.
In ASP.NET 2.0,
validators should inherit from
```
BaseValidator
```
and implement
```
IValidator
```
, which means you should change the RecaptchaControl type to inherit from
```
BaseValidator
```
instead of
```
WebControl
```
. You will then have to modify the code a bit to implement all methods and properties defined in
```
BaseValidator
```
. Then you can use this new control on your page instead, which now supports
```
ValidationGroup
```
.