q: I'm making a study on refactoring limitations on improving existing software architecture and I would be interested to hear your experiences where you have found refactoring to be not enough or still too immature to accomplish your goals.

[A]
Refactoring can be risky
Refactoring is often difficult because the refactorer often isn't the same person as the original designer. Therefore, he or she doesn't have the same background in the system and the decisions that went behind the original design. You always run the risk that bugs avoided in the original design may creep up in the new design.
This may be especially true when a new or young team member, not fully experienced with this system, decides to inject new-cool-wizbang technology or ideas into an otherwise stable system. Often when the new team members are not integrated well into the team and are not given sufficient guidance, they may begin forcing the project in directions unintended by the whole team.
This is just a risk, however, there's also a chance that the team is wrong and the new team member, if put in charge and was allowed to do his or her thing, would actually make a serious improvement.
These problems often come up amongst a team working on legacy systems. Often there are no world-altering enhancements planned, so the team is conservative with their design. Their goal is to prevent new bugs from being injected and fix old ones with a couple extra features thrown in. A new team member might come along and upset the apple cart by insisting that, he rewrite certain subsystems of the code. New bugs are created and users of a fairly stable product are upset because the software, from there perspective is getting worst.
So if your goal is long-term stability without major functionality changes, often major refactoring is not what you want.
If you have larger functionality changes in the pike however, have a user-base that expects your product to not be fully baked quite yet (ie you're in some sort of beta), then its a much better situation to consider serious refactoring because the long-term benefits of the superior design will pay off and you're less likely to disrupt a large user base.


q:
I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing?

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";

            illegal = illegal.Trim(Path.GetInvalidFileNameChars());
            illegal = illegal.Trim(Path.GetInvalidPathChars());

            Console.WriteLine(illegal);
            Console.ReadLine();
        }
    }
}

[A]
For starters,
Trim only removes characters from the beginning or end of the string
. Secondly, you should evaluate if you really want to remove the offensive characters, or fail fast and let the user know their filename is invalid. My choice is the latter, but my answer should at least show you how to do things the right AND wrong way:
StackOverflow question showing how to check if a given string is a valid file name
. Note you can use the regex from this question to remove characters with a regular expression replacement (if you really need to do this).

s: huggingface

c: devops

d: intermediate


q:
I need to randomly fade my background images in and out.

It will be a timed function, like once every 5 seconds.

I need to do it with ASP.NET, Javascript, CSS or all three.

Please help me out here guys.  Thank you.

[A]
This is the Answer:
never mind guys, after making a bit more exact search on Google.  I found a good solution.
```
```

JS-Examples.com

```
```
Found it here
.


q:
Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used?  The only solution I've found is to create, for example, a class like:

Dictionary<string, List<object>>

But this is quite irritating to actually use.  In Java, I believe a MultiMap accomplishes this, but cannot find an analog in .NET.

[A]
I think something like
```
List<KeyValuePair<object, object>>
```
would do the Job.


q:
In Nant, I would like to be able to extract the last name of the directory in a path.

For example, we have the path 'c:\my_proj\source\test.my_dll\'

I would like to pass in that path and extract 'test.my_dll'

Is there a way to easily do this?

[A]
See the
script
task.  You can write custom code in C# or whatever, and return a value that you can assign to a property.


q:
I need to change the DataTemplate for items in a ListBox depending on whether the item is selected or not (displaying different/more information when selected).

I don't get a GotFocus/LostFocus event on the top-most element in the DataTemplate (a StackPanel) when clicking the ListBox item in question (only through tabbing), and I'm out of ideas.

[A]
The easiest way to do this is to supply a template for the "ItemContainerStyle" and NOT the "ItemTemplate" property. In the code below I create 2 data templates: one for the "unselected" and one for the "selected" states. I then create a template for the "ItemContainerStyle" which is the actual "ListBoxItem" that contains the item. I set the default "ContentTemplate" to the "Unselected" state, and then supply a trigger that swaps out the template when the "IsSelected" property is true. (Note: I am setting the "ItemsSource" property in the code behind to a list of strings for simplicity)
```
```
<Window.Resources>

<DataTemplate x:Key="ItemTemplate">
    <TextBlock Text="{Binding}" Foreground="Red" />
</DataTemplate>

<DataTemplate x:Key="SelectedTemplate">
    <TextBlock Text="{Binding}" Foreground="White" />
</DataTemplate>

<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
    <Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
        </Trigger>
    </Style.Triggers>
</Style>

</Window.Resources>
<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource ContainerStyle}" />
```
```


q:
I have a templated class defined (in part) as

template <class T> MyClass
{
public:
   void DoSomething(){}
};

If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.

My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.

Has anyone any suggestions?

[A]
Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those.
Something like this:
```
```
class Base {
public:
  virtual ~Base(){}
  virtual void DoSomething() = 0;
}

template <class T> class MyClass : public Base {
public:
    void DoSomething(){}
};

std::vector<Base *> objects;
objects.push_back(new MyClass<int>);
objects.push_back(new MyClass<char>);
```
```


q:
With a huge influx of newbies to Xcode, I'm sure there are lots of Xcode tips and tricks to be shared.

What are yours?

