q:
I am trying to hide some divs before the user prints this giant form, then display the divs again afterward. Thus I want to ignore the rest of the page, and only print the form itself.

Sure I could open a separate page when the user clicks the print button. The only thing is that the form is really long and it would be quite tedious to do that.

Edit: My previous question did not actually reflect what I was looking for. So I changed it to the current one.

Also thanks to all that suggested window.onbeforeprint and window.onafterprint. That was relevant to my edited question.

[A]
First, The Ok Way:
Take a look at window.onbeforeprint and window.onafterprint (the original question asked about how to do it programmatically I believe).
Now, the Better Way:
A better way to do this is with a style that is specifically for printing.  In other words, your div might look like this:
```
```

My Info

```
```
You would then have this in your stylesheet:
```
```
.someClass {font-family:arial;}
@media print {
    .noPrint { display: none; }
}
```
```
Another Option
You could also put this in a separate stylesheet if you wanted so you don't have to mix styles:
```
```
<link rel="stylesheet" type="text/css" media="print" href="print.css">
```
```
Your screen stylesheet could have ".someClass" defined one way and then your print stylesheet could have it defined a completely different way.


q:
How do I extend my parent's options array for child classes in PHP?

I have something like this:

class ParentClass {

     public $options = array(
          'option1'=>'setting1'
     );

     //The rest of the functions would follow
}

I would like to append to that options array in a child class without erasing any of the parent options. I've tried doing something like this, but haven't quite got it to work yet:

class ChildClass extends ParentClass {

     public $options = parent::options + array(
          'option2'=>'setting2'
     );

     //The rest of the functions would follow
}

What would be the best way to do something like this?

[A]
I think it is better practice to initialize this property in the constructor and then you can extend the value in any descendant class:
```
```
<?php
class ParentClass {

    public $options;
    public function __construct() {
        $this->options = array(
            'option1'=>'setting1'
        );
    }
    //The rest of the functions would follow
}

class ChildClass extends ParentClass {
    public function __construct() {
        parent::__construct();
        $this->options['option2'] = 'setting2';
    }
    //The rest of the functions would follow
}
?>
```
```

s: huggingface

c: devops

d: intermediate


q:
Currently, if I want to apply a method to a group of ActiveRecord objects, I have to structure the call like so:

messages = Message.find(:all)
csv = Message.to_csv(messages)

How can I define the method so it's structured like so?

messages = Message.find(:all)
csv = messages.to_csv

This is the current model code:

require 'fastercsv'
class Message < ActiveRecord::Base
  def Message.to_csv(messages)
    FasterCSV.generate do |csv|
      csv << ["from","to", "received"]
      for m in messages
        csv << [m.from,m.to,m.created_at]
      end
    end
  end
end

[A]
You could create a method on your Message class to do something along the lines of...
In your controller....
```
```
@csv_file = Message.send_all_to_csv
```
```
In your model...
```
```
require 'fastercsv'
class Message < ActiveRecord::Base
  def send_all_to_csv
    @messages = Find.all
    FasterCSV.generate do |csv|
      csv << ["from","to", "received"]
      for message in @messages
        csv << [message.from,message.to,message.created_at]
      end
    end
    # do something with your csv object (return it to the controller
    # or pass it on to another class method
  end
end
```
```


q:
In the spirit of questions like Do your loops test at the top or bottom?:

Which style do you use for an infinite loop, and why?

while (true) { }

do { } while (true);

for (;;) { }

label: ... goto label;

[A]
```
```
while(true) {}
```
```
It seems to convey the meaning of the loop most effectively.


q:
I currently capture MiniDumps of unhandled exceptions using SetUnhandledExceptionFilter however at times I am getting "R6025: pure virtual function".

I understand how a pure virtual function call happens I am just wondering if it is possible to capture them so I can create a MiniDump at that point.

[A]
See
this answer here
to the question
where do “pure virtual function call” crashes come from?
.
To help with debugging these kinds of
  problems you can, in various versions
  of MSVC, replace the runtime library's
  purecall handler. You do this by
  providing your own function with this
  signature:
```
```
int __cdecl _purecall(void)
```
```
and
  linking it before you link the runtime
  library. This gives YOU control of
  what happens when a purecall is
  detected. Once you have control you
  can do something more useful than the
  standard handler. I have a handler
  that can provide a stack trace of
  where the purecall happened; see here:
http://www.lenholgate.com/archives/000623.html
for more details.
(Note you can also call
```
_set_purecall_handler()
```
to install your handler in some versions of
  MSVC).
So, in your purecall handler, make your minidump.


q:
Thanks a million everyone for everyone's response.  Unfortunately, none of the solutions appear to be working on my end, and my guess is that the example I've provided is messed up.

So let me try again.

My table looks like this:

    contract    project activity
row1    1000    8000    10
row2    1000    8000    20
row3    1000    8001    10
row4    2000    9000    49
row5    2000    9001    49
row6    3000    9000    79
row7    3000    9000    78

Basically, the query I'm looking for would return "2000,49" for "contract, activity" because only contract #2000 has one, and ONLY one, unique activity value.

Again, thanks a million in advance,
boroatel

[A]
Updated to use your newly provided data:
The solutions using the original data may be found at the end of this answer.
Using your new data:
```
```
DECLARE  @T TABLE( [contract] INT, project INT, activity INT )
INSERT INTO @T VALUES( 1000,    8000,    10 )
INSERT INTO @T VALUES( 1000,    8000,    20 )
INSERT INTO @T VALUES( 1000,    8001,    10 )
INSERT INTO @T VALUES( 2000,    9000,    49 )
INSERT INTO @T VALUES( 2000,    9001,    49 )
INSERT INTO @T VALUES( 3000,    9000,    79 )
INSERT INTO @T VALUES( 3000,    9000,    78 )

SELECT DISTINCT [contract], activity FROM @T AS A WHERE
    (SELECT COUNT( DISTINCT activity )
     FROM @T AS B WHERE B.[contract] = A.[contract]) = 1
```
```
returns:
    2000, 49
Solutions using original data
WARNING:
The following solutions use the data previously given in the question and may not make sense for the current question.  I have left them attached for completeness only.
```
```
SELECT Col1, Count( col1 ) AS count FROM table
GROUP BY col1
HAVING count > 1
```
```
This should get you a list of all the values in col1 that are not distinct.  You can place this in a table var or temp table and join against it.
Here is an example using a sub-query:
```
```
DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )

INSERT INTO @t VALUES( 'A', 'B', 'C' );
INSERT INTO @t VALUES( 'D', 'E', 'F' );
INSERT INTO @t VALUES( 'A', 'J', 'K' );
INSERT INTO @t VALUES( 'G', 'H', 'H' );

SELECT * FROM @t

SELECT col1, col2 FROM @t WHERE col1 NOT IN
    (SELECT col1 FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) > 1)
```
```
This returns:
```
```
D   E
G   H
```
```
And another method that users a temp table and join:
```
```
DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )

INSERT INTO @t VALUES( 'A', 'B', 'C' );
INSERT INTO @t VALUES( 'D', 'E', 'F' );
INSERT INTO @t VALUES( 'A', 'J', 'K' );
INSERT INTO @t VALUES( 'G', 'H', 'H' );

SELECT * FROM @t

DROP TABLE #temp_table
SELECT col1 INTO #temp_table
    FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) = 1

SELECT t.col1, t.col2 FROM @t AS t
    INNER JOIN #temp_table AS tt ON t.col1 = tt.col1
```
```
Also returns:
```
```
D   E
G   H
```
```


q: How would you program a C/C++ application that could run without opening a window or console?

[A]
In windows:
```
```
#include <windows.h>

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    // <-- Program logic here
    return 0;
}
```
```
Be sure to use the /SUBSYSTEM linker switch as mentioned by Adam Mitz.
On other platforms:
```
```
int main(int argc, char**argv)
{
  // <-- Program logic here
  return 0;
}
```
```


q:
Possible Duplicate:

  How costly is .NET reflection?

I am currently in a programming mentality that reflection is my best friend. I use it a lot for dynamic loading of content that allows "loose implementation" rather than strict interfaces, as well as a lot of custom attributes.

What is the "real" cost to using reflection?

Is it worth the effort for frequently reflected types to have cached reflection, such as our own pre-LINQ DAL object code on all the properties to table definitions?

Would the caching memory footprint outwieght the reflection CPU usage?

[A]
Reflection requires a large amount of the type metadata to be loaded and then processed. This can result in a larger memory overhead and slower execution. According to
this article
property modification is about 2.5x-3x slower and method invocation is 3.5x-4x slower.
Here is an excellent
MSDN article
outlining how to make reflection faster and where the overhead is. I highly recommend reading if you want to learn more.
There is also an element of complexity that reflection can add to the code that makes it substantially more confusing and hence difficult to work with. Some people, like
Scott Hanselman
believe that by using reflection you often make more problems than you solve. This is especially the case if your teams is mostly junior devs.
You may be better off looking into the DLR (Dynamic Language Runtime) if you need alot of dynamic behaviour. With the new changes coming in .NET 4.0 you may want to see if you can incorporate some of it into your solution. The added support for dynamic from VB and C# make using dynamic code very elegant and creating your own dynamic objects fairly straight forward.
Good luck.
EDIT: I did some more poking around Scott's site and found this
podcast
on reflection. I have not listened to it but it might be worth while.


q:
I have a string.

string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";

I need to add a newline after every occurence of "@" symbol in the string.

My Output should be like this

fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@

[A]
Use
```
Environment.NewLine
```
whenever you want in any string. An example:
```
```
string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";

text = text.Replace("@", "@" + System.Environment.NewLine);
```
```


q: I have an array of shorts (short[]) that I need to write out to a file.  What's the quickest way to do this?

[A]
Use the BinaryWriter
```
```
static void WriteShorts(short[] values, string path)
    {
        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
        {
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                foreach (short value in values)
                {
                    bw.Write(value);
                }
            }
        }
    }
```
```


q: When submitting an app to the app store what is the real difference between iPod Touch and iPod Touch 2nd generation?

[A]
The first-gen iPod touch doesn't ship with iPhone OS 2.0, which is required to run App Store apps. End-users can purchase iPhone OS 2.0 for their first-gen iPod touch from Apple.
From an SDK perspective, I'm not sure what, if anything, has changed.


