q:
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.

[A]
(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.


q:
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.

[A]
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

s: huggingface

c: devops

d: intermediate


q: 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?

[A]
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
.


q: 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?

[A]
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);
?>
```
```


q:
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.

[A]
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!


q:
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>

[A]
```
```
public class Animal<SpeciesType,OrderType>
    where SpeciesType : Species
    where OrderType : Order
{
}
```
```


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

[A]
```
```
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.


q:
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))

[A]
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))
```
```


q:
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.

[A]
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.


q: 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?

[A]
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);
```
```


q:
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?

[A]
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


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

[A]
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>.
    //                ^                 ^
```
```


q:
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}';

[A]
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.


q: 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. :)

[A]
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
```
.


q:
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?

[A]
@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.


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

Thanks!

[A]
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.


q: 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?

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


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

[A] 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.


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

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


q:
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?

[A]
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" />
```
```


q:
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);

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


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

[A]
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.


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

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


q: 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?

[A]
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.


q: 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?

[A]
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.


q:
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            '

[A]
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.


q:
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?

[A]
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();
  // ...
}
```
```


q:
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");
}

[A]
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.


q:
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...

[A]
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.


q:
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?

[A]
```
```
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


q:
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

[A]
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


q: 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.

[A]
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.


q: 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?

[A]
```
```
// 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


q:
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?

[A]
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


q:
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.

[A]
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.


q: 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.

[A]
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.


q:
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 :(.

[A]
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
```
```


q:
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

[A]
If you use
named url patterns
you can do the follwing in your template
```
```
{% url create_object %}
```
```


q:
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.

[A]
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).


q:
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?

[A]
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.


q:
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.

[A]
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.


q:
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?

[A]
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


q:
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.

[A]
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.


q:
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?

[A]
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.


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

[A]
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
.


q:
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.

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
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.


q:
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.

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


q: 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?

[A]
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)
```
```


q:
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 ?

[A]
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.


q: Resharper, RefactorPro, etc?

[A]
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.


q:
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.

[A]
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.


q:
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() {}

[A]
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.


q:
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!

[A]
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
```
```


q:
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.

[A]
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


q:
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?

[A]
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.


q:
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?

[A]
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'


q:
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

[A]
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.


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

[A]
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
.


q:
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?

[A]
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."


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

[A]
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


q:
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.

[A] 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.


q:
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?

[A]
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.


q:
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.

[A]
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


q:
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')

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


q:
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?

[A]
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.


q:
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 )

[A]
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"
```


q:
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...

[A]
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.
```
```


q: 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.

[A]
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
.


q:
What is a magic number?

Why should it be avoided?

Are there cases where it's appropriate?

[A]
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.


q:
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.

[A]
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.


q:
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.

