Question:
This happened to me in Visual Studio 2008 pre and post 2008 sp1 on more than one computer and to someone else I know, so it can't be an isolated incident.

Seemingly random, every so often I lose all syntax highlighting in my aspx page (the html) so that Visual Studio now looks like a really expensive version of notepad.

Does anyone know why does happens?  Better yet, anyone know how to fix it?

Answer:
You have basically experienced Visual Studio giving up.  It gives up for many reason, the page is too complicated to highlight which is usually because there are too many syntax errors.  The highlighting is done with some very complicated and intelligent RegEx statements essentially, however if Visual Studio is unable to apply them it just displays black text.
One thing to try is to fix all the syntax issues, if any.
By the way this "giving up" happens in most IDE's.  I have seen it happen once or twice in Elcipse too.


Question:
I'm trying to use Groovy to create an interactive scripting / macro mode for my application. The application is OSGi and much of the information the scripts may need is not know up front. I figured I could use GroovyShell and call eval() multiple times continually appending to the namespace as OSGi bundles are loaded. GroovyShell maintains variable state over multiple eval calls, but not class definitions or methods.

goal: Create a base class during startup. As OSGi bundles load, create derived classes as needed.

Answer:
This might be what you are looking for?
From
Groovy in Action
```
```
def binding = new Binding(x: 6, y: 4)
def shell = new GroovyShell(binding)
def expression = '''f = x * y'''
shell.evaluate(expression)
assert binding.getVariable("f") == 24
```
```
An appropriate use of Binding will allow you to maintain state?


Question:
Example

I have Person, SpecialPerson, and User. Person and SpecialPerson are just people - they don't have a user name or password on a site, but they are stored in a database for record keeping. User has all of the same data as Person and potentially SpecialPerson, along with a user name and password as they are registered with the site.

How would you address this problem? Would you have a Person table which stores all data common to a person and use a key to look up their data in SpecialPerson (if they are a special person) and User (if they are a user) and vice-versa?

Answer:
Personally, I would store all of these different user classes in a single table.  You can then either have a field which stores a 'Type' value, or you can imply what type of person you're dealing with by what fields are filled in.  For example, if UserID is NULL, then this record isn't a User.
You could link out to other tables using a one to one-or-none type of join, but then in every query you'll be adding extra joins.
The first method is also supported by LINQ-to-SQL if you decide to go down that route (they call it 'Table Per Hierarchy' or 'TPH').


Question:
In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful.

Would it make sense to have the listening socket as a serversocket and run it in a separate thread to the socket I'm using to send data to the server?

In a loosely related question. Does anyone know if programming simply for java, in netbeans then exporting it for use on a blackberry (using a plugin) the sockets would still work ?