q:
I want to change the order of XML using XDocument

<root>
  <one>1</one>
  <two>2</two>
</root>

I want to change the order so that 2 appears before 1.  Is this capability baked in or do I have to do it myself.  For example, remove  then AddBeforeSelf()?

Thanks

[A]
This should do the trick. It order the child nodes of the root based on their content and then changes their order in the document. This is likely not the most effective way but judging by your tags you wanted to see it with LINQ.
```
```
static void Main(string[] args)
{
    XDocument doc = new XDocument(
        new XElement("root",
            new XElement("one", 1),
            new XElement("two", 2)
            ));

    var results = from XElement el in doc.Element("root").Descendants()
                  orderby el.Value descending
                  select el;

    foreach (var item in results)
        Console.WriteLine(item);

    doc.Root.ReplaceAll( results.ToArray());

    Console.WriteLine(doc);

    Console.ReadKey();
}
```
```


q:
I have a jQuery datepicker that I want to restrict non work days - weekends, public holidays etc. I have seen examples on how to do this from the client side (javascript), but is there a way to restrict the dates from server side ASP.NET code?

I figure you could do using Page.RegisterClientScriptBlock, but was wondering is there a neater way?

[A]
You just do it when you validate the data being posted, using the same logic you use client-side. You should always be validating data at server-side, NOTHING from the client side can EVER be trusted, even if you have "validation code" there and think you're requiring javascript to be on for it to work.
Doing validation client-side should be a secondary thing, just to provide a nice user experience. There is no security in any client-side code. (Go install firebug and/or the "tamper data" extensions for firefox if you don't believe me).


q:
Is there a better way to negate a boolean in Java than a simple if-else?

if (theBoolean) {
    theBoolean = false;
} else {
    theBoolean = true;
}

[A]
```
```
theBoolean = !theBoolean;
```
```


q:
This should a quick question for some easy rep.

I'm doing some PHP Website development, decided to check out and play around with jQuery as well. I don't want to install and manage a local PHP server/service, but I would like a quick one click method for automatically uploading the PHP file I'm working on to my hosting service so I can test it live.

I'm looking into some different editors like Komodo Edit, Notepad++ but I'm wondering what tool has the ability to one click FTP for me?

Edit after a few posts came in:

Well Shoot, Ultra Edit costs around $100, and Aptana allows you to upload to their "Cloud", but you have to purchase the cloud space. I already have my own server. I'll have look into BlueFish a bit more....Thanks for the help guys.

I'm thinking I might try using Notepad++ and just write a batch file to run windows built in FTP, make a connection and copy all the files in a folder in auto-overwrite mode. Seem feasible?

[A]
UEStudio
has integrated (S)FTP, SVN, etc, plus the ability to open a file over FTP - of course, it actually just downloads to a temp file, but each time you press save, it uploads it to the server again.
I'm pretty much obliged to point out just now that you might want to reconsider your decision to avoid a local development environment. Using
XAMPP
, it's ridiculously easy to set up a local web server. There are a multitude of benefits to this, far too many to list, even.


q:
I have been trying to learn how to add testing to existing code -- currently reading reading Working Effectively With Legacy Code.  I have been trying to apply some of the principles in JavaScript, and now I'm trying to extract an interface.

In searching for creating interfaces in JavaScript, I can't find a lot -- and what I find about inheritance seems like their are several different ways.  (Some people create their own base classes to provide helpful methods to make it easier to do inheritance, some use functions, some use prototypes).

What's the right way?  Got a simple example for extracting an interface in JavaScript?

[A]
There's no definitive
right way
, because so many people are doing so many different things..  There are many useful patterns.
Crockford
suggests that you "go with the grain", or write javascript in a way that corresponds to javascript's prototypal nature.
Of course, he goes on to show that the original model that Netscape suggested is actually broken.  He labels it "pseudoclassical", and points out a lot of the misdirection and unnecessary complexity that is involved in following that model.
He wrote the "object" function as a remedy (now known as Object.create() ).  It allows for some very powerful prototypal patterns.
It's not always easy to do develop a clean interface when you have to work with legacy javascript, especially not when you're dealing with large systems, usually including multiple libraries, and each implementing a unique style and different inheritance pattern.  In general, I'd say that the "right way" to do inheritance is the one which allows you to write a clean interface which behaves well in the context of your legacy code, but also allows you to refactor and eliminate old dependencies over time.
Considering the differences between the major library patterns, I've found that the most successful route to take in my own work is to keep my interfaces independent of the library interfaces entirely.  I'll use a library or module if it's helpful, but won't be bound to it.  This has allowed me to refactor a lot of code, phase out some libraries, and use libraries as scaffolding which can be optimized later.
Along these lines, I've written interfaces that were inspired by Crockford's parasitic inheritance pattern.  It's really a win for simplicity.
On the other side of the coin, I'm sure you could argue for picking a library, enforcing it across your team, and conforming to both its inheritance patterns and its interface conventions.


q:
I see this all the time in Ruby:

require File.dirname(__FILE__) + "/../../config/environment"

What does __FILE__ mean?

[A]
It is a reference to the current file name. In the file
```
foo.rb
```
,
```
__FILE__
```
would be interpreted as
```
"foo.rb"
```
.
Edit:
Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in
his comment
. With these files:
```
```
# test.rb
puts __FILE__
require './dir2/test.rb'
```
```
```
```
# dir2/test.rb
puts __FILE__
```
```
Running
```
ruby test.rb
```
will output
```
```
test.rb
/full/path/to/dir2/test.rb
```
```


q:
Is there a better/simpler way to find the number of images in a directory and output them to a variable?

function dirCount($dir) {
  $x = 0;
  while (($file = readdir($dir)) !== false) {
    if (isImage($file)) {$x = $x + 1}
  }
  return $x;
}

This seems like such a long way of doing this, is there no simpler way?

Note: The isImage() function returns true if the file is an image.

[A]
Check out the Standard PHP Library (aka SPL) for DirectoryIterator:
```
```
$dir = new DirectoryIterator('/path/to/dir');
foreach($dir as $file ){
  $x += (isImage($file)) ? 1 : 0;
}
```
```
(FYI there is an undocumented function called iterator_count() but probably best not to rely on it for now I would imagine. And you'd need to filter out unseen stuff like . and .. anyway.)


q:
I have a string encrypted in PHP that I would like to decrypt in C#.  I used the tutorial below to do the encryption, but am having problems decrypting.  Can anyone post an example on how to do this?

http://www.sanity-free.org/131/triple_des_between_php_and_csharp.html

[A]
Hope this helps:
```
```
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Decrypt("47794945c0230c3d"));
    }

    static string Decrypt(string input)
    {
        TripleDES tripleDes = TripleDES.Create();
        tripleDes.IV = Encoding.ASCII.GetBytes("password");
        tripleDes.Key = Encoding.ASCII.GetBytes("passwordDR0wSS@P6660juht");
        tripleDes.Mode = CipherMode.CBC;
        tripleDes.Padding = PaddingMode.Zeros;

        ICryptoTransform crypto = tripleDes.CreateDecryptor();
        byte[] decodedInput = Decoder(input);
        byte[] decryptedBytes = crypto.TransformFinalBlock(decodedInput, 0, decodedInput.Length);
        return Encoding.ASCII.GetString(decryptedBytes);
    }

    static byte[] Decoder(string input)
    {
        byte[] bytes = new byte[input.Length/2];
        int targetPosition = 0;

        for( int sourcePosition=0; sourcePosition<input.Length; sourcePosition+=2 )
        {
            string hexCode = input.Substring(sourcePosition, 2);
            bytes[targetPosition++] = Byte.Parse(hexCode, NumberStyles.AllowHexSpecifier);
        }

        return bytes;
    }
}
```
```


q:
I'm using a decimal column to store money values on a database, and today I was wondering what precision and scale to use.

Since supposedly char columns of a fixed width are more efficient, I was thinking the same could be true for decimal columns. Is it?

And what precision and scale should I use? I was thinking precision 24/8. Is that overkill, not enough or ok?

This is what I've decided to do:

Store the conversion rates (when applicable) in the transaction table itself, as a float

Store the currency in the account table

The transaction amount will be a DECIMAL(19,4)

All calculations using a conversion rate will be handled by my application so I keep control of rounding issues

I don't think a float for the conversion rate is an issue, since it's mostly for reference, and I'll be casting it to a decimal anyway.

Thank you all for your valuable input.

[A]
The money datatype on SQL Server has four digits after the decimal.
From SQL Server 2000 Books Online:
Monetary data represents positive or negative amounts of money. In Microsoft® SQL Server™ 2000, monetary data is stored using the money and smallmoney data types. Monetary data can be stored to an accuracy of four decimal places. Use the money data type to store values in the range from -922,337,203,685,477.5808 through +922,337,203,685,477.5807 (requires 8 bytes to store a value). Use the smallmoney data type to store values in the range from -214,748.3648 through 214,748.3647 (requires 4 bytes to store a value). If a greater number of decimal places are required, use the decimal data type instead.


q:
Uhm I'm not sure if anyone has encountered this problem

