q:
Here is a simple scenario with table characters:

CharacterName GameTime Gold Live
Foo 10 100 3
Foo 20 100 2
Foo 30 95 2

How do I get this output for the query SELECT Gold, Live FROM characters WHERE name = 'Foo' ORDER BY GameTime:

Gold Live
100 3
0 -1
-5 0

using MySQL stored procedure (or query) if it's even possible? I thought of using 2 arrays like how one would normally do in a server-side language, but MySQL doesn't have array types.

While I'm aware it's probably easier to do in PHP (my server-side langauge), I want to know if it's possible to do in MySQL, just as a learning material.

[A]
Do you have an ID on your Table.
```
```
GameID      CharacterName GameTime    Gold        Live
----------- ------------- ----------- ----------- -----------
1           Foo           10          100         3
2           Foo           20          100         2
3           Foo           30          95          2
```
```
If so you could do a staggered join onto itself
```
```
SELECT
    c.CharacterName,
    CASE WHEN c_offset.Gold IS NOT NULL THEN c.Gold - c_offset.Gold ELSE c.Gold END AS Gold,
    CASE WHEN c_offset.Live IS NOT NULL THEN c.Live - c_offset.Live ELSE c.Live END AS Live
FROM Characters c
    LEFT OUTER JOIN Characters c_offset
        ON c.GameID - 1 = c_offSet.GameID
ORDER BY
    c.GameTime
```
```
Essentially it joins each game row to the previous game row and does a diff between the values. That returns the following for me.
```
```
CharacterName Gold        Live
------------- ----------- -----------
Foo           100         3
Foo           0           -1
Foo           -5          0
```
```


q:
What's your opinion for the best possible way to build asp.net multilingual localized web application (only UI localization of string resources). Especially this two things:

How to store resources? Xml files, resx files or something else?

How to handle URL's? I don't want to keep language parameter in query string all the time so I need to use URL rewriting maybe?

/BR

[A]
Have you looked into the localization support in ASP.NET?  It uses resource assemblies and sets the default resource based on the browser's settings.  You can also override the setting by setting the culture and uiculture settings for the thread handling the request.
If you don't like using the resource assemblies (which do require a project rebuild when you want to make changes), you can also create a custom resource provider for ASP.NET (
this link
uses MS Access as an example, you can try to customize it for SQL or some other provider).
http://asp.net
has some tutorials to get you started, like
this one
.

s: huggingface

c: devops

d: intermediate


q:
I am writing a quick application myself - first project, however I am trying to find the VBA code for writing the result of an input string to a named cell in Excel.

For example, a input box asks the question "Which job number would you like to add to the list?"... the user would then enter a reference number such as "FX1234356".  The macro then needs to write that information into a cell, which I can then use to finish the macro (basically a search in some data).