Answer:
If you can afford the threading, try this (keep in mind I've left out some details like exception handling and playing nice with threads). You may want to look into
```
SocketChannels
```
and/or NIO async sockets / selectors. This should get you started.
```
```
boolean finished = false;
int port = 10000;
ServerSocket server = new ServerSocket(port);

while (!finished) {
    // This will block until a connection is made
    Socket s = server.accept();
    // Spawn off some thread (or use a thread pool) to handle this socket
    // Server will continue to listen
}
```
```


Question:
How do you rewrite this in Linq?

SELECT Id, Name FROM TableA WHERE TableA.Id IN (SELECT xx from TableB INNER JOIN Table C....)

So in plain english, I want to select Id and Name from TableA where TableA's Id is in a result set from a second query.

Answer:
```
```
from a in TableA
where (from b in TableB
       join c in TableC on b.id equals c.id
       where .. select b.id)
.Contains(a.Id)
select new { a.Id, a.Name }
```
```


Question:
I was wondering if there is an open source library or algorithm that can expand a non-numeric range.  For example, if you have 1A to 9A you should get

1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A.

I've tried Googling for this and the best I could come up with were Regex that would expand numerics with dashes (1-3 becoming 1,2,3).

Answer: I was trying to leave it somewhat open because the number of possibilities is staggering.  I believe this one of those questions that could not be answered 100% here without going through a lot of technical detail about is considered a "good" or "bad" range.  I'm just trying to find a jumping point for ideas on how other people have tackled this problem.  I was hoping that someone wrote a blog post explaining how they went about it solving this problem or created a whole library to handle this.


Question:
I inserted some values into a table. There is a column whose value is auto-generated. In the next statement of my code, I want to retrieve this value.

Can you tell me how to do it the right way?

Answer:
```
```
SELECT @@Scope_Identity as Id
```
```
There is also @@identity, but if you have a trigger, it will return the results of something that happened during the trigger, where scope_identity respects your scope.


Question:
Is there a limit with the number of SSL connections?

We are trying to connect through SSL with 2000 sessions. We have tried it a couple of times but it always dies at 1062nd. Is there a limit?

Answer:
Yes, everything has a limit. As far as I'm aware, there is no inherit limit with "SSL".. it is after all just a protocol.
But, there is a limited amount of memory, ports, CPU on the machine you are connected to, from and every single one in between.
The actually server you are connected to may have an arbitrary limit set too.
This question doesn't have enough information to answer beyond "YES".


Question: Let's say I want to run a .NET application on a machine where the .NET framework is not available; Is there any way to compile the application to native code?

Answer:
Yes, using
Ngen
, the Native Image Generator. There are, however, a number of things you need to be aware of:
You still need the CLR to run your executable.
The CLR will not dynamically optimize your assemblies based on the environment it's run in (e.g. 486 vs. 586 vs. 686, etc.)
All in all, it's only worth using Ngen if you need to reduce the startup time of your application.


Question:
Can't get to my site. Apache gives the following error message:

[Fri Sep 05 08:47:42 2008] [error] (OS 10060)A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.  : proxy: HTTP: attempt to connect to 10.10.10.1:80 (10.10.10.1) failed

Answer: Can you connect to the proxied host (10.10.10.1) directly?  Is it functioning normally?


Question:
I'm curious about everyones practices when it comes to using or distributing libraries for an application that you write.

First of all, when developing your application do you link the debug or release version of the libraries? (For when you run your application in debug mode)

Then when you run your app in release mode just before deploying, which build of the libraries do you use?

How do you perform the switch between your debug and release version of the libraries? Do you do it manually, do you use macros, or whatever else is it that you do?

Answer:
I would first determine what requirements are needed from the library:
Debug/Release
Unicode support
And so on..
With that determined you can then create configurations for each combination required by yourself or other library users.
When compiling and linking it is very important that you keep that libraries and executable consistent with respect to configurations used i.e. don't mix release & debug when linking.
I know on the Windows/VS platform this can cause subtle memory issues if debug & release libs are mixed within an executable.
As Brian has mentioned to Visual Studio it's best to use the Configuration Manager to setup how you want each configuration you require to be built.
For example our projects require the following configurations to be available depending on the executable being built.
Debug+Unicode
Debug+ASCII
Release+Unicode
Release+ASCII
The users of this particular project use the Configuration Manager to match their executable requirements with the project's available configurations.
Regarding the use of macros, they are used extensively in implementing compile time decisions for requirements like if the debug or release version of a function is to be linked. If you're using VS you can view the pre-processor definitions attribute to see how the various macros are defined e.g. _DEBUG _RELEASE, this is how the configuration controls whats compiled.
What platform are you using to compile/link your projects?
EDIT: Expanding on your updated comment..
If the
Configuration Manager
option is not available to you then I recommend using the following properties from the project:
Linker
->
Additional Library Directories
or
Linker
->
Input
Use the macro
```
$(ConfigurationName)
```
to link with the appropriate library configuration e.g. Debug/Release.
```
```
$(ProjectDir)\..\third-party-prj\$(ConfigurationName)\third-party.lib
```
```
Build Events
or
Custom Build Step
configuration property
Execute a copy of the required library file(s) from the dependent project prior (or after) to the build occurring.
```
```
xcopy $(ProjectDir)\..\third-party-prj\$(ConfigurationName)\third-party.dll $(IntDir)
```
```
The macro
```
$(ProjectDir)
```
will be substituted for the current project's location and causes the operation to occur relative to the current project.
The macro
```
$(ConfigurationName)
```
will be substituted for the currently selected configuration (default is
```
Debug
```
or
```
Release
```
) which allows the correct items to be copied depending on what configuration is being built currently.
If you use a regular naming convention for your project configurations it will help, as you can use the
```
$(ConfigurationName)
```
macro, otherwise you can simply use a fixed string.


Question:
I've had some trouble forking of processes from a Perl CGI script when running on Windows. The main issue seems to be that 'fork' is emulated when running on windows, and doesn't actually seem to create a new process (just another thread in the current one). This means that web servers (like IIS) which are waiting for the process to finish continue waiting until the 'background' process finishes.

Is there a way of forking off a background process from a CGI script under Windows? Even better, is there a single function I can call which will do this in a cross platform way?

(And just to make life extra difficult, I'd really like a good way to redirect the forked processes output to a file at the same time).

Answer:
perlfork
:
Perl provides a fork() keyword that
  corresponds to the Unix system call of
  the same name. On most Unix-like
  platforms where the fork() system call
  is available, Perl's fork() simply
  calls it.
On some platforms such as Windows
  where the fork() system call is not
  available, Perl can be built to
  emulate fork() at the interpreter
  level. While the emulation is designed
  to be as compatible as possible with
  the real fork() at the the level of
  the Perl program, there are certain
  important differences that stem from
  the fact that all the pseudo child
  ``processes'' created this way live in
  the same real process as far as the
  operating system is concerned.


Question: Is there a way with WPF to get an array of elements under the mouse on a MouseMove event?

Answer:
Can you use the
VisualTreeHelper.HitTest
?
http://lukieb.blogspot.com/2008/07/visualtreehelperhittest.html


Question:
How do you automatically set the focus to a textbox when a web page loads?

Is there an HTML tag to do it or does it have to be done via Javascript?

Answer:
You need to use javascript:
```
```
<BODY onLoad="document.getElementById('myButton').focus();">
```
```
@Ben notes that you should not add event handlers like this. While that is another question, he recommends that you use this function:
```
```
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
```
```
And then put a call to addLoadEvent on your page and reference a function the sets the focus to you desired textbox.


Question: I am using js2-mode to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2.

Answer:
Do you have
```
(setq-default indent-tabs-mode nil)
```
in your .emacs? It works fine for me in emacs 23.0.60.1 when I do that. js2-mode uses the standard emacs function indent-to, which respects indent-tabs-mode, to do its indenting.


Question: I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's text, value, and selected properties, but I don't think that javascript's built in Array.sort() would work correctly.

Answer:
Well, in IE6 it seems to sort on the nested array's [0] item:
```
```
function sortSelect(selectToSort) {
    var arrOptions = [];

    for (var i = 0; i < selectToSort.options.length; i++)  {
        arrOptions[i] = [];
        arrOptions[i][0] = selectToSort.options[i].value;
        arrOptions[i][1] = selectToSort.options[i].text;
        arrOptions[i][2] = selectToSort.options[i].selected;
    }

    arrOptions.sort();

    for (var i = 0; i < selectToSort.options.length; i++)  {
        selectToSort.options[i].value = arrOptions[i][0];
        selectToSort.options[i].text = arrOptions[i][1];
        selectToSort.options[i].selected = arrOptions[i][2];
    }
}
```
```
I'll see if this works in other browsers...
Edit: it works in Firefox too, woo hoo!
Is there an easier way than this though? is there some method built into javascript or jQuery that sorts selects that I am missing, or is this the best way?


Question:
In an application that I'm writing I have some code like this:

NSWorkspace* ws = [NSWorkspace sharedWorkspace];
NSString* myurl = @"http://www.somewebsite.com/method?a=%d";

NSURL* url = [NSURL URLWithString:myurl];

[ws openURL:url];

The main difference being that myurl comes from somewhere outside my control. Note the %d in the URL which isn't entirely correct and means that URLWithString fails, returning nil.

What is the "correct" way of handling this? Do I need to parse the string and properly encode the arguments? Or is there some clever method in Cocoa that does all the hard work for me?

Answer:
I think the behaviour here is correct, because %d is not a valid component of a URL (% is the escape, but expects two hex characters to follow it).
You can't just URL encode the URL as given to you, because that would encode the /s and ?s as well, which you don't want.
So, the question is, what's the correct behaviour here?
Perhaps you would want it to be turned into...
```
```
http://www.somewebsite.com/method?a=%25d
```
```
(i.e. the % is encode to the encoded version of % in a URL, so when method gets the input, it sees a as being set to %d)
I don't think there's any library function which will do that sort of thing for you, since there's no 'correct' way to do it. About he only correct thing you can do is return an error message saying the URL you were given is invalid (just as URLWithString is)
If you wanted to try to handle the input, I guess you would need to search the URL for any % symbols which are not immediately followed by two hex characters, and then replace the % with %25 in that case. That should be quite possible with a regular expression, though I suspect there may be some additional complexities if your URLs start containing encoded versions of characters outside the ASCII character set.


Question:
I've used subversion for a  while, and used the svnmerge.py script for a while in my old job to manage merges between branches. I believe Subversion 1.5 is now out, and was supposed to have some branch / merge management system integrated with it.

So, can someone give me a quick overview of how to track merges in a branch with Subversion 1.5? Are there any pitfalls with using this support? Do I need to ensure all the team upgrades to 1.5 before using this support?

Answer:
Usage
Merge tracking is managed by the client and stored in a property (
svn:mergeinfo
).
To use merge tracking you just merge as usual but without the revision range:
```
```
svn merge trunkURL
```
```
The client will take care of reading the properties to see what revision(s) need to be merged in and then update the properties with the newly-merged revision(s).
Here
is a pretty basic overview of the process.
Pitfalls, etc.
I personally haven't run into any problems with merge tracking, but my usage of the feature has been pretty light.
Upgrading
There are two upgrades you'll need to do to get merge tracking:
Server: Your server
must
be running 1.5 to get merge tracking support.
Client: You can use a 1.x client against a 1.5 server,
but you won't get merge tracking.
Just upgrade everyone.


Question:
I'm building a website that requires very basic markup capabilities. I can't use any 3rd party plugins, so I just need a simple way to convert markup to HTML. I might have a total of 3 tags that I'll allow.

What is the best way to convert ==Heading== to <h2>Heading</h2>, or --bold-- to <b>bold</b>? Can this be done simply with Regex, or does somebody have a simple function?

I'm writing this in C#, but examples from other languages would probably work.

Answer:
It's not really a simple problem, because if you're going to display things back to the user, you'll need to also sanitise the input to ensure you don't create any
cross site scripting
vulnerabilities.
That said, you could probably do something pretty simple as you describe most easily with a regular expression replacement.
For example
```
```
replace the pattern ==([^=]*)== with <h2>\1</h2>
```
```


Question:
How can I change default Generate Method Stub behavior in Visaul Studio to generate method with body

throw new NotImplementedException();

instead of

throw new Exception("The method or operation is not implemented.");

Answer:
Taken from:
http://blogs.msdn.com/ansonh/archive/2005/12/08/501763.aspx
Visual Studio 2005 supports targeting the 1.0 version of the compact framework.  In order to keep the size of the compact framework small, it does not include all of the same types that exist in the desktop framework.  One of the types that is not included is NotImplementedException.
You can change the generated code by editing the code snippet file:
C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Refactoring\MethodStub.snippet
and changing the Declarations section to the following:
```
```
<Declarations>
            <Literal Editable="true">
                <ID>signature</ID>
                <Default>signature</Default>
            </Literal>
            <Literal>
                <ID>Exception</ID>
                <Function>SimpleTypeName(global::System.NotImplementedException)</Function>
            </Literal>
        </Declarations>
```
```


Question:
My work has a financial application, written in VB.NET with SQL, that several users can be working on at the same time.

At some point, one user might decide to Post the batch of entries that they (and possibly other people) are currently working on.

Obviously, I no longer want any other users to add, edit, or delete entries in that batch after the Post process has been initiated.

I have already seen that I can lock all data by opening the SQL transaction the moment the Post process starts, but the process can be fairly lengthy and I would prefer not to have the Transaction open for the several minutes it might take to complete the function.

Is there a way to lock just the records that I know need to be operated on from VB.NET code?

Answer:
add
```
```
with (rowlock)
```
```
to your SQL query
SQL Server Performance article
EDIT:
ok, I misunderstood the question. What you want is transaction isolation. +1 to Joel :)


Question:
Details:

Only disable after user clicks the submit button, but before the posting back to the server

ASP.NET Webforms (.NET 1.1)

Prefer jQuery (if any library at all)

Must be enabled if form reloads (i.e. credit card failed)

This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep)

Answer:
in JQuery:
```
```
$('#SubmitButtonID').click(function() { this.disabled = true; });
```
```


Question:
I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it?

(My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.)

Answer:
Subversion has native support for moving files.
```
```
svn move SOURCE DESTINATION
```
```
See the online help (svn help move) for more information.


Question:
I've seen people doing things like this in their HTML:

<!--[if IE]>
  <link rel="stylesheet" href="ie.css" type="text/css" />
<![endif]-->

Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement?

Edit

Thanks Ross.  Interesting to find out about gt, lt, gte, & lte.

Answer:
This works across all browsers because anything except IE sees
```
<!--IGNORED COMMENT-->
```
. Only IE reads the comment if it contains a conditional clause. Have a look at
this article
You can also specify which version of IE. For example:
```
```
<!--[if IE 8]>
<link rel="stylesheet type="text/css" href="ie8.css" />
<![endif]-->
```
```


Question:
I want to do this:

//*fu

which returns all nodes whose name ends in fu, such as <tarfu /> and <snafu />, but not <fubar />

Answer:
Do something like:
```
```
//*[ends-with(name(), 'fu')]
```
```
For a good XPath reference, check out
W3Schools
.


Question: I have a list of Foo. Foo has properties Bar and Lum. Some Foos have identical values for Bar. How can I use lambda/linq to group my Foos by Bar so I can iterate over each grouping's Lums?

Answer:
```
```
var q = from x in list
        group x by x.Bar into g
        select g;

foreach (var group in q)
{
    Console.WriteLine("Group " + group.Key);
    foreach (var item in group)
    {
        Console.WriteLine(item.Bar);
    }
}
```
```