a brief description is on IE6 any <select> objects get displayed over any other item, even div's... meaning if you have a fancy javascript effect that displays a div that's supposed to be on top of everything (e.g: lightbox, multibox etc..) onclick of a certain element and that div overlaps a <select> your div get's to be displayed as if it's under the <select> [on this case a max and minimum z-index doesn't work ]

I've tried googling and found the iframe shim solution

but I wanted some pretty clean alternatives
or better yet has anyone found a better solution?
since the method using iframes uses around 130mb of ram might slow down poor people's machines

[A]
Prior to IE7 the drop down list was a "windowed" control meaning that it was rendered as a control directly by Windows rather than the browser synthesizing it. As such, it wasn't possible for it to support z-indexing against other synthesized controls.
In order to appear over a DDL, you must use another windowed control, like IFRAME. You can also use a little known IE-only feature called window.createPopup() which essentially makes a chromeless popup. It has limitations, like unstoppable click-out, but they are actually kinda helpful if you are building a hover menu system.


q:
I wonder if is possible to use FTS with LINQ using .NET Framework 3.5. I'm searching around the documentation that I didn't find anything useful yet.

Does anyone have any experience on this?

[A]
I don't believe so.  You can use 'contains' on a field, but it only generates a
```
LIKE
```
query.  If you want to use full text I would recommend using a stored proc to do the query then pass it back to LINQ


q:
I have always found this to be a very useful feature in Visual Studio.  For those who don't know about it, it allows you to edit code while you are debugging a running process, re-compile the code while the binary is still running and continue using the application seamlessly with the new code, without the need to restart it.

How is this feature implemented?  If the code I am modifying is in a DLL loaded by the application, does the application simply unload the DLL and reload it again?  This would seem to me like it would be prone to instability issues, so I assume it would be smarter than this.  Any ideas?

[A]
My
guess
is that it recompiles the app (and for small changes this wouldn't mean very much would have to be recompiled). Then since Microsoft makes both the compiler and debugger they can make guarantees about how memory and the like are laid out. So, they can use the debugging API to re-write the code segments with the new ones as long as the changes are small enough.
If the changes redirect to entirely new code, this can obviously be loaded into memory in a similar style as DLLs.
Microsoft also has a mechanism for "hot-patching". Functions have a 2 byte no-op instruction usually something like "mov edx, edx" before any real code. This allows them to redirect the execution of a function cleanly. This may be an option as well.
The key thing to remember is that the application isn't "running", all it's threads are in the stopped state. So as far as the process is concerned any modifications the debugger makes are entirely atomic.
Of course, this is all speculation ;)


q:
Short of putting a UIWebView as the back-most layer in my nib file, how can I add a repeating background image to an iPhone app (like the corduroy look in the background of a grouped UITableView)?

Do I need to create an image that's the size of the iPhone's screen and manually repeat it using copy and paste?

[A]
Apparently a UIColor is not necessarily a single color, but can be a pattern as well. Confusingly, this is not supported in Interface Builder.
Instead you set the backgroundColor of the view (say, in -viewDidLoad) with the convenience method +colorWithPatternImage: and pass it a UI Image. For Instance:
```
```
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"gingham.png"]];
}
```
```
Of course, don't forget to add the image file to your application bundle.
There are also some built-in background pattern "colors":
groupTableViewBackgroundColor
viewFlipsideBackgroundColor
Because the are used globally across all iPhone apps, you incur the double-edged sword of an OS update updating the look and feel of your application (giving it a fresh new look that may or may not work right).
For instance:
```
```
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
}
```
```


q: I am working on creating a daemon in Ruby using the daemons gem. I want to add output from the daemon into a log file. I am wondering what is the easiest way to redirect puts from the console to a log file.

[A]
Try
```
```
$stdout = File.new( '/tmp/output', 'w' )
```
```
To restore:
```
```
$stdout = STDOUT
```
```


q: How do you estimate a EAI project using Function point?

[A]
Well given that FP counting is based on storage and end user interface, not sure if its even meaningful for EAI (from what little I remember).
I would say you can't, at least not in a useful way. FP counting is generally viewed as a dubious practice of varying accuracy, doing it to an integration project would just add more fuzzyness.


q:
What is difference between Server.Transfer and Response.Redirect?

What are advantages and disadvantages of each?

When is one appropriate over the other?

When is one not appropriate?

[A]
```
Response.Redirect
```
simply sends a message
(HTTP 302)
down to the browser.
```
Server.Transfer
```
happens without the browser knowing anything, the browser request a page, but the server returns the content of another.


q:
I have a fingerprint image taken from a sliding scanner. However the output does not have clean background. It looks like this:

dirty http://img208.imageshack.us/img208/2622/dirtyie0.png

I want to remove the background so that further processing will be more accurate. Something like this:

cleaned http://img515.imageshack.us/img515/7530/cleanhh6.png

How to do that? What image processing technique (if any) can be used? Thank you.

[A] To start, I'd increase the contrast to 100% to get a pure black and white image (not greyscale).


q: I'm considering altering some tables to use nvarchar(50) as primary key instead of an int primary key. Using an int ID for a key really is irrelevant data, it's the string I'm interested in. What sort of performance hit will occur, or where do you research this? Other than cut and try that is.

[A]
Consider using a surrogate key (an int primary key) as the primary key/clustered index key. The trouble with using a nvarchar(50) as a primary key/clustered index key is that your table will be ordered by that key which means it is likely to get highly fragmented, and that any other indexes will have the burden of referencing this heavy primary key.
Another issue is that presumably you are needing to JOIN on other tables by this type of value which is a more expensive operation as the size of the key grows.
I think there are very few situations where an nvarchar(50) primary key would make sense.
Generally, primary keys should be a surrogate UNLESS you have a small natural immutable key. Arguably, SSN, for example, could be considered a natural immutable key.


q:
Given this HTML:

<div>foo</div><div>bar</div><div>baz</div>

How do you make them display inline like this:

foo bar baz

not like this:

foo

  bar

  baz

[A]
Try writing it like this:
```
```
div { border: 1px solid #CCC; }
```
```
```
```

a

b

c

```
```


q: I'm trying to program ARM using Eclipse + CDT + yagarto (gnu toolchain) + OpenOCD. In several sample projects (from yagarto site for example) I found linker scripts (*.ld) where a lot of linking information specified (along with sections definitions). Actually I haven't faced this files before (IAR doesn't need them), and I find them somewhat difficult to understand from a first glance. So my question is can I use one single such script file for my target processor (STR710FZ2T6) with all my projects or I have to get familiar in writing this scripts and write them for each project. If I can use single file for all projects for particular target processor can you please advice where I can find such universal one.

[A]
There is not a universal linker script. These scripts are very important, since they define where in memory (RAM or ROM) the various data and program sections will be placed. There is something equivalent in IAR compilers (xcl files if I remember correctly). You've obviously only used the default ones until now.
There is a nice document about STR7xx called "Using Open Source Tools for STR7xx Cross
Development". You can find a link in yagarto homepage. I recommend that you have a look at it and try to understand how linker files work. There are also some other configuration files that you need to have some understanding of.


q:
Recently I wrote an extremely basic Java Swing program with a couple of text fields and buttons. The program works fine for me on Ubuntu with Java 1.5. But when I try to run it on OSX (10.4), the main window is displayed correctly but the program seems unresponsive. Nothing seems to happen, no matter which button I click on.

I know next to nothing about Mac OSX, so is there something I might be doing wrong?

[A]
Could it be that you are executing something off the Event-Dispatch Thread? For example, you might be creating, displaying and then modifying a
```
JTextArea
```
in the
```
main
```
thread.


q:
Double out = otherTypes.someMethod(c, c2);
assertEquals((Double)-1.0D, out);

I get error "Double cannot be resolved" (the Double in assertEquals), is there any way to hack around it except extracting variable?

Is this bug in Java or just very usefull feature that wont be fix?

[A]
My variation is similar to jjnguy's
```
```
assertEquals(Double.valueOf(-1.0D), out)
```
```
This biggest difference is Double.valueOf can returned a cached copy rather than having to create a new object.


q: What is an external and internal iterator in Java ?

[A]
It is about
who controls the iteration
Other details are in this question
What are the benefits of the Iterator interface in Java?


q: What is the difference between a proxy server and a reverse proxy server?

[A]
My understanding from an
Apache
perspective is that proxy means that if site x proxies for site y, then requests for x return y.
The reverse proxy means that the response from y is adjusted so that all references to y become x.
So that the user cannot tell that a proxy is involved...


q: i want to get datetime for 2days before. i.e) how to subtract 2 days from datetime.now

[A]
I think you are just looking for:
```
```
DateTime.Now.AddDays(-2);
```
```


q:
I had setup my clients & server for passwordless login.
Like passwordless login by copying RSA key of server to all client's /root/.ssh/id-rsa.pub. but this, I have done manually. I like to automate this process using shell script and providing password to the machines through script.
If this problem is solved then I also want to use rsync to automate push items to all servers.
Can any body help me in this regard.

Thank you

[A]
This script comes in Debian (and derivatives) machines, to distribute the keys. It's called ssh-copy-id. You'd use it like this:
```
```
ssh-copy-id [-i identity_file] [user@]machine
```
```
Then you'd enter the password and the copying would be done. You would do this one time only and then could use the rsync over ssh as usual.
```
```
#!/bin/sh

# Shell script to install your identity.pub on a remote machine
# Takes the remote machine name as an argument.
# Obviously, the remote machine must accept password authentication,
# or one of the other keys in your ssh-agent, for this to work.

ID_FILE="${HOME}/.ssh/identity.pub"

if [ "-i" = "$1" ]; then
  shift
  # check if we have 2 parameters left, if so the first is the new ID file
  if [ -n "$2" ]; then
    if expr "$1" : ".*\.pub" ; then
      ID_FILE="$1"
    else
      ID_FILE="$1.pub"
    fi
    shift         # and this should leave $1 as the target name
  fi
else
  if [ x$SSH_AUTH_SOCK != x ] ; then
    GET_ID="$GET_ID ssh-add -L"
  fi
fi

if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
  GET_ID="cat ${ID_FILE}"
fi

if [ -z "`eval $GET_ID`" ]; then
  echo "$0: ERROR: No identities found" >&2
  exit 1
fi

if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
  exit 1
fi

{ eval "$GET_ID" ; } | ssh $1 "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1

cat <<EOF
Now try logging into the machine, with "ssh '$1'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

EOF
```
```


q:
I'm after some good tips for fluent interfaces in C#. I'm just learning about it myself but keen to hear what others think outside of the articles I am reading. In particular I'm after:

when is fluent too much?

are there any fluent patterns?

what is in C# that makes fluent interfaces more fluent (e.g. extension methods)

is a complex fluent interface still a fluent one?

refactoring to arrive at a fluent interface or refactoring an existing fluent interface

any good examples out there that you have worked with or could recommend?

If you could post one tip or thought, or whatever per post. I want to see how they get voted on, too.

Thank you in advance.

[A]
On your 4th point;
Yes I think that a complex fluent interface can still be fluent.
I think fluent interfaces are somewhat of a compromise. (although a good one!) There has been much research into using natural language for programming and generally natural language isn't precise enough to express programs.
Fluent interfaces are constructed so that they write like a programming language, only a small subset of what you can express in a natural language is allowed, but they read like a natural language.
If you look at rhino mocks for example the writing part has been complicated compared to a normal library. I took me longer to learn mostly due to the fluent interface but it makes code a lot easier to read. Because programs are usually written once and read a lot more than once this is a good tradeoff.
So to qualify my point a bit. A fluent interface that's complex to write but easy to read can still be fluent.


q: How do i make the plus minus icons bigger in the tree view in C# .net with out making visual styles disable.

[A]
I don't think you have any control about it. The only thing you can do is override the DrawNode event and paint the nodes yourself.
First you need to change the DrawMode to OwnerDrawAll. Take a look at the relevant msdn page, it contains surprisingly much detail:
http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.drawnode.aspx


q:
I am trying to create a user interface using XAML. However, the file is quickly becoming very large and difficult to work with. What is the best way for splitting it across several files.

I would like to be able to set the content of an element such as a ComboBox to an element that is defined in a different xaml file (but in the same VS project).

thanks

[A]
You can split up XAML files by using a
ResourceDictionary
. The ResourceDictionary can be used to merge other files:
```
```
<Page.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="myresourcedictionary.xaml"/>
      <ResourceDictionary Source="myresourcedictionary2.xaml"/>
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Page.Resources>
```
```
In the ResourceDictionary, you can also declare Styles that you can use at your elements, such that the main XAML file gets smaller.
Another possibility to get a smaller XAML file is to define your own controls that you then use in your main app.


q: In python how do you read multiple files from a mysql database using the cursor or loop one by one and store the output in a separate table?

[A]
I don't understand your question (what are files?, what's your table structure?), but here goes a simple sample:
```
```
>>> import MySQLdb
>>> conn = MySQLdb.connect(host="localhost",
                           user="root",
                           password="merlin",
                           db="files")