[A]
⌘ Command
+
```
Double-Click on a symbol
```
: Jump to Definition of a symbol.
⌥ Option
+
```
Double-Click on a symbol
```
: Find Text in Documentation of a symbol. (Only works if you have they symbol's Doc Set installed.)
Favorites Bar:
Favorites bar is just like you have in Safari for storing - well - favorites. I often use it as a place to store shortcuts (which you can do by drag-dropping) to files I am using right now. Generally this is more useful when I'm working with a large or unfamiliar project.
To show the Favorites Bar, select the following menu option:
```
View
```
>
```
Layout
```
>
```
Show Favorites Bar
```


q:
Are there some principles of organizing classes into namespaces?

For example is it OK if classes from namespace N depends on classes from N.X?
And if classes from N.X depends on classes from N?

[A]
Classes in
```
N.X
```
can rely on classes in
```
N
```
. But classes in
```
N
```
shouldn't rely on classes in
```
N.X
```
; that's bad design.
Some namespace guidelines:
Namespace Naming Guidelines
Names of Namespaces


q:
I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.

So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically?

$database = 'live';
if (some staging environment variable is true) {
    $database = 'testing'; // and not live
}

If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile

Hope this makes sense

many thanks

Ian

[A]
Yep...you can do this:
```
```
SetEnv DATABASE_NAME testing
```
```
and then in PHP:
```
```
$database = $_SERVER["DATABASE_NAME"];
```
```
or
```
```
$database = getenv("DATABASE_NAME");
```
```


q:
I am trying to figure out this:

c = 1
def f(n):
    print c + n
def g(n):
    c = c + n

f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment

Thanks!

[A]
Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the
```
global
```
statement:
```
```
def g(n):
    global c
    c = c + n
```
```
This is one of the quirky areas of Python that has never really sat well with me.


q:
I work for a small web development company (only 2 to 3 developers) that work on a wide range of projects for different customers (everything from CMS's to eCommerce sites).

Usually we work on our own projects but occasionally we need to work together on one. We use subversion as our source control software and sites are developed in .NET using VS 2008 and SQL 2005.

After reading through plenty of posts regarding unit testing and other "enterprise" level coding practices I was wondering what other developers do for small projects that only require minimal maintenance and have short development times?

I am thinking in particular of things like is unit testing necessary, etc.

[A]
Unit testing IS necassary no matter what. If you write code, you unit test. I work by myself alot too. I still test. I dont know how I ever wrote code before it.
Heres the way I look at it. you dont necassarily need the same expensive tools as the big boys, but if you want to be big, you have to think big. Do the same htings, follow the same practices. As your needs grow, get better tools. For example, if you do any UML diagramnming, you porbably dont need any saftware. Just a whiteboard/paper. But still use UML. When your needs grow, you can look at getting special software.
Even project management. You dont necassarily need the expensive tools to track projects, as long as you do it. As your needs grow, you can get specialized softwaare.
In short, do the same things you would do if you were bigger, but you dont necassarily need the same tools. Aquire as needed.
EDIT: I should mention though that some of what you do of course is dependant on your methodolies/processes that you use. For example, do you do agile development? Being small you dont necassarily need to do everything exactly the same. For example, I try to be agile, but I obviously dont pair program :). You just need to learn to adapt them to what works for you.


q: I have just started reading Introduction to 80x86 Assembly Language and Computer Architecture.I am trying to use NASM, to run the first example shown in chapter 3 ,but unsuccessfully.Has anyone read the book,and run the examples?

[A]
According to Google Books, you should be using
MASM
, not NASM. Try that.
For reference guys, page 47
here
.


q:
I'd like to get uniform distribution in range [0.0, 1.0)

If possible, please let the implementation make use of random bytes from /dev/urandom.

It would also be nice if your solution was thread-safe. If you're not sure, please indicate that.

See some solution I thought about after reading other answers.

[A]
```
```
#include <stdlib.h>
printf("%f\n", drand48());
```
```
/dev/random:
```
```
double c;
fd = open("/dev/random", O_RDONLY);
unsigned int a, b;
read(fd, &a, sizeof(a));
read(fd, &b, sizeof(b));
if (a > b)
   c = fabs((double)b / (double)a);
else
    c = fabs((double)a / (double)b);
```
```
c is your random value


q:
I am thinking of changing my web site's homegrown search engine. Before I break out Visual Studio, I wondered if anyone can suggest an alternative that gives me what I need. This being:

Works with an ASP.NET site (is a .NET project)

Creates a file-based index

Fast search across hundreds or thousands of pages

Performs word-stemming to find variations upon words

Gives full control over the output styles

Is cheap (or better still, free!)

[A]
You can't really beat
Google Site Search
for this.  It's fully customizable - and no need for embedding or maintaining.
EDIT: found this
ASP.NET opensource search engine
that you can take and run with, In response to your comment about knowing what google does, this is
well documented and they have TONS of webmaster tools for you
.


q:
In python you can use a tuple in a formatted print statement and the tuple values are used at the indicated positions in the formatted string.  For example:

>>> a = (1,"Hello",7.2)
>>> print "these are the values %d, %s, %f" % a
these are the values 1, Hello, 7.200000

Is there some way to use any array or collection in a java printf statement in a similar way?

I've looked at the documentation and it appears to have built in support for some types like Calendar, but I don't see anything for collections.

If this isn't provided in java, is there any java idiom that would be used in a case like this where you are populating collections and then printing the values from many collections using one format string (other than just nested looping)?

[A]
printf will have a declaration along the lines of:
```
```
public PrintString printf(String format, Object... args);
```
```
... means much the same as
```
[]
```
. The difference is
```
...
```
allows the caller to omit explicitly creating an array. So consider:
```
```
out.printf("%s:%s", a, b);
```
```
That is the equivalent of:
```
```
out.printf("%s:%s", new Object[] { a, b });
```
```
So, getting back to your question, for an array, you can just write:
```
```
out.printf("%s:%s", things);
```
```
For a collection:
```
```
out.printf("%s:%s", things.toArray());
```
```


q:
I can't figure out a use case for being able to annotate interfaces in Java.

Maybe someone could give me an example?

[A]
More an example, but
Local
and
Remote
annotations in EJB3. According to the java doc,
When used on an interface, designates
  that interface as a local business
  interface.
I guess the use case here is that the interface has a special function best denoted by an annotation.


q:
I have a file temp.txt, that I want to sort with the sort command in bash.

I want the sorted results to replace the original file.

This doesn't work for example (I get an empty file):

sortx temp.txt > temp.txt

Can this be done in one line without resorting to copying to temporary files?

EDIT: The -o option is very cool for sort. I used sort in my question as an example. I run into the same problem with other commands:

uniq temp.txt > temp.txt.

Is there a better general solution?

[A]
Read up on the non-interactive editor,
```
ex
```
.


q:
Here's the idea, I'd like to make a service? that will look for a certain program starting up and dissallow it unless certain conditions are met.

Let's say I have a game I want to stop myself from playing during the week. So if I start it up on any day other than Friday/Saturday/Sunday, it will intercept and cancel.  Is this possible with C#?

Main thing I am looking for is how to catch a program starting up, rest should be easy.

[A]
I'm not sure if you can catch it starting up, but you could try to look for the program in the list of windows (was it ENUM_WINDOWS? I can never remember) and shut it down as soon as it shows up.
You could probably even do this in AutoIt!
Drag out the Petzold and have some fun with windows...
EDIT:
Check out sysinternals for source on how to list the active processes - do this in a loop and you can catch your program when it starts. I don't think the official site still has the source though, but it's bound to be out there somewhere...


q:
I've come across this term POD-type a few times.

What does it mean?

[A]
POD
stands for
Plain Old Data
- that is, a class (whether defined with the keyword
```
struct
```
or the keyword
```
class
```
) without constructors, destructors and virtual members functions.
Wikipedia's article on POD
goes into a bit more detail and defines it as:
A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.
Greater detail can be found in
this answer for C++98/03
. C++11 changed the rules surrounding POD, relaxing them greatly, thus
necessitating a follow-up answer here
.


q: Can some one specify the windows API, one need to use in order to be able to change programmatically the screen refresh rate?

[A]
I found this via a google search. Hope it helps some.
http://www.codeproject.com/KB/winsdk/changerefresh.aspx
http://msdn.microsoft.com/en-us/library/ms533260(VS.85).aspx


q:
Say I'm writing some ruby code and I want to use the standard Date type to get the current date. Instead of using a search engine, is there a faster way to find the documentation for this class?  I know I can get the methods for Date by typing Date.methods, but as far as I know this doesn't provide details about argument types or return value.

Editor-specific answers are welcomed.  My editor of choice is Emacs.

[A]
On your console use "ri"
```
```
ri Date
```
```
That works with all classes. (e.g. ri String)
To see documentation for a particular method you use this:
```
```
ri Date#yourMethod
```
```


q: I have a SQL table with news stories and Unix timestamps. I'd like to only keep the 50 newest stories. How would I write an SQL statement to delete any amount of older stories?

[A]
Blockquote
```
```
delete from table where id not in (
    select id from table
    order by id desc
    limit 50
)
```
```
You select the ids of the data you don't want to delete, and the you delete everything NOT IN these value...


q:
I have a couple of header files, which boil down to:

tree.h:

#include "element.h"

typedef struct tree_
{
    struct *tree_ first_child;
    struct *tree_ next_sibling;
    int tag;
    element *obj;
    ....
} tree;

and element.h:

#include "tree.h"

typedef struct element_
{
    tree *tree_parent;
    char *name;
    ...
} element;

The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included.

This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known.

How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)?

[A]
These are known as "once-only headers." See
http://developer.apple.com/DOCUMENTATION/DeveloperTools/gcc-4.0.1/cpp/Once_002dOnly-Headers.html#Once_002dOnly-Headers


q:
Has anyone successfully built an Adobe Air application with Maven?  If so, what are the steps to get it working?

I have been trying to use flex-mojos to build an Air applications.  When I set the packaging type to "aswf", as suggested in the DashboardSamplePom, Maven complains that aswf is an unknown packaging type.  I also found their air-super-pom, but could not figure out how to reference it as the parent of my POM.

[A]
When a plugin declares a new packaging type, like 'aswf', you need to declare it as an extension. In your top-level pom, add the extensions element to the plugin config.
```
```
<plugin>
  <groupId>...</groupId>
  <artifactId>...</artifactId>
  <extensions>true</extensions>
...
</plugin>
```
```


q:
In ruby I am parsing a date in the following format: 24092008.
I want to convert each section (year, month, date) into a number.

I have split them up using a regex which produces three Strings which I am passing into the Integer constructor.

  date =~ /^([\d]{2})([\d]{2})([\d]{4})/
  year = Integer($3)
  month = Integer($2)
  day = Integer($1)

When it hits the month line it crashes as follows:

`Integer': invalid value for Integer: "09" (ArgumentError)

It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07").

Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first?

Thanks.

[A]
I'm not familiar with regexes, so forgive me if this answer's off-base.  I've been assuming that $3, $2, and $1 are strings.  Here's what I did in IRB to replicate the problem:
```
```
irb(main):003:0> Integer("04")
=> 4
irb(main):004:0> Integer("09")
ArgumentError: invalid value for Integer: "09"
    from (irb):4:in `Integer'
    from (irb):4
    from :0
```
```
But it looks like .to_i doesn't have the same issues:
```
```
irb(main):005:0> "04".to_i
=> 4
irb(main):006:0> "09".to_i
=> 9
```
```


q: Puzzled by the Lua 5.0 documentation references to things like _LOADED, LUA_PATH, _ALERT and so on (that I could not use in Lua 5.1), I discovered all of those have been removed and the functionality put elsewhere. Am I right in thinking that the only one global variable left in Lua 5.1 is _VERSION?


q: So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures?

[A]
When you will need a function in the future which performs a task that you have decided upon now.
For example, if you read a config file and one of the parameters tells you that the
```
hash_method
```
for your algorithm is
```
multiply
```
rather than
```
square
```
, you can create a closure that will be used wherever you need to hash something.
The closure can be created in (for example)
```
config_parser()
```
; it creates a function called
```
do_hash_method()
```
using variables local to
```
config_parser()
```
(from the config file). Whenever
```
do_hash_method()
```
is called, it has access to variables in the local scope of
```
config_parser()
```
even though it's not being called in that scope.
A hopefully good hypothetical example:
```
```
function config_parser()
{
    // Do some code here
    // $hash_method is in config_parser() local scope
    $hash_method = 'multiply';

    if ($hashing_enabled)
    {
        function do_hash_method($var)
        {
            // $hash_method is from the parent's local scope
            if ($hash_method == 'multiply')
                return $var * $var;
            else
                return $var ^ $var;
        }
    }
}

function hashme($val)
{
    // do_hash_method still knows about $hash_method
    // even though it's not in the local scope anymore
    $val = do_hash_method($val)
}
```
```


q:
I need to store a list of key value pairs of (integer, boolean) in .NET

When I use a dictionary it re-orders them.  Is there a built in collection that will handle this.

[A]
```
```
List<KeyValuePair<int, bool>> l =
                        new List<KeyValuePair<int, bool>>();
    l.Add(new KeyValuePair<int, bool>(1, false));
```
```


q:
For some reason when I create a new namespace in Visual Studio 2008 its not being recognized. I'm using asp.net mvc, I don't know if that has anything to do with it.

Has anyone come across this before?...and how do you fix it?
Also is there a way to force Visual Studio to maybe re-examine new namespaces?

Answer:
I figured out the problem...check it.