[A]
You can use the Range object in VBA to set the value of a named cell, just like any other cell.
```
```
Range("C1").Value = Inputbox("Which job number would you like to add to the list?)
```
```
Where "C1" is the name of the cell you want to update.
My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.


q:
I'm relatively new to jQuery, but so far what I've seen I like. What I want is for a div (or any element) to be across the top of the page as if "position: fixed" worked in every browser.

I do not want something complicated. I do not want giant CSS hacks. I would prefer if just using jQuery (version 1.2.6) is good enough, but if I need jQuery-UI-core, then that's fine too.

I've tried $("#topBar").scrollFollow(); <-- but that goes slow... I want something to appear really fixed.

[A]
Using this HTML:
```
```

This stays at the top

```
```
This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.
```
```
$(window).scroll(function() {
    $('#myElement').css('top', $(this).scrollTop() + "px");
});
```
```
As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's
debounce/throttle
plugin to reduce overhead.


q:
in C++ I have two chars holding hex values e.g.:

char t = 0x4;
char q = 0x4;

How would i compare if the two values held in the char are the same?? I tried

if (t == q) // should give me true

but no, any help, thanks!

[A]
Ah, I found the solution:
```
```
if (t & q)
```
```


q:
Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class?

Here's a simple example of what I would want to write:

template<class T>
std::string optionalToString(T* obj)
{
    if (FUNCTION_EXISTS(T->toString))
        return obj->toString();
    else
        return "toString not defined";
}

So, if class T has toString() defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.

[A]
This is what type traits are there for. Unfortunately, they have to be defined manually. In your case, imagine the following:
```
```
template <typename T>
struct response_trait {
    static bool const has_tostring = false;
};

template <>
struct response_trait<your_type_with_tostring> {
    static bool const has_tostring = true;
}
```
```


q:
I need to add 30 minutes to values in a Oracle date column.  I do this in my SELECT statement by specifying

to_char(date_and_time + (.000694 * 31)

which works fine most of the time.  But not when the time is on the AM/PM border.  For example, adding 30 minutes to 12:30 [which is  PM] returns 1:00 which is AM. The answer I expect is 13:00.  What's the correct way to do this?

[A]
Be sure that Oracle understands that the starting time is PM, and to specify the HH24 format mask for the final output.
```
```
SELECT to_char((to_date('12:40 PM', 'HH:MI AM') + (1/24/60) * 30), 'HH24:MI') as time
  FROM dual

TIME
---------
13:10
```
```
Note: the
```
'AM'
```
in the HH:MI is just the placeholder for the AM/PM meridian indicator. Could be also
```
'PM'
```


q:
If I have a range of say 000080-0007FF
and I want to see if a char containing hex is within that range, how can I do it?

Example

char t = 0xd790;

if (t is within range of 000080-0007FF) // true

[A]
```
```
wchar_t t = 0xd790;

if (t >= 0x80 && t <= 0x7ff) ...
```
```
In C++, characters are interchangeable with integers and you can compare their values directly.
Note that I used
```
wchar_t
```
, because the
```
char
```
data type can only hold values up to 0xFF.


q:
Is there a native c++ variable type that's "bigger" than a double?

float is 7

double is 15  (of course depending on the compiler)

Is there anything bigger that's native, or even non-native?

[A]
C++ has
```
long double
```
, but there is no guarantee that it's any more precise than a plain
```
double
```
. On an x86 platform, usually
```
double
```
is 64 bits, and
```
long double
```
is either 64 or 80 bits (which gives you 19 significant figures, if I remember right).
Your mileage may vary, especially if you're not on x86.


q:
I would like to know if anyone here knows an API where it's possible for me to create a live webcam broadcast from inside my website?

I was checking the uStream API and it seems that you can't create anything, just retrieve data... Does anyone knows anything like this?

Thanks in advance!

[A]
See
Basics of video
at adobe.com


q:
I have a const char arr[] parameter that I am trying to iterate over,

char *ptr;
for (ptr= arr; *ptr!= '\0'; ptr++)
  /* some code*/

I get an error: assignment discards qualifiers from pointer target type

Are const char [] handled differently than non-const?

[A]
Switch the declaration of *ptr to be.
```
```
const char* ptr;
```
```
The problem is you are essentially assigning a const char* to a char*.  This is a violation of const since you're going from a const to a non-const.


q: Is there a UI library to create a message box or input box in python?

[A]
Your best bet is the tkMessageBox module, which should work on all systems (as Python will typically come with Tkinter).
If you can restrict yourself to a specific operating system, better choices might be available.


q: I am trying to load UIImage object from NSData, and the sample code was to NSImage, I guess they should be the same. But just now loading the image, I am wondering what's the best to troubleshoot the UIImage loading NSData issue.

[A]
UIImage has an -
```
initWithData:
```
method. From the docs: "The data in the data parameter must be formatted to match the file format of one of the system’s supported image types."


q:
I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)

Is it good for anything else? Do you use it?

[A]
It is a way to simplify error checking and avoid deep nested if's.  For example:
```
```
do {
  // do something
  if (error) {
    break;
  }
  // do something else
  if (error) {
    break;
  }
  // etc..
} while (0);
```
```


q:
I've been trying to trace down why I have 100% iowait on my box. If I do something like a mysql select query, system goes to 100% iowait (on more than one cpu on my server,) which kills my watchdogs and sometimes kills httpd itself.

In vmstat I see that every 8 seconds or so, there's a 5MB disk write. And that causes at least one cpu (out of 4) to be blocking for one or two seconds.

I have to say that there are a few million files in my ext3 (and I tried ext2, and I have no atime and no journaling enabled.) There is a hardware raid, mirroring two 300GB ides.

I'm missing dtrace. Is there any way to find out what causes these writes? and how do I speed my filesystem up?

Ideas are welcome!

Thank you!

[A]
OK, possible diagnosis steps (for posterity):
Have you confirmed that you're not actually running out of virtual memory and therefore swapping processes out to disk?
If it's not the kernel swapping, you may be able to use
```
strace
```
(as you don't have
```
dtrace
```
) to prove whether it's MySQL doing the writes
Can you please provide more details of the hardware and O/S configuration?


q:
So I have this c# application that needs to ping my web server thats running linux/php stack.

I am having problems with the c# way of base 64 encoding bytes.

my c# code is like:

byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("the string");
String enc = Convert.ToBase64String(encbuff);

and php side:

$data = $_REQUEST['in'];
$raw = base64_decode($data);

with larger strings 100+ chars it fails.
I think this is due to c# adding '+'s in the encoding but not sure.
any clues

[A]
Convert.ToBase64String doesn't seem to add anything extra as far as I can see. For instance:
```
```
byte[] bytes = new byte[1000];
Console.WriteLine(Convert.ToBase64String(bytes));
```
```
The above code prints out a load of AAAAs with == at the end, which is correct.
My guess is that
```
$data
```
on the PHP side doesn't contain what
```
enc
```
did on the C# side - check them against each other.


q:
What's the difference between these two?
Which is better/faster/reliable?

[A]
They are both specifications for plugging a web application into a web server. One glaring difference is that WSGI comes from the Python world, and I believe there are no non-python implementations.
Specifications are generally not comparable based on better/faster/reliable.
Only their implementations are comparable, and I am sure you will find good implementations of both specifications.
Perhaps
read
and
read
.


q:
Within an unordered list:

<li><span></span> The lazy dog.</li>
<li><span>AND</span> The lazy cat.</li>
<li><span>OR</span> The active goldfish.</li>

Adding a class or style attribute is permitted but padding the text and adding or changing tags is not allowed.

The page is rendering with Courier New.

Goal is to have text after span lined up.

    The lazy dog.
AND The lazy cat.
OR  The active goldfish.

Justification of the "OR" is unimportant.

The lazy animal text may be wrapped in an additional element but I'll have to double check.

[A]
```
```
ul {
  list-style-type: none;
  padding-left: 0px;
}

ul li span {
  float: left;
  width: 40px;
}
```
```
```
```

 The lazy dog.

AND The lazy cat.

OR The active goldfish.

```
```
Like Eoin said, you need to put a non-breaking space into your "empty" spans, but you can't assign a width to an inline element, only padding/margin so you'll need to make it float so that you can give it a width.
For a jsfiddle example, see
http://jsfiddle.net/laurensrietveld/JZ2Lg/


q: I understand how the implementation of dynamic binding works and also the difference between static and dynamic binding, I am just having trouble wrapping my brain around the definition of dynamic binding. Basically other than it is a run-time binding type.

[A]
I understand it being evident in polymorphism.  Typically when creating multiple classes that derive from a base class.  If each one of the derived classes contains a function that each one uses.  The base class can be used to execute a function of the derived classs and it will be properly call the correct function.
For example:
```
```
class Animal
{
void talk();
}

class Dog extends Animal
{
public void talk() { System.out.println("woof"); }
}

class Cat extends Animal
{
public void talk() { System.out.println("meow"); }
}

....
Animal zoo[2];
zoo[0] = new Dog();
zoo[1] = new Cat();

for(Animal animalToggle: zoo)
{
animalToggle.talk();
}
```
```
will print:
woof
meow
My interpretation hopefully it helps.


q:
I'd like to develop a few applications for a device I own which has Windows Mobile 2003 on it, but I don't care to hunt down a copy of Visual Studio 2003 to do so. I'd like to know if the Mobile 6 SDK can be used for this purpose.

There's no upgrade path to newer versions of Windows Mobile for this device, and I doubt I'll be getting any newer devices any time soon. Just in case you'd suggest something like that...

[A]
You can create programs for WM2003. As long as you can install the .net cf you will be able to run programs compiled under the compact framework. The list of requirements are:
From
microsoft.com
:
System Requirements
* Supported Operating Systems: Windows CE .NET; Windows Mobile 2003 software for Pocket PCs
* Supported Device Operating Systems: Windows Mobile Software for Pocket PC 2003, Windows Mobile 5.0 for PocketPC and Smartphone, Windows CE .NET 5.0 and higher.


q:
Does anyone know of a simple way for a C++ program to communicate directly with a MySQL database?  I have looked at MySQL++ and found it to be very confusing.  If anyone knows of a very simple way of doing this, please let me know.

Thanks

P.S. I am developing on a Windows machine.  PHP and MySQL web web application setup.  C++ setup to talk to the serial port.  Thus why I need a way for C++ to talk to the MySQL database directly.

[A]
Use the C API:
http://dev.mysql.com/doc/refman/5.0/en/c.html


q:
Im thinking of updating my practices, and looking for a little help and advice!

I do a lot of work on sites that run joomla, oscommerce, drupal etc and so I have created a lot of custom components/plugins and hacks etc. Currently each site has its own folder on my xampp setup.  What I would like to do is have a default setup of (for example) a Joomla setup and when I make changes updates, I can do something which updates all the other folders that contain joomla, almost like an auto update?

Im also looking at using Aptana IDE more and SVN service such as unfuddle to share my work with others, but I have not used SVN before and not sure if its possible to do the above using SVN?

It would be great to be able to work on a main/core item and send the updates to both local updates and to actual servers, without having to maintain lots of different individual sites.

Suggestions?

[A]
Yes, SVN would be a great tool for this purpose. Store your code (eg: a custom Joomla component) in source control. Wherever you want to use that component, just do a
```
checkout
```
or
```
export
```
of that particular folder into your live site. Here's one way you could structure your repository:
```
unfuddle.com/myRepo/trunk/com_myComponent
unfuddle.com/myRepo/trunk/com_anotherComponent
```
Log in to your live server via SSH and run this command:
```
> cd path/to/joomla/components
> svn co http://unfuddle.com/myRepo/trunk/com_myComponent
```
Any time you change your code, commit the changes and then log back into the server and run:
```
> cd path/to/joomla/components
> svn up com_myComponent
```
A real benefit of this is that should you do an update and break something, you can always roll it back to the last known "good" version.
As for automating this process, you might be out of luck if it's on different servers. For multiple deployments on the same server, you could quite easily write a shell script to run the above commands for each site/component. If you needed this to be fully automated, you could even set up a cron job to run this script every day at 2am or something - personally I'd stick with the manual approach, but it's still an option.
For working locally with your SVN repositories, I'd recommend looking at
TortoiseSVN
(if you're on Windows): it's the simplest and easiest way to work with SVN.


q:
As a hobby project I am currently trying to create a small browser-based game - and I thought it would be the "right thing" to code it using the MVC pattern, separating the game's "engine" from presentation. It would be a simple "rpg" game, where the player's character wander the world fighting monsters and gathering items.

My problem is that I got stuck with the engine's structure. In the current design most of the engine is dominated by the "player's character" object - there are such things as location, monster or item, but it is a character that does most of the actions: travels, attacks, buys items etc. I know there are probably other ways to design such engine, but somehow I can't figure it out, so I'm asking for some tips or advices here.

Oh, and the server backend will be php+mysql, if that in any way matters.

[A]
"but it is a character that does most of the actions:"
Yes, but...
First, separate the human user ("player") from their character.  The character is not the player.
You have a large number of objects.  Locations, passive things, active things (monsters), and the character.  They all interact with each other.
You have to isolate responsibility completely.  The character doesn't dominate, the character merely participates.
You'll find it more pleasant if you define each possible human-player action as a
Command
.  Each subclass of
Command
can make a change to the state of the model.  Things move, monsters move, the character moves (character, not player.)
Picking something up or laying it down are each a subclass of
Command
that moves a thing from character to location or location to character.  The player issues the command; the command updates the location, item and character.
The Character is passive.  Things are mostly passive.  Locations are mostly passive.  The Command objects have algorithms to update the state and association among all the various things in your model.
If you want to carry this a step further, each
Command
can be a
Memento
with an undo capability as well as a do capability.  Then the history of the game is a history of these
Mementos
.


q:
How can I bring my WPF application to the front of the desktop? So far I've tried:

SwitchToThisWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle, true);

SetWindowPos(new WindowInteropHelper(Application.Current.MainWindow).Handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

SetForegroundWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle);

None of which are doing the job (Marshal.GetLastWin32Error() is saying these operations completed successfully, and the P/Invoke attributes for each definition do have SetLastError=true).

If I create a new blank WPF application, and call SwitchToThisWindow with a timer, it works exactly as expected, so I'm not sure why it's not working in my original case.

Edit: I'm doing this in conjunction with a global hotkey.

[A]
Well I figured out a work around. I'm making the call from a keyboard hook used to implement a hotkey. The call works as expected if I put it into a BackgroundWorker with a pause. It's a kludge, but I have no idea why it wasn't working originally.
```
```
void hotkey_execute()
{
    IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
    BackgroundWorker bg = new BackgroundWorker();
    bg.DoWork += new DoWorkEventHandler(delegate
        {
            Thread.Sleep(10);
            SwitchToThisWindow(handle, true);
        });
    bg.RunWorkerAsync();
}
```
```


q:
In my web application, I need to log all the SOAP messages to my SQL 2005 database whenever I make a web service call to my business partners' web service. How do I accomplish that?

Thanks in Advance,

Tony

[A]
You haven't specified what language you are using but assuming C# / .NET you could use
SOAP extensions
to get the SOAP content as a string and then use a simple INSERT to add to an arbitrary DB table.
There are probably far more elegant methods but I've implemented the above and it works fine.
Just remember to have a large column size in the DB table since the SOAP output could potentially be large.
Note: seems to be a bug in stackoverflow - the URL is:
http://msdn.microsoft.com/en-us/library/esw638yk(VS.71).aspx


q:
Having a problem trying to create a function, as part of a BizTalk helper class that returns a value of type (Microsoft.XLANGs.BaseTypes.XLANGMessage). The function code is as follows:

public XLANGMessage UpdateXML (XLANGMessage inputFile)
{
   XmlDocument xDoc = new XmlDocument();
   XLANGMessage outputFile;
   xDoc = (System.Xml.XmlDocument) inputFile[0].RetrieveAs(typeof(System.Xml.XmlDocument));

   // Modify xDoc document code here

   outputFile[0].LoadFrom(xDoc.ToString());
   return outputFile;
}

This code does not build as I receive an error stating "Use of unassigned local variable
'outputFile'. I have tried to initialize the 'outputFile' using the new keyword ( = new ....), but that also results in a build error.

What am I doing wrong?

[A]
In the code you have provided, change the line:
```
```
XLANGMessage outputFile;
```
```
to:
```
```
XLANGMessage outputFile = null;
```
```
and change the
```
TypeOf
```
to
```
typeof
```
You might want to take a look at these two blog articles
here
and
here
that both mention some better ways of doing this including passing classes based on your xsd instead of the XLANGMessage, and using a stream instead of the
```
XMLDocument
```
.
After doing a quick once over with this (because I had a bad feeling) I'm not sure if BizTalk will consume the returned
```
XLANGMessage
```
the way you are trying. It fails with an unconstructed error when I try to use it in my test harness. Later tonight when I have some free time I'll see if there is an easy way to use the
```
XLANGMessage
```
directly in orchestration shapes. Add a comment if you manage to get it working before I update.


q: I have a program that uses save files. It needs to load the newest save file, but fall back on the next newest if that one is unavailable or corrupted. Can I use the windows file creation timestamp to tell the order of when they were created, or is this unreliable? I am asking because the "changed" timestamps seem unreliable. I can embed the creation time/date in the name if I have to, but it would be easier to use the file system dates if possible.

[A]
If you have a directory full of arbitrary and randomly named files and 'time' is the only factor, it may be more pointful to establish a filename that matches the timestamp to eliminate need for using tools to view it.
```
```
2008_12_31_24_60_60_1000
```
```
Would be my recommendation for a flatfile system.
Sometimes if you have a lot of files, you may want to group them, ie:
```
```
2008/
2008/12/
2008/12/31
2008/12/31/00-12/
2008/12/31/13-24/24_60_60_1000
```
```
or something larger
```
```
2008/
2008/12_31/
```
```
etc etc etc.
( Moreover, if you're not embedding the time, what is your other distinguishing characteritics, you cant have a null file name, and creating monotonically increasing sequences is way harder ?  need info )


q: As I don't use vi all that much and certainly not for my primary editor, I can't remember any of the vi commands.  Does anyone have a recommendation for a quick start guide or command summary?

[A]
type
```
vim-tutor
```


q:
I am using Structure map like the MVC storefront by Rob Conery does and I have an AdminController and so to get to it I just type:

website/Admin/action

however if I miss spell the controller name I get the error below:

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: key

There error occurs on this line:

Controller controller = ObjectFactory.GetInstance(controllerType) as Controller;

Does anyone have any ideas on how I can handle this error or not allow it to happen at all and maybe just goto a 404 page??

Cheers in advance

[A]
You have a couple different options (or if you want, two things you can combine for a solution).  To remove some of the potential problems between the chair and address bar you can
implement a SoundEx solution
in C#
using the new routing framework to potentially capture some misspellings and re-route them to the expected URL (and/or add routes for what you believe common misspellings or requests will be).  This, however, isn't a solution that will fully solve the problem so you'll need to
look in to implementing custom error pages
for your application.


q:
I recently switched my hosting provider and due to the time zone that the server is now in, my code has stopped working.

The hosting server reports in Pacific time, However, my code needs to work with GMT as my site is for the UK market. So, all my displays and searches need to be in the format dd/MM/yyyy

How can I account for the difference?

For instance, when I do a DateTime.Parse("03/11/2008") it fail as I assume the 'Parse' is against the servers settings. I also get "String was not recognized as a valid DateTime." throughout my code.

[A]
Try
```
```
DateTime.Parse("28/11/2008", new CultureInfo("en-GB"))
```
```
Have a look at
the overload for DateTime.Parse on MSDN
.
Also, be careful not to confuse time zones (pacific, GMT) with cultures.
Cultures are your actual problem here.


q:
I'm trying to add an header file to dev-C++ but when I compile it it doesn't work.
Here are my exact steps (for my example, I'm trying to get mysql.h to work):

copy "mysql.h" into c:\dev-c++\includes

check that in dev-C++ tools > compiler options > directories > c includes and c++ includes have the path to "c:\dev-c++\includes"

include #include  at the top of my file

compiled

This is what the dev-C++ compiler told me:

13 C:\Documents and Settings\Steve\Desktop\server code\setup1\main.c `mysql' undeclared (first use in this function)

As well as other errors due to not locating the header file

Are the steps I've outlined correct? Or is there something else I need to do to get the header files to compile.

P.S. I tried doing the same with VS2008 (put mysql.h in the vs2008 include folder, etc)
but still have the same error.  I would like to stick with Dev-c++ if possible.

[A]
You didn't say how you included it at the top of your file. This should work if you did
```
```
#include "mysql.h"
```
```
rather than
```
```
#include <mysql>
```
```
which is a mistake that people sometimes make.
EDIT: Perhaps try using relative paths rather than an absolute path (as you seem to be doing) when specifying additional include directories? I don't know if that would make a difference (and I don't have the time to check) but I've always used relative paths and it's always worked for me (it's also good practice anyway). So, instead of
C:\Projects\ProjectName\Include
something like
\Include or ..\Include depending on your project file structure.


q:
I wrote a C++ project in VS2005, and used lots of STL container with its plus-in STL. However, I found STL in VS2005 does not have a hash_map in it, I want to use SGI hash_map. How can I change my project to use SGI STL?

Thanks for Brian's method, it works! And it's simple.

[A]
VS2005 does have a hash_map:
```
```
#include <hash_map>
stdext::hash_map
```
```
If you still want to though you can
download the sgi stl here
.  You should be able to just set the include directory to the sgi location.  It will take precedence over the VC++ global include directories.


q:
Previously, I asked the question.

The problem is the demands of our file structure are very high.

For instance, we're trying to create a container with up to 4500 files and 500mb data.

The file structure of this container consists of

SQLite DB (under 1mb)

Text based xml-like file

Images inside a dynamic folder structure that make up the rest of the 4,500ish files

After the initial creation the images files are read only with the exception of deletion.

The small db is used regularly when the container is accessed.

Tar, Zip and the likes are all too slow (even with 0 compression). Slow is subjective I know, but to untar a container of this size is over 20 seconds.

Any thoughts?

[A]
Working on the assumption that you're only going to need read-only access to the files why not just merge them all together and have a second "index" file (or an index in the header) that tells you the file name, start position and length. All you need to do is seek to the start point and read the correct number of bytes. The method will vary depending on your language but it's pretty straight forward in most of them.
The hardest part then becomes creating your data file + index, and even that is pretty basic!


q:
I want to force Apache to use HTTPS for a particular URL in the following form:

https://www.example.com/signup/*

so

if someone goes to any of the following example URLs directly, Apache will forward the URL over to the HTTPS equivalent site.

e.g.

http://www.example.com/signup  -->  https://www.example.com/signup
http://www.example.com/signup/basic+plan  -->  https://www.example.com/signup/basic+plan
http://www.example.com/signup/premium  -->  https://www.example.com/signup/premium

Anyone know how?

Thanks in advance

[A]
You should take a look at
mod_rewrite
documentation


q: Can you provide examples of applications today that are procedural and maintain a high level of integrity and efficiency? Are there any books, tutorials or links that provide examples of how to successfully build and maintain an imperative system? If you were to give guidance in this area, what tips would you give on how it should be structured? I ask because OOP is often presented as a natural progression of procedural programming, but I have trouble believing that is always the case.

[A]
While I cant point toward any existing system directly, there are massive amounts of legacy enterprise systems written pre-OO COBOL. Many classic 4GL programs are procedural and are aimed at high integrity systems engineering. Some are well written, others not so much.
Books include "COBOL from Micro to Mainframes", "Enterprise COBOL Programming Guide."
Structural tips on good imperative code are similar to OO techniques: name things well, seperate your concerns, dont repeat yourself, single responsibility principle, dont leave broken windows unmended.
In fact I'd simply suggest reading the "Pragmatic Programmer" would give most people the right idea in any paradigm.
As far as a compelling reason for moving to OO for business oriented applications; procedural languages allow for a
transaction script
approach to domain logic, whereas OO languages allow for the
domain model
approach.
Certainly for simple exercises, there is no real need for the use of OO languages, but as soon as complexity rises, the maintainability of OO languages wins over procedural languages low overhead.


q:
I'm using this script to display all the images in a folder, but I can't figure out how to get each image's file name to display underneath it. Any suggestions?

<?php

$dirname = "images";
$images = scandir($dirname);
$ignore = Array(".", "..", "otherfiletoignore");

foreach($images as $curimg){
    if (!in_array($curimg, $ignore)) {
        echo "<img src='images/$curimg' /><br />\n";
    }
}
?>


q: I have seen lots of chat examples in Erlang but what about lists, like a work queue?  If I want to build a work queue system, like a project management system, is it possible to re-order messages in a process mailbox or do I have to use message priorities?  Are there examples of workflow systems built in Erlang?

[A]
You cannot reorder messages in process message queues in Erlang.
You can, however do selective receives in which you can receive the message you deem most important first. It's not entirely the same but works for most purposes.
Here's an example:
```
```
receive
    {important, Msg} ->
        handle(Msg)
after 0 ->
    ok
end,
receive
    OtherMsg ->
        handle(Msg)
end
```
```
It differs from:
```
```
receive
    {important, Msg} ->
        handle(Msg);
    OtherMsg ->
        handle(Msg)
end
```
```
In that it will always scan the whole message queue for
```
{important, Msg}
```
before continuing handling the rest of the messages. It means that those kinds of messages will always be handled before any others, if they exist. This of course comes at some performance cost (it takes more time scanning the whole queue twice).


q:
The activity monitor in sql2k8 allows us to see the most expensive queries. Ok, that's cool, but is there a way I can log this info or get this info via query analyser? I don't really want to have the Sql Management console open and me looking at the activity monitor dashboard.

I want to figure out which queries are poorly written/schema is poorly designed, etc.

Thanks heaps for any help!

[A]
Would the SQL Server Profiler do what you need?  I haven't used 2008 yet so I don't know if the tool is still in there but if it is I believe you can set up a trace to log queries that meet specific criteria (such as those that execute and drive CPU up above a certain threshold).
We've used this on our project and it did a pretty good job of helping us troubleshoot poorly executing queries (though don't leave it on full time, rely on the general Windows Performance Counters for performance health tracking).


q:
I work in a shop that is certified at CMMI level 5.  This certification is important because it gives us access to certain customers and contracts.  I'm looking at how to blend Scrum with CMMI.  I've found some info on mixing Scrum with CMMI-3, but quite a bit of it is "hand wavy" and wouldn't hold up to intense scrutiny.  Specifically, the organizational KPAs seem challenging.

What experiences have you had (good and bad) mixing the two processes?

[A]
Here is an
experience report on the results of introducing Scrum into a CMMI Level 5 environment to replace waterfall projects for large defense and healthcare contracts
(pdf).
Abstract:
Projects combining agile methods with
  CMMI1 are more successful in producing
  higher quality software that more
  effectively meets customer needs at a
  faster pace. Systematic Software
  Engineering works at CMMI level 5 and
  uses Lean Software Development as a
  driver for optimizing software
  processes. Early pilot projects at
  Systematic showed productivity on
  Scrum teams almost twice that of
  traditional teams. Other projects
  demonstrated a story based test driven
  approach to software development
  reduced defects found during final
  test by 40%. We assert that Scrum and
  CMMI together bring a more powerful
  combination of adaptability and
  predictability than either one alone
  and suggest how other companies can
  combine them.
HTH,


q:
Most statistics out there for browser stats show you the resolution of the screen.

Thats fine for Windows where browsers typically open full screen and most people leave it as that. So if the browser stats say 1024x768 you just need to subtract a little width for the browser chrome.

On a Mac however browsers typically dont open full screen.

What kind of width is a mac browser likely to be when it opens as such.

I'm thinking of a width of 960 as recommended by what-is-the-best-absolute-width-for-a-webpage. However I'm wondering if this is equally as good width for a mac?

I'm not sure when Apple last made 1280x768 laptops or screens anyway so its probably a non issue. It just frustrates me a little that most places I find statistics on screen resolution dont show you the actual available width.

[A]
Design away, my friend. The Apple display packs many pixels.
A window
will open to fullscreen
on the Mac, no problem.  It simply conserves space when it can, unlike the PC behavior, which will fill the screen regardless of how much space the site actually needs.
In other words, the case where the Mac doesn't open the window fullscreen is the case where the user has
room to spare
.  So those are cases you don't need to worry about. If a Mac OS browser has to go fullscreen to fit the site, it will.  But when the site is only 960px and the user has a gorgeous
2560x1600 cinema display
, it will stop at 960, enough to eliminate the horizontal scrollbars.
The reason people notice this behavior is because apple displays are often too big, so the fullscreen is often not needed. The
smallest
display Apple ships on any notebook is a roomy
1280x800
.  The smallest iMac is already
1680x1050
. They only get bigger from there.
As far as choosing your dimensions, the normal considerations apply.  Play to your
lowest common denominator
.  Simply know that the screen resolution of even a modest apple display will be on par with the industry standard.  If you're willing to go 990 or 960 for the PC, it will
also be acceptable for the Mac
.
(source:
akamai.net
)
Most of the designers I work with are more concerned with making designs
too narrow
for Apple users.  They design in the 960 pixel realm so that it works for the larger audience, and then they try to find creative ways of showing a little extra love to the owners of that giant cinema display.
Sidenote:
@Taylor Marshall asks a good question: "What if the widths are all set to 100%? How big does [the browser window] get..?"
Without any constraints, Firefox will simply go fullscreen, like the MS Windows behavior.  Safari will expand up to a width of 800px, unless the width is already greater than 800, in which case it maintains that width and only modifies the window height. Of course, if there aren't any hard width values, then the design is a liquid layout, so the concern about designing for a particular width is somewhat altered.  Usually good liquid layouts, despite being displayed correctly at any dimension, are nonetheless designed to be viewed at reasonable window widths.


q:
Before anyone recommends that I do a google search on this, I have. I just need a bit more clarity around what codepages and encodings.

If I use UTF8 encoding, and use an italian code page and then a french code page, does this mean ill get different characters even though the bytes havent changed?

[A]
Joel has a nice summary of this:
http://www.joelonsoftware.com/articles/Unicode.html
And no. if I understand your question correctly it doesn't mean that.
When you're converting UTF-8 to a specific code page, it is possible that only some of the characters are going to be converted. What happens to the ones that don't get converted depends on how you call the conversion. A possible result is that the characters which could not be mapped to the code page would be converted to question mark characters.


q: How can I make the command button in my VC++ 6.0 dialog visible or invisible on load?

[A]
What do you mean by 'commnad button' exactly ?
Anyway, you need to obtain the handle of the button then call ShowWindow function:
```
```
BOOL prevState = ShowWindow( itemHandle, SW_HIDE );
```
```


q:
I am using windsor DI framework in one of my MVC project. The project works fine when I tried to run from Visual Studio 2008.

But when i tried to run the project creating an application in IIS7 then I recieved the following error message:

Looks like you forgot to register the http module
  Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule Add '<add
  name="PerRequestLifestyle"
  type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
  Castle.MicroKernel" />' to the  section on your
  web.config

But this module already exists in the httpmodule section of web.config file.

Does anyone know what I have to do to eliminate this problem.

[A]
Try adding it to the
```
system.webServer
```
section as well?
```
```
<configuration>
    <system.web>
        <httpModules>
            <add name="PerRequestLifestyle" type="..." />
        </httpModules>
    </system.web>
    <system.webServer>
        <modules>
            <add name="PerRequestLifestyle" type="..." />
        </modules>
    </system.webServer>
</configuration>
```
```


q: I've read the description of "functionoids" here. They look like a poor-man's version of Boost::function and Boost::bind. Am I missing something? Is there a good reason to use them if you're already using Boost?

[A]
No.
Alternatively see the FQA answer
here.


q:
I need to create a panel which should be invisible but the components inside it (for example, JTextArea, JButton, etc.) should be visible. When I click on the invisible panel, it should become visible.

I can only use JRE 1.4 and nothing more than that. :(

Any idea how to create such a transparent panel???

[A]
```
JComponent.setOpaque(false)
```
is the way to go.


q:
I recently installed VS 6.0 after installing VS 2008 and overwrite JIT settings .. when i started VS 2008 option dialog .. it said another debugger has taken over VS 2008 debugger and I asked me to reset .. so I did ..

Now everything works fine except javascript debugging. I am unable to debug javascript .. I can set breakpoint .. but in debug mode when I hover the breakpoint it says "The breakpoint will not currently be hit. The document is not loaded" ..

How can I solve this issue? Can I reset JIT Settings?

[A]
It sounds like your script debugging is disabled.  To enable it goto, tools internet options, advanced and make sure disable script debugging is unticked.
What I also found helps is if you put a
"debugger;"
line in your javascript.  Remeber that if you put a debugger statement on the first line in a function it will not attach the debugger, as far as I am aware that is a known bug with the implemention of the javascript debugger engine.
```
```
var myFunction = new function()
{
  debugger;
  alert('This will not properly attach the debugger');
}
```
```
A workaround to that is:
```
```
var myFunctionThatDoesAttachTheDebugger = new function()
{
    var x = 0;
    debugger;
    alert('this should work and attach the debugger');
}
```
```
A very usefull way I have also found, is by opening the website you want to debug, and then simply type the following in the url bar:
```
```
javascript:debugger;
```
```
That will also launch the debugger and give you a opportunity to attach the debugger.
Hope it helps
Rihan Meij


q:
I have some code in .Net to draw some text content using GDI+. I used GraphicsUnit.Point to size the text. It's working wonderfully on-screen, and even if Print it.

I've been asked to make a system that generates a PDF, and I got ComponentOne's PDF control. It has got similar interface to GDI+.

The problem is: Font sizes are not working. If I use GraphicsUnit.Point, the text is much smaller, and I am getting empty space below the text. When I use GraphicsUnit.World, the text is still small, but there's no extra empty space below the text.

I want to understand how to convert GraphicsUnit.World to GraphicsUnit.Point.

All help will be appreciated.

Thanks

[A]
After some Googeling and from what I know from personal experience with GDI+ and String drawing it comes down to DPI (Dots per Inch). Basically the different devices (and as far as GDI+ is concerned, PDF is probably a device) have different DPI values. Displays usually have something like 70 DPI. Printers use 72. I don't know what PDFs use, but it might be 100 (as this is a common value for device independence and would explain the smaller text).
Now, Points are defined as being 72 DPI. This is always true. What GDI+ should do, when drawing to a PDF with a different DPI is, to transform the string drawing accordingly. But this does not always work, especially with text.
The GraphicsUnit.World should (according to some googeling) be device independent and should look the same on all devices.


q:
In excel 2007, I have a formula in a cell like the following:

=COUNTIFS('2008-10-31'!$C:$C;">="&'$A7)

Now I want to make the name of the sheet ('2008-10-31') be dependent on the value of some cell (say A1). Something like:

=COUNTIFS(A1!$C:$C;">="&'$A7) // error

Is there is way to do this? Or do I have to write a VBA-Macro for it?

[A]
You are looking for the INDIRECT worksheet function:
```
```
=INDIRECT("SHEET2!A1")
=COUNTIFS(INDIRECT(A1 & "!$C:$C"); ">=" & $A7)
```
```
The function turns a string into a real cell reference.


q:
I need to get the data of an particular <td>, but I don't have any id or name for that particular <td>. How do you get the contents of that <td>?

For example:

<table>
  <tr><td>name</td><td>praveen</td></tr>
  <tr><td>designation</td><td>software engineer</td></tr>
</table>

Is it possible to get the value "designation" from this table.. I need to extract the word "software engineer" using javascript.

[A]
Something along the line of:
(not tested, just quick code to give an idea)
```
```
var tables = document.getElementById('TABLE'); // instead of document.all.tag
var rows;
var cells;
var maxCells = 1;
var designation;
if (tables) {
    for (var t=0; t<tables.length; t++) {
        rows = tables[t].all.tags('TR');
        if (tables[t].all.tags('TABLE').length == 0) {
            for (var r=0; r<rows.length; r++) {
                if (rows[r].innerText != '') {
                    cells = rows[r].all.tags('TD');
                    for (var c=0; c<cells.length; c++) {
                        if (cells[c].innerText == 'designation' && c<(cells.length-1)) {
                            designation = cells[c+1].innerText;
                        }
                    }
                }
            }
        }
    }
}
```
```
Since document.all is IE specific, you should rather user getElementById, with the following to
redefine that function for IE
:
```
```
if (/msie/i.test (navigator.userAgent)) //only override IE
{
    document.nativeGetElementById = document.getElementById;
    document.getElementById = function(id)
    {
        var elem = document.nativeGetElementById(id);
        if(elem)
        {
            //make sure that it is a valid match on id
            if(elem.attributes['id'].value == id)
            {
                return elem;
            }
            else
            {
                //otherwise find the correct element
                for(var i=1;i<document.all[id].length;i++)
                {
                    if(document.all[id][i].attributes['id'].value == id)
                    {
                        return document.all[id][i];
                    }
                }
            }
        }
        return null;
    };
}
```
```


q:
This is javascript, but a virtually identical regex is failing in PHP too, so I don't think it's language specific

var r = new RegExp(
    "^(:19|20)?[0-9][0-9]"            // optional 19/20 start followed by 2 numbers
    + "-"                             // a hyphen
    + "(:0?[1-9]|1[0-2])"             // optional 0 followed by 1-9, or 10, 11, 12
    + "-"                             // a hyphen
    + "(:3[01]|[12][0-9]|0?[1-9])$"   // you get the idea.
);
r.test("2008-07-01");                // == false

What on earth am I missing?

[A]
I think your non-capturing blocks should be e.g.
```
(?:19|20)
```
rather than
```
(:19|20)
```


q:
I have a web page where the user select a Company and with that I keep the Company name in memory though a Session but when I go to the next page the Session only last like 5 minutes?
Any reason why and how I can fix this, I did extend the Session state in the Web.config but that did not work.

Example: Session("CompanyName") = "Bytes Technology"

In my web.config I have:
timeout="40" />

I move from Default.aspx to CompanyDetail.aspx with my Session("CompanyName")

But if I let the program idle in CompanyDetail.aspx I lose the Session State.

Any ideas?

Regards
Etienne

[A]
some questions:
the timeout time is always the same? 5 minutes?
is your site running in a load-balancing server farm? with more than one front-end server?
what are you telling in your web.confing regarding sessions and sessionstate?


q:
What is the proper way to terminate a Swing application from the code, and what are the pitfalls?

I'd tried to close my application automatically after a timer fires. But just calling dispose() on the JFrame didn't do the trick - the window vanished but the application did not terminate. However when closing the window with the close button, the application does terminate. What should I do?

[A]
Try:
```
```
System.exit(0);
```
```
Crude, but effective.


q:
I have signed numbers (2s complement) stored in 32-bit integers, and I want to extract 16-bit fields from them. Is it true that if I extract the low 16 bits from a 32-bit signed number, the result will be correct as long as the original (32-bit) number fits into 16 bits ?

For positive numbers it is trivially true, and it seems that for negatives as well. But can it be proven ?

Thanks in advance

[A]
Yes, in two's complement the sign bits extend "all the way" to the left. When you cast a signed short to a signed int then the number is
"sign extended"
and has the same value.
Example:
```
Nibble
```
```
(-2) = 1110 => Byte(-2) = 1111_1110
```
Obviously the opposite it true too, if you capture at least one sign bit then the value of the number remains unchanged.


q:
I'm doing some FK analysis of our tables by making a directed
graph representing FK dependencies and then traversing the
graph.  In my code, I name everything using directed graph
terminology, but I'd like to have something a bit more
"user friendly" in the report.

In this scenario:

create table t1(a varchar2(20));
alter table t1 add constraint t1_fk foreign key(a) references t2(b);

t1.a must exist in t2.b.  So, what words should I use in the blanks?

t1 is the _______ of t2.
t2 is the _______ of t1.

Many TIA!

[A]
I'd say (things between brackets are optional, but I'd use them)
```
[Column a of] table t1 references [column b of] table t2
```
and
```
[Column b of] table t2 is referenced by [column a of] table t1
```
?
I'd also specify the action that happens on delete/update if any.
```
Column b of table t2 is referenced by column a of table t1.
Deleting a record in table t2 will delete matching records on table t1
```


q:
I found a clear squared bug on IE7/8, which appears via automation (still looking for a workaround, btw).

So, I tried with no luck to find a way to log this bug. Tried the forum way, but it seems this site is somehow not so active these days.

I even tried to mail Chris Wilson, but honestly, I don't put so much hope in this attempt ;o)

So, do anyone know a way to log a bug on IE?

Thanks,
Vincent

[A]
According to
http://blogs.msdn.com/ie/archive/2008/07/30/wanted-ie8-beta-testers.aspx
:
Currently the only way to directly
  file a bug with the IE Team is to be a
  part of the IE8 Technical Beta program
  on
Microsoft Connect
.
However, that post also said:
If you wish to be a part of making IE
  better by contributing great bug
  reports then please email us at
  IESO@microsoft.com and tell us a
  little about yourself including why
  you’d be a great beta tester.
Maybe emailing Chris Wilson was a good idea!


q:
Since version 1.5 Subversion supports to have a local caching-proxy for the main Master-repository.

I got the slave synced and the master replaying the commits to the slave.
Everything works fine so far, but now I am wondering how to do the authentication (working with this guide).

When both, the master and the slave, have authentication set, the slave asks for username/password on reads, but both ask on writes.

What is the way to also get authentication transparent to the user of the slave (meaning requiring only 1 authentication independent if it is read or write)?

I am testing with:

Apache/2.2.3, Subversion 1.4.2 on the slave (Debian)

Apache/2.2.8, Subversion 1.5.1 (Ubuntu)

[A]
Remembering the password must surely be up to the svn client you're using, why would it ask you again if you told it to remember it?
Also you might want to read up on apache, specifically the Require directive, which controls HTTP authentication:
http://httpd.apache.org/docs/2.2/mod/core.html#require
Usually
```
Require valid-user
```
is used


q:
In MSBuild, I would like to call a task that extracts all the files in all the project in a specific solution and hold these files in a property that can be passed around to other tasks (for processing etc.)

I was thinking something along the lines of:

<ParseSolutionFile SolutionFile="$(TheSolutionFile)">
  <Output TaskParameter="FilesFound" ItemName="AllFilesInSolution"/>
</ParseSolutionFile>

<Message Text="Found $(AllFilesInSolution)" />

which would output the list of all files in the projects in the solution and I could use the AllFilesInSolution property as input to other analysis tasks. Is this an already existing task or do I need to build it myself? If I need to build it myself, should the task output an array of strings or of ITaskItems or something else?

[A]
I don't know about tasks, but there are already properties that hold all items. Just look in your typical project file and you'll see which collection they're being added to.
Note the properties
Content
,
Compile
,
Folder
... any time you add a file to a project, it gets put in one of the main collections like this:
```
```
<ItemGroup>
  <Content Include="Default.aspx" />
  <Content Include="Web.config" />
</ItemGroup>
<ItemGroup>
  <Compile Include="Default.aspx.cs">
    <SubType>ASPXCodeBehind</SubType>
    <DependentUpon>Default.aspx</DependentUpon>
  </Compile>
  <Compile Include="Default.aspx.designer.cs">
    <DependentUpon>Default.aspx</DependentUpon>
  </Compile>
</ItemGroup>
<ItemGroup>
  <Folder Include="App_Data\" />
</ItemGroup>
```
```
Then you can do stuff like this to put the values from existing properties into your properties (the Condition attribute acts as a filter):
```
```
<CreateItem Include="@(Content)" Condition="'%(Extension)' == '.aspx'">
    <Output TaskParameter="Include" ItemName="ViewsContent" />
</CreateItem>
```
```
Or you can do it manually (the Include attribute uses the existing property OutputPath, but it indicates a path that inclues all files):
```
```
<CreateItem Include="$(OutputPath)\**\*">
  <Output TaskParameter="Include" ItemName="OutputFiles" />
</CreateItem>
```
```
There are more details in the MSDN MSBuild documentation that I read when I was mucking with custom build tasks and stuff that was very helpful. Go read up on the CreateItem task and you'll be able to make more sense out of what I posted here. It's really easy to pick up on.


q:
I have been bitten by something unexpected recently. I wanted to make something like that:

try :
     thing.merge(iterable) # this is an iterable so I add it to the list
except TypeError :
     thing.append(iterable) # this is not iterable, so I add it

Well, It was working fine until I passed an object inheriting from Exception which was supposed to be added.

Unfortunetly, an Exception is iterable. The following code does not raise any TypeError:

for x in Exception() :
    print 1

Does anybody know why?

[A]
NOT VALID. Check Brian anwser.
Ok, I just got it :
```
```
for x in Exception("test") :
    print x
   ....:
   ....:
test
```
```
Don't bother ;-)
Anyway, it's good to know.
EDIT : looking to the comments, I feel like adding some explanations.
An exception contains a message you passed to during instantiation :
```
```
raise Exception("test")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: test
```
```
It's fair to say that the message is what defines the Exception the best, so str() returns it :
```
```
print Exception("test")
test
```
```
Now, it happens that Exceptions are implicitly converted to string when used in something else than an Exception context.
So when I do :
```
```
for x in Exception("test") :
    print x
```
```
I am iterating over the string "test".
And when I do :
```
```
for x in Exception() :
    print x
```
```
I do iterate over an empty string. Tricky. Because when it comes to my issue :
```
```
try :
    thing.merge(ExceptionLikeObject)
except TypeError :
    ...
```
```
This won't raise anything since ExceptionLikeObject is considered as a string.
Well now, we know the HOW, but I still not the WHY. Maybe the built-in Exception inherit from the built-in String ? Because as far as I know :
adding
str
does not make any object iterable.
I bypassed the problem by overloding
iter
, making it raising TypeError !
Not a problem anymore, but still a mystery.


q:
How do I apply 'use base' in Perl to inherit subs from some base module?

I'm used to C++ inheritance mechanics, and all the sites I googled for this caused more confusion then help. I want to do something like the following:

#! /usr/bin/perl
#The base class to inherit from
use strict;
use warnings;

package 'TestBase';

#-------------------------------
sub tbSub
{
    my ($self, $parm) = @_;
    print "\nTestBase: $parm\n";
}

1;

.

#! /usr/bin/perl
#The descendent class
use strict;
use warnings;

use base qw(TestBase);
sub main;
sub mySub;

#-------------------------------
#Entry point...
main();

#---code------------------------
sub main
{
    mySub(1);
    tbSub(2);
    mySub(3);
}

#-------------------------------
sub mySub
{
    my $parm = shift;
    print "\nTester: $parm\n";
}

Perl complains/cannot find tbSub.

[A]
Perl's inheritance inherits
methods
, not functions. That means you will have to call
```
```
main->tbSub(2);
```
```
However, what you really want is to inherit the method into a proper class:
```
```
package Derived;
use base "TestBase";

package main;
Derived->somemethod("foo");
```
```
Calling methods in the current package as functions won't pass in the $self or "this" object nor the class name magically. Internally,
```
```
Class->somemethod("foo")
```
```
essentially ends up being called as
```
```
Class::somemethod("Class", "foo")
```
```
internally. Of course, this assumes Class has a subroutine/method named "somemethod". If not, the superclasses of Class will be checked and if those don't have a method "somemethod" either, you'll get a fatal error. (Same logic applies for $obj->method("foo").)


q: Is there any way of using Memcached for fragment caching in Rails?

[A]
You can set the fragment_cache_store in your environment.rb
```
```
ActionController::Base.cache_store = ActiveSupport::Cache::MemCacheStore.new()
```
```
http://api.rubyonrails.org/classes/ActionController/Caching.html#M000628


q:
Heres the link:

DAMNIE6TOHELL

As you can see if viewed in glorious 'IE6-o-color', the footer is shifting 1px over to the left.
I'm struggling to find a fix for this, I've whittled it down to a bare minimum of HTML.

Is it something to do with haslayout perhaps? Any help much appreciated.

[A]
Add
```
```
background-position: 50% top;
```
```
to the css of container_bottom.
It works for me with IE Developer toolbar, but it's on a IE6 Virtual machine, so I'm not sure about real world results


q:
I'm trying to run a command-line process (which is extraction of a .7z archive) on a file that lies in a temporary folder on the windows user temp directory
(C:\Documents and Settings\User\Local Settings\Temp), using Process in my c# app.

I think the process return error that happens because of "access denied" because I can see a win32Exception with error code 5 when I dig in the prcoess object of .NET.

doing the same on some other location worked fine before, so I guess maybe it's something I'm not supposed to do ? (running a process to use a file on the the %TEMP%)
perhaps I need to pass security somehow?

[A]
Assuming that you are using regular .NET (not CF/Silverlight, etc) Accessing files in the user's temp area is entirely expected. I wonder if the problem isn't more that you've accidentally left the file open after creating it, perhaps by not using a "using" or similar?
I probably wouldn't suggest using environment variables (%TEMP% etc) when shelling out to a separate process; ideally you'd pass the full path to the file (less things to get wrong...), making sure to
quote
any path arguments (in case of space) - i.e. so your args are @"... ""c:\some path\whatever\tmp""..." (if you see what I mean).
Finally, if you are extracting files, you need to think about the existing contents.
```
Path.GetTempFileName()
```
is fine for creating a single file place-holder, but for extracting an archive you probably want to create a directory - guids are handy for this purpoes (while avioding conflicts, and remember to remove it afterwards):
```
```
string dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
```
```


q:
In either a Windows or Mac OS X terminal if you type...

nslookup -type=SRV _xmpp-server._tcp.gmail.com

... (for example) you will receive a bunch of SRV records relating to different google chat servers..

Does anyone have any experience in this area and possibly know how to service this information (hostname, port, weight, priority) using the iPhone SDK? I have experimented with the Bonjour classes, but as yet have had no luck..

Thanks!

[A]
Hmm, looks like I can't run
```
system()
```
on the Simulator or the device. I can run
```
NSTask
```
on the Simulator, but not the iPhone, and
```
NSTask
```
is not part of the
```
Foundation
```
framework.
The
ISC BIND
package has a BSD license. If feasible, perhaps relevant parts of the
```
dig
```
code could be wrapped into the project directly.


q: I'm working through some homework and a question on a previous exam paper asks to name all of the abstract classes in a given UML diagram. Fairly straightforward, I suppose. There are one abstract class and three interfaces. Do these interfaces qualify as abstract classes, in general?

[A]
Yes, an Interface is implicitly Abstract. Look behind the scenes as to the way it is encoded to a
```
.class
```
file.
Semantics are a funny thing though; under exam conditions "abstract class" would have to literally be compiled from a
```
.java
```
source file using
```
abstract class
```
in the Class' declaration.


q:
Currently, I have a UIView subclass that "stamps" a single 2px by 2px CGLayerRef across the screen, up to 160 x 240 times.

I currently animate this by moving the UIView "up" the screen 2 pixels (actually, a UIImageView) and then drawing the next "row".

Would using multiple CALayer layers speed up performance of rendering this animation?

Are there tutorials, sample applications or code snippets for use of CALayer with the iPhone SDK?

The reason I ask is that most of the code snippets I find that demonstrate simple examples of CALayer employ method calls that do not work with the iPhone SDK. I appreciate any advice or pointers.

[A]
What CALayer methods are you seeing that don't work on iPhone? Aside from animation features tied to CoreImage I have not noticed much that is missing. The big thing you are likely to notice is that all views are layer backed (so you do not need to do anything special to use layers, you can just grab a UIView's layer through the layer accessors methos), and the coordinate system has a top left origin.
In any event, generally having more things is slower than having fewer things. If you are just repeating the same pattern over and over again you are likely to find the best performance is implementing a custom UIView/CALayer/UIColor that knows how to draw what you want, rather than placing visually identical layers or views next to each other.
Having said that, generally layers are lighter weight than views, so if you have a lot of separate elements that you need to keep logically separated you will find that moving to layers can be a win over using views.
You might want to look at -[UIColor initWithPatternImage:] depending on exactly what you are trying to do. If you are using this two pixel pattern as a background color you could just make a UIColor that draws it and set the background.


q:
I have a models A and B, that are like this:

class A(models.Model):
  title = models.CharField(max_length=20)
  (...)

class B(models.Model):
  date = models.DateTimeField(auto_now_add=True)
  (...)
  a = models.ForeignKey(A)

Now I have some A and B objects, and I'd like to get a query that selects all A objects that have less then 2 B pointing at them.

A is something like a pool thing, and users (the B) join pool. if there's only 1 or 0 joined, the pool shouldn't be displayed at all.

Is it possible with such model design? Or should I modify that a bit?

[A]
Sounds like a job for
```
extra
```
.
```
```
A.objects.extra(
    select={
        'b_count': 'SELECT COUNT(*) FROM yourapp_b WHERE yourapp_b.a_id = yourapp_a.id',
    },
    where=['b_count < 2']
)
```
```
If the B count is something you often need as a filtering or ordering criterion, or needs to be displayed on list views, you could consider denormalisation by adding a b_count field to your A model and using signals to update it when a B is added or deleted:
```
```
from django.db import connection, transaction
from django.db.models.signals import post_delete, post_save

def update_b_count(instance, **kwargs):
    """
    Updates the B count for the A related to the given B.
    """
    if not kwargs.get('created', True) or kwargs.get('raw', False):
        return
    cursor = connection.cursor()
    cursor.execute(
        'UPDATE yourapp_a SET b_count = ('
            'SELECT COUNT(*) FROM yourapp_b '
            'WHERE yourapp_b.a_id = yourapp_a.id'
        ') '
        'WHERE id = %s', [instance.a_id])
    transaction.commit_unless_managed()

post_save.connect(update_b_count, sender=B)
post_delete.connect(update_b_count, sender=B)
```
```
Another solution would be to manage a status flag on the A object when you're adding or removing a related B.
```
```
B.objects.create(a=some_a)
if some_a.hidden and some_a.b_set.count() > 1:
    A.objects.filter(id=some_a.id).update(hidden=False)

...

some_a = b.a
some_b.delete()
if not some_a.hidden and some_a.b_set.count() < 2:
    A.objects.filter(id=some_a.id).update(hidden=True)
```
```


q:
Is it possible to define a spring-managed EJB3 hibernate listener?

I have this definition in my persistence.xml:

<properties>
    <property name="hibernate.ejb.interceptor"
        value="my.class.HibernateAuditInterceptor" />
    <property name="hibernate.ejb.event.post-update"
        value="my.class.HibernateAuditTrailEventListener" />
</properties>

But I would like to manage HibernateAuditInterceptor and HibernateAuditTrailEventListener with spring, so I can do some bean injection (ex: session-scoped bean) within these classes. Is this possible?

[A]
The problem is that those properties are just strings. Even if you define your SessionFactory as a Spring bean, any properties you pass to it through the hibernateProperties setter are just strings:
```
```
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource"ref="myDataSource"/>
    <property name="mappingResources">
        <list>
            <value>whatever.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <value>
            hibernate.ejb.interceptor= my.class.HibernateAuditInterceptor
        </value>
        <value>
            hibernate.ejb.event.post-update=my.class.HibernateAuditTrailEventListener
        </value>
    </property>
</bean>
```
```
So I don't think you can do that.


q:
I'm trying to find a way to automate some exception logging code to add to the stack information already available.

Is there any way to use reflection to retrieve the values of all variables on the stack (locals and parameters) - I sincerely doubt the names of the variables are available, but in many cases it would be useful to see the values.

[A]
Not really. For this level of digging you'd probably need something like WinDbg.
If a
specific
variable is of interest, you can add it to the exception yourself (although even this introduces issues with duplicate keys, re-entrancy, etc):
```
```
string dir = ...todo...
    try
    {
        // some code
    }
    catch (Exception ex)
    {
        ex.Data.Add("dir", dir);
        throw;
    }
```
```


q: I am very familiar with the Command pattern, but I don't yet understand the difference in theory between a Functor and a command. In particular, I am thinking of Java implementations. Both are basically programming "verbs" represented as objects. However, in the case of functors, as I have seen from some examples anonymous inner class implementations seem common. Can anyone out there clear this up for me nicely?

[A]
From the description of the
Apache Commons Functor
page:
A functor is a function that can be manipulated as an object, or an object representing a single, generic function.
Functors support and encourage a number of powerful programming techniques including:
programming in a functional style
higher order functions
internal iterators
reuse and specialization through composition rather than inheritance and overloading
generic "callback" or "extension point" APIs
generic "filters" or predicate APIs
many "behavioral" design patterns, such as Visitor, Strategy, Chain of Responsibility, etc.


q:
looking for the standard bug-proofed way to convert "long names" such as "C:\Documents and settings" to their equivalent "short names" "C:\DOCUME~1"

I need this to run an external process from withing my C# app. It fails if I feed it with paths in the "long name".

[A]
If you are prepared to start calling out to Windows API functions, then GetShortPathName() and GetLongPathName() provide this functionality.
See
http://csharparticles.blogspot.com/2005/07/long-and-short-file-name-conversion-in.html
```
```
const int MAX_PATH = 255;

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern int GetShortPathName(
        [MarshalAs(UnmanagedType.LPTStr)]
         string path,
        [MarshalAs(UnmanagedType.LPTStr)]
         StringBuilder shortPath,
        int shortPathLength
        );

    private static string GetShortPath(string path) {
        var shortPath = new StringBuilder(MAX_PATH);
        GetShortPathName(path, shortPath, MAX_PATH);
        return shortPath.ToString();
    }
```
```


q:
I have a div container and have defined its style as follows:

div#tbl-container
{
    width: 600px;
    overflow: auto;
    scrollbar-base-color:#ffeaff
}

This gives me both horizontal and vertical scroll bars automatically once I populate my table which is contained by this div.
I just want only horizontal scroll bars to appear automatically. I will modify the height of the table programmatically.

How do I do this?

[A]
CSS3
has the
```
overflow-x
```
property, but I wouldn't expect great support for that. In
CSS2
all you can do is set a general
```
scroll
```
policy and work your
```
widths
```
and
```
heights
```
not to mess them up.


q: How would I specify a color in app.config and then convert that into an actual System.Drawing.Color object at runtime?

[A]
One way would be to specify one of the
KnownColor
values as the config text and then use
Color.FromName
to create the Color object.


q:
I am desiging a new website for my company and I am trying to implement switch navigation which is what I have used on all my sites in the past.

<?php
switch($x) {

default:
include("inc/main.php");
break;

case "products":
include("inc/products.php");
break;

}
?>

For some reason when I go to index.php?x=products nothing happens, it still displays inc/main.php, in other words it hasn't detected the X variable from the URL. Is this something to do with global variables?

[A]
Yes, your PHP configuration has
correctly
got
```
register_globals
```
turned off, because that's incredibly insecure.
Just put:
```
```
$x = $_REQUEST['x']
```
```
at the top of your script.
You can also use
```
$_GET
```
if you specifically only want this to work for the
```
GET
```
HTTP method.  I've seen some people claim that
```
$_REQUEST
```
is somehow insecure, but no evidence to back that up.


q:
Using qsort in C we pass in a comparison function e.g.

int cmp(const void*, const void*);

the protoype of qsort expects a int (* )(const void* , const void*) so we call:

qsort(..., cmp);

but it is equally valid to call:

qsort(..., &cmp);

and this is what we would have to do if we passed in a static member-function in C++. Kernighan & Ritchie (2nd Edition, 5.11 "Pointers To Functions" p119) states that "since [cmp] is known to be a function, the & operator is not necessary, in the same way that it is not needed before an array name."

Does anyone else feel slightly uncomfortable with this (esp. regarding type-safety)?

[A]
Whether you feel uncomfortable or not doesn't change the fact that C is not considered a type-safe language.  Case in point:
```
```
int main()
{
   int integer = 0xFFFFFF;
   void (*functionPointer)() = (void(*)())integer;

   functionPointer();

   return 0;
}
```
```
This is completely valid at compile time, but it is obviously not safe.


q:
I have a large project for which I am attempting to use TDD.
I am using Tut as my test framework, which has its flaws but is sufficient for what I need.

I need to exploit link time test seams, each test must be in its own executable. The project for this executable then launches itself as a post build step.

Unfortunately, this means that my Visual Studio Sln is filling up with tests, which is not scalable and also hides the actual important projects.

Does anyone know of a better way of running these tests?
Is it possible to hide projects from a build and yet still have them build?

[A]
"Is it possible to hide projects from a build and yet still have them build?"
You can make separate solution for test cases.
Then you can set up post build step of your main projects. This post-build should build tests-projects via separate solution and run them. Building test-projects should be done via command line (see e.g.
here
for details).
If you need to link your unit tests with some lib-s from main projects, you can use
```
```
#pragma comment(lib, "libname")
```
```
See
this MSDN page
for details.


q: Does hitting the back button in a web browser cause the session data set in the preceding call to be deleted?

[A]
No, it does not.
Well, if the user arrived to the previous page by POST (as opposed to GET) and reposts the page, the server is going to process the request again. It won't delete the data in the session though. It is possible to achieve this behaviour with some code, but that's not how it works by default.


q: These seem to mean the same thing. But what term is more appropriate in what context?

[A]
```
```
<property attribute="attributeValue">proopertyValue</property>
```
```
would be one way to look at it.
In C#
```
```
[Attribute]
public class Entity
{
    private int Property{get; set;};
```
```


q:
I am trying to migrate a part of an SVN repository using svnadmin dump.

The provided svndumpfilter tool doesn't manage copy/move/rename dependencies from directories not included in the export.

Is there a tool which can manage these dependencies?

[A]
With dependencies you mean those specified by the property svn:external?
If yes, I think you should pass to svndumpfilter also the paths referrend in the property.
For example, if your project is in
```
http://host/project
```
and the svn:external property is set to
```
http://host/dependencies
```
you can do something like
```
```
svndumpfilter include http://host/project http://host/dependencies < total.dump > project.dump
```
```


q:
In any (non-web) .net project, the compiler automatically declares the DEBUG and TRACE constants, so I can use conditional compiling to, for example, handle exceptions differently in debug vs release mode.

For example:

#if DEBUG
    /* re-throw the exception... */
#else
    /* write something in the event log... */
#endif

How do I obtain the same behavior in an ASP.net project?
It looks like the system.web/compilation section in the web.config could be what I need, but how do I check it programmatically?
Or am I better off declaring a DEBUG constant myself and comment it out in release builds?

EDIT: I'm on VS 2008

[A]
Look at
ConfigurationManager.GetSection()
- this should get you most of the way there.. however, I think you're better off just changing between debug and release modes and letting the compiler determine to execute the "#if DEBUG" enclosed statements.
```
```
#if DEBUG
/* re-throw the exception... */
#else
/* write something in the event log... */
#endif
```
```
the above will work just fine, just make sure you have at least two build configurations (right-click the project you're working on and go to "Properties" there's a section in there on Builds) - make sure that one of those builds has the "define DEBUG" checked and the other does not.


q:
Is it possible in Actionscript 3 to create a weak reference to an object, so that it can be garbage collected.

I'm creating some classes to make debugging easier, so I don't want the objects to hang around in memory if they are only referenced here (and of course I don't want to fill the code with callbacks to remove the objects)

[A]
Right now I've made a simple class to  take advantage of the Dictionary weakKeys parameter:
```
```
public class WeakReference
{
    private var dic

    public function WeakReference(object)
    {
        this.dic = new Dictionary(true)
        this.dic[object] = true
    }

    public function get Value()
    {
        for (var object in this.dic)
        {
            return object
        }
        return null
    }
}
```
```


q:
I would like to know what the pros and cons are for using an Anemic Domain Model (see link below).

Fowler Article

[A]
It seems to me that Fowler's main objection is that ADMs are not OO, in the following sense. If one designs a system "from scratch" around passive data structures that are manipulated by other pieces of code, then this certainly smells more like procedural design than object-oriented design.
I suggest that there are at least two forces that can produce this kind of design:
Designers/programmers who still think procedurally being required to work in an object-oriented environment (or assuming that they can...) to produce a
new
system, and
Developers working to put a service-like "face" on a
legacy
system designed in a non-OO fashion (regardless of language).
If, for example, one were building a set of services to expose the functionality of an existing COBOL mainframe application, one might define services and interfaces in terms of a conceptual model that does
not
mirror the internal COBOL data structures. However, if the service maps the new model to the legacy data to use the existing-but-hidden implementation, then the new model might very well be "anemic" in the sense of Fowler's article -- e.g. a set of TransferObject-style definitions and relationships with no real behavior.
This kind of compromise may very well be common for the boundaries at which idealistically-pure OO systems must interact with an existing, non-OO environment.


q: Are there other possibilities besides IIS for hosting web sites and web services based on ASP.NET, which are recommended by Microsoft for small-scale environments?

[A]
Ohad has a tutorial on getting it to run on apache:
asp.net on apache
.  I'm not really sure how well it runs but it works.  I don't think Microsoft recommends anything other than IIS, but why would they.  For most small scale uses a Windows Server will have everything a small site needs already packaged in.  I'm not sure why you need to find alternatives unless you don't have a windows server available, in which case, the apache port should work for you.


q:
I have an SVN repository structure like below. We are using multiple levels under branches for various release maintenance branches, plus a directory for feature branches.

git-svn init seems to work with a single --branches argument, i.e. it seems to expect all of the branches to be in a single location.

trunk
branches
  1.1
    1.2.1
    1.2.2
  1.2
    1.2.1
    1.2.2
    1.2.3
  features
    feature1
    feature2

Any ideas on how to handle this?

Thanks

[A]
Would it be feasible to create a
```
git
```
repo for each of the branch subdirectories?


q: I'm looking for tutorials or walkthroughs for converting DTS packages into the new SSIS 2005. Any one knows.

[A]
Migrating DTS Packages to Integration Services
SQL Server Integration Services provides a robust way to process millions of rows of data. The platform is highly extensible and performs much faster than the previous DTS platform. Migration of old DTS packages can be done two ways: through the built-in Package Migration Wizard, which handles simple package migrations; and through DTS xChange, which handles both simple and complex DTS migrations, while applying best practices to the migrated packages.


q:
Anyone know how to detect if a television is currently connected to a PC in c#?

Cheers

[A]
How is the device attached?
Whenever a device arrival/removal happens, Windows sends a message called WM_DEVICECHANGE to all the applications running currently in the system. But to receive this message our application should handle the "Windows Process function". C# applications will not have default support for this function, but it's possible to add it. You could extend the form class.
The code to do this for a usb mass storage device would be something like:
```
```
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace WindowsApplication
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        [StructLayout(LayoutKind.Sequential)]
            public struct DEV_BROADCAST_VOLUME
        {
            public int dbcv_size;
            public int dbcv_devicetype;
            public int dbcv_reserved;
            public int dbcv_unitmask;
        }

        protected override void WndProc(ref Message m)
        {
            //you may find these definitions in dbt.h and winuser.h
            const int WM_DEVICECHANGE = 0x0219;
            const int DBT_DEVICEARRIVAL = 0x8000;  // system detected a new device
            const int DBT_DEVICEREMOVECOMPLETE = 0x8001;  // system detected a new device
            const int DBT_DEVTYP_VOLUME = 0x00000002;  // logical volume
            switch(m.Msg)
            {
                case WM_DEVICECHANGE:
                switch(m.WParam.ToInt32())
                {
                    case DBT_DEVICEARRIVAL:
                        {
                            int devType = Marshal.ReadInt32(m.LParam,4);
                            if(devType == DBT_DEVTYP_VOLUME)
                            {
                                DEV_BROADCAST_VOLUME vol;
                                vol = (DEV_BROADCAST_VOLUME)
                                    Marshal.PtrToStructure(m.LParam,typeof(DEV_BROADCAST_VOLUME));
                                MessageBox.Show(vol.dbcv_unitmask.ToString("x"));
                            }
                        }
                        break;
                    case DBT_DEVICEREMOVECOMPLETE:
                        MessageBox.Show("Removal");
                        break;
                }

                    break;
            }
            //we detect the media arrival event
            base.WndProc (ref m);

        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {

        }
    }
}
```
```
It might give you an idea how to implement it.


q:
I have a GridView defined like this:

<asp:GridView ID="myGridView" ruant="server">
    <asp:BoundField DataField="myField" />
    <asp:CommandField ShowDeleteButton="true" ShowEditButton="true" />
</asp:GridView>

After I put a row into edit mode with the Edit button, how do I capture the Enter key and trigger the resulting Update on the row? Right now if I hit enter, the page reloads, what was entered into the TextBox is lost, and the row stays in edit mode. I know how to disable the enter key entirely on the form (the current workaround), but I'd like to have it fire the Update command.

[A]
Well, using the knowledge from the question you linked, it's simple:
```
```
string js = "if (event.keyCode == 13) this.form.submit();"
myGridView.Attributes.Add("onkeydown", js);
```
```
As we found out in the comments, this introduces a small problem. The
```
GridView_RowUpdating
```
server event does not fire anymore, but the question author relies on it.
In short - the server event model relies on the form field
```
__EVENTTARGET
```
to be set. This form field is not sent when just calling the
```
form.submit()
```
. A solution would be to "click" the relevant button with JavaScript.
```
```
string js = "if ((event.which && event.which == 13) || "
            + "(event.keyCode && event.keyCode == 13)) "
            + "{document.myForm.Update.click();return false;} "
            + "else return true;";
myGridView.Attributes.Add("onkeydown", js);
```
```
See
"Using the enter key to submit a form"
on AllAsp.net, which covers the issue in more detail.


q:
In GWT, what is the best way to convert a JavaScriptObject overlay type into a JSON string?

I currently have

public final String toJSON() {
    return new JSONObject(this).toString();
}

Which seems to work fine. I would like to know if there are any better approaches.

[A]
I've never actually tried that (only consumed JSON so far, never needed to produce it). This seems to be native browser/javascript functionality.
You
could
write it as:
```
```
public native String toJSON() /*-{
  return this.toString();
}-*/;
```
```
They essentially just do the exact same thing and likely result in identical JavaScript output. The optimizing compiler is really amazing.


q: Is there a possible htaccess directive that can transparently forward request from index.php to index_internal.php if the request is coming from an internal ip range?

[A]
Something like this should do it (obviously change the IP address to match your network):
```
```
RewriteCond %{REMOTE_ADDR} ^192\.168\.
RewriteRule index.php index_internal.php
```
```
If you want an actual header then make it
```
RewriteRule index.php index_internal.php [L,R,QSA]
```


q:
I am using an XmlDocument to parse and manipulate an XHTML string, converting some nodes to non-HTML nodes.

What is the best way to get a list of all nodes with a given class name? Can it be done with XPath?

[A]
With a given class? If it is just the one class, then you should be able to do something like .SelectNodes("//*[@class='foo']"). If it isn't xhtml, then the
HTML Agility Pack
is worth looking at.
At the client, jQuery would be a good option - and supports composite class names.
If you have multiple class names on individual elements, and need to handle it at the server, I expect you might need to find the candidate classes first ("//*[@class!='']), and then loop over them doing a
```
Split()
```
and checking for the class-name in the results; i.e. pull it apart manually.
In LINQ terms, something like:
```
```
var qry = from XmlElement el in d.SelectNodes("//*[@class!='']")
                  let classes = el.GetAttribute("class").Split(new[] {' '},
                          StringSplitOptions.RemoveEmptyEntries)
                  where classes.Contains("foo")
                  select el;
```
```


q:
For a one-shot operation, i need to parse the contents of an XML string and change the numbers of the "ID" field. However, i can not risk changing anything else of the string, eg. whitespace, line feeds, etc. MUST remain as they are!

Since i have made the experience that XmlReader tends to mess whitespace up and may even reformat your XML i don't want to use it (but feel free to convince me otherwise). This also screams for RegEx but ... i'm not good at RegEx, particularly not with the .NET implementation.

Here's a short part of the string, the number of the ID field needs to be updated in some cases. There can be many such VAR entries in the string. So i need to convert each ID to Int32, compare & modify it, then put it back into the string.

<VAR NAME="sf_name" ID="1001210">

I am looking for the simplest (in terms of coding time) and safest way to do this.

[A]
The regex pattern you are looking for is:
```
```
ID="(\d+)"
```
```
Match group 1 would contain the number. Use a
MatchEvaluator Delegate
to replace matches with dynamically calculated replacements.
```
```
Regex r = new Regex("ID=\"(\\d+)\"");
string outputXml = r.Replace(inputXml, new MatchEvaluator(ReplaceFunction));
```
```
where
```
ReplaceFunction
```
is something like this:
```
```
public string ReplaceFunction(Match m)
{
  // do stuff with m.Groups(1);
  return result.ToString();
}
```
```
If you need I can expand the Regex to match more specifically. Currently
all
ID values (that contain numbers only) are replaced. You can also build that bit of "extra intelligence" into the match evaluator function and make it return the match unchanged if you don't want to change it.


q: Which cryptography algorithm is the most secure that ships with .net?

[A]
I'm somewhat partial to
SHA-512
. If 512 is a little excessive, the other members of the SHA-2 family might be helpful -
SHA-256
and
SHA-384
are both in the SHA-2 family. But AviewAnew's suggestion of
AES 256
is good as well.


q:
Apologies if this has been covered frequently, but I was wondering about how other people approach personal task management.

I've read (parts of) GTD, proceeded to get excited, installed a tonne of plug-ins all over the place, then let it all fall by the wayside.  I've used todoist, outlook, google calendar, project. I've tried writing lists in a notepad, in 'notebook', on post-it-notes and in spreadsheets etc.  None of it lasts.

Why is a simple and effective todo application so difficult to find?  Because the application is so frequently used, I find that any small niggles with the application become overly exaggerated after a few days use.

So far, my favourite application is a variation of todo.txt called task

What do you use?

[A]
I think this is almost a duplicate of
How can I apply David Allen’s “Getting Things Done” as a programmer?
See also:
What Can Someone Do to Get Organized Around Here?
Time management tricks, tools & tips
What do you use to keep notes as a developer?


q:
When working with my .Net 2.0 code base ReSharper continually recommends applying the latest c# 3.0 language features, most notably; convert simple properties into auto-implement properties or declaring local variables as var.  Amongst others.

When a new language feature arrives do you go back and religiously apply it across your existing code base or do you leave the code as originally written accepting that if new code is written using new language features there will be inconsistencies across your code?

[A]
If it ain't broke, don't fix it. Of course, if you have confidence in your unit tests, you can give it a whirl, but you shouldn't really go randomly changing code "just because".
Of course - in some cases, simplifying code is a valid reason to make a change - but even something as innocent as switching to an auto-implemented property could break code that makes assumptions and uses reflection to update the fields directly. Or it could break serialization.
Changing to "var" can actually give you a different (more specific) type, which might cause a different method overload to get selected, etc.
So again; it comes down to your confidence in the unit tests.
Other considerations:
does the rest of the team understand the new syntax yet?
does your project need to support C# 2.0 (for example, some open source projects might want to retain compatibility with C# 2.0).
If neither of these are an issue, you should be OK to use the new features in new code... just be a
little
cautious before hitting "update all" on old code...
Here's a trivial example of "var" as a breaking change:
```
```
static void Main() {
        using (TextReader reader = File.OpenText("foo.bar")) { // [HERE]
            Write(reader);
        }
    }
    static void Write(TextReader reader) {
        Console.Write(reader.ReadToEnd());
    }
    static void Write(StreamReader reader) {
        throw new NotImplementedException();
    }
```
```
Now switch to
```
var reader
```
on the line marked
```
[HERE]
```
...


q:
I am using this command:

cut -d: -f2

To sort and reedit text, Is there a more efficient way to do this without using sed or awk?

I would also like to know how I would append a period to the end of each field

At the moment the output is like $x['s'] and I would like it to be $x['s'] .

Just using standard unix tools

edit: I just wanted to know if it was possible without sed or awk, otherwise how would you do it with awk?

[A]
Short answer:
not really
Longer answer:
```
cut
```
is intended for slicing up lines of text, it does that well. If you need a more complicated behavior, you'll  need a text manipulation language. You have rejected the old time answers, so I'll recommend
```
perl
```
.
Any particular reason you don't want to use
```
sed
```
or
```
awk
```
?


q: This is hopefully a simple question: I have an OpenGL texture and would like to be able to change its opacity, how do I do that? The texture already has an alpha channel and blending works fine, but I want to be able to decrease the opacity of the whole texture, to fade it into the background. I have fiddled with glBlendFunc, but with no luck – it seems that I would need something like GL_SRC_ALPHA_MINUS_CONSTANT, which is not available. I am working on iPhone, with OpenGL ES.

[A]
I have no idea about OpenGL ES, but in standard OpenGL you would set the opacity by declaring a colour for the texture before you use it:
```
```
//          R,   G,   B,   A
glColor4f(1.0, 1.0, 1.0, 0.5);
```
```
The example would give you 50% alpha without affecting the colour of your texture. By adjusting the other values you can shift the texture colour too.


q:
I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below:

http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3

How could I slice out:

http://www.domainname.com/page?CONTENT_ITEM_ID=1234

Sometimes there is more than two parameters after the CONTENT_ITEM_ID and the ID is different each time, I am thinking it can be done by finding the first & and then slicing off the chars before that &, not quite sure how to do this tho.

Cheers

[A]
I figured it out below is what I needed to do:
```
```
url = "http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3"
url = url[: url.find("&")]
print url
'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'
```
```


q:
Is there a way in .NET 2.0 (C#) to serialize object like you do using XmlSerializer in a simple / customizable human readable format thats for instance looks like PXLS or JSON?
Also I know that XML is human readable, I'm looking for something with less annoying redundancy, something that you can output to the console as a result for the user.

[A]
The built-in serialization options for .Net are Xml, Xml-Soap, and binary.  Since you've ruled out xml and binary is definitely not human readable, you'll have to roll your own.
When rolling your own, you have a few options:
Add Utility or Extention methods to the class, like AviewAnew suggested
Extend System.Runtime.Serialization.Formatter / Implement System.Runtime.Serialization.IFormatter
Find a generic component online via google that will do what you want.
Note that the 2nd item can be specialized for your specific class (it doesn't have to be able to handle any class, if you don't want it to) and the latter two items are not mutually exclusive.
I have searched for a .Net JSON formatter in the past, and there are definitely multiple options out there.  However, I ended up going a different direction that time.  I just didn't feel very confident in any of them.  Maybe someone else can provide a more specific recommendation.  JSON is becoming big enough that hopefully Microsoft will include "native" support for it in the framework soon.