[A]
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>
```


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

[A]
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.


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

[A]
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.


q:
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.

[A]
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.


q:
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?

[A]
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.


q: I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?

[A]
From the
Python Enterprise Application Kit community
:
"Eggs are to Pythons as Jars are to Java..."
Python eggs are a way of bundling
  additional information with a Python
  project, that allows the project's
  dependencies to be checked and
  satisfied at runtime, as well as
  allowing projects to provide plugins
  for other projects. There are several
  binary formats that embody eggs, but
  the most common is '.egg' zipfile
  format, because it's a convenient one
  for distributing projects. All of the
  formats support including
  package-specific data, project-wide
  metadata, C extensions, and Python
  code.
The primary benefits of Python Eggs
  are:
They enable tools like the "Easy Install" Python package manager
.egg files are a "zero installation" format for a Python
  package; no build or install step is
  required, just put them on PYTHONPATH
  or sys.path and use them (may require
  the runtime installed if C extensions
  or data files are used)
They can include package metadata, such as the other eggs they depend on
They allow "namespace packages" (packages that just contain other
  packages) to be split into separate
  distributions (e.g. zope.
, twisted.
,
  peak.* packages can be distributed as
  separate eggs, unlike normal packages
  which must always be placed under the
  same parent directory. This allows
  what are now huge monolithic packages
  to be distributed as separate
  components.)
They allow applications or libraries to specify the needed
  version of a library, so that you can
  e.g. require("Twisted-Internet>=2.0")
  before doing an import
  twisted.internet.
They're a great format for distributing extensions or plugins to
  extensible applications and frameworks
  (such as Trac, which uses eggs for
  plugins as of 0.9b1), because the egg
  runtime provides simple APIs to locate
  eggs and find their advertised entry
  points (similar to Eclipse's
  "extension point" concept).
There are also other benefits that may come from having a standardized
  format, similar to the benefits of
  Java's "jar" format.
-Adam


q: How do I set, clear, and toggle a bit?

[A]
Setting a bit
Use the bitwise OR operator (
```
|
```
) to set a bit.
```
```
number |= 1UL << n;
```
```
That will set the
```
n
```
th bit of
```
number
```
.
```
n
```
should be zero, if you want to set the
```
1
```
st bit and so on upto
```
n-1
```
, if you want to set the
```
n
```
th bit.
Use
```
1ULL
```
if
```
number
```
is wider than
```
unsigned long
```
; promotion of
```
1UL << n
```
doesn't happen until after evaluating
```
1UL << n
```
where it's undefined behaviour to shift by more than the width of a
```
long
```
.  The same applies to all the rest of the examples.
Clearing a bit
Use the bitwise AND operator (
```
&
```
) to clear a bit.
```
```
number &= ~(1UL << n);
```
```
That will clear the
```
n
```
th bit of
```
number
```
. You must invert the bit string with the bitwise NOT operator (
```
~
```
), then AND it.
Toggling a bit
The XOR operator (
```
^
```
) can be used to toggle a bit.
```
```
number ^= 1UL << n;
```
```
That will toggle the
```
n
```
th bit of
```
number
```
.
Checking a bit
You didn't ask for this, but I might as well add it.
To check a bit, shift the number n to the right, then bitwise AND it:
```
```
bit = (number >> n) & 1U;
```
```
That will put the value of the
```
n
```
th bit of
```
number
```
into the variable
```
bit
```
.
Changing the
n
th bit to
x
Setting the
```
n
```
th bit to either
```
1
```
or
```
0
```
can be achieved with the following on a 2's complement C++ implementation:
```
```
number ^= (-x ^ number) & (1UL << n);
```
```
Bit
```
n
```
will be set if
```
x
```
is
```
1
```
, and cleared if
```
x
```
is
```
0
```
.  If
```
x
```
has some other value, you get garbage.
```
x = !!x
```
will booleanize it to 0 or 1.
To make this independent of 2's complement negation behaviour (where
```
-1
```
has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.
```
```
number ^= (-(unsigned long)x ^ number) & (1UL << n);
```
```
or
```
```
unsigned long newbit = !!x;    // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);
```
```
It's generally a good idea to use unsigned types for portable bit manipulation.
or
```
```
number = (number & ~(1UL << n)) | (x << n);
```
```
```
(number & ~(1UL << n))
```
will clear the
```
n
```
th bit and
```
(x << n)
```
will set the
```
n
```
th bit to
```
x
```
.
It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like
the community wiki answer further down
) or some sort of encapsulation.


q:
Is there a risk of legal trouble if you include  GPL or LGPL licensed icons in a closed source software?

Would it force it to become open source just to include the icon?

Does it matter if the icon is compiled as a resource?

Are the creative common licensed icons safe to use if you follow the attribution rules specified by the license?

[A]
For GPL, yes. Any GPL Code/Content that's compiled into your Application or the Package will make it GPL. (Edit: What could be safe is if the Icon is a separate file and is used. That could be a grey area, as you are not using GPL Code to access it. But any attempt to embed it will force your program to GPL, it's one of the most restrictive licenses out there)
LGPL is fine: Any modification to LGPL Content has to be released under LGPL, but using the Code/Content is safe.
Addition: Like LGPL, CreativeCommons usually only affects the Content you're using. So if you're using a CC Icon and modify it, you will have to give out the modified item under CreativeCommons, but your Application is not affected. Just mind the "Non-Commercial" Clause if it exists.


q:
What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP

<?php
  $class_name = 'SomeClassName';
  $object = new $class_name;
?>

This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement.

Problems that come immediately to mind are

<s>You lose the ability to pass arguments into a constructor</s> (LIES. Thanks Jeremy)

Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?)

What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?

[A]
It looks you can still pass arguments to the constructor, here's my test code:
```
```
<?php

class Test {
    function __construct($x) {
        echo $x;
    }
}

$class = 'Test';
$object = new $class('test'); // echoes "test"

?>
```
```
That is what you meant, right?
So the only other problem you mentioned and that I can think of is the security of it, but it shouldn't be too difficult to make it secure, and it's obviously a lot more secure than using eval().


q: Can someone explain the mechanics of a jump table and why is would be needed in embedded systems?

[A]
From Wikipedia
:
In computer programming, a branch
  table (sometimes known as a jump
  table) is a term used to describe an
  efficient method of transferring
  program control (branching) to another
  part of a program (or a different
  program that may have been dynamically
  loaded) using a table of branch
  instructions. The branch table
  construction is commonly used when
  programming in assembly language but
  may also be generated by a compiler.
A branch table consists of a serial
  list of unconditional branch
  instructions that is branched into
  using an offset created by multiplying
  a sequential index by the instruction
  length (the number of bytes in memory
  occupied by each branch instruction).
  It makes use of the fact that machine
  code instructions for branching have a
  fixed length and can be executed
  extremely efficiently by most
  hardware, and is most useful when
  dealing with raw data values that may
  be easily converted to sequential
  index values. Given such data, a
  branch table can be extremely
  efficient; it usually consists of the
  following steps: optionally validating
  the input data to ensure it is
  acceptable; transforming the data into
  an offset into the branch table, this
  usually involves multiplying or
  shifting it to take into account the
  instruction length; and branching to
  an address made up of the base of the
  table and the generated offset: this
  often involves an addition of the
  offset onto the program counter
  register.


q: I'm working on a project with a friend that will utilize Hbase to store it's data.  Are there any good query examples?  I seem to be writing a ton of Java code to iterate through lists of RowResult's when, in SQL land, I could write a simple query.  Am I missing something?  Or is Hbase missing something?

[A]
I think you, like many of us, are making the mistake of treating bigtable and HBase like just another RDBMS when it's actually a column-oriented storage model meant for efficiently storing and retrieving large sets of sparse data. This means storing, ideally, many-to-one relationships within a single row, for example. Your queries should return very few rows but contain (potentially) many datapoints.
Perhaps if you told us more about what you were trying to store, we could help you design your schema to match the bigtable/HBase way of doing things.
For a good rundown of what HBase does differently than a "traditional" RDBMS, check out this awesome article:
Matching Impedance: When to use HBase
by Bryan Duxbury.


q:
I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation.

Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point?

const int FIZZ = 6;
for(int x = 0; x < MAXCOUNT; x++)
{
    if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems
}

vs:

The way I am currently doing it:

const int FIZZ = 6;
int fizzcount = 1;
for(int x = 1; x < MAXCOUNT; x++)
{
    if(fizzcount >= FIZZ)
    {
        print("Fizz\n");
        fizzcount = 0;
    }
}

[A]
In the embedded world, the "modulus" operations you need to do are often the ones that break down nicely into bit operations that you can do with
```
&
```
,
```
|
```
and sometimes
```
>>
```
.


q: I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a List<string>.

[A]
Iterate through and for each element make the probability of selection = (number needed)/(number left)
So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often you'll have all of them before that.
This technique is called
selection sampling
, a special case of
Reservoir Sampling
. It's similar in performance to shuffling the input, but of course allows the sample to be generated without modifying the original data.


q:
I'm using an Ubuntu 8.04 (x86_64) machine to connect to my employer's Cisco VPN. (The client didn't compile out of the box, but I found patches to update the client to compile on kernels released in the last two years.) This all works great, until my DHCP client decides to renew its lease and updates /etc/resolv.conf, replacing the VPN-specific name servers with my general network servers.

Is there a good way to prevent my DHCP client from updating /etc/resolv.conf while my VPN is active?

[A]
If you are running without NetworkManager handling the connections, use the resolvconf package to act as an intermediary to programs tweaking /etc/resolv.conf:
```
sudo apt-get install resolvconf
```
If you are using NetworkManager it will handle this for you, so get rid of the resolvconf package:
```
sudo apt-get remove resolvconf
```
I found out about this when setting up vpnc on Ubuntu last week. A search for
```
vpn resolv.conf
```
on ubuntuforums.org has 250 results, many of which are very related!


q: How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?

[A]
First make a string with all your possible characters:
```
```
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
```
```
You could also use
range()
to do this more quickly.
Then, in a loop, choose a random number and use it as the index to the
```
$characters
```
string to get a random character, and append it to your string:
```
```
$string = '';
 $max = strlen($characters) - 1;
 for ($i = 0; $i < $random_string_length; $i++) {
      $string .= $characters[mt_rand(0, $max)];
 }
```
```
```
$random_string_length
```
is the length of the random string.


q: Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter?

[A]
it looks like it's answered in this post:
http://forums.mysql.com/read.php?52,198596,198717#msg-198717
With mysqli PHP API:
Assume sproc myproc( IN i int, OUT j int ):
```
```
$mysqli = new mysqli(  "HOST", "USR", "PWD", "DBNAME" );
$ivalue=1;
$res = $mysqli->multi_query( "CALL myproc($ivalue,@x);SELECT @x" );
if( $res ) {
  $results = 0;
  do {
    if ($result = $mysqli->store_result()) {
      printf( "Result #%u:
", ++$results );
      while( $row = $result->fetch_row() ) {
        foreach( $row as $cell ) echo $cell, " ";
      }
      $result->close();
      if( $mysqli->more_results() ) echo "
";
    }
  } while( $mysqli->next_result() );
}
$mysqli->close();
```
```


q: Can somebody suggest a good free tool for analyzing .Net memory dumps other than Adplus/windbg/sos ?

[A]
You can
load sos
and your memory dump into Visual Studio to at least insulate you from the 'interesting' ui that WinDbg presents.


q:
I need to automate a process involving a website that is using a login form. I need to capture some data in the pages following the login page.

I know how to screen-scrape normal pages, but not those behind a secure site.

Can this be done with the .NET WebClient class?

How would I automatically login?

How would I keep logged in for the other pages?

[A]
You can easily simulate user input. You can submit form on the web page from you program by sending post\get request to a website.
Typical login form looks like:
```
```
<form name="loginForm" method="post" Action="target_page.html">
   <input type="Text" name="Username">
   <input type="Password" name="Password">
</form>
```
```
You can send a post request to the website providing values for Username & Password fields. What happens after you send your request is largely depends on a website, usually you will be redirected to some page. You authorization info will be stored in the sessions\cookie. So if you scrape client can maintain web session\understands cookies you will be able to access protected pages.
It's not clear from your question what language\framework you're going to use. For example there is a framework for screen scraping (including login functionality) written in perl -
WWW::Mechanize
Note, that you can face some problems if site you're trying to login to uses java scripts or some kind of CAPTCHA.


q:
I want to put songs on a web page and have a little play button, like you can see on Last.fm or Pandora. There can be multiple songs listed on the site, and if you start playing a different song with one already playing, it will pause the first track and begin playing the one you just clicked on. I think they use Flash for this, and I could probably implement it in a few hours, but is there already code I could use for this? Maybe just a flash swf file that you stick hidden on a web page with a basic Javascript API that I can use to stream mp3 files?

Also, what about WMA or AAC files? Is there a universal solution that will play these 3 file types?

http://musicplayer.sourceforge.net/

[A]
There are
many
flash mp3 players that you can use that do this. Usually, you just have to edit a text file to point at the mp3s you want to have available.
Here is the first one that showed up on a google search for
```
flash mp3 player
```
:
http://www.flashmp3player.org/demo.html


q:
I was looking out for a free plugin for developing/debugging JSP pages in eclipse.

Any suggestions?

[A]
The
Eclipse Web Tools Platform Project
includes a JSP debugger. I have only ever needed to use it with Tomcat so I cannot say how well it works with other servlet containers.


q:
In podcast #15, Jeff mentioned he twittered about how to run a regular event in the background as if it was a normal function - unfortunately I can't seem to find that through twitter. Now I need to do a similar thing and are going to throw the question to the masses.

My current plan is when the first user (probably me) enters the site it starts a background thread that waits until the alloted time (hourly on the hour) and then kicks off the event blocking the others (I am a Windows programmer by trade so I think in terms of events and WaitOnMultipleObjects) until it completes.

How did Jeff do it in Asp.Net and is his method applicable to the Java web-app world?

[A]
Jeff's mechanism was to create some sort of cached object which ASP.Net would automatically recreate at some sort of interval - It seemed to be an ASP.Net specific solution, so probably won't help you (or me) much in Java world.
See
https://stackoverflow.fogbugz.com/default.asp?W13117
Atwood: Well, I originally asked on Twitter, because I just wanted something light weight.  I really didn't want to like write a windows service.  I felt like that was out of band code. Plus the code that actually does the work is a web page in fact, because to me that is a logical unit of work on a website is a web page.  So, it really is like we are calling back into the web site, it's just like another request in the website, so I viewed it as something that should stay inline, and the little approach that we came up that was recommended to me on Twitter was to essentially to add something to the application cache with a fixed expiration, then you have a call back so when that expires it calls a certain function which does the work then you add it back in to the cache with the same expiration.  So, it's a little bit, maybe "ghetto" is the right word.
My approach has always been to have to OS (i.e. Cron or the Windows task scheduler) load a specific URL at some interval, and then setup a page at that URL to check it's queue, and perform whatever tasks were required, but I'd be interested to hear if there's a better way.
From the transcript, it looks like FogBugz uses the windows service loading a URL approach also.
Spolsky: So we have this special page called heartbeat.asp.  And that page, whenever you hit it, and anybody can hit it at anytime: doesn't hurt.  But when that page runs it checks a queue of waiting tasks to see if there's anything that needs to be done.  And if there's anything that needs to be done, it does one thing and then looks in that queue again and if there's anything else to be done it returns a plus, and the entire web page that it returns is just a single character with a plus in it.  And if there's nothing else to be done, the queue is now empty, it returns a minus.  So, anybody can call this and hit it as many times, you can load up heartbeat.asp in your web browser you hit Ctrl-R Ctrl-R Ctrl-R Ctrl-R until you start getting minuses instead of pluses.  And when you've done that FogBugz will have completed all of its maintenance work that it needs to do.  So that's the first part, and the second part is a very, very simple Windows service which runs, and its whole job is to call heartbeat.asp and if it gets a plus, call it again soon, and if it gets a minus call it again, but not for a while.  So basically there's this Windows service that's always running, that has a very, very, very simple task of just hitting a URL, and looking to see if it gets a plus or a minus and, and then scheduling when it runs again based on whether it got a plus or a minus.  And obviously you can do any kind of variation you want on this theme, like for example, uh you could actually, instead of returning just a plus or minus you could say "Okay call me back in 60 seconds" or "Call me back right away I have more work to be done."  And that's how it works... so that maintenance service it just runs, you know, it's like, you know, a half page of code that runs that maintenance service, and it never has to change, and it doesn't have any of the logic in there, it just contains the tickling that causes these web pages to get called with a certain guaranteed frequency.  And inside that web page at heartbeat.asp there's code that maintains a queue of tasks that need to be done and looks at how much time has elapsed and does, you know, late-night maintenance and every seven days delete all the older messages that have been marked as spam and all kinds of just maintenance background tasks.  And uh, that's how that does that.


q: Now that I know C++ I want to get into desktop application that have a UI instead of Command Prompt stuff, where should I start?, and what are some good online resources?

[A]
I use
Codegear
's C++ Builder. It's C++ language support is not 100% but it more than makes up for it by having a great two-way RAD IDE and the ability to use a huge library of existing Delphi components.


q:
I would like to know how people implement the following data structures in C# without using the base class library implementations:-

Linked List

Hash Table

Binary Search Tree

Red-Black Tree

B-Tree

Binomial Heap

Fibonacci Heap

and any other fundamental data structures people can think of!

I am curious as I want to improve my understanding of these data structures and it'd be nice to see C# versions rather than the typical C examples out there on the internet!

[A]
There's a series of
MSDN articles
on this subject. However, I haven't really read the text myself. I believe that the collections framework by .NET has a broken interface and cannot be extended very well.
There's also
C5
, a libray that I am investigating right now.
For the reason mentioned above, I've had the project to implement my own collections library for .NET but I've stopped this project after the first benchmark revealed that even a straightforward, non-thread-safe generic
```
Vector
```
implementation is slower than the native
```
List<T>
```
. Since I've taken care not to produce any inefficient IL code, this means that .NET is simply not suited (yet) for writing on-par replacements for intrinsic data structures, and that the .NET framework has to use some behind-the-scenes knowledge to optimize the builtin collection classes.


q:
I'm planning on creating a social networking + MP3 lecture downloading / browsing / commenting / discovery website using Ruby on Rails. Partially for fun and also as a means to learn some Ruby on Rails. I'm looking for a social networking framework that I can use as a basis for my site. I don't want to re-invent the wheel.

Searching the web I found three such frameworks. Which of these three would you recommend using and why?

http://portal.insoshi.com/

http://www.communityengine.org/

http://lovdbyless.com/

[A]
I've not worked with these but am aware of this comparison:
"Unlike Insoshi and Lovd By Less, which
  are full social networking Rails
  applications, Community Engine is a
  plugin that can add social networking
  features to existing Rails
  applications"
from
http://www.rubyinside.com/community-engine-rails-plugin-that-adds-social-networking-to-your-app-901.html


q:
I'm interested in writing eclipse plugins where do I start?

What resources have helped you?

I'm looking for:

  1. Tutorials

  2. Sites devoted to plugin development

  3. Books

[A]
You can find a good step by step detailed tutorial here:
http://www.eclipsepluginsite.com/
Other tutorials:
http://www.ibm.com/developerworks/opensource/library/os-eclipse-snippet/index.html?ca=dgr-lnxw16RichEclipse
http://www.vogella.de/articles/EclipsePlugIn/article.html
A decent book, that I've used is "
Eclipse: Building Commercial-Quality Plug-Ins
".


q: My gcc build toolchain produces a .map file. How do I display the memory map graphically?

[A]
Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the
```
sections
```
and
```
symbols
```
lists).
You can control the script by modifying these lines:
```
```
with open('t.map') as f:
colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']
total_height = 32.0
```
```
map2html.py
```
```
from __future__ import with_statement
import re

class Section:
    def __init__(self, address, size, segment, section):
        self.address = address
        self.size = size
        self.segment = segment
        self.section = section
    def __str__(self):
        return self.section+""

class Symbol:
    def __init__(self, address, size, file, name):
        self.address = address
        self.size = size
        self.file = file
        self.name = name
    def __str__(self):
        return self.name

#===============================
# Load the Sections and Symbols
#
sections = []
symbols = []

with open('t.map') as f:
    in_sections = True
    for line in f:
        m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+((\[[ 0-9]+\])|\w+)\s+(.*?)\s*$', line)
        if m:
            if in_sections:
                sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5)))
            else:
                symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5)))
        else:
            if len(sections) > 0:
                in_sections = False

#===============================
# Gererate the HTML File
#

colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']
total_height = 32.0

segments = set()
for s in sections: segments.add(s.segment)
segment_colors = dict()
i = 0
for s in segments:
    segment_colors[s] = colors[i % len(colors)]
    i += 1

total_size = 0
for s in symbols:
    total_size += s.size

sections.sort(lambda a,b: a.address - b.address)
symbols.sort(lambda a,b: a.address - b.address)

def section_from_address(addr):
    for s in sections:
        if addr >= s.address and addr < (s.address + s.size):
            return s
    return None

print ""
print "  "
print ""
print "
"
for sym in symbols:
    section = section_from_address(sym.address)
    height = (total_height/total_size) * sym.size
    font_size = 1.0 if height > 1.0 else height
    print "
" % \
        (segment_colors[section.segment], height, height, font_size)
    print "%s" % (sym.name, sym.name)
    print "
"
print "
"
print ""
```
```
And here's a bad rendering of the HTML it outputs:


q:
Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set?

For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap?

[A]
About your first question...
List, Map and Set serve different purposes. I suggest reading about the Java Collections Framework at
http://java.sun.com/docs/books/tutorial/collections/interfaces/index.html
.
To be a bit more concrete:
use List if you need an array-like data structure and you need to iterate over the elements
use Map if you need something like a dictionary
use a Set if you only need to decide if something belongs to the set or not.
About your second question...
The main difference between Vector and ArrayList is that the former is synchronized, the latter is not synchronized. You can read more about synchronization in
Java Concurrency in Practice
.
The difference between Hashtable (note that the T is not a capital letter) and HashMap is similiar, the former is synchronized, the latter is not synchronized.
I would say that there are no rule of thumb for preferring one implementation or another, it really depends on your needs.


q:
How do you schedule a Windows Mobile application to periodically start up to perform some background processing.  For example, assume I'm writing an email client and want to check for email every hour, regardless of whether my app is running at the time.

The app is a native C/C++ app on Windows Mobile 5.0 or later.

[A]
the function you need is:
```
CeRunAppAtTime( appname, time )
```
that isn't the exact signature, there is also
```
CeRunAppAtEvent
```
, they should both be in the MSDN docs (but linking is useless the way MSDN urls always change)
The normal way to use these (and
```
RunAppAtTime
```
in the managed world via
```
OpenNETCF.Win32.Notify
```
) is that for periodic execution, every time your app runs, it will rescedule itself for its next run-time.
If your app is running, the new instance should bring up the already running process. If it isn't running, then it is just like starting up normally - from mmory it passes some argument to the process so it can tell it is being scheduled and not started some other way.