[A]
Questions:
Is the namespace and class thats not being picked up in the same project or is it referenced?
Is this a vb or a c# project? - I cant remember which way round (think its c#) but one of them defaults the root namespace to the project name. You can run into problems or get a confusing namespace e.g MyProject.MyProject if you create one at the same level of the root namespace.
Couple of things to try:
Press ctrl alt b to rebuild the project does it pick up the namespace?
Add a new method to an existing class that is working - is this picked up?
Try creating a completley different namespace is this picked up e.g.
namespace StackOverflow.Test
{
}
Finally have seen studio not pick up new namespaces and methods when its not compiling properly. This can be due to NTFS permissions and read only permissions. Check the build date of the dll. You can also try clearing ASP.net temporary files.


q: What are the best SNMP libraries to use with .NET?  Specifically for listening for traps or sending set or get requests.

[A]
here's a library and a few examples
http://www.c-sharpcorner.com/UploadFile/malcolmcrowe/SnmpLib11232005011613AM/SnmpLib.aspx


q:
Specifically, when you create an interface/implementor pair, and there is no overriding organizational concern (such as the interface should go in a different assembly ie, as recommended by the s# architecture) do you have a default way of organizing them in your namespace/naming scheme?

This is obviously a more opinion based question but I think some people have thought about this more and we can all benefit from their conclusions.

[A]
What I generally do is to create an Interfaces namespace at a high level in my hierarchy and put all interfaces  in there (I do not bother to nest other namespaces in there as I would then end up with many namespaces containing only one interface).
```
```
Interfaces
|--IAnimal
|--IVegetable
|--IMineral
MineralImplementor
Organisms
|--AnimalImplementor
|--VegetableImplementor
```
```
This is just the way that I have done it in the past and I have not had many problems with it, though admittedly it might be confusing to others sitting down with my projects.  I am very curious to see what other people do.


q:
I can't use the Get*Profile functions because I'm using an older version of the Windows CE platform SDK which doesn't have those. It doesn't have to be too general.

[section]
name = some string

I just need to open the file, check for the existence of "section", and the value associated with "name". Standard C++ is preferred.

[A]
I don't think you can un-register a dependency property but you can redefine it by overriding the metadata like this:
```
```
MyDependencyProperty.OverrideMetadata(typeof(MyNewType),
                     new PropertyMetadata());
```
```


q:
I am using virtual machines for development,but each time I need a new VM, I copy the file and create a new server, but I need a new name for the server to add it to our network.

After renaming the server, the Sharepoint sites have many errors and do not run.


q:
I have a project the requires the use of the exec family. My project consist of making an interactive shell. The shell will implement a few basic commands like cd, ls, echo, etc. I have been researching the use of exec, but have not found a useful site. Any suggested links would help.

int ret;
ret = execl ("/bin/ls", "ls", "-1", (char *)0);

How would i get the output of this operation to show on the screen?

[A]
doing
```
```
int fd = 1;
dup(fd);
close(fd);
```
```
gets the output to the screen.


q:
I am a firm believer in the idea that one of the most important things you get from learning a new language is not how to use a new language, but the knowledge of concepts that you get from it. I am not asking how important or useful you think Assembly is, nor do I care if I never use it in any of my real projects.

What I want to know is what concepts of Assembly do you think are most important for any general programmer to know? It doesn't have to be directly related to Assembly - it can also be something that you feel the typical programmer who spends all their time in higher-level languages would not understand or takes for granted, such as the CPU cache.

[A]
Memory, registers, jumps, loops, shifts and the various operations one can perform in assembler.  I don't miss the days of debugging my assembly language class programs - they were painful! - but it certainly gave me a good foundation.
We forget (or never knew, perhaps) that all this fancy-pants stuff that we use today (and that I love!) boils down to all this stuff in the end.
Now, we can certainly have a productive and lucrative career without knowing assembler, but I think these concepts are good to know.


q:
How can I access UserId in ASP.NET Membership without using Membership.GetUser(username) in ASP.NET Web Application Project?

Can UserId be included in Profile namespace next to UserName (System.Web.Profile.ProfileBase)?

[A]
Is your reason for this to save a database call everytime you need the UserId? If so, when I'm using the ASP.NET MembershipProvider, I usually either do a custom provider that allows me to cache that call, or a utility method that I can cache.
If you're thinking of putting it in the Profile, I don't see much reason for doing so, especially as it also will still require a database call and unless you are using a custom profile provider there, it has the added processing of parsing out the UserId.
If you're wondering why they did not implement a GetUserId method, it's simply because you're not always guaranteed that that user id will be a GUID as in the included provider.
EDIT:
See
ScottGu's article on providers
which provides a
link to downloading the actual source code for i.e. SqlMembershipProvider
.
But the simplest thing to do really is a GetUserId() method in your user object, or utility class, where you get the UserId from cache/session if there, otherwise hit the database, cache it by username (or store in session), and return it.
For something more to consider (but be very careful because of cookie size restrictions):
Forms Auth: Membership, Roles and Profile with no Providers and no Session


q: Is there any way to see an overview of what kind of queries are spent the most time on every day on MySQL?

[A]
You can always set up query logging as described here:
http://dev.mysql.com/doc/refman/5.0/en/query-log.html


q:
I have the following problem:

I have an HTML textbox (<input type="text">) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components).

I want to be notified in my script every time the value of that textbox changes, so I can react to it.

I've tried this:

txtStartDate.observe('change', function() { alert('change' +  txtStartDate.value) });

which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value.

Is there another event I can listen to, that i'm not aware of?

I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com)

[A]
As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fire any events.  Your only solution is to find some hook into the control that you can hook up to your listener.
Here is how I would do it:
```
```
basicDatePicker.selectDate = basicDatePicker.selectDate.wrap(function(orig,year,month,day,hide) {
  myListener(year,month,day);
  return orig(year,month,day,hide);
});
```
```
That's based on a cursory look with Firebug (I'm not familiar with the component). If there are other ways of selecting a date, then you'll need to wrap those methods as well.


q:
I'm writing some semi-portable code and want to be able to detect when I'm compiling for iPhone. So I want something like #ifdef IPHONE_SDK....

Presumably Xcode defines something, but I can't see anything under project properties, and Google isn't much help.

[A]
It's in the SDK docs under "Compiling source code conditionally"
The relevant definitions are TARGET_OS_IPHONE (and he deprecated TARGET_IPHONE_SIMULATOR), which are defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:
```
```
#include "TargetConditionals.h"
```
```
but this is no longer necessary on the current (xCode 6/iOS8) toolchain.
So, for example, if you want to only compile a block of code if you are building for the device, then you should do
```
```
#if !(TARGET_OS_SIMULATOR)
...
#endif
```
```


q:
One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a this. For example: this.process(this.event).

A few of my students commented on this, and I'm wondering if I am teaching bad habits.

My rationale is:

Makes code more readable — Easier to distinguish fields from local variables.

Makes it easier to distinguish standard calls from static calls (especially in Java)

Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass.

Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable?

Note: I turned it into a CW since there really isn't a correct answer.

[A]
I think it's less readable, especially in environments where fields are highlighted differently from local variables.  The only time I want to see "this" is when it is required, for example:
```
```
this.fieldName = fieldName
```
```
When assigning the field.
That said, if you need some way to differentiate fields for some reason, I prefer "this.fieldName" to other conventions, like "m_fieldName" or "_fieldName"


q: When you create a new web user control in visual studio it by default adds the Page_Load event.  What is the advantage to using this rather than overriding the base OnLoad event on the control?  Is it just that the Page_Load event fires before OnLoad?

[A]
The
```
OnLoad
```
method should be the place where the
```
Load
```
event is raised.  I personally always try to handle the event unless I need to do extra processing around raising the event.
I recommend handling the event itself under normal circumstances.


q: Is there a way to have Visual Studio 2008 automatically add heading information to files? For example, "Copyright 2008" or something along those lines. I've been digging through the options, but nothing seems to be jumping out at me.

[A]
I assume you'd like to modify the class file templates.  They're in:
```
```
%ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033
```
```
More specific details here


q:
In other words, is it correct to use:

public class CustomerList : System.Collections.Generic.List<Customer>
{
    /// supposed to be empty
}

instead of:

using CustomerList = System.Collections.Generic.List<Customer>

I'd rather use the first approach because I'd just define CustomerList once, and every time I needed a customer list I'd always use the same type. On the other hand, using the name aliasing approach not only forces me to have to redefine it everywhere, but also a different alias could be given every time someone wanted to use it (think of a big team), and thus cause the code to be less readable.

Please note that the intention in this case would never be to extend the class, just to create an alias.

[A]
well, unless you are adding some functionality to the base class there is no point in creating a wrapper object.  I would go with number two if you really need to, but why not just create a variable?
```
```
List<Customer> customerList = new List<Customer>();
```
```


q:
I am programming a UNIX shell and I have to use the execv() system call to create a process.
One of the parameters for execv() is the filepath for the executable.  So if somebody types in /bin/ls, it will run the ls executable.  But what I need is a function such that when ls is typed, it will search for the filepath of ls (like the which command).  Is there a function which allows me to do that?

Unfortunately, this is a school project and I am not allowed to use execvp(). I need to implement some path searching function and then add that filepath to the execv() parameter.

[A]
I think execvp() does what you need.
Edit:
So you're actually asking how to do this manually? In that case...
Find your PATH in envp (3rd argument to main())
Split this into individual paths
Check for your program's existance in each of these with stat()
Execute the first one you find to exist
Or if you want a
really
solid implementation, use
this
. It might set off the plagarism detectors though :)


q: Does iPhone support XML-RPC, Is their any open source framework which I can use?

[A]
Checkout the source for the wordpress app.  They might be using XML-RPC. :)
http://iphone.wordpress.org/