Question:
I have a large codebase that targetted Flash 7, with a lot of AS2 classes.  I'm hoping that I'll be able to use Flex for any new projects, but a lot of new stuff in our roadmap is additions to the old code.

The syntax for AS2 and AS3 is generally the same, so I'm starting to wonder how hard it would be to port the current codebase to Flex/AS3.  I know all the UI-related stuff would be iffy (currently the UI is generated at runtime with a lot of createEmptyMovieClip() and attachMovie() stuff), but the UI and controller/model stuff is mostly separated.

Has anyone tried porting a large codebase of AS2 code to AS3?  How difficult is it?  What kinds of pitfalls did you run into?  Any recommendations for approaches to doing this kind of project?

Answer:
Some notable problems I saw when attempting to convert a large number of AS2 classes to AS3:
Package naming
```
```
class your.package.YourClass
{
}
```
```
becomes
```
```
package your.package
{
    class YourClass
    {
    }
}
```
```
Imports are required
You must explicitly import any outside classes used -- referring to them by their fully qualified name is no longer enough.
Interface methods can't be labelled 'public'
This makes total sense, but AS2 will let you do it so if you have any they'll need to be removed.
Explicit 'override' keyword
Any functions that override a parent class function must be declared with the
override
keyword, much like C#.  Along the same lines, if you have interfaces that extend other interfaces and redeclare functions, those overrides must be removed (again, as with
public,
this notation didn't make sense anyway but AS2 let you do it).
All the Flash builtin stuff changed
You alluded to this above, but it's now
flash.display.MovieClip
instead of just
MovieClip,
for example.  There are a lot of specifics in this category, and I didn't get far enough to find them all, but there's going to be a lot of annoyance here.
Conclusion
I didn't get to work on this conversion to the point of success, but I was able in a matter of hours to write a quick C# tool that handled every aspect of this except the
override
keyword.  Automating the imports can be tricky -- in my case the packages we use all start with a few root-level packages so they're easy to detect.


Question: Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.

Answer:
```
```
public static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEX4DECCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_6HEX4DEC_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEXCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z";
public static final String IPV6_REGEX = "\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z";
```
```
Got these from some blog. Someone good w/ regexes should be able to come up with a single regex for all IPv6 address types.  Actually, I guess you could have a single regex that matches both IPv4 and IPv6.


Question:
Have just started using Google Chrome, and noticed in parts of our site, e.g. all the links on the page, are bright red. They should be black with a dotted underline.

Is there some gotcha in WebKit rendering that turns all links red regardless of the style?

Answer:
Have you set a
```
:visited
```
setting in your stylesheet?


Question: I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?

Answer:
JavaScript can match a regular expression:
```
```
emailAddress.match( / some_regex /);
```
```
Here's an
RFC22
regular expression for emails:
```
```
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*
"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x
7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<
!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])
[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
```
```


Question: I have a collection of objects to which I'd like to just add a new property. How do I do that with LINQ?

Answer:
```
```
var a = from i in ObjectCollection select new {i.prop1, i.prop2, i.prop3, ..., newprop = newProperty}
```
```


Question:
If I have a

<input id="uploadFile" type="file" />

tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.

In FF, I just do:

var selected = document.getElementById("uploadBox").files.length > 0;

But that doesn't work in IE.

Answer:
This works in IE (and FF, I believe):
```
```
if(document.getElementById("uploadBox").value != "") {
   // you have a file
}
```
```


Question:
I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging.
Essentially my app displays an image and when touched plays a short sound.
When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes.

I get the following error:

Application Specific Information:
iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331)
*** Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<UIView 0x34efd0> setValue:forUndefinedKey:]: this class is not key value
coding-compliant for the key kramerImage.'

kramerImage here is the image I'm using for the background.

I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key.

Answer:
(This isn't really iPhone specific - the same thing will happen in regular Cocoa).
NSUnknownKeyException is a common error when using
Key-Value Coding
to access a key that the object doesn't have.
The properties of most Cocoa objects can be accessing directly:
```
```
[@"hello world" length]    // Objective-C 1.0
@"hello world".length      // Objective-C 2.0
```
```
Or via Key-Value Coding:
```
```
[@"hello world" valueForKey:@"length"]
```
```
I would get an NSUnknownKeyException if I used the following line:
```
```
[@"hello world" valueForKey:@"purpleMonkeyDishwasher"]
```
```
because NSString does not have a property (key) called 'purpleMonkeyDishwasher'.
Something in your code is trying to set a value for the key 'kramerImage' on an UIView, which (apparently) doesn't support that key.  If you're using Interface Builder, it might be something in your nib.
Find where 'kramerImage' is being used, and try to track it down from there.


Question:
We have an encryption service that we've exposed over net. tcp. Most of the time, the service is used to encrypt/decrypt strings. However, every now and then, we the need to encrypt large documents (pdf, JPG, bmp, etc.).

What are the best endpoint settings for a scenario like this? Should I accept/return a stream? I've read a lot about this, but no one gives guidance on what to do when the large file doesn't occur frequently.

Answer:
One pattern you could follow is to have an asynchronous service that works on files on a shared file system location:
Place the file to be encrypted on a shared location
Call the service and tell it to encrypt the file, passing both the location and name of the file, and the addres of a callback service on the client
The service would encrypt the file and place the encrypted copy in a shared location (the same as where the unencrypted was placed or different, doesn't matter)
The service would call back to the client, giving the name and location of the encrypted file
The client can retrieve the encrypted file


Question: We have a service that has some settings that are supported only over net.tcp. What's the best way to add another endpoint? Do I need to create an entire new host?

Answer:
A service may have multiple endpoints within a single host, but every endpoint must have a unique combination of address, binding and contract. For an IIS-hosted service (that is, an .SVC file), just set the address of the endpoint to a
relative
URI and make sure that your Visual Studio or wsdl.exe generated client specifies the endpoint's name in its constructor.
See also the MSDN article
Multiple Endpoints
.


Question: I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter?

Answer:
In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model.
```
```
<?php
// in your controller
$model1 = new Model1();
$model2 = new Model2();
$model2->setWhatever($model1);
?>
```
```


Question:
I'm trying to perform a SQL query through a linked SSAS server.  The initial query works fine:

SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')

But if I try to add:

WHERE "Value" > 0

I get an error

Invalid column name 'Value'

Any ideas what I might be doing wrong?

So the problem was that the order in which elements of the query are processed are different that the order they are written.  According to this source:

http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx

The order of evaluation in MSSQL is:

FROM

ON

JOIN

WHERE

GROUP BY

HAVING

SELECT

ORDER BY

So the alias wasn't processed until after the WHERE and HAVING clauses.

Answer:
Oh, bummer. I just saw, you select AS FOO. Don't you need a HAVING claus in this case?
```
```
SELECT whatever AS value FROM table HAVING value > 1;
```
```
I still would not use "value". But to be sure, look it up in your docs!


Question:
What is the syntax for placing constraints on multiple types?  The basic example:

class Animal<SpeciesType> where SpeciesType : Species

I would like to place constraints on both types in the following definition such that SpeciesType must inherit from Species and OrderType must inherit from Order:

class Animal<SpeciesType, OrderType>

Answer:
```
```
public class Animal<SpeciesType,OrderType>
    where SpeciesType : Species
    where OrderType : Order
{
}
```
```


Question: What's the best way to delete all rows from a table in sql but to keep n number of rows on the top?

Answer:
```
```
DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)
```
```
Edit:
Chris brings up a good performance hit since the TOP 10 query would be run for each row. If this is a one time thing, then it may not be as big of a deal, but if it is a common thing, then I did look closer at it.


Question:
I have a function that gets x(a value) and xs(a list) and removes all values that are bigger than x from the list. Well it doesn't work, can you tell me why?

(defun biggerElems(x xs)
  (let ((xst))
    (dolist (elem xs)
      (if (> x elem)
          (setf xst (remove elem xs))))
    xst))

Answer:
I think it's this line that's not right:
```
```
(setf xst (remove elem xs))))
```
```
The first argument to
```
setf
```
is the place, followed by the value.  It looks like you have it backwards (and
```
xst
```
is either
```
nil
```
or uninitialized).
You might find it easier to do this:
```
```
(defun biggerElems (x xs)
  (remove-if (lambda (item) (> item x)) xs))
```
```


Question:
I have ms sql databases that grow very large. Upon examination I find that there is a bunch of unused space in certain tables. I don't do many physical deletes, so I don't think that its just deleted records. DBCC SHRINK doesn't make the file smaller. But, if I dump the table to a new, empty database, the size goes down about 80%. Instead of the 7gb I have in this table in the current database, I end up with about 1.5gb in the fresh database. Its as if sql server is allocating too much memory. Anyone encountered this before? I'd like to be able to shrink the table by removing unused allocated space without having to create a whole new database.

Additional information:

Full recovery model used. I'll try rebuilding the indexes, i think its been a while. ldf's are shrunk daily using some wacky stored proc that truncates them.

Answer:
In the options, you can specify how much you want to grow by. By default i believe it's 10%, so given a 200MB database, when you fill your last page, it will allocate another 20MB of page space. At 7GB it would allocate 700MB.
I don't know exactly where you can modify it after you create a db, but i know it has it when you create the db. a little google work will most likely reveal the answer to you.
NOTE: my answer is not how to fix it, but maybe how to prevent / explain why you might see all this unallocated space.