>>> cursor = conn.cursor()
>>> cursor.execute("SELECT * FROM files")
5L
>>> rows = cursor.fetchall()
>>> cursor.execute("CREATE TABLE destination (file varchar(255))")
0L
>>> for row in rows:
...   cursor.execute("INSERT INTO destination VALUES (%s)" % row[0])
...
1L
1L
1L
1L
1L
```
```


q:
I'm working on a project where we mix .NET code and native C++ code via a C++/CLI layer. In this solution I want to use Thread Local Storage via the __declspec(thread) declaration:

__declspec(thread) int lastId = 0;

However, at the first access of the variable, I get a NullReferenceException.
To be more precise, the declaration is done within a ref class (a .NET class implemented in C++/CLI).

I have already read something about __declspec(thread) does not work with delay loaded DLLs.
Am I using delay loaded DLLs automatically if I use .NET?

[A]
It seems that __declspec(thread)
isn't supported by CLR
.
Take in mind that .net threads aren't necesarily native threads,
but can be also fibers
, so standard API's for threads don't work on them.
If you have a managed class, then you should use managed threading API's for
thread local storage
.
There are a lot of articles regarding this difference. This is just to get you started.
As a tip: You could use the ThreadStatic Attribute instead of the TLS in order to improve
performance
. In case you are working with ASP.NET applications, you need to remember
some things
about TLS.


q:
I am working with a larger than average sqlite database (for use on both on windows and linux) and am looking to maximize the performance I get out of it. The database is to be installed on commodity hardware along with an sqlite gui. The users I am delivering this to are sql savvy but are unlikely to undertake their own optimizations (creation of indexes, setting of pragma etc.) so I am keen to get as much out of the box performance as possible (to ensure maximum usage of the data).

One issue Windows seems to throttle the execution of queries much more than Linux and another is that I am less familiar with sqlite's approach to indexing (compared to other databases such as postgres).

[A]
Have you read the
SQLite Optimization FAQ
(a few years old, but still seems useful)?
I don't think 1gb is particularly large, even for SQLite.  It can certainly handle much larger databases stably.


q:
I have a large script file (nearly 300MB, and feasibly bigger in the future) that I am trying to run.  It has been suggested in the comments of Gulzar's answer to my question about it that I should change the script timeout to 0 (no timeout).

What is the best way to set this timeout from within the script?  At the moment I have all of this at the top of the script file in the hopes that one of them does something:

sp_configure 'remote login timeout', 600
go
sp_configure 'remote query timeout', 0
go
sp_configure 'query wait', 0
go
reconfigure with override
go

However, I'm still getting the same result and I can't tell if I'm succeeding in setting the timeout because the response from sqlcmd.exe is the world's least helpful error message:

Sqlcmd: Error: Scripting error.

[A]
I think there is
no concept of timeout within a SQL script
on SQL Server. You have to set the timeout in the calling layer / client.
According to
this MSDN article
you could try to increase the timeout this way:
```
```
exec sp_configure 'remote query timeout', 0
go
reconfigure with override
go
```
```
"Use the remote query timeout option to specify how long, in seconds, a remote operation can take before Microsoft SQL Server times out. The default is 600, which allows a 10-minute wait. This value applies to an outgoing connection initiated by the Database Engine as a remote query. This value has no effect on queries received by the Database Engine."
P.S.: By 300 MB you mean the resulting file is 300 MB? I don't hope that the script file itself is 300 MB. That would be a world record. ;-)


q:
I'm wondering if there are any simple ways to get a list of all fixed-width (monospaced) fonts installed on a user's system in C#?

I'm using .net 3.5 so have access to the WPF System.Windows.Media namespace and LINQ to get font information, but I'm not sure what I'm looking for.

I want to be able to provide a filtered list of monospaced fonts and/or pick out monospaced fonts from a larger list of fonts (as seen in the VS options dialog).

[A]
AFAIK you can't do it using BCL libraries only. You have to use WinAPI interop.
You need to analyze 2 lowest bits of
LOGFONT
.lfPitchAndFamily member. There is a constant FIXED_PITCH (means that font is fixed-width) that can be used as a bit mask for lfPitchAndFamily.
Here is a useful article:
Enumerating Fonts
Enumerating fonts can be a little
  confusing, and unless you want to
  enumerate all fonts on your system,
  can be a little more difficult than
  MSDN suggests. This article will
  explain exactly the steps you need to
  use to find every fixed-width font on
  your system, and also enumerate every
  possible size for each individual
  font.


q:
I know it's simple to implement, but I want to reuse something that already exist.

Problem I want to solve is that I load configuration (from XML so I want to cache them) for different pages, roles, ... so the combination of inputs can grow quite much (but in 99% will not). To handle this 1%, I want to have some max number of items in cache...

Till know I have found org.apache.commons.collections.map.LRUMap in apache commons and it looks fine but want to check also something else. Any recommendations?

[A]
You can use a
LinkedHashMap
(Java 1.4+) :
```
```
// Create cache
final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
    // This method is called just after a new entry has been added
    public boolean removeEldestEntry(Map.Entry eldest) {
        return size() > MAX_ENTRIES;
    }
};

// Add to cache
Object key = "key";
cache.put(key, object);

// Get object
Object o = cache.get(key);
if (o == null && !cache.containsKey(key)) {
    // Object not in cache. If null is not a possible value in the cache,
    // the call to cache.contains(key) is not needed
}

// If the cache is to be used by multiple threads,
// the cache must be wrapped with code to synchronize the methods
cache = (Map)Collections.synchronizedMap(cache);
```
```


q:
Is it possible to do the equivalent of the following in xslt:

.//TagA[./TagB/[@AttrA='AttrAValue'] = 'TagBValue']

This is failing within Visual Studio 2008 with the following error:

error: Unexpected token '[' in the expression.
.//TagA[./TagB/ -->[<-- @AttrA='AttrAValue'] = 'TagBValue']

Should this be working? Is this a problem in the MS implementation of XSLT, or is there a way I can get all TagA nodes that have a TagB node whose AttrA is equal to AttrAValue and whose TagB innerText is equal to TagBValue.


q:
What is the best way to find out whether two number ranges intersect?

My number range is 3023-7430, now I want to test which of the following number ranges intersect with it: <3000, 3000-6000, 6000-8000, 8000-10000, >10000. The answer should be 3000-6000 and 6000-8000.

What's the nice, efficient mathematical way to do this in any programming language?

[A]
Just a pseudo code guess:
```
```
Set<Range> determineIntersectedRanges(Range range, Set<Range> setofRangesToTest)
{
  Set<Range> results;
  foreach (rangeToTest in setofRangesToTest)
  do
    if (rangeToTest.end <range.start) continue; // skip this one, its below our range
    if (rangeToTest.start >range.end) continue; // skip this one, its above our range
    results.add(rangeToTest);
  done
  return results;
}
```
```


q:
for example, I have the following xml document:

def CAR_RECORDS = '''
    <records>
      <car name='HSV Maloo' make='Holden' year='2006'/>
      <car name='P50' make='Peel' year='1962'/>
      <car name='Royale' make='Bugatti' year='1931'/>
    </records>
'''

and I want to move the car "Royale" up to first one, and insert a new car just after car"HSV Maloo", the result would be:

'''
    <records>
      <car name='Royale' make='Bugatti' year='1931'/>
      <car name='HSV Maloo' make='Holden' year='2006'/>
      <car name='My New Car' make='Peel' year='1962'/>
      <car name='P50' make='Peel' year='1962'/>
    </records>
'''

How to do it with Groovy? comments are welcome.

[A]
<hand-wave>
these are not the codz you seek
</hand-wave>
```
```
Node root = new XmlParser().parseText(CAR_RECORDS)
NodeList carNodes = root.car
Node royale = carNodes[2]
carNodes.remove(royale)
carNodes.add(0, royale)
carNodes.add(2, new Node(root, 'car', [name:'My New Card', make:'Peel', year:'1962']))
```
```
I don't know if there's a smarter way to create new nodes... but that works for me.
EDIT: uhg... thanks guys... I got lazy and was printing carNodes when i tested this instead of the root... yikes.


q:
Imagine you're creating a presentation that will be translated into a dozen different languages, including ones with non-latin characters (Chinese, for instance). The client's branding style guide dictates that certain fonts are acceptable for certain languages. The content itself is required to be externalized, so that the text can be replaced without ever opening a .fla, or re-saving a graphic.

So we're talking dynamic TextField s, populated from XML, with the font swapped out to accommodate the viewer's locale - what's the most painless way to dynamically load only the fonts required (regardless of the filesize), and apply them as necessary? I'm looking for solutions using Flash only, not Flex.