q:
I'm not asking this question because of the merits of garbage collection first of all.  My main reason for asking this is that I do know that Bjarne Stroustrup has said that C++ will have a garbage collector at some point in time.

With that said, why hasn't it been added?  There are already some garbage collectors for C++.  Is this just one of those "easier said than done" type things?  Or are there other reasons it hasn't been added (and won't be added in C++11)?

Cross links:

Garbage collectors for C++

Just to clarify, I understand the reasons why C++ didn't have a garbage collector when it was first created.  I'm wondering why the collector can't be added in.

[A]
What type? should it be optimised for embedded washing machine controllers, cell phones, workstations or supercomputers?
Should it prioritise gui responsiveness or server loading?
should it use lots of memory or lots of CPU?
C/c++ is used in just too many different circumstances.
I suspect something like boost smart pointers will be enough for most users
Edit - Automatic garbage collectors aren't so much a problem of performance (you can always buy more server) it's a question of predicatable performance.
Not knowing when the GC is going to kick in is like employing a narcoleptic airline pilot, most of the time they are great - but when you really need responsiveness!


q:
I am trying to understand some assembly.

The assembly as follows, I am interested in the testl line:

000319df  8b4508        movl   0x08(%ebp), %eax
000319e2  8b4004        movl   0x04(%eax), %eax
000319e5  85c0          testl  %eax, %eax
000319e7  7407          je     0x000319f0

I am trying to understand that point of testl between %eax and %eax? I think the specifics of what this code isn't important, I am just trying to understand the test with itself - wouldn't the value always be true?

[A]
It tests whether
```
eax
```
is 0, or above, or below. In this case, the jump is taken if
```
eax
```
is 0.


q:
What web app architecture works well receiving/sending SMS text messages? By "architecture, I mean specific architecture, not generally, such as MVC.

Background: I'm building a web app that receives queries from/sends answers to cell phones. The app design (and business model) expects to communicate with cell devices via SMS text messages. IOW: There is no MVC web page "view". The cell phone screen is effectively the "view".

[A]
This depends on how you will be receiving and sending the SMS messages.
There is a specific Short message protocol (SMPP -
http://en.wikipedia.org/wiki/SMPP
).
For that you will need an SMPP server.
If you are using a one of the various SMS over HTTP providers (such as Clickatell -
http://www.clickatell.com
), then a web framework such as RoR is fine as both the sending and receiving of SMS messages are actually web requests.
In this case your system view is the HTTP response to the gateway, not the cellphone screen. There are actually quite a few steps involved:
```
Cellphone -> Cellular Network -> Gateway -> Your Service
```
and the reply:
```
Cellphone <- Cellular Network <- Gateway <- Your Service
```


q:
What is the practical benefit of using HTTP GET, PUT, DELETE, POST, HEAD? Why not focus on their behavioral benefits (safety and idempotency), forgetting their names, and use GET, PUT or POST depending on which behavior we want?

Why shouldn't we only use GET, PUT and POST (and drop HEAD, DELETE)?

[A]
The [REST][1] approach uses POST, GET, PUT and DELETE to implement the CRUD rules for a web resource.  It's a simple and tidy way to expose objects to requests on the web.  It's web services without the overheads.
Just to clarify the semantic differences.  Each operation is rather different.  The point is to have nice HTTP methods that have clear, distinct meanings.
POST creates new objects.  The URI has no key; it accepts a message body that defines the object.  SQL Insert.  [
Edit
While there's no technical reason for POST to have no key, the REST folks suggest strongly that for POST to have distinct meaning as CREATE, it should not have a key.]
GET retrieves existing objects. The URI
may
have a key, depends on whether you are doing singleton GET or list GET.  SQL Select
PUT updates an existing object.  The URI has a key; It accepts a message body that updates an object.  SQL Update.
DELETE deletes an existing object.  The URI has a key.  SQL Delete.
Can you update a record with POST instead of PUT?  Not without introducing some ambiguity.  Verbs should have unambiguous effects.  Further, POST URI's have no key, where PUT must have a key.
When I POST, I expect a 201 CREATED.  If I don't get that, something's wrong.  Similarly, when I PUT, I expect a 200 OK.  If I don't get that, something's wrong.
I suppose you could insist on some ambiguity where POST does either POST or PUT.  The URI has to be different; also the associated message could be different.  Generally, the REST folks take their cue from SQL where INSERT and UPDATE are different verbs.
You could make the case that UPDATE should insert if the record doesn't exist or update if the record does exist.  However, it's simpler if UPDATE means UPDATE and failure to update means something's wrong.  A secret fall-back to INSERT makes the operation ambiguous.
If you're not building a RESTful interface, then it's typical to only use GET and POST for retrieve and create/update. It's common to have URI differences or message content differences to distinguish between POST and PUT when a person is clicking submit on a form.   It, however, isn't very clean because your code has to determine if you're in the POST=create case or POST=update case.


q:
I'm wondering how you'd implement the following use-case in REST. Is it even possible to do without compromising the conceptual model?

Read or update multiple resources within the scope of a single transaction. For example, transfer $100 from Bob's bank account into John's account.

As far as I can tell, the only way to implement this is by cheating. You could POST to the resource associated with either John or Bob and carry out the entire operation using a single transaction. As far as I'm concerned this breaks the REST architecture because you're essentially tunneling an RPC call through POST instead of really operating on individual resources.

[A]
You'd have to roll your own "transaction id" type of tx management.  So it would be 4 calls:
```
```
http://service/transaction (some sort of tx request)
http://service/bankaccount/bob (give tx id)
http://service/bankaccount/john (give tx id)
http://service/transaction (request to commit)
```
```
You'd have to handle the storing of the actions in a DB (if load balanced) or in memory or such, then handling commit, rollback, timeout.
Not really a RESTful day in the park.


q: Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to display: none;, the table with shrinks to fit the contents of the visible rows.

[A]
If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value:
```
```
table.style.width = table.clientWidth + "px";
table.rows[3].style.display = "none";
```
```
However, this may cause the individual columns to reflow when you hide the row. A possible way to mitigate this is by adding a style to your table:
```
```
table {
  table-layout: fixed;
 }
```
```


q: I have a T-SQL table variable (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done?

[A]
Truncating the table will dump ALL the data, and reset the identity seed.
Otherwise, you can use this call to reset the identity while retaining any of the data:
```
```
DBCC CHECKIDENT (yourtableName, reseed, @NewStartSeedValue)
```
```


q: The GetVersions() call to the Versions.asmx web service in SharePoint 2003 returns a localised date format, with no way of determining what the format is. It's the site regional setting of date format, but I can't find a way to get even that out of SharePoint 2003. Locally, it looks like SPRegionalSettings can be used (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spregionalsettings.aspx) but what about a web service version of this?

[A]
Sadly, it isn't available. However, you can specify a query option to specify that you want the values returned in UTC:
http://www.sharepointblogs.com/pm4everyone/archive/2006/10/03/sharepoint-2003-querying-with-gmt-datetime.aspx


q:
Here's what I am trying to do:

typedef enum { ONE, TWO, THREE } Numbers;

I am trying to write a function that would do a switch case similar to the following:

char num_str[10];
int process_numbers_str(Numbers num) {
  switch(num) {
    case ONE:
    case TWO:
    case THREE:
    {
      strcpy(num_str, num); //some way to get the symbolic constant name in here?
    } break;
    default:
      return 0; //no match
  return 1;
}

Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above?

[A]
There's no built-in solution. The easiest way is with an array of
```
char*
```
where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse
```
enum
```
(one that doesn't start at 0 or has gaps in the numbering) where some of the
```
int
```
mappings are high enough to make an array-based mapping impractical then you could use a hash table instead.


q:
I currently have heavily multi-threaded server application, and I'm shopping around for a good multi-threaded memory allocator.

So far I'm torn between:

Sun's umem

Google's tcmalloc

Intel's threading building blocks allocator

Emery Berger's hoard

From what I've found hoard might be the fastest, but I hadn't heard of it before today, so I'm skeptical if its really as good as it seems. Anyone have personal experience trying out these allocators?

[A] Maybe this is the wrong way to approach what you are asking, but maybe a different tactic could be employed altogether. If you are looking for a really fast memory allocator maybe you should ask why you need to be spending all that time allocating memory when you could perhaps just get away with stack allocation of variables. Stack allocation, while way more annoying, done right could save you lots in the way of mutex contention, as well as keeping strange memory corruption issues out of your code. Also, you potentially have less fragmentation which could help.


q:
I need to accept form data to a WCF-based service. Here's the interface:

[OperationContract]
[WebInvoke(UriTemplate = "lead/inff",
    BodyStyle = WebMessageBodyStyle.WrappedRequest)]
int Inff(Stream input);

Here's the implementation (sample - no error handling and other safeguards):

public int Inff(Stream input)
{

    StreamReader sr = new StreamReader(input);
    string s = sr.ReadToEnd();
    sr.Dispose();

    NameValueCollection qs = HttpUtility.ParseQueryString(s);
    Debug.WriteLine(qs["field1"]);
    Debug.WriteLine(qs["field2"]);

    return 0;
}

Assuming WCF, is there a better way to accomplish this besides parsing the incoming stream?

[A]
I remember speaking to you about this at DevLink.
Since you have to support form fields the mechanics of getting those (what you are currently doing) don't change.
Something that might be helpful, especially if you want to reuse your service for new applications that don't require the form fields is to create a channel that deconstructs your stream and repackages it to XML/JSON/SOAP/Whatever and have your form clients communicate with the service through that while clients that don't use forms can use another channel stack. Just an idea...
Hope that helps. If you need help with the channel feel free to let me know.


q:
In general, what needs to be done to convert a 16 bit Windows program to Win32? I'm sure I'm not the only person to inherit a codebase and be stunned to find 16-bit code lurking in the corners.

The code in question is C.

[A]
The original win32 sdk had a tool that scanned source code and flagged lines that needed to be changed, but I can't remember the name of the tool.
When I've had to do this in the past, I've used a brute force technique - i.e.:
1 - update makefiles or build environment to use 32 bit compiler and linker. Optionally, just create a new project in your IDE (I use Visual Studio), and add the files manually.
2 - build
3 - fix errors
4 - repeat 2&3 until done
The pain of the process depends on the application you are migrating. I've converted 10,000 line programs in an hour, and 75,000 line programs in less than a week. I've also had some small utilities that I just gave up on and rewrote (mostly) from scratch.


q: In one of my ASP.NET Web Applications, I am using a BulkEditGridView (a GridView which allows all rows to be edited at the same time) to implement an order form. In my grid, I have a column which calculates the total for each item (cost x quantity) and a grand total field at the bottom of the page. Currently, however, these fields are only refreshed on every post-back. I need to have these fields updated dynamically so that as users change quantities, the totals and grand total update to reflect the new values. I have attempted to use AJAX solutions to accomplish this, but the asynchronous post-backs interfere with the focus on the page. I imagine that a purely client-side solution exists, and I'm hopeful that someone in the community can share.

[A]
One solution is to build some javascript in you RowDataBound method to constantly update those totals when the textboxes change.
So during the RowDataBound, start building a javascript string in memory that will add up the textboxes you need added. What's nice in RowDataBound is you can get the Client Side id's of these textboxes by calling TextBox.ClientId.
Add this javascript to the page, then also add an onkeyup event to each textbox you require to call this script.
So something like (this is a row bound event from a gridview)
```
```
private string _jscript;
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      //Get your textbox
      Textbox tb = e.Row.FindControl("tbAddUp");
      //Add the event that you're going to call to this textbox's attributes
      tb.Attributes.Add("onkeyup", "MyAddUpJavaScriptMethod();");
      //Build the javascript for the MyAddUpJavaScriptMethod
      jscript += "document.getElementById('" + tb.ClientId + '").value + ";
   }
}
```
```
Then once you've built that whole script, use your Page.ClientScript class to add a method to you page which will be called by your onkeyup in your textboxes "MyAddUpJavaScriptMethod"
Hope that makes sense and helps


q:
So, one commonly heard comment when talking about performance is that you write your code with whatever language gets the job done fastest. If performance in specific areas is a problem, then rewrite those bits in C/C++.

But, what if you're starting with a native C++ app? What options do you have if you want to write the easy bits, or refactor the old bits, in a language like Python, Ruby, C#, or whatever? Keep in mind that transferring data between the native and other sides is a must. Being able to simply call a function written in an "easier" language, while passing C++ classes as data, would be beautiful.

We've got a crusty Win32 app that would benefit greatly if we could crank out new code, or refactor old code, in C# or something. Very little of it requires the complexity of C++, and dealing with the little fiddly bits is dragging down the programming process.

[A]
If you want to work between C++ and Python, than
Boost Python
is what you're looking for.  You can write C Python bindings by hand for Cython, but that limits in many ways how you're going to write your code.  This is the easiest way, as seen in some snippets from
this tutorial
:
A simple function that performs a hello world:
```
```
char const* greet()
{
   return "hello, world";
}
```
```
The Boost python code needed to expose it to python:
```
```
#include <boost/python.hpp>

BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}
```
```
How to use this code from python:
```
```
>>> import hello_ext
>>> print hello.greet()
hello, world
```
```
Going in the opposite direction is  bit tougher, since python doesn't compile to native code.  You have to embed the python interpreter into your C++ application, but the work necessary to do that is documented
here
.  This is an example of calling the python interpreter and extracting the result (the python interpreter defines the object class for use in C++):
```
```
object result = eval("5 ** 2");
int five_squared = extract<int>(result);
```
```


q:
In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this:

For Each item As Host In hostCollection1
    hostCollection2.Add(item)
Next

My collections are generic collections, inherited from the base class -- Collection(Of )

[A]
I know you're asking for VB, but in C# you can just use the constructor of the collection to initialize it with any IEnumerable.  For example:
```
```
List<string> list1 = new List<string>();
list1.Add("Hello");
List<string> list2 = new List<string>(list1);
```
```
Perhaps the same kind of thing exists in VB.


q:
I have a self built JSP webapp and at the moment I'm using tomcats built in admin pannel to manage user accounts (that are stored in tomcats config xml files) but this is limited because i can not create new accounts from within the web-app (eg. I can not have a sign up website) and need to manually create the accounts.

What is the most straight forward way of implementing accounts in a tomcat environment?

dennis

[A]
Set up a
database realm in Tomcat
, either a simple JDBC realm or a DataSource realm that will allow for connection pooling. Then adding users is a very simple CRUD web application, possibly combined with some confirmation emails.


q:
It is much more convenient and cleaner to use a single statement like

import java.awt.*;

than to import a bunch of individual classes

import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...

What is wrong with using a wildcard in the import statement?

[A]
The only problem with it is that it clutters your local namespace.  For example, let's say that you're writing a Swing app, and so need
```
java.awt.Event
```
, and are also interfacing with the company's calendaring system, which has
```
com.mycompany.calendar.Event
```
.  If you import both using the wildcard method, one of these three things happens:
You have an outright naming conflict between
```
java.awt.Event
```
and
```
com.mycompany.calendar.Event
```
, and so you can't even compile.
You actually manage only to import one (only one of your two imports does
```
.*
```
), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
When you compile your code there is no
```
com.mycompany.calendar.Event
```
, but when they later add one your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly
wrong
, but future maintainers will thank you for your clarity otherwise.


q:
I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous.

Now, the documentation says that the 5th parameter (see below) controls this.  Specifically, when you pass 'false' it's supposed to be a non-asynchronous call.  However, regardless if it's true or false, it still processes the call asynchronously.

Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);

Is there a work-around for this or perhaps I'm doing something wrong?

[A]
ASPX Page
```
```
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="How-to-use-GetCallbackEventReference.aspx.vb" Inherits="How_to_use_Callback" %>

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

    <title>How to use GetCallbackEventReference</title>

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

        <input id="Button1" type="button" value="Get Random Number" onclick="GetNumber()" />

        <asp:TextBox ID="txtGetNumber" runat="server"></asp:TextBox>

    </form>

```
```
Code Behind
```
```
Partial Class How_to_use_Callback
    Inherits System.Web.UI.Page
    Implements System.Web.UI.ICallbackEventHandler
    Dim CallbackResult As String = Nothing
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Me, "arg", "GetRandomNumberFromServer", "context")
        Dim cbScript As String = "function UseCallback(arg,context)" & "{" & cbReference & " ; " & "}"
        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "UseCallback", cbScript, True)
    End Sub

    Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
        Return CallbackResult
    End Function

    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
        CallbackResult = Rnd().ToString()
    End Sub