Question: I am working on a simple chat application using a System.Windows.Forms.WebBrowser Control to display the messages between the user and the recipient. How do I get the control to automatically scroll to the bottom every time I update the DocumentText of the control?

Answer:
I would use the AutoScrollOffset property and set it the the bottom left of the WebBrowser control, so something like:
```
```
webCtrl.AutoScrollOffset = new Point(0, webCtrl.Height);
```
```


Question:
Is there an easy way to read an entire Access file (.mdb) into a DataSet in .NET (specifically C# or VB)?

Or at least to get a list of tables from an access file so that I can loop through it and add them one at a time into a DataSet?

Answer:
You should be able to access it using an
OleDbConnection
.
Heres
a tut on DB access using it for MS Access files.
In terms of getting the table names, back in my VB6 days I always used ADOX, not sure how they do this in .NET now.. Although I know there is a system table in the access file - wanna say "mso...". I google!
EDIT
Ah ha!
msysobjects
!! xD


Question: What are the differences between htmlspecialchars() and htmlentities(). When should I use one or the other?

Answer:
From the PHP documentation for
htmlentities
:
This function is identical to
```
htmlspecialchars()
```
in all ways, except with
```
htmlentities()
```
, all characters which have HTML character entity equivalents are translated into these entities.
From the PHP documentation for
htmlspecialchars
:
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use
```
htmlentities()
```
instead.
The difference is what gets encoded. The choices are everything (entities) or "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars).
I prefer to use
```
htmlspecialchars
```
whenever possible.
For example:
```
```
echo htmlentities('<Il était une fois un être>.');
    // Output: <Il était une fois un être>.
    //                ^^^^^^^^                 ^^^^^^^

    echo htmlspecialchars('<Il était une fois un être>.');
    // Output: <Il était une fois un être>.
    //                ^                 ^
```
```


Question:
In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using ClientScriptManager.GetWebResourceUrl(). However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.

this.drophint = document.createElement('img');
this.drophint.src = '/_layouts/images/dragdrophint.gif';

Could become something like:

this.drophint = document.createElement('img');
this.drophint.src = '{resource:assembly.location.dragdrophint.gif}';

Answer:
I'd suggest that you emit the web resources as a dynamic javascript associative array.
Server side code:
```
```
StringBuilder script = new StringBuilder();
script.Append("var imgResources = {};");
script.AppendFormat("imgResources['{0}'] = '{1}';",
    "drophint",
    Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.dragdrophint.gif"));
script.AppendFormat("imgResources['{0}'] = '{1}';",
    "anotherimg",
    Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.anotherimg.gif"));

Page.ClientScript.RegisterClientScriptBlock(
    Page.GetType(),
    "imgResources",
    script.ToString(),
    true);
```
```
Then your client side code looks like this:
```
```
this.drophint = document.createElement('img');
this.drophint.src = imgResources['drophint'];
this.anotherimg = document.createElement('img');
this.anotherimg.src = imgResources['anotherimg'];
```
```
Hope this helps.


Question: Name the design considerations in deciding between use of a singleton versus a static class. In doing this, you're kind of forced to contrast the two, so whatever contrasts you can come up with are also useful in showing your thought process! Also, every interviewer likes to see illustrative examples. :)

Answer:
When the single class needs state.  Singletons maintain a global state, static classes do not.
For instance, making a helper around a registry class:  If you have  changable hive (HKey Current User vs. HKEY Local Machine) you could go:
```
```
RegistryEditor editor = RegistryEditor.GetInstance();
editor.Hive = LocalMachine
```
```
Now any further calls to that singleton will operate on the Local Machine hive.  Otherwise, using a static class, you would have to specify that Local Machine hive everytiem, or have a method like
```
ReadSubkeyFromLocalMachine
```
.


Question:
I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack.  Basically my work involves adding <cfqueryparam> tags to all of the inline sql.  For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator?

If my query looks like this:

select * from Foo where name like '%Bob%'

what should my <cfqueryparam> tag look like?

Answer:
@Joel, I have to disagree.
```
```
select a,b,c
from Foo
where name like <cfqueryparam cfsqltype="columnType" value="%#variables.someName#%" />
```
```
Never suggest to someone that they should "select star." Bad form! Even for an example! (Even copied from the question!)
The query is pre-compiled and you should include the wild card character(s) as part of the parameter being passed to the query. This format is more readable and will run more efficiently.
When doing string concatenation, use the ampersand operator (&), not the plus sign. Technically, in most cases, plus will work just fine... until you throw a NumberFormat() in the middle of the string and start wondering why you're being told that you're not passing a valid number when you've checked and you are.


Question:
Looking at what's running and nothing jumps out.

Thanks!

Answer:
It should be w3wp.exe
EDIT: In line with Darren's comment, you should also check the "Show processes from all users" in Task Manager if that is where you are looking for the process.


Question: What's the best way to copy a file from a network share to the local file system using a Windows batch file?  Normally, I would use "net use *" but using this approach how can I get the drive letter?

Answer:
Can you just use the full UNC path to the file?
```
```
copy \\myserver\myshare\myfolder\myfile.txt c:\myfiles
```
```


Question: just wondering if anyone knows of a truly restful Put/delete implementation asp.net mvc preview 5 preferably.

Answer: I don't know of one off the top of my head, but you might look into the way that Rails handles it if you don't find anything else, and try porting it over. Rails utilizes POST, GET, PUT, and DELETE, but it apparently has to do some fakery for PUT. Could be worth looking into if you come up dry here.


Question: Is there a tool that allows one to monitor GDI calls?

Answer:
Tools like
AutomatedQA AQTime
can help you diagnose GDI usage. A much simpler, but free tool one can be found
here
.


Question:
I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables?

Is there one elegant solution that works for the majority of the cases?

Answer:
You basically make another CSS file that hide things or gives simpler "printer-friendly" style to things then add that with a
```
media="print"
```
so that it only applies to print media (when it is printed)
```
```
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
```
```


Question:
I have a regex call that I need help with.

I haven't posted my regex, because it is not relevant here.
What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex.

Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag.

RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase;
text = Regex.Replace(text, regexBold, @"<b>${text}</b>", regexOptions);

Answer:
Don't use Regex.Replace in this case...  use..
```
```
foreach(Match in Regex.Matches(...))
{
    //do your stuff here
}
```
```


Question: Is there a way to bind a MemoryStream to asp:image control?

Answer:
Best bet is to create an HttpHandler that would return the image.  Then bind the ImageUrl property on the asp:Image to the url of the HttpHandler.
Here is some code.
First create the HttpHandler:
```
```
<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

public class ImageHandler : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        context.Response.Clear();

        if (!String.IsNullOrEmpty(context.Request.QueryString["id"]))
        {
            int id = Int32.Parse(context.Request.QueryString["id"]);

            // Now you have the id, do what you want with it, to get the right image
            // More than likely, just pass it to the method, that builds the image
            Image image = GetImage(id);

            // Of course set this to whatever your format is of the image
            context.Response.ContentType = "image/jpeg";
            // Save the image to the OutputStream
            image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        }
        else
        {
            context.Response.ContentType = "text/html";
            context.Response.Write("
Need a valid id
");
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
   }

   private Image GetImage(int id)
   {
       // Not sure how you are building your MemoryStream
       // Once you have it, you just use the Image class to
       // create the image from the stream.
       MemoryStream stream = new MemoryStream();
       return Image.FromStream(stream);
   }
}
```
```
Next, just call it inside your aspx page where you are using the asp:Image.
```
```
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

            <asp:Image ID="myImage" ImageUrl="~/ImageHandler.ashx?id=1" runat="server" />

    </form>

```
```
And that is it.


Question: I want to use an image or icon as a custom cursor in WPF app. How can I do that?

Answer:
You could try this
```
```
<Window Cursor=""C:\WINDOWS\Cursors\dinosaur.ani"" />
```
```


Question: Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas?

Answer:
Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE.  To build relationships you need to use SQL commands such as:
```
```
ALTER TABLE Orders
ADD CONSTRAINT FK_Customer_Order
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
```
```
If you are doing CE development, i would recomend this FAQ:
EDIT
: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.


Question: I'm working on a C# winforms application (VS.NET 2008, .NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this?

Answer:
You will need to use some P/Inovke interop code to do this. Look for the Win32 API
```
SendMessage
```
function and the
```
EM_SETCUEBANNER
```
message.


Question:
How do I concatenate together two strings, of unknown length, in COBOL? So for example:

WORKING-STORAGE.
    FIRST-NAME    PIC X(15) VALUE SPACES.
    LAST-NAME     PIC X(15) VALUE SPACES.
    FULL-NAME     PIC X(31) VALUE SPACES.

If FIRST-NAME = 'JOHN           ' and LAST-NAME = 'DOE            ', how can I get:

FULL-NAME = 'JOHN DOE                       '

as opposed to:

FULL-NAME = 'JOHN            DOE            '

Answer:
At first glance, the solution is to use reference modification to STRING together the two strings, including the space. The problem is that you must know how many trailing spaces are present in FIRST-NAME, otherwise you'll produce something like 'JOHNbbbbbbbbbbbbDOE', where b is a space.
There's no intrinsic COBOL function to determine the number of trailing spaces in a string, but there is one to determine the number of leading spaces in a string. Therefore, the fastest way, as far as I can tell, is to reverse the first name, find the number of leading spaces, and use reference modification to string together the first and last names.
You'll have to add these fields to working storage:
```
```
WORK-FIELD        PIC X(15) VALUE SPACES.
TRAILING-SPACES   PIC 9(3)  VALUE ZERO.
FIELD-LENGTH      PIC 9(3)  VALUE ZERO.
```
```
Reverse the FIRST-NAME
MOVE FUNCTION REVERSE (FIRST-NAME) TO WORK-FIELD.
WORK-FIELD now contains leading spaces, instead of trailing spaces.
Find the number of trailing spaces in FIRST-NAME
INSPECT WORK-FIELD TALLYING TRAILING-SPACES FOR LEADING SPACES.
TRAILING-SPACE now contains the number of trailing spaces in FIRST-NAME.
Find the length of the FIRST-NAME field
COMPUTE FIELD-LENGTH = FUNCTION LENGTH (FIRST-NAME).
Concatenate the two strings together.
STRING FIRST-NAME (1:FIELD-LENGTH – TRAILING-SPACES) “ “ LAST-NAME DELIMITED BY SIZE, INTO FULL-NAME.


Question:
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it,  what is the most efficient way of going through the map?

Will the ordering of elements depend on the specific map implementation that I have for the interface?

Answer:
Yes, the order depends on the specific Map implementation.
@ScArcher2 has the more elegant Java 1.5 syntax
. In 1.4, I would do something like this:
```
```
Iterator entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Entry thisEntry = (Entry) entries.next();
  Object key = thisEntry.getKey();
  Object value = thisEntry.getValue();
  // ...
}
```
```


Question:
I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once.

Is this the proper way to use a mutex to prevent this from happening?

lock (this.GetType()) {
    _log.Info("Doing Sync");
    DoSync();
    _log.Info("Sync Completed");
}

Answer:
TheSeeker is correct.
Jeff Richter's advice in
Clr Via C#
(p638-9) on locking is to create a private object specifically for the purpose of being locked.
```
```
private Object _lock = new Object();

// usage
lock( _lock )
{
    // thread-safe code here..
}
```
```
This works because _lock cannot be locked by anything outside the current class.
EDIT: this is applicable to threads executing within a single process. @David Mohundro's answer is correct for inter-process locking.


Question:
As a follow up to this question: Developing a online exam application, how do I prevent cheaters?

Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab?

I read this: Detecting when a Flex application loses focus but was not very clear...

Answer:
The key part of the code at that link is the
```
```
systemManager.stage.addEventListener(Event.DEACTIVATE,deactivate);
```
```
The Flash player send outs activate and deactivate events when the focus enters and leaves the player. All you need to do is create a listenr for them and react appropriately.
A more clear example of how to use to the activate and deactivate events can be seen at
blog.flexaxamples.com
.
Also, it looks like the activate and deactivate events have trouble in some browsers.
Colin Moock has more info on that here.


Question:
What is the proper way to minimize a WinForms app to the system tray?

Note: minimize to system tray; on the right side of the taskbar by the clock. I'm not asking about minimizing to taskbar, which is what happens when you hit the "minus" button on the window.

I've seen hackish solutions like, "minimize, set ShowInTaskbar = false, then show your NotifyIcon."

Solutions like that are hackish because the app doesn't appear to minimize to the tray like other apps, the code has to detect when to set ShowInTaskbar = true, among other issues.

What's the proper way to do this?

Answer:
```
```
this.WindowState = FormWindowState.Minimized
```
```
That is the built in way to do it and it looks fine to me most of the time. The only time is has some weirdness to it is if you call it on startup which has some weirdness sometimes which is why most people will also set the ShowInTaskbar = false and hide the form too.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.windowstate.aspx


Question:
Does anyone have any tips or gotcha moments to look out for when trying to migrate MySQL tables from the the default case-insenstive swedish or ascii charsets to utf-8? Some of the projects that I'm involved in are striving for better internationalization and the database is going to be a significant part of this change.

Before we look to alter the database, we are going to convert each site to use UTF-8 character encoding (from least critical to most) to help ensure all input/output is using the same character set.

Thanks for any help

Answer:
I am going to be going over the following sites/articles to help find an answer.
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) - Joel on Software
UTF-8 And Unicode FAQ
Hanselminutes episode "Sorting out Internationalization with Michael Kaplan"
And I also just found a very on topic post by Derek Sivers @ O'Reilly ONLamp Blog as I was writing this out.
Turning MySQL data in latin1 to utf8 utf-8


Question: A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system.

Answer:
Just to answer this myself in keeping with Jeff's suggestion of using Stackoverflow as a place to keep technical snippets....
From the command line use:
```
```
p4 changes -m1 @<clientname>
```
```
And just replace  with the name of your client spec. This will produce output of the form:
```
```
Change 12345 on 2008/08/21 by joebloggs@mainline-client '....top line of description...'
```
```
Which is easily parsed to extract the changelist number.


Question: Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this?

Answer:
```
```
// Store the formatted string in 'result'
String result = String.format("%4d", i * j);

// Write the result to standard output
System.out.println( result );
```
```
See
format
and its
syntax


Question:
About 6 months ago I rolled out a site where every request needed to be over https.  The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event.  If the request was not over http I would response.redirect("https://example.com")

Is there a better way -- ideally some setting in the web.config?

Answer:
Please use
HSTS
(HTTP Strict Transport Security)
from
http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx
```
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
                        redirectType="Permanent" />
                </rule>
            </rules>
            <outboundRules>
                <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
                    <match serverVariable="RESPONSE_Strict_Transport_Security"
                        pattern=".*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="on" ignoreCase="true" />
                    </conditions>
                    <action type="Rewrite" value="max-age=31536000" />
                </rule>
            </outboundRules>
        </rewrite>
    </system.webServer>
</configuration>
```
```
Original Answer
(replaced with the above on 4 December 2015)
basically
```
```
protected void Application_BeginRequest(Object sender, EventArgs e)
{
   if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
   {
    Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+   HttpContext.Current.Request.RawUrl);
   }
}
```
```
that would go in the global.asax.cs (or global.asax.vb)
i dont know of a way to specify it in the web.config


Question:
Is there a way to disallow publishing of debug builds with ClickOnce?

I only want to allow release builds through, but right now human error causes a debug build to slip through once in a while.

We're publishing the build from within Visual Studio.

Answer:
One thing you can do is add a condition to the .csproj or .vbproj file that MSBuild will check when doing a build.
The condition would check if a publish is occurring and check if the build is a debug build, then do something like run an external tool or otherwise interrupt the build process or cause it to fail.
An example might be something like this:
```
```
<Choose>
    <When Condition=" '$(Configuration)'=='Debug' ">
        <Exec Command="C:\foo.bat" ContinueOnError="false" />
    </When>
 </Choose>
```
```
Where foo.bat is a batch file that return non-zero, thus stopping the publish from occurring.


Question: We maintain a system that has over a million lines of COBOL code. Does someone have suggestions about how to migrate to a GUI (probably Windows based) without losing all the business logic we have written in COBOL? And yes, some of the business logic is buried inside the current user interface.

Answer:
Writing a
screen scraper
is probably your best bet. Some of the major ERP systems have done this for years during a transition from server based apps to 3-tier applications. One i have worked with had loads of interesting features such as drop down lists for regularly used fields, date pop ups and even client based macro languages based on the scraping input.
These weren't great but worked well for the clients and made sure the applications still worked in a reliable fashion.
There is a lot of different ways to put this together, but if you put some thought into it you could probably use java or .net to create a desktop based application and with a little extra effort make a web based implementation.


Question:
I'd like to enable/disable some other controls based on how many items are in my ListView control. I can't find any event that would do this, either on the ListView itself or on the ListViewItemCollection. Maybe there's a way to generically watch any collection in C# for changes?

I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the ControlAdded and Layout events didn't work :(.

Answer:
I can't find any events that you could use.  Perhaps you could subclass ListViewItemCollection, and raise your own event when something is added, with code similar to this.
```
```
Public Class MyListViewItemCollection
    Inherits ListView.ListViewItemCollection

    Public Event ItemAdded(ByVal Item As ListViewItem)

    Sub New(ByVal owner As ListView)
        MyBase.New(owner)
    End Sub

    Public Overrides Function Add(ByVal value As System.Windows.Forms.ListViewItem) As System.Windows.Forms.ListViewItem
        Dim Item As ListViewItem

        Item = MyBase.Add(value)

        RaiseEvent ItemAdded(Item)

        Return Item
    End Function
End Class
```
```


Question:
Can i print out a url /admin/manage/products/add of a certain view in a template?

Here is the rule i want to create a link for

(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),

I would like to have /manage/products/add in a template without hardcoding it. How can i do this?

Edit: I am not using the default admin (well, i am but it is at another url), this is my own

Answer:
If you use
named url patterns
you can do the follwing in your template
```
```
{% url create_object %}
```
```


Question:
We have literally 100's of Access databases floating around the network. Some with light usage and some with quite heavy usage, and some no usage whatsoever. What we would like to do is centralise these databases onto a managed database and retain as much as possible of the reports and forms within them.

The benefits of doing this would be to have some sort of usage tracking, and also the ability to pay more attention to some of the important decentralised data that is stored in these apps.

There is no real constraints on RDBMS (Oracle, MS SQL server) or the stack it would run on (LAMP, ASP.net, Java) and there obviously won't be a silver bullet for this. We would like something that can remove the initial grunt work in an automated fashion.

Answer:
We upsize (either using the upsize wizard or by hand) users to SQL server. It's usually pretty straight forward. Replace all the access tables with linked tables to the sql server and keep all the forms/reports/macros in access. The investment in access isn't lost and the users can keep going business as usual. You get reliability of sql server and centralized backups. Keep in mind  -  we’ve done this for a few large access databases, not hundreds. I'd do a pilot of a few dozen and see how it works out.
UPDATE:
I just found this, the sql server migration assitant, it might be worth a look:
http://www.microsoft.com/sql/solutions/migration/default.mspx
Update: Yes, some refactoring will be necessary for poorly designed databases. As for how to handle access sprawl? I've run into this at companies with lots of technical users (engineers esp., are the worst for this... and excel sprawl). We did an audit - (after backing up) deleted any databases that hadn't been touched in over a year. "Owners" were assigned based the location &/or data in the database. If the database was in "S:\quality\test_dept" then the quality manager and head test engineer had to take ownership of it or we delete it (again after backing it up).


Question:
Quite a few methods exist for passing data into a Flex binary from a Rails application.  Right now, I'm using the old e4x resultFormat with a xml.erb template.  I've done AMF before, but I feel like inlining parameters into the embed itself is a better solution because you don't have to wait for the browser to load a swf binary and the binary to make a web request.

Taking all of that into account, what is the best practice for rendering a Flex widget with a Rails back-end these days?

Answer:
Sounds to me like you shouldn't use Flex at all. Flex is great for writing applications that load and display data, but is a huge overhead if you just want to display charts. If you're worried about delivering the SWF and the data in two separate responses, you should be worrying about the 200-300 K overhead of the Flex framework.
Go with something more lightweight like
Flot
and deliver the JavaScript code that generates the charts along with the data. I don't think Flex is a suitable platform for what you want.


Question:
I'm trying to install GODI on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing.

$ ./bootstrap --prefix /home/nlucaroni/godi
$ ./bootstrap_stage2
.: 1: godi_confdir: not found
Error: Command fails with code 2: /bin/sh
Failure!

I had added the proper directories to the path, and they show up with a quick echo $path, and godi_confdir reported as being:

 /home/nlucaroni/godi/etc

(...and the directory exists, with the godi.conf file present). So, I can't figure out why ./bootstrap_stage2 isn't working.

Answer:
What is the output of
```
which godi_confdir
```
?
P.S. I remember having this exact same problem, but I don't remember precisely how I fixed it.


Question:
I am looking for easy steps that are simple and effective in making a web application more secure.

What are your top tips for secure web applications, and what kind of attack will they stop?

Answer:
Escape user provided content to avoid
XSS
attacks.
Using
paremeterised SQL
or stored procedures to avoid
SQL Injections
attacks.
Running the webserver as an unprivileged account to minimise attacks on the OS.
Setting the webserver directories to an unprivileged account, again, to minimise attacks on the OS.
Setting up unprivileged accounts on the SQL server and using them for the application to minimise attacks on the DB.
For more in depth information, there is always the
OWASP Guide to Building Secure Web Applications and Web Services


Question:
I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value  of ) an extra query item (eg. "page"):

"Default.aspx?page=1"
"Default.aspx?page=2"
"Default.aspx?someother=true&page=2"

etc.

Is there a simple helper method that I can use  in the Render method  ... uhmm ... like:

Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1");
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2");

That will take care of generating a correct URL, maintain existing query string items and not create duplicates  eg. page=1&page=2&page=3?

Rolling up my own seems like such an unappealing task.

Answer:
I'm afraid I don't know of any built-in method for this, we use this method that takes the querystring and sets parameters
```
```
/// <summary>
    /// Set a parameter value in a query string. If the parameter is not found in the passed in query string,
    /// it is added to the end of the query string
    /// </summary>
    /// <param name="queryString">The query string that is to be manipulated</param>
    /// <param name="paramName">The name of the parameter</param>
    /// <param name="paramValue">The value that the parameter is to be set to</param>
    /// <returns>The query string with the parameter set to the new value.</returns>
    public static string SetParameter(string queryString, string paramName, object paramValue)
    {
        //create the regex
        //match paramname=*
        //string regex = String.Format(@"{0}=[^&]*", paramName);
        string regex = @"([&?]{0,1})" + String.Format(@"({0}=[^&]*)", paramName);

        RegexOptions options = RegexOptions.RightToLeft;
        // Querystring has parameters...
        if (Regex.IsMatch(queryString, regex, options))
        {
            queryString = Regex.Replace(queryString, regex, String.Format("$1{0}={1}", paramName, paramValue));
        }
        else
        {
            // If no querystring just return the Parameter Key/Value
            if (queryString == String.Empty)
            {
                return String.Format("{0}={1}", paramName, paramValue);
            }
            else
            {
                // Append the new parameter key/value to the end of querystring
                queryString = String.Format("{0}&{1}={2}", queryString, paramName, paramValue);
            }
        }
        return queryString;
    }
```
```
Obviously you could use the QueryString
```
NameValueCollection
```
property of the URI object to make looking up the values easier, but we wanted to be able to parse any querystring.


Question:
I like how SQLite library can be included into an application and the application has a full-fledged database to use.

Similarly, is there an open source versioning library that I can include into my application so that I can save versions of files as well as do diffs and merges?

Answer:
In my opinion
Firebird
is one of the best choices for embedded DB scenarios.
Also
Microsoft SQL Server Compact
(closed source, but free) might be suitable, however it less capable than Firebird.
EDIT:
I misread you question. If you don't need RDBMS, you can try to embed
SVN
to your application.


Question: What is the command to list all triggers in a MySQL database?

Answer:
The command for listing all triggers is:
```
```
show triggers;
```
```
or you can access the
```
INFORMATION_SCHEMA
```
table directly by:
```
```
select trigger_schema, trigger_name, action_statement
from information_schema.triggers
```
```
You can do this from version 5.0.10 onwards.
More information about the
```
TRIGGERS
```
table is here
.


Question:
We're a .NET team which uses the Oracle DB for a lot of reasons that I won't get into. But deployment has been a bitch. We are manually keeping track of all the changes to the schema in each version, by keeping a record of all the scripts that we run during development.

Now, if a developer forgets to check-in his script to the source control after he ran it - which is not that rare - at the end of the iteration we get a great big headache.

I hear that SQL Compare by Red-Gate might solve these kind of issues, but it only has SQL Server support. Anybody knows of a similar tool for Oracle? I've been unable to find one.

Answer:
TOAD is a great generic tool for Oracle development and i think a similar feature is in the basic version. You can download a trial version (make sure you don't get the old free version of TOAD, that is about 4 years old)
If you don't want to buy a tool, and you need something less flash you could roll your own quite easily. I just found
Schema Compare Tool for Oracle
which looks very simple, and has a nice baseline concept. This is very handy if you want to track changes since the last code check-in. This way you discover changes that may have been made to multiple DBs by hand, but not documented.
PS: The "SQL Compare by Red-Gate" demo looked very nice indeed... however the voice over cracked me up... sounded like a BBC documentary.


Question:
I've been hearing about triggers, and I have a few questions.

What are triggers?

How do I set them up?

Are there any precautions, aside from typical SQL stuff, that should be taken?

Answer:
A trigger is a named database object that is associated with a table and that is activated when a particular event occurs for the table.
To create a trigger:
```
```
CREATE TRIGGER triggerName [BEFORE|AFTER] [INSERT|UPDATE|DELETE|REPLACE] ON tableName FOR EACH ROW SET stuffToDoHERE;
```
```
Even though I answered this part the other question still stands.


Question:
With the code, forms and data inside the same database I am wondering what are the best practices to design a suite of tests for a Microsoft Access application (say for Access 2007).

One of the main issues with testing forms is that only a few controls have a hwnd handle and other controls only get one they have focus, which makes automation quite opaque since you cant get a list of controls on a form to act on.

Any experience to share?

Answer:
I would design the application to have as much work as possible done in queries and in vba subroutines so that your testing could be made up of populating test databases, running sets of the production queries and vba against those databases and then looking at the output and comparing to make sure the output is good.  This approach doesn't test the GUI obviously, so you could augment the testing with a series of test scripts (here I mean like a word document that says open form 1, and click control 1) that are manually executed.
It depends on the scope of the project as the level of automation necessary for the testing aspect.


Question:
Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

Example input and output:

>>> reverse_words("this is a string")
'string a is this'

It should be O(N) time and O(1) space (split() and pushing on / popping off the stack are not allowed).

The puzzle is taken from here.

Answer:
In pseudo code:
```
```
reverse input string
reverse each word (you will need to find word boundaries)
```
```


Question: It's common to have a table where for example the the fields are account, value, and time.  What's the best design pattern for retrieving the last value for each account?  Unfortunately the last keyword in a grouping gives you the last physical record in the database, not the last record by any sorting.  Which means IMHO it should never be used.  The two clumsy approaches I use are either a subquery approach or a secondary query to determine the last record, and then joining to the table to find the value.  Isn't there a more elegant approach?

Answer:
The subquery option sounds best to me, something like the following psuedo-sql.  It may be possible/necessary to optimize it via a join, that will depend on the capabilities of the SQL engine.
```
```
select *
from table
where account+time in (select account+max(time)
                       from table
                       group by account
                       order by time)
```
```


Question:
This free collection library comes from IT University of Copenhagen.

http://www.itu.dk/research/c5/

There is a video with one of the authors on Channel 9. I am trying to learn how to use these collections and I was wondering whether anyone has more experiences or what are your thoughts on this specific collection library for .NET. Do you like the way they are designed, do you like their performance and what were your major problems with them ?

Answer:
I've used it in the past and there are a couple of notes I must make:
The library is very good, very fast and very useful. It has lots of very nice data structures, some of which I did not know before starting to use this library.
It's Open-Source! This is a huge benefit.
Sometimes you don't have exactly what you want. As far as my experience showed, the library's authors decided to go with a very fault-intolerant attitude, throwing exceptions about everything. This caused me to add a few fault-tolerant methods.
All in all, a very nice library with some advanced data structures. Unfortunately, support for it is very lacking, as you can see from the fact that new releases (bugfixes, et al) range somewhere from 6 months to a year.
Note:
Starting with Mono 2.0, C5 is
bundled as a 3rd party API
, which I believe to be a wonderful show of faith in the product from the Mono team.


Question: Resharper, RefactorPro, etc?

Answer:
I have tried using Resharper for some while and also CodeRush with Refactor later on.
I have stayed with CodeRush/Refactor. There is one major difference - the discoverability of the commands. Their learning videos are quite nice and show you a lot.
Most importantly Coderush has one key/shortcut for all refactorings which makes you much more likely to actually use them. There is side window that shows you what keys to press in order to use the templates as well. I have liked Resharper's searching for usage of a method, but CodeRush has a similar feature ignited by Shift + F12 and you can also simply press Tab on a variable, function etc. to jump to its next usage.
I also liked the interface of CodeRush/Refactor more.
One of the pro's for Resharper is the integrated testing tool so yuo can run test directly from Visual Studio.


Question:
As one of those people that never got around to properly learning design (or having no talent for it), the design seems to be the step always holding me back. It's not a problem for rich-clients, as the standard GUI toolkits provide some acceptable ways to design a good-looking interface, but the web is another story.

Question: Does anyone know of a high-quality framework for designing the interface of web applications? I'm thinking of standard snippets of html for an adequate set of controls (the standard html controls plus maybe navigations, lists, forms) and style sheets to give it an acceptable, modern look. If such a thing existed, it could even support themes in the way wordpress, drupal etc. allow it.

I know of the yahoo yui, but that's mostly javascript, though their grid css is a step in the right direction.

Answer:
I'm not sure that what you're looking for exists in the way you're looking for it. However, I've had some luck with places like
Open Source Web Design
and
Open Designs
, which have some really slick templates that can be adapted to a web application so they at least don't look like crap.
There are also some commercial offerings, such as
Gooey Templates
.
Once you're getting closer to launch, you can contact a pro to fix the details for you, or simply build on what you've got.
Edited to add
: You might also want to consider learning
Blueprint CSS
. I've found it helps guide my layouts and helps them look "right", without constraining me to the layout constructed for another purpose.


Question:
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}

verse

[Test]
public void UserNameTestValidation1() {}

Answer:
i wouldn't put conditions that test needs to meet in the name, because conditions may change in time. in your example, i'd recommend naming like
```
```
UserNameLengthValidate()
```
```
or
```
```
UserNameLengthTest()
```
```
or something similar to explain what the test does, but not presuming the testing/validation parameters.


Question:
Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas?

This works fine

ALTER TABLE documents ADD COLUMN membersOnly NUMBER

I want this to work:

ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0

Have googled and seen instructions for default values work for other field types but I want to add number. Thanks!

Answer:
Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database.
then you can execute your query:
```
```
ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0
```
```


Question:
Does anyone know if there is a c# Console app, similar to the Python or Ruby console? I know the whole "Compiled versus Interpreted" difference, but with C#'s reflection power I think it could be done.

UPDATE
Well, it only took about 200 lines, but I wrote a simple one...It works a lot like osql. You enter commands and then run them with go.

SharpConsole http://www.gfilter.net/junk/sharpconsole.jpg

If anyone wants it, let me know.

Answer:
Given your mention of "C#'s reflection power", I am unsure whether you're looking for an interactive C# console for small code snippets of your own (à la Ruby's
```
irb
```
), or a means of interacting with an existing, compiled application currently running as a process.
In the former case:
Windows PowerShell
might be your friend
Another candidate would be the
C# shell
Finally,
CSI
, a Simple C# Interpreter


Question:
I am coming from an Enterprise Java background which involves a fairly heavyweight software stack, and have recently discovered the
Stripes framework; my initial impression is that this seems to do a good job of minimising the unpleasant parts of building a web application in Java.

Has anyone used Stripes for a project that has gone live? And can you share your experiences from the project? Also, did you consider any other technologies and (if so) why did you chose Stripes?

Answer:
We converted a home-grown web framework to stripes in about a week. We're using it in production at this time and it's a great framework. The community is extremely helpful, and the framework doesn't get in your way. It can be extended in many places to change the behavior as you see fit. The url binding feature is awesome as well. We implemented a robust security framework using annotations and interceptors. We're using spring for dependency injection and stripes has excellent support for that.
I'd definitely use the new 1.5 release if you're going to use it.
I'm a huge fan of the framework. I came from a struts background and it's the exact framework I was looking for. The other developers on our team really enjoy using the stripes framework.
I just bought the stripes beta book from the pragmatic programmer's site. It's a great resource on Stripes 1.5.


Question:
I'm dealing with a MySQL table that defines the JobName column as UNIQUE.  If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning.

I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately.  Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it.

Is this possible?  If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?

Answer:
First, you should
turn warnings off
so that your visitors don't see your
MySQL
errors. Second, when you call
```
mysql_query()
```
, you should check to see if it returned false. If it did, call
```
mysql_errno()
```
to find out what went wrong. Match the number returned to the error codes on
this page
.
It looks like this is the error number you're looking for:
Error: 1169 SQLSTATE: 23000 (ER_DUP_UNIQUE)
Message: Can't write, because of unique constraint, to table '%s'


Question:
Specifically, I am looking to use CA on properties of types other than

integers and doubles

CGRect, CGPoint, CGSize, and CGAffineTransform structures

CATransform3D data structures

CGColor and CGImage references

and in objects other than CALayers or NSViews

Answer:
Well, it seems I cannot do that. What I should be doing is [subclassing NSAnimation](
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/AnimationGuide/Articles/TimingAnimations.html
subclassing NSAnimation). This will work on a MacOS 10.4+ app, but not on Cocoa Touch, in which I cannot find any alternatives apart from using a NSTimer.


Question: I would like to do full-text searching of data in my Ruby on Rails application.  What options exist?

Answer:
You can use Ferret (which is Lucene written in Ruby). It integrates seamless with Rails using the acts_as_ferret mixin. Take a look at "
How to Integrate Ferret With Rails
". A alternative is
Sphinx
.


Question:
A while ago I read the Mocks Aren't Stubs article by Martin Fowler and I must admit I'm a bit scared of external dependencies with regards to added complexity so I would like to ask:

What is the best method to use when unit testing?

Is it better to always use a mock framework to automatically mock the dependencies of the method being tested, or would you prefer to use simpler mechanisms like for instance test stubs?

Answer:
Read Luke Kanies' discussion of exactly this question in
this blog post
. He references
a post from Jay Fields
which even suggests that using [a equivalent to ruby's/mocha's] stub_everything is preferrable to make the tests more robust. To quote Fields' final words: "Mocha makes it as easy to define a mock as it is to define a stub, but that doesn't mean you should always prefer mocks. In fact, I generally prefer stubs and use mocks when necessary."


Question: Anyone have a quick method for de-duplicating a generic List in C#?

Answer:
Sort it, then check two and two next to each others, as the duplicates will clump together.
Something like this:
```
```
list.Sort();
Int32 index = list.Count - 1;
while (index > 0)
{
    if (list[index] == list[index - 1])
    {
        if (index < list.Count - 1)
            (list[index], list[list.Count - 1]) = (list[list.Count - 1], list[index]);
        list.RemoveAt(list.Count - 1);
        index--;
    }
    else
        index--;
}
```
```
Notes:
Comparison is done from back to front, to avoid having to resort list after each removal
This example now uses C# Value Tuples to do the swapping, substitute with appropriate code if you can't use that
The end-result is no longer sorted


Question:
I have an inherited project that uses a build script (not make) to build and link the project with various libraries.

When it performs a build I would like to parse the build output to determine what and where the actual static libraries being linked into the final executable are and where are they coming from.

The script is compiling and linking with GNU tools.

Answer: Static libraries, that makes life more difficult in this regard. In case of dynamic libraries you could just have used ldd on the resulting executable and be done with it. The best bet would be some kind of configuration file. Alternatively you could try to look for -l arguments to gcc/ld. Those are used to specify libraries. You could write a script for extracting it from the output, though I suspect that you will have to do it manually because by the time you know what the script should look for you probably already know the answer.


Question:
Simple one really.  In SQL, if I want to search a text field for a couple of characters, I can do:

SELECT blah FROM blah WHERE blah LIKE '%text%'

The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem?

Answer:
BigTable, which is the database back end for App Engine, will scale to millions of records. Due to this, App Engine will not allow you to do any query that will result in a table scan, as performance would be dreadful for a well populated table.
In other words, every query must use an index. This is why you can only do
```
=
```
,
```
>
```
and
```
<
```
queries. (In fact you can also do
```
!=
```
but the API does this using a a combination of
```
>
```
and
```
<
```
queries.)  This is also why the development environment monitors all the queries you do and automatically adds any missing indexes to your
```
index.yaml
```
file.
There is no way to index for a
```
LIKE
```
query so it's simply not available.
Have a watch of
this Google IO session
for a much better and more detailed explanation of this.


Question:
I am trying to create a web application using Pylons and the resources on the web point to the PylonsBook page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?

I tried downloading the SimpleSiteTemplate from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:

  File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__
    table = metadata.tables[key]
AttributeError: 'module' object has no attribute 'tables'

I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.

Answer:
I don't think AuthKit is actively maintained anymore. It does use the Paste (
http://pythonpaste.org
) libs though for things like HTTP Basic/Digest authentication. I would probably go ahead and take a look at the source for some inspiration and then use the Paste tools if you want to use HTTP authentication.
There is also OpenID which is very easy to setup. The python-openid libs have an excellent example that is easy to translate to WSGI for wrapping a Pylons app. You can look at an example:
http://ionrock.org/hg/brightcontent-main/file/d87b7dcc606c/brightcontent/plugins/openidauth.py


Question:
I'm struggling to find the right terminology here, but if you have jQuery object...

$('#MyObject')

...is it possible to extract the base element? Meaning, the equivalent of this:

document.getElementById('MyObject')

Answer:
Yes, use
```
.get(index)
```
.  According to the
documentation
:
The
```
.get()
```
method grants access to the DOM nodes underlying each jQuery object.


Question:
I have wondered about the appropriateness of reflection in C# code. For example I have written a function which iterates through the properties of a given source object and creates a new instance of a specified type, then copies the values of properties with the same name from one to the other. I created this to copy data from one auto-generated LINQ object to another in order to get around the lack of inheritance from multiple tables in LINQ.

However, I can't help but think code like this is really 'cheating', i.e. rather than using using the provided language constructs to achieve a given end it allows you to circumvent them.

To what degree is this sort of code acceptable? What are the risks? What are legitimate uses of this approach?

Answer:
It may be just me, but the way I'd get into this is by creating a code generator - using reflection at runtime is a bit costly and untyped. Creating classes that would get generated according to your latest code and copy everything in a strongly typed manner would mean that you will catch these errors at build-time.
For instance, a generated class may look like this:
```
```
static class AtoBCopier
{
    public static B Copy(A item)
    {
        return new B() { Prop1 = item.Prop1, Prop2 = item.Prop2 };
    }
}
```
```
If either class doesn't have the properties or their types change, the code doesn't compile. Plus, there's a huge improvement in times.


Question:
I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File.  It can be referred to by V:\ . I'd like to refer to it by MyLabel.

(This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it )

Answer:
You can use the WMI query language for that.
Take a look at
http://msdn.microsoft.com/en-us/library/aa394592(VS.85).aspx
for examples.
The information you are looking for is available e.g. through the property VolumeName of the Win32_LogicalDisk class,
http://msdn.microsoft.com/en-us/library/aa394173(VS.85).aspx
```
SELECT * FROM Win32_LogicalDisk WHERE VolumeName="MyLabel"
```


Question:
I'm loading a SQL Server 2000 database into my new SQL Server 2005 instance. As expected, the full-text catalogs don't come with it. How can I rebuild them?

Right-clicking my full text catalogs and hitting "rebuild indexes" just hangs for hours and hours without doing anything, so it doesn't appear to be that simple...

Answer:
Try it using SQL.
CREATE FULLTEXT CATALOG
ALTER FULLTEXT CATALOG
Here's an example from Microsoft.
```
```
--Change to accent insensitive
USE AdventureWorks;
GO
ALTER FULLTEXT CATALOG ftCatalog
REBUILD WITH ACCENT_SENSITIVITY=OFF;
GO
-- Check Accentsensitivity
SELECT FULLTEXTCATALOGPROPERTY('ftCatalog', 'accentsensitivity');
GO
--Returned 0, which means the catalog is not accent sensitive.
```
```


Question: What is the most efficient way to determine how many comments a particular blog post has? We want to store the data for a new web app. We have a list of permalink URl's as well as the RSS feeds.

Answer:
If the blog is controlled by you, a "Select count(commentid) FROM comments WHERE postID = 2" will possibly the best thing. If you only have the URL but still it's your blog/db, you need to create a subquery "WHERE postID = (SELECT whatever FROM posts WHERE permalink = url)" or whatever your way to join the comments to the posts from a URL.
If it's a remote blog, you have the problem that each blog has different HTML. Essentially, you're going to need to build a parser that parses the HTML and looks for repeating elements like "div class=comment". But that will be mostly a manual labour for each different blogs.
Some blogs may have better ways like a comment count somewhere in the HTML or some interface, but i'm not aware of any standardized way.
EDIT: If you got a Comment-RSS feed, you
may
have luck using a mechanism that counts XML nodes, like XPath's
Count
.


Question:
What is a magic number?

Why should it be avoided?

Are there cases where it's appropriate?

Answer:
A magic number is a sequence of characters at the start of a file format, or protocol exchange.  This number serves as a sanity check.
Example:
Open up any GIF file, you will see at the very start: GIF89.  "GIF89" being the magic number.
Other programs can read the first few characters of a file and properly identify GIFs.
The danger is that random binary data can contain these same characters.  But it is very unlikely.
As for protocol exchange, you can use it to quickly identify that the current 'message' that is being passed to you is corrupted or not valid.
Magic numbers are still useful.


Question:
I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86.

I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers.

What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker.

Answer:
You can override the path by setting the environmental variable LD_LIBRARY_PATH.  However I would suggest changing the system paths as well so you don't have to change the library path for all users.  This can be done using crel.
```
```
crle -l -c /var/ld/ld.config -l /usr/lib:/usr/local/lib:/opt/gnu/lib
```
```
For the includes just add -I/opt/gnu/include to your CFLAGS variable.


Question:
We have an SEO team at my office, and one of their dictums is that having lots of <script> blocks inline with the HTML is apocalypticly bad. As a developer that makes no sense to me at all. Surely the Google search engineers, who are the smartest people on the planet, know how to skip over such blocks?

My gut instinct is that minimizing script blocks is a superstition that comes from the early ages of search engine optimizations, and that in today's world it means nothing. Does anyone have any insight on this?

per our SEO guru, script blocks (especially those that are in-line, or occur before actual content) are very, very bad, and make the google bots give up before processing your actual content. Seems like bull to me, but I'd like to see what others say.

Answer:
I don't know about the SEO aspect of this (because I never can tell the mambo jambo from the real deal). But as Douglas Crockford pointed out in one of his javascript webcasts the browser always stops for parsing the script, at each  element. So, if possible, I'd rather deliver the whole document and enhance the page as late as possible with scripts anyway.
Something like
```
<head>
    --stylesheets--
</head>
<body>
  Lorem ipsum dolor
  ...
  ...
  <script src="theFancyStuff.js"></script>
</body>
```


Question: Is it possible for UDP data to come to you corrupted? I know it is possible for it to be lost.

Answer:
Possible? Absolutely. Undetected?
Unlikely
, since UDP employs a checksum that would require multiple-bit errors to appear valid. If an error is detected, the system will likely drop the packet - such are the risks of using UDP.


Question: For general protocol message exchange, which can tolerate some packet loss.  How much more efficient is UDP over TCP?

Answer:
UDP is slightly quicker in my experience, but not by much. The choice shouldn't be made on performance but on the message content and compression techniques.
If it's a protocol with message
exchange
, I'd suggest that the very slight performance hit you take with TCP is more than worth it. You're given a connection between two end points that will give you everything you need. Don't try and manufacture your own reliable two-way protocol on top of UDP unless you're really, really confident in what you're undertaking.


Question:
I'm interested in finding good icons/images that can be used in both 'free' and proprietary programs.

Please include a description of any license restrictions associated with the source of the icons you suggest.

Answer:
I use two search engines:
IconFinder
and
IconLook
.
If you can't find what you want, this
blog post
has a list of great resources.


Question:
I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of .h files, but I'm not sure what their function is (or why having 2 files is better than 1).

What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file?

This question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every .h file has a corresponding .c file?

Answer:
Try to make each .c focus on a particular area of functionality. Use the corresponding .h file to declare those functions.
Each .h file should have a 'header' guard around it's content. For example:
```
```
#ifndef ACCOUNTS_H
#define ACCOUNTS_H
....
#endif
```
```
That way you can include "accounts.h" as many times as you want, and the first time it's seen in a particular compilation unit will be the only one that actually pulls in its content.