[A]
Well, you'll some how have to know what language you're loading. Autodetection can be quite difficult.
Assuming you know what language the content is you can register fonts to be used in runtime using
Font.registerFont()
; With this you can load a swf that contains a font, register it, and it's available for future use in all textfields.
print("code sample");
```
```
[Embed(src="someFont.ttf", fontFamily="myFont", mimeType="application/x-font")]
private var fontClass:Class;

...

Font.registerFont(fontClass);
```
```
Note that you'll have to compile using the flex compiler to support the Embed tag.
A good utility in addition is
Font.hasGlyphs()
, which you can use to check if the characters you are using are available in an embedded fonts. This can be used to either jump back to a system font or display a warning to you as the developer (if you forgot some characters or whatever). Subclassing TextField to do this check automatically may be a good idea.
If this is going to be online, in general embedding Chinese is something you should think about twice. Embedding all characters will increase the filesize
a lot
and afaik there aren't that many complete Chinese fonts available anyway. The technique above is of course still useful for many other languages.


q:
What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just

String content = new File("test.txt").readFully();

[A]
```
```
String content = (new RandomAccessFile(new File("test.txt"))).readUTF();
```
```
Unfortunately Java is very picky about the source file being valid UTF8 though, or you will get an EOFException or UTFDataFormatException.


q:
What is the difference between private and protected members in C++ classes?

I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC seems to favor protected.

What's the difference and which should I use?

[A]
Private members are only accessible within the class defining them.
Protected members are accessible in the class that defines them and in classes that inherit from that class.
Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.
Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check
C++ FAQ
for a better understanding of the issue.
This question about protected variables
might also help.


q:
I have a string (char) and I want to extract numbers out of it.

So I have string: 1 2 3 4 /0

And now I want some variables, so I can use them as integer: a=1, a=2, a=3, a=4

How can I do that?

[A]
sscanf() can do that.
```
```
#include <stdio.h>

int main(void)
{
  int a, b, c, d;
  sscanf("1 2 3 4", "%d %d %d %d", &a, &b, &c, &d);
  printf("%d,%d,%d,%d\n", a, b, c, d);
}
```
```


q:
What is the "canonical" way to access the MessageContext from a PayloadEndpoint?

We are using PayloadEndpoint and AbstractMarshallingPayloadEndpoint which do not expose the MessageContext to their invoke / invokeinternal methods, but will now need to access the HTTP request parameters.

[A]
Easiest way I can think of: create a 'wrapper' endpoint which implements
MessageEndpoint
. Then you can extract your request parameters and pass them down to your actual endpoint.
You could store the request variables in a ThreadLocal so the original endpoint can access them.


q:
When debugging in Internet Explorer, I first get an alert box with extremely limited if not useless information (sorry IE) and choose to debug it. After selecting yes, I get another option every time to choose between 'New instance of Microsoft script debugger' and 'New instance of Visual Studio'. I'm fed up with having to click the yes button again after having clicked it once already on the alert box.

Update: I found that you can disable the Microsoft script debugger from within its own options; just disabling the JIT debugger from Tools -> Options, and JIT. This stops it appearing on the menu but now I get the dialog box asking me which one to choose and it only displays the Visual Studio - WHY? If there's only one option and you've already asked me if I want to debug, why ask again?!?! Bleh.

Can you tell I'm getting sick of clicking, "yes" twice? Lol.

[A]
Maybe not the complete solution, but you could try to set the default script debugger can be set
in the registry
directly. To do so, follow these steps:
Click Start, Run and type regedit.exe
Navigate to the following branch:
HKEY_CLASSES_ROOT \ CLSID \ {834128A2-51F4-11D0-8F20-00805F2CD064} \ LocalServer32
Backup the branch by exporting it to a file
In the above key, double-click (default) and set its value data to:
"C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"
(or whatever your path to devenv.exe is)
Exit the Registry Editor.


q: I am using a native library which returns an IntPtr to a memory location, which contains the value of an attribute.  I know what the type of the attribute is and I have a method for marshalling a value (taking the IntPtr and the type of the attribute) from the memory pointed at by the pointer.  This method either calls Marshal.ReadInt32, or reads a series of bytes and converts them to a double, or reads a string with Marshal.PtrToStringUni etc etc.  I would like to write some unit tests for this method but am not sure how I go about creating the IntPtr to pass to the method.  I'm using NUnit and cannot use a mocking framework.

[A]
If I understood correctly, you want to unit-test your logic of deserializing, given an IntPtr.
If that is the case, all you have to do is have copies of the different combinations of serialized output to test each unique path. For each test, obtain the IntPtr to a possible serialized entity, call your method and verify expected results.
Something like obtaining pointers to an area in memory. Hold the serialized output in a string and obtain an Intptr from it.  GCHandle looks like something you need here. (never tried this though)
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.gchandle.tointptr.aspx


q:
I'm currently looking for a possibility in Java to identify a font as symbolic like OpenOffice does.
Characters with the font Windings or Webdings and so on should be rendered with the correct "pictures".

Anyone an idea how to distinguish between normal fonts and fonts with symbols?

[A]
The bug
Java doesn't display all characters in the windows symbol font
gives a clue regarding a characteristic which is unique to symbol fonts.
They are part of
SYMBOL_CHARSET
(a WindowsCharsetName of a font.properties file)
So the [jdk1.6.0_10]\jre\lib\fontconfig.98.properties.src could be a first source of information to establish if a name of a font matches a symbol font, and should be loaded through
Property.load()
.


q: Is this possible? I am looking forward to a tutorial which explains the steps to achieve this.

[A]
TestDriven.NET
has the ability to test (NUnit/MSTest/etc) with Team Coverage (which you already have since you have Team System : Dev).
Walkthrough:
here
(you also get the coverage results window for looking at the coverage per method) - but this says it all:
(source:
mutantdesign.co.uk
)
You can use NUnit tests, but use the MS IDE integration for colorization, percentagaes, etc (no need for NCover). I use this all the time ;-p
The advantages are:
no need to set up a "Test Run Configuration" (sorry, MSFT, but an own-goal there)
fully integrated with VS (Code Coverage Results and Coloring)
easy to use (just right-click -> Test With -> Team Coverage)
easy to debug too (right-click -> Test With -> Debugger)
easy to use the separate NUnit/NCover apps if you want  (right-click etc)


q:
I've been reading up on conditional-style expressions in ruby. However I came across one I couldn't quite understand to define the classic FizzBuzz problem. I understand the FizzBuzz problem and even wrote my own before finding the following quick solution utilising the ternary operator. If someone can explain to me how this chain works to satisfy the FizzBuzz problem it would be very much appreciated :)

for i in 0...100
  puts i%3==0 ? i%5==0 ? "FizzBuzz" : "Buzz" : i%5==0 ? "Fizz" : i
end

[A]
Some parentheses might help:
```
```
puts (i%3 == 0) ? ((i%5 == 0) ? "FizzBuzz" : "Buzz") : ((i%5 == 0) ? "Fizz" : i)
```
```
So, if i is divisible by 3, then it checks whether i is also divisible by 5. If so, it prints "FizzBuzz" otherwise just "Buzz". If i is not divisible by three, then it checks divisibility by 5 again and prints "Fizz" if so, otherwise just i.


q:
How do I get the KeyDown event to work in a Delphi (2007) MDI Applications Parent window, even if a Child window  has focus?

I would like to implement a shortcut key (F1) that brings up a help screen in a MDI application, I have added the KeyDown procedure to the MDI Parent window and enabled KeyPreview in both the Parent and Child windows, but it does not work as expected.

If I put a break point in the Parents KeyDown code I can see it never executes, even it there are no child windows open. But if I add the same code to the child window it works fine.

Is there a way to get the parent window to receive the key presses, even if the child window has focus, as adding the code to 25+ forms seams a little wasteful?

[A]
You could use a local (global is not needed)
keyboard hook
. You could also derive all your MDI Child forms from a signle form base class and implement it there once. You will find that this design comes in handy for other problems as well.
edit
Application wide hotkeys/shortcuts can also be implemented with the TApplication.OnShortCut event. See
http://delphi.about.com/od/adptips2004/a/bltip0904_3.htm
F1 is already the standard help shortcut which triggers TApplication.OnHelp. So maybe you want to use the OnHelp event? And if you use the HelpFile, HelpContext, HelpType and HelpKeyword properties you probably don't even need to implement any code at all.


q: I am making an web based appliaction in java (using jsp). When the appliaction is invoked login page will come, when the user enter the valid credientials, he will be taken to the index page. But the problem is, when the login is success, the index page is coming but it is opening behind the login page. (means login page appears on the top of the monitor, I want index page should appear on the top of the window.) Can anyone help me out in this...Please


q:
Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format

Sun, 06 Nov 1994 08:49:37 GMT

Using strftime does not work, since the strings are locale-dependant. Do I have to build the string by hand?

[A]
You can set LC_TIME to force stftime() to use a specific locale:
```
```
>>> locale.setlocale(locale.LC_TIME, 'en_US')
'en_US'
>>> datetime.datetime.now().strftime(locale.nl_langinfo(locale.D_T_FMT))
'Wed 22 Oct 2008 06:05:39 AM '
```
```


q:
Why can't we initialize members inside a structure ?

example:

struct s {
   int i = 10;
};

[A]
If you want to initialize
non-static
members in
```
struct
```
declaration
:
In C++ (not C),
```
structs
```
are almost synonymous to classes and can have members initialized in the constructor.
```
```
struct s {
    int i;

    s(): i(10)
    {
    }
};
```
```
If you want to initialize an
instance
:
In C or C++:
```
```
struct s {
    int i;
};

...

struct s s_instance = { 10 };
```
```
C99 also has a feature called designated initializers:
```
```
struct s {
    int i;
};

...

struct s s_instance = {
    .i = 10,
};
```
```
There is also a GNU C extension which is very similar to C99 designated initializers, but it's better to use something more portable:
```
```
struct s s_instance = {
    i: 10,
};
```
```


q:
I'm starting to look into the whole world of RJS and Prototype/jQuery in Rails and am a little bit confused. There seems to be no clear line of where to use one or the other.

Say I wanted one of the "Active, Hot, Week" tabs like the ones here on SO. When pressing one of them, I want to remove a CSS class (like "active-tab") from the one I was on and add it to the one I clicked on. Then I also want to reload the div containing the items and put in the new items into it.