End Class
```
```


q:
I've developed a Visual C#.NET 2008 Express Edition solution containing three projects. I am cleaning it up to commit it into a CVS repository.

There are several files that are created during the build process that are not necessary to be placed in the repository since they will be regenerated automatically.

The question: Can anyone suggest a list of patterns to be placed into a .cvsignore file so that these generated files and folders are ignored?

[A]
Typically these are the only things that you
have
to commit:
.sln files
.cs files
.csproj files
.config files
External DLLs and corresponding XML/config files that you are referencing
other non-generated files that your application uses
All the rest are to be ignored, including:
.suo files
.csproj.user files
/bin folder and contents
/obj folder and contents
practically everything else


q:
Given the following XML structure

<html>
  <body>
    <div>
      <span>Test: Text2</span>
    </div>
    <div>
      <span>Test: Text3</span>
    </div>
    <div>
      <span>Test: Text5</span>
    </div>
  </body>
</html>

What is the best XPath query to locate any span with text that starts with Test?

[A]
```
```
//span[starts-with(.,'Test')]
```
```
References:
http://www.w3.org/TR/xpath/#function-starts-with
https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/starts-with


q: Is it possible to include one CSS file in another?

[A]
Yes:
```
```
@import url("base.css");
```
```
Note:
The
```
@import
```
rule
must precede
all other rules (except
```
@charset
```
).
Additional
```
@import
```
statements require additional server requests. As an alternative, concatenate all CSS into one file to avoid multiple HTTP requests. For example, copy the contents of
```
base.css
```
and
```
special.css
```
into
```
base-special.css
```
and reference only
```
base-special.css
```
.


q:
Given a string with a module name, how do you import everything in the module as if you had called:

from module import *

i.e. given string S="module", how does one get the equivalent of the following:

__import__(S, fromlist="*")

This doesn't seem to perform as expected (as it doesn't import anything).

[A]
Please reconsider. The only thing worse than
```
import *
```
is
magic
```
import *
```
.
If you really want to:
```
```
m = __import__ (S)
try:
    attrlist = m.__all__
except AttributeError:
    attrlist = dir (m)
for attr in attrlist:
    globals()[attr] = getattr (m, attr)
```
```


q:
How do you calculate the least common multiple of multiple numbers?

So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers.

So far this is how I did it

LCM = num1 * num2 /  gcd ( num1 , num2 )

With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm

But I can't figure out how to calculate it for 3 or more numbers.

[A]
You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e.
```
```
lcm(a,b,c) = lcm(a,lcm(b,c))
```
```


q:
Are there any IDE's for developing HLSL code?  The three key features I want are:

1) syntax highlighting

2) auto-complete

3) interaction debugging

Visual Studio doesn't do any of these things, and it doesn't seem that RenderMonkey or FX Composer do either.

Is there some IDE that I'm not aware of, or does one of these three IDE's actually support these features and I'm too clueless to figure out how to use them properly?

[A]
Have you actually tried ATI's RenderMoney or NVidia's FX Composer?
Both actually provide syntax highlighting. Futher more, NVidia's Cg toolkits actually allows you to enable syntaxhightling in Visual Studio with some custom setting.
As for auto-completion, I don't think it's much needed as compare to our normal programming. It's because you won't be writing a very long code for your shader programming. Shader is quite critical in that it is run on every frame generated, and every instruction require 1 to a few clock cycle to execute, thus there's always a physical limit to how long you can afford to write.
Interactive debugging is currently the limitation of GPU hardware. To actually do that, the GPU has to be emulated with our CPU, which is quite impossible considering that the REF (software rendering) device can never cop up with even obsolete GPU, what more to say about emulating shader.


q:
class someclass {};

class base
{
    int a;
    int *pint;
    someclass objsomeclass;
    someclass* psomeclass;
public:
    base()
    {
        objsomeclass = someclass();
        psomeclass = new someclass();
        pint = new int();
        throw "constructor failed";
        a = 43;
    }
}

int main()
{
    base temp();
}

In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?

int main()
{
    base *temp = new base();
}

How about in the above code? How can the memory leaks be avoided after the constructor throws?

[A]
Everything you "new" needs to be deleted, or you'll cause a memory leak. So these two lines:
```
```
psomeclass = new someclass();
pint = new int();
```
```
Will cause memory leaks, because you need to do:
```
```
delete pint;
delete psomeclass;
```
```
In a finally block to avoid them being leaked.
Also, this line:
```
```
base temp = base();
```
```
Is unnecessary. You just need to do:
```
```
base temp;
```
```
Adding the "= base()" is unnecessary.


q:
in Javascript, the following:

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/".*?"/g);
alert(result);

yields "the quick","brown fox","jumps over","the lazy dog"

I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog

what regexp will do this?

[A]
You can use the
Javascript replace() method
to strip them out.
```
```
var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';

var result = test.replace(/"/, '');
```
```
Is there more to it than just getting rid of the double-quotes?


q:
What is the best way to detect if a user leaves a web page?

The onunload JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser).

Creating one will probably be blocked by current browsers.

[A]
One (slightly hacky) way to do it is replace and links that lead away from your site with an AJAX call to the server-side, indicating the user is leaving, then use that same javascript block to take the user to the external site they've requested.
Of course this won't work if the user simply closes the browser window or types in a new URL.
To get around that, you'd potentially need to use Javascript's setTimeout() on the page, making an AJAX call every few seconds (depending on how quickly you want to know if the user has left).


q:
What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading.

What is the best way to achieve this?

[A]
There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than).
However; if you just want it to work, then in .NET 3.5 there are some options...
I have put together a library
here
that allows efficient and simple access to operators with generics - such as:
```
```
T result = Operator.Add(first, second); // implicit <T>; here
```
```
It can be downloaded as part of
MiscUtil
Additionally, in C# 4.0, this becomes possible via
```
dynamic
```
:
```
```
static T Add<T>(T x, T y) {
    dynamic dx = x, dy = y;
    return dx + dy;
}
```
```
I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as
```
```
interface ICalc<T>
{
    T Add(T,T)()
    T Subtract(T,T)()
}
```
```
etc, but then you need to pass an
```
ICalc<T>;
```
through all the methods, which gets messy.


q: I have Eclipse setup with PyDev and love being able to debug my scripts/apps.  I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?

[A]
Create a new launch configuration (Python Run)
Main tab
Use paster-script.py as main module (you can find it in the Scripts sub-directory in your python installation directory)
Don't forget to add the root folder of your application in the PYTHONPATH zone
Arguments
Set the base directory to the root folder also.
As Program Arguments use "serve development.ini" (or whatever you use to debug your app")
Common Tab
Check allocate console and launch in background


q: How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET.

[A]
Execute:
```
SELECT name FROM master.sys.databases
```
This the preferred approach now, rather than
```
dbo.sysdatabases
```
, which has been deprecated for some time.
Execute this query:
```
```
SELECT name FROM master.dbo.sysdatabases
```
```
or if you prefer
```
```
EXEC sp_databases
```
```


q: How can I extract the list of available SQL servers in an SQL server group? I'm planning to put that list in a combo box in VB.NET.

[A]
The only way I knew to do it was using the command line:
```
```
osql -L
```
```
But I found the below article which seems to solve your specific goal filling a combobox:
http://www.sqldbatips.com/showarticle.asp?ID=45


q:
I'm looking at ways to deploy a Ruby on Rails app (running on JRuby) to a Tomcat instance for testing.

The tomcat instance is running on a Solaris server that I can SSH to. I've looked at using Capistrano, but there doesn't seem to be a lot out there about using it to deploy to Tomcat, or even about running it under JRuby, and I keep hitting bugs in Capistrano due to the Windows/JRuby environment my PC is running (yeah, it's corporate - not my choice, but I've got to live with it).

I'm using warble to build the .war file, and the app deploys and runs fine once I manually copy it up and deploy it. I'm wanting something easier and more automated to actually get it there.

Anyone done this before? Documentation on the web seems pretty thin.

[A]
I don't have much experience on this, so I don't know if I can give you the BEST way, but if Capistrano doesn't work, and you can't have a separate MRI install just to run it, you have just a few alternatives left:
Try running plain Rake and write your own deployment target:
http://www.gra2.com/article.php/deploy-ruby-on-rails-applications-rake
Or use Ant or Maven.
Or if it just ONE server you have to deploy to, you could just hack together two Ruby scripts - one that listens on the server for shutdown/startup requests, and one local that you run to: Send shutdown, scp over the file, send startup.
By the way, have you submitted any integration bugs you find with Capistrano to the JRuby team? I'm sure they'd be happy to have any contribution.
:)


q: How do you calculate the length of the string that would be returned by Array::pack?  Is there something like Python's calcsize?

[A]
By making an interpreter complying to the specifications found in
Array::pack
.
Or, reusing the existing implementation to count the number of characters instead of appending them to a string.


q:
In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:

unsigned long value = 0xdeadbeef;
value &= ~(1<<10);

How do I do that in Python ?


q: Is there a Delphi equivalent of the C# #if(DEBUG) compiler directive?

[A]
Use this:
```
```
{$IFDEF DEBUG}
...
{$ENDIF}
```
```


q:
In a text file, there is a string "I don't like this".

However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use

f1 = open (file1, "r")
text = f1.read()

command to do the reading.

Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?

Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?

[A]
Actually, U+2018 is the Unicode representation of the special character ‘ . If you want, you can convert instances of that character to U+0027 with this code:
```
```
text = text.replace (u"\u2018", "'")
```
```
In addition, what are you using to write the file?
```
f1.read()
```
should return a string that looks like this:
```
```
'I don\xe2\x80\x98t like this'
```
```
If it's returning
this
string, the file is being written incorrectly:
```
```
'I don\u2018t like this'
```
```


q:
In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:

APPROVAL_CHOICES = (
    ('yes', 'Yes'),
    ('no', 'No'),
    ('cancelled', 'Cancelled'),
)

client_approved = models.CharField(choices=APPROVAL_CHOICES)

to create a drop down box in your form and force the user to choose one of those options.

I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.

[A]
In terms of the forms library, you would use the
MultipleChoiceField
field with a
CheckboxSelectMultiple
widget to do that. You could validate the number of choices which were made by writing a validation method for the field:
```
```
class MyForm(forms.Form):
    my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())

    def clean_my_field(self):
        if len(self.cleaned_data['my_field']) > 3:
            raise forms.ValidationError('Select no more than 3.')
        return self.cleaned_data['my_field']
```
```
To get this in the admin application, you'd need to customise a ModelForm and
override the form used in the appropriate ModelAdmin
.


q:
We are setting up a Selenium test campaign on a big web application.
The first thing we've done was to build a framework which initialize SQL data in database before the test, launch the test, archive results and then clear data.

We've integrate that in a Maven 2 process, run every day by TeamCity on a dedicated database.

We've set up several Selenium tests now but It's not as used as planned.

Reasons are that tests are sometimes broken for other reasons than regressions (data may have changed, stored procedure may have been recompiled and so on).

I would like to know if there are big success in user interface testing and if so, reasons to that. Commons errors may also interest me.

[A]
I use http-unit which has the added benefit of working before any styling has been added to the page.
http://httpunit.sourceforge.net/
You can attach the tests to run in the integration test phase for maven2.
From the site
Written in Java, HttpUnit emulates the
  relevant portions of browser behavior,
  including form submission, JavaScript,
  basic http authentication, cookies and
  automatic page redirection, and allows
  Java test code to examine returned
  pages either as text, an XML DOM, or
  containers of forms, tables, and
  links.


q: With the recent buzz on multicore programming is anyone exploring the possibilities of using MPI ?