Seems the class-changing thing would be easiest to do in pure javascript, say put the code in application.js and then updating the div with the content would obviously be easiest in RJS. But what should one do?

[A]
If you want to give users that ability to link to the generated page directly, then definitly go for a static page. Using AJAX breaks the back button unless you use something like
Really Simple History
(
which is not 100% cross browser
), so
going the JS route with your page navigation
will almost certainly cause some of your users problems.
That said, what you have discussed already would be fine, I think - just have a class change in your RJS file, then you might even find it useful to update the div contents using page.replace and a partial:
```
```
page.replace(dom_id, :partial => @page_content);
```
```


q:
<td title="this is a really long line that I'm going to truncate">this is a really long line that I'm going to trunc ...</td>

Is this the correct way to do it?

[A] Yes, that's how you supposed to assign tooltips to html elements. I wouldn't use it on <td> though. Although I haven't tested it, I have the feeling that you might run into issues on some browsers if you use it on table rows/cells directly since these elements have somewhat different behaviour from other elements. You should rather  use it on more "regular" elements, for example <div>, <span>, <img>  or <input>.


q:
We are team of few Delphi developers who have been using VSS since years (I know it's a pity), but we don't use any of the advanced features of VCS, so it was working fine in many cases (but some times it was driving me crazy :( ).

The good thing that we have with  VSS that we use third-party plug-ins to integrate VSS with Delphi, which is working great, but now when our projects becomes larger, and we would like to move a way from VSS.

I have looked at few other VCS (free and commercial) and found most of them seems be made for Linux guys, and you have to use command line for many admin work(I know I'm windows guy :P).

What I'm looking for the new Version control that it should be easy to use and to maintain and Integrated nicely with Delphi IDE (D2007), or at least have a good UI for the Admins an developers.

[A]
Just use
SVN
and an excellent
TortoiseSVN
client which integrates with the Windows Explorer.
P.S. Found this question:
What is the best set of tools to develop Win32 Delphi applications?
and this Delphi IDE/TortoiseSVN integration tools in one of the answers:
http://delphiaddinfortortoisesvn.tigris.org/


q:
I'm tryint to post to a ADO.NET Data Service but the parameters seems to get lost along the way.

I got something like:

[WebInvoke(Method="POST")]
public int MyMethod(int foo, string bar) {...}

and I make an ajax-call using prototype.js as:

var args = {foo: 4, bar: "'test'"};
new Ajax.Requst(baseurl + 'MyMethod',
  method: 'POST',
  parameters: args,
  onSuccess: jadda,
  onFailure: jidda
}

If I replace "method: 'POST'" with "method: 'GET'" and "WebInvoke(Method="POST")" with "WebGet" everything works but now (using post) all I get is:

Bad Request - Error in query syntax.

from the service.

The only fix (that I don't want to use) is to send all parameters in the URL even when I perform a post. Any ideas are welcome.

[A]
If you want to use POST, you need to specify the parameters to be wrapped in the request in WebInvoke attribute unless the parameters contains on object (e.g. message contract). This makes sense since there is no way to serialize the parameters without wrapped in either json or xml.
Unwrapped which is not XML indeed as missing root element
```
```
<foo>1</foo>
<bar>abc</bar>
```
```
Wrapped, valid XML
```
```
<Request>
   <foo>1</foo>
   <bar>abc</bar>
</Request>
```
```
This sample also applies to JSON


q:
I recently upgraded a c# windows service to run as a 64 bit .net process. Normally, this would be trivial, but the system makes use of a 32-bit DLL written in C++. It is not an option to convert this DLL to 64 bit, so I wrapped the DLL in a separate 32 bit .net process and exposed a .net interface via remoting.

This is quite a reliable solution, but I would prefer to run the system as a single process. Is there any way I can load my 32 bit DLL into a 64 bit process and access it directly (perhaps through some sort of thunking layer)?

[A]
No, you can't.
Both 16-bit and 32-bit Windows lived in a 32-bit linear address space. The terms 16 and 32 refer to the size of the offset relative to the selector.
...
First, notice that a full-sized 16-bit pointer and a 32-bit flat pointer are the same size. The value 0x0123:0x467 requires 32 bits, and wow, so too does a 32-bit pointer. This means that data structures containing pointers do not change size between their 16-bit and 32-bit counterparts. A very handy coincidence.
Neither of these two observations holds true for 32-bit to 64-bit thunking. The size of the pointer has changed, which means that converting a 32-bit structure to a 64-bit structure and vice versa changes the size of the structure
. And the 64-bit address space is four billion times larger than the 32-bit address space. If there is some memory in the 64-bit address space at offset 0x000006fb`01234567, 32-bit code will be unable to access it. It's not like you can build a temporary address window, because 32-bit flat code doesn't know about these temporary address windows; they abandoned selectors, remember?
http://blogs.msdn.com/oldnewthing/archive/2008/10/20/9006720.aspx


q:
vi treats dash - and space   as word separators for commands such as dw and cw.

Is there a way to add underscore _ as well?

I quite often want to change part of a variable name containing underscores, such as changing src_branch to dest_branch. I end up counting characters and using s (like 3sdest), but it would be much easier to use cw (like cwdest).

[A]
You could type
```
cf_dest_
```
and save the counting part.
Edit:
or as suggested:
```
ct_
```
changes text until right before the underline character. (I'm using the
```
f
```
motion more, so it came more naturally to me)
Or you could redefine
```
'iskeyword'
```
(
```
:help iskeyword
```
for details).


q:
Currently I am working with a custom regular expression validator (unfortunately).

I am trying to set the Regex pattern using a server side inline script like this:

ValidationExpression="<%= RegExStrings.SomePattern %>"

However, the script is not resolving to server side code. Instead it is being interpreted literally and I end up with something like this in the rendered markup:

ctl00_DefaultContent_regexValidatorInvitation.validationexpression = "<%= RegExStrings.SomePattern %>";

Any clues as to why this is not resolving properly?

[A]
Values in a web control do not render server side code.
Rather set that from the Code Behind
```
```
RegExValidator1.ValidationExpression = RegExStrings.SomePattern;
```
```


q:
I'm writing a tool to report information about .NET applications deployed across environments and regions within my client's systems.

I'd like to read the values of assembly attributes in these assemblies.

This can be achieved using Assembly.ReflectionOnlyLoad, however even this approach keeps the assembly loaded.  The issue here is that I cannot load two assemblies that have the same name from different paths, so naturally I can't compare the same application deployed in different systems.

At this point I'm assuming the solution will involve using temporary AppDomains.

Can someone detail how to load an assembly into another AppDomain, read the attributes from it and then unload the AppDomain?

This needs to work for assemblies on the file system as well as those at URL addresses.

[A]
From the
MSDN documentation of System.Reflection.Assembly.ReflectionOnlyLoad (String)
:
The reflection-only context is no
  different from other contexts.
  Assemblies that are loaded into the
  context can be unloaded only by
  unloading the application domain.
So, I am afraid the only way to unload an assembly is unloading the application domain.
To create a new AppDomain and load assemblies into it:
```
```
public void TempLoadAssembly()
{
    AppDomain tempDomain = AppDomain.CreateDomain("TemporaryAppDomain");
    tempDomain.DoCallBack(LoaderCallback);
    AppDomain.Unload(tempDomain);
}

private void LoaderCallback()
{
    Assembly.ReflectionOnlyLoad("YourAssembly");
    // Do your stuff here
}
```
```


q:
I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492').

In other words, I need to add correct amount of leading zeros to the number.

int n = 999;
string str = some_function(n,6);
//str = '000999'

Is there a function like this in C++?

[A]
There are many ways of doing this. The simplest would be:
```
```
int n = 999;
char buffer[256]; sprintf(buffer, "%06d", n);
string str(buffer);
```
```


q: Yes, I know you could use regular objects as associative arrays in JavaScript, but I'd like to use something closer to java's Map's implementation (HashMap, LinkedHashMap etc). Something that could have any kind of data used as key. Are there any good hash(code/table) in JavaScript implementation out there?

[A]
In javascript,
objects are literally a hash implementation
.  A Java HashMap will be a little bit of a fake-out, so I'd
challenge you
to re-think your needs.
The
straight answer is no
, I don't believe that there is a great implementation of Java's HashMap in javascript.  If there is, it's bound to be part of a library that you may or may not want to use, and you certainly
don't need to include a library
just to have a little hash table.
So let's go ahead and write one, just to
examine the problem
. You can use it if you like.  We'll just start by writing a constructor, and we'll piggyback off of Array, which is Object, but has some useful methods that will keep this example from getting too tedious:
```
```
function HashMap () {
    var obj = [];
    return obj;
}

var myHashMap = HashMap();
```
```
We'll add some methods straight from the world of Java, but translate into javascript as we go...
```
```
function HashMap() {
    var obj = [];
    obj.size = function () {
        return this.length;
    };
    obj.isEmpty = function () {
        return this.length === 0;
    };
    obj.containsKey = function (key) {
        for (var i = 0; i < this.length; i++) {
            if (this[i].key === key) {
                return i;
            }
        }
        return -1;
    };
    obj.get = function (key) {
        var index = this.containsKey(key);
        if (index > -1) {
            return this[index].value;
        }
    };
    obj.put = function (key, value) {
        if (this.containsKey(key) !== -1) {
            return this.get(key);
        }
        this.push({'key': key, 'value': value});
    };
    obj.clear = function () {
        this = null;  // Just kidding...
    };
    return obj;
}
```
```
We could continue to build it out, but I think it's the wrong approach.  At the end of the day, we end up using what javascript provides behind the scenes, because we just simply don't have the HashMap type.  In the process of
pretending
, it lends itself to all kinds of
extra work
.
It's a bit ironic that one of the things that makes javascript such an interesting and diverse language is the ease with which it handles this kind of
wrestling
.  We can literally do anything we'd like, and the quick example here does nothing if it doesn't illustrate the deceptive power of the language.  Yet given that power, it seems
best not to use it
.
I just think javascript wants to be lighter.  My personal recommendation is that you re-examine the problem before you try implement a proper Java HashMap.
Javascript neither wants nor affords for one
.
Remember the native alternative
:
```
```
var map = [{}, 'string', 4, {}];
```
```
..so fast and easy by comparison.
On the other hand, I don't believe that there are any hard-and-fast answers here.  This implementation really
may be a perfectly acceptable solution
.  If you feel you can use it, I'd say
give it a whirl
.  But I'd never use it if I felt that we have
reasonably simpler and more natural means
at our disposal.. which I'm almost certain that we do.
Sidenote:
Is efficiency related to style? Notice the
performance hit
.. there's a big O staring us in the face at HashMap.put()... The less-than-optimal performance probably isn't a show-stopper here, and you'd probably need to be doing something very ambitious or have a large set of data before you'd even notice a performance hickup a modern browser.  It's just interesting to note that operations tend to become less efficient when you're working against the grain, almost as if there is a natural entropy at work.  Javascript is a high level language, and should offer efficient solutions when we keep in line with its conventions, just as a HashMap in Java will be a much more natural and high performing choice.


q:
How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?

$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);

$C = array_intersect($A,$B);  //equals (1,2,3,4)
$A = array_diff($A,$B);       //equals (5,6,7,8)

Is this the simplest way or is there a way to use another function that I haven't thought of?  My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.

[A]
You've got it. Just use
```
array_diff
```
or
```
array_intersect
```
. Doesn't get much easier than that.
Edit:
For example:
```
```
$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);
```
```
Source


q:
I have a List of strings that is regenerated every 5 seconds. I want to create a Context Menu and set its items dynamically using this list.
The problem is that I don't have even a clue how to do that and manage the Click action for every item generated (which should use the same method with different parameter DoSomething("item_name")).

How should I do this?

Thanks for your time.
Best regards.

[A]
So, you can clear the items from the context menu with:
```
```
myContextMenuStrip.Items.Clear();
```
```
You can add an item by calling:
```
```
myContextMenuStrip.Items.Add(myString);
```
```
The context menu has an ItemClicked event.  Your handler could look like so:
```
```
private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
    DoSomething(e.ClickedItem.Text);
}
```
```
Seems to work OK for me.  Let me know if I misunderstood your question.


q: With VS2005, I want to create a DLL and automatically export all symbols without adding __declspec(dllexport) everywhere, and without hand-creating .def files. Is there a way to do this?

[A]
No, you will need a macro that resolves to
```
__declspec(dllexport)
```
when it's included by the .cpp file that implements the exported functions, and resolves to
```
__declspec(dllimport)
```
otherwise.


q: I just realized from an article in CACM that Doxygen works with Java (and several other languages) too. But Java has already the Javadoc tool. Can someone explain what are the pros and cons of either approach? Are they mutually exclusive? Is there a Maven plugin for Doxygen?

[A]
I'd only use Doxygen with Java if you're new to Java and you've used Doxygen before, reducing the learning curve you'd experience with javadoc.  If you haven't used Doxygen before, I'd stick with javadoc, since it was specifically designed with Java in mind.  If you don't know either one, and you work in C++ (or other supported languages) as much as you do Java, Doxygen is a good choice, as you'll be able to use it for both languages.
Both tools are easy to use, with a similar feature set.  Both have plugins (or are pre-built in) for NetBeans and Eclipse making it even faster to generate doc.  There is a lot of overlap in the comment style used by each, but they're not
exactly
the same, so it would be difficult to mix them together (you'd have to know the details of
both
, leaving out any features that are specific to one or the other).  I've never used it, but there does seem to be a
Maven plugin for Doxygen
.


q:
I'm looking for a way to embed an image in a library (Windows-only). I don't want to go the 'traditional' way of putting it in the resources (because of special circumstances that make it not so convenient to mess around with the resource handle.

Ideally, there would be something like xpm files: a 'text' representation of an image that is put in a c array and that some code converts into a bitmap in memory, which can then somehow be loaded into an HIMAGE or an HICON. The images I want to embed are 32-bit bitmaps (bmp). Any ideas? I'm using MFC so an MFC library would be fine, but of course I can use a library that doesn't use MFC too. Thanks.

[A]
Google for a bin2c utility (something like
http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c
).  It takes a file's binary representation and spits out a C source file that includes an array of bytes initialized to that data.
Just link the file in and you have your image sitting in a chunk of memory.
Using this kind of tool is really common on embedded systems where such things as 'resources' and even files might not exist.


q:
In regular Java, you can get the text of a stack trace by passing a PrintWriter to printStackTrace. I have a feeling I know the answer to this (i.e. "No") but,

Is there any way to obtain the text of a stack trace in JavaME as a String?

Update:

I should mention that I'm restricted to CLDC 1.0

[A]
You can have the PrintWriter write to a ByteArrayOutputStream and reconstruct the String from the bytes.
```
```
try{
    throw new Exception("Message");
} catch (Exception ex){
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ex.printStackTrace(new PrintStream(out));
    System.out.println(new String(out.toByteArray()));
}
```
```
It's not pretty, but it should work pretty much everywhere. Before you try the above, make sure you don't have access to [Throwable#getStackTrace](
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace())
, Eclipse claims it's available in CDC/Foundation 1.1, but that doesn't say anything about other profiles.


q:
Today I changed the application pool identity of our ASP.NET application from "Network Service" to a domain user.

I added the user to the local group "IIS_WPG", done a iisreset just in case, and
everything works fine with IE6 and Firefox 3.0

But when I go to the website with IE7, an authentication popup appears, I type my credentials, and then :

HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials. Internet Information Services (IIS)

Any ideas ?

[A]
Typically, if you see an issue with authentication where it works in IE 6 but not IE 7, I'd check to make sure Kerberos is configured correctly.
Running as Network Service, your Kerberos SPNs should attached to the machine account.  As a domain account, the SPN's need to be on that account.
As to why IE 6 is different than IE 7, its most likely due to some of the Kerberos HotFixes that apply to CNames and ticket time outs. Search MS Support for "kerberos HotFix"
To turn off Kerberos for the site:
cscript adsutil.vbs set w3svc/###/NTAuthenticationProviders "NTLM"
Where ### is the SiteID from the MetaBase.


q:
Is there any way to display scrollabletext in loose xaml?  The equivalent in HTML would be

<div style="overflow:scroll">some long bit of text here</div>

Can you do this in loose xaml?

From my experiments so far it seems that in loose xaml:

You cannot use TextBox -- it must be TextBlock.

TextBlock doesn't seem to have any styling settings which would make it scrollable.

ScrollViewer doesn't seem to be allowed in loose xaml.

Any help gratefully appreciated.


q:
I have a Makefile that starts by running a tool before applying the build rules (which this tool writes for me). If this tool, which is a python script, exits with a non-null status code, I want GNU Make to stop right there and not go on with building the program.

Currently, I do something like this (top level, i.e. column 1):

$(info Generating build rules...)
$(shell python collect_sources.py)
include BuildRules.mk

But this does not stop make if collect_sources.py exits with a status code of 1. This also captures the standard output of collect_sources.py but does not print it out, so I have the feeling I'm looking in the wrong direction.

If at all possible, the solution should even work when a simple MS-DOS shell is the standard system shell.

Any suggestion?

[A]
There might be a better way, but I tried the following and it works:
```
```
$(if $(shell if your_command; then echo ok; fi), , $(error your_command failed))
```
```
Here I did assume that
```
your_command
```
does not give any output, but it shouldn't be hard to work around such a situation.
Edit: To make it work with the default Windows shell (and probably any decent shell) you could write
```
your_command && echo ok
```
instead of the
```
if
```
within the
```
shell
```
function. I do not think this is possible for (older) DOS shells. For these you probably want to adapt
```
your_command
```
or write a wrapper script to print something on error (or success).


q:
I'm creating a C# dll, which is going to be used by others developers in WinForms. For some reasons, I want to detect, if methods from this library, are called from Main (GUI) Thread and warn developer he has done such a thing (ie. in log file). Is there any reasonable way to detect calling method from main thread?
Remember I have no access to WinForm application.

[A]
An easy solution in this case is to declare a static control in the library assembly that is created on the Main UI thread. If you want to detect if the library is called from the main thread, then use the following
```
```
if (MyLibraryControl.InvokeRequired)
  //do your thing here
```
```


q: Where can I find algorithms for image distortions? There are so much info of Blur and other classic algorithms but so little of more complex ones. In particular, I am interested in swirl effect image distortion algorithm.

[A]
I can't find any references, but I can give a basic idea of how distortion effects work.
The key to the distortion is a function which takes two coordinates (x,y) in the distorted image, and transforms them to coordinates (u,v) in the original image. This specifies the inverse function of the distortion, since it takes the distorted image back to the original image
To generate the distorted image, one loops over x and y, calculates the point (u,v) from (x,y) using the inverse distortion function, and sets the colour components at (x,y) to be the same as those at (u,v) in the original image. One ususally uses interpolation (e.g.
http://en.wikipedia.org/wiki/Bilinear_interpolation
) to determine the colour at (u,v), since (u,v) usually does not lie exactly on the centre of a pixel, but rather at some fractional point between pixels.
A swirl is essentially a rotation, where the angle of rotation is dependent on the distance from the centre of the image. An example would be:
```
```
a = amount of rotation
b = size of effect

angle = a*exp(-(x*x+y*y)/(b*b))
u = cos(angle)*x + sin(angle)*y
v = -sin(angle)*x + cos(angle)*y
```
```
Here, I assume for simplicity that the centre of the swirl is at (0,0). The swirl can be put anywhere by subtracting the swirl position coordinates from x and y before the distortion function, and adding them to u and v after it.
There are various swirl effects around: some (like the above) swirl only a localised area, and have the amount of swirl decreasing towards the edge of the image. Others increase the swirling towards the edge of the image. This sort of thing can be done by playing about with the angle= line, e.g.
```
```
angle = a*(x*x+y*y)
```
```


q:
I think questions like this are the reason why I don't like working with PHP. The manual is good, if you can find what you are looking for. After reading through the Array Functions, I didn't see one that provides the functionality I need.

I have an array (in my case, numerically indexed) that I want to scan for a particular value and, if it's there, remove it. And then, when all instances of that value have been removed, I want to rearrange the array using array_values.

[A]
```
array_diff
```
is what you want.
```
```
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
```
```
Result:
```
"blue"
```
.


q:
I've implemented a set of draggable elements that can be dropped into some containers using jQuery. What I need is an animation that moves an element to a specific container without user interaction. The problem is that the elements and the drop containers are in completely different parts of the DOM and mostly positioned using float.

All I need is some code to get the absolute position difference between 2 floating DOM elements, preferrably using jQuery. The only thing I found were some hacks parsing upwards the DOM but always very browser-specific (e.g. "this does not work well with Firefox or IE or whatever").

Best would be something like this:

var distance = getDistance(element1, element2);

or in jQuery notation:

var distance = $(element1).distanceTo($(element2));

[A]
I never used jQuery, just looked up API, so I can assume you can do the following:
```
var o1 = $(element1).offset();
var o2 = $(element2).offset();
var dx = o1.left - o2.left;
var dy = o1.top - o2.top;
var distance = Math.sqrt(dx * dx + dy * dy);
```


q: When printing RFC documents on my A4 format printer I noticed that I print more than it is considered to be one page in RFC document. I figure this is because probably RFC is written in North American paper letter format (216 × 279 mm) and I want to use ISO A4 format (210 × 297 mm). Info on Paper size. So my question is if there is some way or program with which I would at least be able to print every letter format page on to the separate A4 format page. I know there will be some unused space at the bottom but at least there will just be one text page per A4 paper page. I tried changing paper size on printer from A4 to letter, but it didn't help.

[A]
The RFC documents contain page breaks and such in the form of line printer control codes. Just printing a plain text rfc out of vi / notepad / word / whatever will
probably
not work as expected. Try searching for the rfc in PDF form, they'll be easier to print and the page numbering should be correct. You may be able to find pdfs in A4, else the printer dialogues "shrink to fit" feature should handle it.
Oh and shop around, some PDFs are much nicer than others...
You could find PDF format here
http://tools.ietf.org/pdf/
, for RFC 1928, it's
http://tools.ietf.org/pdf/rfc1928.pdf
.


q:
Can Thread.getContextClassLoader() be null ? The javadoc is not really clear.

Should a library take this case into account ?

Update: the reason I asked is that beansbinding.dev.java.net does not work in this case (and my code does setContextClassLoader(null)

[A]
Yes you should, someone could have called
```
Thread.setContextClassLoader(null)
```
and your library IMO should be able to deal with that.


q: Is there any plans for Microsoft to support LINQ to SQL beyond MS SQL server?

[A]
I do not know whether Microsoft plans to do so, but it is probably unlikely. However, if you want to use something similar, you could probably use
DbLinq
meanwhile.


q:
I have a site, and it will be sold to different clients but for maintenance reasons, we will be keeping one codebase. So this means that this one codebase will have to be dynamic enough to have different styles and so forth, depending on the client.

The domain would be a subdomain-type system, so: projectname.clientname.com , projectname.clientname.com, and so forth, where client name is the company who we have sold the system to.

What I'm trying to do is to have a different theme load up depending on the domain. So I may have ecards.savills.com, and for that, I have a folder in Themes called Savills, and inside that folder called Savills, a .CSS file and I want to load that. I've been playing with the request object, but no luck.

I've tried several methods to achieve this, using stylesheettheme (don't need to skin buttons btw), but I keep getting stack overflows in a system dll for .NET.

What is a robust way to achieve this?

[A]
```
```
/* Do you have a folder in "Themes" or "APP_Themes" called Savillis? */
```
```
When you designate a Theme for a page, all stylesheets in that theme folder will be loaded. They will be loaded alphabetically, so watch the order.
On a page level, you can set the theme in the Page directive (aspx) or the PreInit (codebehind), or you can set a default theme in the web.config. (You can also set a global theme, but thats not usually used.
```
```
/* Are you doing that? */
```
```
Are there separate web site instances?


q:
In order to handle concurrency issue, is locking-- any form of locking, whether it's row, table or database locking a good solution?

If not, how to handle concurrency issue?

[A]
I think not, because it is all the way "down" and makes your application more complex. Most languages have excelent concurrency handling techniques, and even then the best way is to write code which can handle concurrency "natively".
For more info on concurrency in Java:
http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html


q:
Using the client-side ASP.NET AJAX library, I have created an instance of a client component with the $create shortcut-method (http://msdn.microsoft.com/da-dk/library/bb397487(en-us).aspx). The object is attached to a DOM element. Now I need to get a reference to the instance, but it is neither registered on window or on the DOM element, and I cannot find it anywhere.

Does someone know how you can obtain a reference to the instance?

Best regards,

JacobE

[A]
According to MSDN, Sys.Component.Create should return the object that it just created. And, $create is just a shortcut for Sys.Component.create.
```
```
Returns: A new instance of a component that uses the specified parameters.
```
```
So, try:
```
```
var instance = $create(someType);
```
```


q:
I recently installed RailRoad gem to generate an .svg diagram of my app's models and controllers.

The rake task keeps breaking with a similar error:

1.8/usr/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:263:in `load_missing_constant': uninitialized constant

I tried the rake task on 2 seperate apps and the error keeps appearing with a different "constant" name.

Anyone using it with similar problems?

[A]
I'm running it without any problems (though I did have to make a quick edit as it was representing the crows feet the wrong way).
This problem
also appears to be in their tracker
.  I would go ahead and add your stack trace to that ticket as well.  I'm curious if it's your version of ActiveSupport?  Bur your version and the version in use are both displaying the same problem so there's got to be a similarity somewhere.


q: How do you add a page break into a document with XSL-FO? I'm using Apache FOP to create PDFs, if that makes a difference.

[A]
The
FOP compliance page
says that it supports
```
page-break-after
```
,
```
page-break-before
```
, and
```
page-break-inside
```
in the later versions, plus partial support for
```
keep-together
```
,
```
keep-with-next
```
,
```
keep-with-previous
```
.


q:
I have a singleton that uses the "static readonly T Instance = new T();" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for unit tests. How can I modify this pattern to support a disposable singleton?

The interface I would like is something like:

var x = Foo.Instance;
var y = Foo.Instance; // x == y
...
x.Release(); // this causes the next Foo.Instance to return a fresh object
             // also, it assumes no further operations on x/y will be performed.

Note - the pattern has to be thread-safe, of course.

Edit - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it.

I would also prefer a pattern that can be reused, if possible.

[A]
At that point I don't think I'd really consider it to be a singleton any more, to be honest.
In particular, if a client uses a singleton they're really not going to expect that they have to dispose of it, and they'd be surprised if someone else did.
What's your production code going to do?
EDIT: If you really, really need this for unit tests and
only
for unit tests (which sounds questionable in terms of design, to be frank) then you could always fiddle with the field using reflection. It would be nicer to work out whether it should
really
be a singleton or whether it should
really
be disposable though - the two very rarely go together.


q:
Given a FieldInfo object and an object, I need to get the actual bytes representation of the field. I know that the field is either int,Int32,uint,short etc.

How can I get the actual byte representation? BinaryFormatter.Serialize won't help, since it'll give me more information than I need (it also records type name etc.). The Marshal class does not seem to have facilities to use bytes array (but maybe I'm missing something).

Thanks

[A]
Use BitConverter.GetBytes()
You'll first have to convert the value to it's native type, than use BitConverter to get the bytes:
```
```
byte[] Bytes;

if (valType == typeof(int))
{
    int intVal = (int) GetFieldValue(....);
    Bytes = BitConverter.GetBytes(intVval);
}
else if (valType == typeof(long))
{
    int lngVal = (long) GetFieldValue(....);
    Bytes = BitConverter.GetBytes(lngVal);
} else ....
```
```


q:
Is there an easy way to rename a group of files already contained in a directory, using Python?

Example:   I have a directory full of *.doc files and I want to rename them in a consistent way.

X.doc -> "new(X).doc"

Y.doc -> "new(Y).doc"

[A]
Try:
http://www.mattweber.org/2007/03/04/python-script-renamepy/
I like to have my music, movie, and
  picture files named a certain way.
  When I download files from the
  internet, they usually don’t follow my
  naming convention. I found myself
  manually renaming each file to fit my
  style. This got old realy fast, so I
  decided to write a program to do it
  for me.
This program can convert the filename
  to all lowercase, replace strings in
  the filename with whatever you want,
  and trim any number of characters from
  the front or back of the filename.
The program's source code is also available.


q:
For a web app I'm working on, I need to know the lat/lon of about 300 US cities.  I also need to know the lat/lon for every US zip code.

Does anyone know of a free source to get this information?

[A]
Freebase
will likely be able to help you.
Here is New York
and it has Lat/Long.
The
Wal-Mart Expansion video
used Freebase to get it's data, and it sounds like you're doing something similar.


q: Since a lot of email clients ignore the HEAD tag, can I embed an inline stylesheet in the body?

[A]
The short answer is no. Gmail strips the tag and it's content.
Hotmail, Yahoo! Mail and Windows Live Mail does not strip style-tags in the body-element.
But take a look at
"The Ultimate Guide to CSS" for HTML email
over at Campaign Monitor.


q:
I have to add a coupon table to my db. There are 3 types of coupons : percentage, amount or 2 for 1.

So far I've come up with a coupon table that contains these 3 fields. If there's a percentage value not set to null then it's this kind of coupon.

I feel it's not the proper way to do it. Should I create a CouponType table and how would you see it? Where would you store these values?

Any help or cue appreciated!

Thanks,

Teebot

[A]
You're correct, I think a CouponType table would be fit for your problem.
Two tables: Coupons and CouponTypes.  Store the CouponTypeId inside the Coupons table.
So for an example, you'll have a Coupon record called "50% off", if would reference the percent off CouponType record and from there you could determine the logic to take 50% off the cost of the item.
So now you can create unlimited coupons, if it's a dollar amount coupon type it will take the "amount" column and treat it as a dollar amount.  If it's a percent off it will treat it as a percentage and if it's an "x for 1" deal, it will treat the value as x.
```
```
- Table Coupons
  - ID
  - name
  - coupon_type_id # (or whatever fits your style guidelines)
  - amount # Example: 10.00 (treated as $10 off for amount type, treated as
           # 10% for percent type or 10 for 1 with the final type)
  - expiration_date

- Table CouponTypes
  - ID
  - type # (amount, percent, <whatever you decided to call the 2 for 1> :))
```
```