[A]
No, in my opinion it is unsuitable for most processing you would do on a multicore system.  The overhead is too high, the objects you pass around must be deeply cloned, and passing large objects graphs around to then run a very small computation is very inefficient. It is really meant for sharing data between separate processes, most often running in separate memory spaces, and most often running long computations.
A multicore processor is a shared memory machine, so there are much more efficient ways to do parallel processing, that do not involve copying objects and where most of the threads run for a very small time. For example, think of a multithreaded Quicksort. The overhead of allocating memory and copying the data to a thread before it can be partioned will be much slower with MPI and an
unlimited
number of processors than Quicksort running on a single processor.
As an example, in Java, I would use a BlockingQueue (a shared memory construct), to pass object
references
between threads, with very little overhead.
Not that it does not have its place, see for example the Google search cluster that uses message passing. But it's probably not the problem you are trying to solve.


q:
I'm creating an installation script for an application that I'm developing and need to create databases dynamically from within PHP. I've got it to create the database but now I need to load in several .sql files. I had planned to open the file and mysql_query it a line at a time - until I looked at the schema files and realised they aren't just one query per line.

So, how do I load an sql file from within PHP (as phpMyAdmin does with its import command)?

[A]
```
```
mysql_query("LOAD DATA LOCAL INFILE '/path/to/file' INTO TABLE mytable");
```
```


q:
To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII.
Anyone has a clue?

[A]
Why not let the window resize itself based on the runtime height/width?
Run something like this in your pop-up:
```
```
window.resizeTo(document.body.clientWidth, document.body.clientHeight);
```
```


q:
I am already excited about document databases and especially about CouchDB's simplicity. But I have a hard time understanding if such databases are a viable option for multi user systems. Since those systems require some kind of relations between records which document databases do not provide.

Is it completely the wrong tool for such cases? Or some tagging and temporary views are the way to accomplish this? Or else...

UPDATE:

I understand the answers so far. But let me rephrase the question a bit. Lets say I have a load of semi-structured data which is normally a fit for CouchDB. I can tag them like "type=post" and "year=2008". My question is how far can I go with this type of tagging? Say can I create an array field with 10.000 names in it? Or is there a better way of doing this? It is a matter of understanding how to think in this document based sense.

[A]
Multi-user systems do not
require
relational databases, though RDBMSs are a staple technology for data storage/retrieval for a vast number of (especially CRUD) applications.
If you want to read-up on document/object -oriented, distributed database solutions of yore, search on "Lotus Notes/Domino" (it's a mature technology/product in this area that's good background knowledge in how applications are designed in a document-based paradigm. Classically, it's really good at workflow type applications).
On CouchDB specifically, check out:
http://wiki.apache.org/couchdb/
(this shouldn't be a surprise)
http://seanoc.wordpress.com/2007/10/12/more-on-couchdb/
(easy reading description overview)
http://twit.tv/floss36
(Podcast interview all about CouchDB)


q:
I have the problem that an specific step in Ant can only be executed when we have Java 1.5 installed in the build computer.  The task definition uses  uses a jar file that was compiled using 1.5, so running with a 1.4 virtual machine will throw an IncompatibleClassVersion exception.

I have to find a solution meanwhile to have this task working for this specific project that requires 1.4, but a question came to me.  How can I avoid defining this task and executing this optional step if I don't have a specific java version?

I could use the "if" or "unless" tags on the target tag, but those only check if a property is set or not.  I also would like to have a solution that doesn't require extra libraries, but I don't know if the build-in functionality in standard is enough to perform such a task.

[A]
The Java version is exposed via the
ant.java.version
property. Use a
condition
to set a property and execute the task only if it is true.
```
```
<?xml version="1.0" encoding="UTF-8"?>

<project name="project" default="default">

    <target name="default" depends="javaCheck" if="isJava6">
        <echo message="Hello, World!" />
    </target>

    <target name="javaCheck">
        <echo message="ant.java.version=${ant.java.version}" />
        <condition property="isJava6">
            <equals arg1="${ant.java.version}" arg2="1.6" />
        </condition>
    </target>

</project>
```
```


q:
I want to generate some XML in a stored procedure based on data in a table.

The following insert allows me to add many nodes but they have to be hard-coded or use variables (sql:variable):

SET @MyXml.modify('
      insert
         <myNode>
            {sql:variable("@MyVariable")}
         </myNode>
      into (/root[1]) ')

So I could loop through each record in my table, put the values I need into variables and execute the above statement.

But is there a way I can do this by just combining with a select statement and avoiding the loop?

Edit I have used SELECT FOR XML  to do similar stuff before but I always find it hard to read when working with a hierarchy of data from multiple tables. I was hoping  there would be something using the modify where the XML generated is more explicit and more controllable.

[A]
Can you tell a bit more about what exactly you are planning to do.
Is it simply generating XML data based on a content of the table
or adding some data from the table to an existing xml structure?
There are
great series of articles
on the subject on XML in SQLServer written by Jacob Sebastian, it starts with the
basics of generating XML from the data in the table


q:
Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties.

Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow.

[A]
There were a number of gotchas I discovered:
Although it may appear like a double in XAML, the actual value for a *Definition's Height or Width is a 'GridLength' struct.
All the properties of GridLength are readonly, you have to create a new one each time you change it.
Unlike every other property in WPF, Width and Height don't default their databinding mode to 'TwoWay', you have to manually set this.
Thusly, I used the following code:
```
```
private GridLength myHorizontalInputRegionSize = new GridLength(0, GridUnitType.Auto)
public GridLength HorizontalInputRegionSize
{
    get
    {
        // If not yet set, get the starting value from the DataModel
        if (myHorizontalInputRegionSize.IsAuto)
            myHorizontalInputRegionSize = new GridLength(ConnectionTabDefaultUIOptions.HorizontalInputRegionSize, GridUnitType.Pixel);
        return myHorizontalInputRegionSize;
    }
    set
    {
        myHorizontalInputRegionSize = value;
        if (ConnectionTabDefaultUIOptions.HorizontalInputRegionSize != myHorizontalInputRegionSize.Value)
        {
            // Set the value in the DataModel
            ConnectionTabDefaultUIOptions.HorizontalInputRegionSize = value.Value;
        }
        OnPropertyChanged("HorizontalInputRegionSize");
    }
}
```
```
And the XAML:
```
```
<Grid.RowDefinitions>
    <RowDefinition Height="*" MinHeight="100" />
    <RowDefinition Height="Auto" />
    <RowDefinition Height="{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}" MinHeight="50" />
</Grid.RowDefinitions>
```
```


q: I miss it so much (used it a lot in C#). can you do it in C++?

[A]
Yes, you can. See
here
.
```
```
#pragma region Region_Name
//Your content.
#pragma endregion Region_Name
```
```


q: Can share with me any of this script?

[A]
The default one is called commit-email.pl and is included when you install Subversion. But
here
is one in ruby:
```
```
#!/usr/bin/ruby -w

# A Subversion post-commit hook. Edit the configurable stuff below, and
# copy into your repository's hooks/ directory as "post-commit". Don't
# forget to "chmod a+x post-commit".

# ------------------------------------------------------------------------

# You *will* need to change these.

address="FOO@SOME_DOMAIN.com"
sendmail="/usr/sbin/sendmail"
svnlook="/usr/bin/svnlook"

# ------------------------------------------------------------------------

require 'cgi'

# Subversion's commit-email.pl suggests that svnlook might create files.
Dir.chdir("/tmp")

# What revision in what repository?
repo = ARGV.shift()
rev = ARGV.shift()

# Get the overview information.
info=`#{svnlook} info #{repo} -r #{rev}`
info_lines=info.split("\n")
author=info_lines.shift
date=info_lines.shift
info_lines.shift
comment=info_lines

# Output the overview.
body = "
#{author} #{date}
"
body << "
"
comment.each { |line|  body << "#{CGI.escapeHTML(line)}
\n" }
body << "
"
body << "
"

# Get and output the patch.
changes=`#{svnlook} diff #{repo} -r #{rev}`
body << "
"
changes.each do |top_line|
  top_line.split("\n").each do |line|
    color = case
      when line =~ /^Modified: / || line =~ /^=+$/ || line =~ /^@@ /: "gray"
      when line =~ /^-/: "red"
      when line =~ /^\+/: "blue"
      else "black"
    end
    body << %Q{#{CGI.escapeHTML(line)}
\n}
 end
end
body << "
"

# Write the header.
header = ""
header << "To: #{address}\n"
header << "From: #{address}\n"
header << "Subject: [SVN] #{repo} revision #{rev}\n"
header << "Reply-to: #{address}\n"
header << "MIME-Version: 1.0\n"
header << "Content-Type: text/html; charset=UTF-8\n"
header << "Content-Transfer-Encoding: 8bit\n"
header << "\n"

# Send the mail.
begin
    fd = open("|#{sendmail} #{address}", "w")
    fd.print(header)
    fd.print(body)
rescue
    exit(1)
end
fd.close

# We're done.
exit(0)
```
```


q:
In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company, Region, Area, Site, Room, Till. For a particular company I need to write some MDX that lists all regions, areas and sites (but not any levels below Site). Currently I am achieving this with the following MDX

HIERARCHIZE({
[Location].[Test Company],
Descendants([Location].[Test Company], [Location].[Region]),
Descendants([Location].[Test Company], [Location].[Area]),
Descendants([Location].[Test Company], [Location].[Site])
})

Because my knowledge of MDX is limited, I was wondering if there was a simpler way to do this, with a single command rather that four? Is there a less verbose way of achieveing this, or is my example the only real way of achieving this?

[A]
The command you want is DESCENDANTS. Keep the 'family tree' analogy in mind, and you can see that this will list the descendants of a member, down as far as you want.
You can specify the 'distance' (in levels) from the chosen member, 3 in your case.
There are a few weird options you can specify with the third argument, you want SELF_AND_AFTER, see
http://msdn.microsoft.com/en-us/library/ms146075.aspx
EDIT - oops, as santiiiii noticed, it should be SELF_AND_BEFORE


q:
I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby.  Python (which Kent writes in) has an assert() method in the language which is used extensively.  Ruby does not.  I think it should be easy to add this but is Kernel the right place to put it?

BTW, I know of the existence of the various Unit frameworks in Ruby - this is an exercise to learn the Ruby idioms, rather than to "get something done".

[A]
What's your reason for adding the assert method to the Kernel module? Why not just use another module called
```
Assertions
```
or something?
Like this:
```
```
module Assertions
  def assert(param)
    # do something with param
  end

  # define more assertions here
end
```
```
If you really need your assertions to be available
everywhere
do something like this:
```
```
class Object
  include Assertions
end
```
```
Disclaimer: I didn't test the code but in principle I would do it like this.


q:
I'm making a simple jquery command:

element.html("&nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;");

using the attributes/html method:  http://docs.jquery.com/Attributes/html

It works on my local app engine server, but it doesn't work once I push to the Google server. The element empties but doesn't fill with spaces.

So instead of "      " (6 spaces) it's just "".

Once again, this is running on App Engine, but I don't think that should matter...

[A]
Have you tried using
```

```
instead of spaces? The
```
html()
```
method just pumps the string into the innerHTML of the element(s).


q:
In SQL, how do update a table, setting a column to a different value for each row?

I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use:

update person set unique_number = (select nextval('number_sequence') );

but it seems that nextval is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead?

[A]
Don't use a subselect, rather use the nextval function directly, like this:
```
```
update person set unique_number = nextval('number_sequence');
```
```


q:
When using IF statements in Python, you have to do the following to make the "cascade" work correctly.

if job == "mechanic" or job == "tech":
        print "awesome"
elif job == "tool" or job == "rock":
        print "dolt"

Is there a way to make Python accept multiple values when checking for "equals to"? For example,

if job == "mechanic" or "tech":
    print "awesome"
elif job == "tool" or "rock":
    print "dolt"

[A]
```
```
if job in ("mechanic", "tech"):
    print "awesome"
elif job in ("tool", "rock"):
    print "dolt"
```
```
The values in parentheses are a tuple. The
```
in
```
operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple.
Note that when Python searches a tuple or list using the
```
in
```
operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a
```
frozenset
```
:
```
```
AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ])
def func():
    if job in AwesomeJobs:
        print "awesome"
```
```
The use of
```
frozenset
```
over
```
set
```
is preferred if the list of awesome jobs does not need to be changed during the operation of your program.


q:
I'm experimenting with OpenSSL on my network application and I want to test if the data sent is encrypted and can't be seen by eavesdropper.

What tools can you use to check? Could this be done programmatically so it could be placed in a unit test?

[A]
check out wire shark
http://www.wireshark.org/
and tcp dump
http://en.wikipedia.org/wiki/Tcpdump
Not sure about integrating these into unit tests. They will let you look at a very low level whats going on at the network level.
Perhaps for the unit test determine what the stream looks like unencrypted and make sure the encrypted stream is not similar


q: Is the sorting algorithm used by .NET's Array.Sort() method a stable algorithm?

[A]
From
MSDN
:
This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
The sort uses introspective sort. (Quicksort in version 4.0 and earlier of the .NET framework).
If you need a stable sort, you can use
Enumerable.OrderBy
.


q:
Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this?

Answer - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.

[A]
For a general InputStream, I would wrap it in a BufferedInputStream and do something like this:
```
```
BufferedInputStream bis = new BufferedInputStream(inputStream);
bis.mark(2);
int byte1 = bis.read();
int byte2 = bis.read();
bis.reset();
// note: you must continue using the BufferedInputStream instead of the inputStream
```
```


q: I've been searching and can't find the download files on opengl.org. can someone please point me to the right direction?

[A]
OpenGL is just a standard. The implementations come with your graphics card drivers and are exposed using WGL extensions in Windows. There is a 'standard' implementation in the platform SDK that is accessed by including the OpenGL headers and the windows header, but this is a basic version (1.1 in XP. I think it's 1.4 in Vista).
If you want an easier method to gain access to all the features from your card's supported features and the basic set of features in the Windows standard OpenGL implementation then I'd suggest looking at GLEW (The openGL Extension Wrangler) which handles all the WGL calls to set up extensions for you.


q:
C++ preprocessor #define is totally different.

Is the PHP define() any different than just creating a var?

define("SETTING", 0);
$something = SETTING;

vs

$setting = 0;
$something = $setting;

[A]
Here are the differences, from the
manual
Constants do not have a dollar sign    ($) before them;
Constants may only be defined using the define() function, not by simple assignment;
Constants may be defined and accessed anywhere without regard to variable scoping rules;
Constants may not be redefined or undefined once they have been set; and
Constants may only evaluate to scalar values.
For me, the main benefit is the global scope. I certainly don't worry about their efficiency - use them whenever you need a global scalar value which should not be alterable.


q:
Microsoft recently announced that the Javascript/HTML DOM library jQuery will be integrated into the ASP.NET MVC framework and into ASP.NET / Visual Studio.

What is the best practice or strategy adopting jQuery using ASP.NET 2.0? I'd like to prepare a large, existing ASP.NET Web Application (not MVC) for jQuery. How would I deal with versioning and related issues?

Are the any caveats integrating jQuery and ASP.NET Ajax? Or 3rd party components like Telerik or Intersoft controls?

[A]
There's a small issue which is mentioned by David Ward here:
http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/
But there should not be any major concerns about integrating jQuery into an existing application, you wouldn't notice major advantages unless you're planning a lot of updating/ reworking of existing code to take advantages of jQuerys power.


q:
last time I asked how to populate a data structure here. Now I would like to know if there's something in Java, like the print_r I use in PHP, to represent what I have populated in the Maps and lists without having to do my own algorithm.

Any ideas?

[A]
Calling
```
toString
```
on the collection should return a string containing all the elements string representations.
This won't work with built-in arrays though, as they don't have a
```
toString
```
override and will just give you a memory address.


q:
Background:
I am developing a site in Asp.net 2.0 . Up until now i was handling both the design and development of the site. I used css for the design part.
Now the company wants to outsource the design work to a web designer.

Question:
How exactly are a designer and developer supposed to coordinate
What specifications should i give to the web designer, Do i need to provide him with the aspx pages i have developed, does he also need to look at the code behind.

And how do i incorporate the designed pages in the existing aspx pages.

I would appreciate if someone who is experienced in this provides some insight

thanks.

[A]
How will the designer deliver their designs? Will they just provide the necessary graphic elements or will they deliver a valid HTML page? I would suggest you both agree on the DOM for the page and work from there.If they just provide graphics you have full control of the DOM.
The code behind model for .Net was supposed to help separate design and development but IMHO nothing has yet managed a perfect separation because you can't always make a 100% distinction.


q:
Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.

Particular order doesn't matter much here.

I generally know that I need to shift bits and truncate to the size of unsigned short int.  But I think I may make some weird mistake somewhere, so I ask.

[A]
```
```
#include <stdint.h>
#include <stdio.h>

union ui64 {
    uint64_t one;
    uint16_t four[4];
};

int
main()
{
    union ui64 number = {0x123456789abcdef0};
    printf("%x %x %x %x\n", number.four[0], number.four[1],
                            number.four[2], number.four[3]);
    return 0;
}
```
```


q: I am am trying to load a SQL table from a flat file. The flat i am talking about is a comma separated file. This has all the data required to populate a table will each column separated by a comma ",". I need some way by which i can load this content into the table faster.

[A]
If you are using SQL Server, use
```
BULK INSERT
```
If you are using Oracle, see my answer
here


q:
My favorite equation for centering an xhtml element using only CSS is as follows:

display: block;
position: absolute;
width: _insert width here_;
left: 50%;
margin-left: _insert width divided by two & multiplied by negative one here_

There's also the simpler margin:auto method in browsers that support it. Does anyone else have tricky ways to force content to display centered in its container? (bonus points for vertical centering)

edit - oops, forgot the 'negative' part of one in the margin-left. fixed.

[A]
Well that seems like massive overkill, I've got to say. I tend to set the container to
```
text-align:center;
```
for old browsers,
```
margin:auto;
```
for modern browsers, and leave it like that. Then reset text-align in the element (if it contains text).
Of course, some things need setting as block, and widths need setting... But what on earth are you trying to style that needs
that
much hacking around?
```
```

```
```


q:
In Oracle, I have set the log_archive_dest1='D:\app\administrator\orcl\archive' parameter and shutdown the database. When I tried to start up the db, I got the following error:

SQL> startup mount;

ORA-16032: parameter LOG_ARCHIVE_DEST_1 destination string cannot be translated

ORA-09291: sksachk: invalid device specified for archive destination

OSD-04018: Unable to access the specified directory or device.

O/S-Error: (OS 3) The system cannot find the path specified.

Does anyone have any ideas of how I might fix this?

[A]
I've never used Oracle but some things you might try are
Make sure the permissions on the file path you're using allow the database to read / write to it?
Make sure all the folders in the path already exist
On Windows you might find the '\' characters confuse the database. Do you specify other paths in the same way for Oracle? An alternative may be to use '/' instead of '\'. Different programs that originated in the Unix world handle Windows paths in different ways