Question:
What's the best way to move a document from one doc library to another? I don't care about version history or preserving CreatedBy and ModifiedBy metadata...

SPList lib1 = (SPDocumentLibrary) web.Lists["lib1"];
SPList lib2 = (SPDocumentLibrary) web.Lists["lib2"];
SPItem item1 = lib1.Items[0];
//insert code to move item1 to lib2

I'm currently looking at SPItem.MoveTo() but wonder if anyone already solved this problem and has some advice.

Thanks in advance.

Answer:
Got it:
```
```
SPList lib1 = (SPDocumentLibrary) web.Lists["lib1"];
SPList lib2 = (SPDocumentLibrary) web.Lists["lib2"];
SPListItem item1 = lib1.Items[0];
byte[] fileBytes = item1.File.OpenBinary();
string destUrl = lib2.RootFolder.Url + "/" + item1.File.Name;
SPFile destFile = lib2.RootFolder.Files.Add(destUrl, fileBytes, true /*overwrite*/);
```
```


Question:
I have created a Registry class in .NET which is a singleton. Apparently this singleton behaves as if it were kept in the Cache (the singleton object is available to each session). Is this a good practice of should I add this Singleton to the Cache?
+ do I need to wacth out for concurrency problems with the GetInstance() function?

namespace Edu3.Business.Registry
{
    public class ExamDTORegistry
    {
        private static ExamDTORegistry instance;
        private Dictionary<int, ExamDTO> examDTODictionary;

        private ExamDTORegistry()
        {
            examDTODictionary = new Dictionary<int, ExamDTO>();
        }

        public static ExamDTORegistry GetInstance()
        {
            if (instance == null)
            {
                instance = new ExamDTORegistry();
            }
            return instance;
        }
    }
}

Answer:
Well, your GetInstance method certainly isn't thread-safe - if two threads call it at the same time, they may well end up with two different instances. I have a
page on implementing the singleton pattern
, if that helps.
Does your code
rely
on it being a singleton? Bear in mind that if the AppDomain is reloaded, you'll get a new instance anyway.
I don't really see there being much benefit in putting the object in the cache though. Is there anything you're thinking of in particular?


Question: does anybody know any resources that I can refer to?

Answer:
I believe you are referring to the
JQuery FadeOut effect
(since
Stackoverflow uses JQuery
)


Question: In VB.NET, what is the difference between And and AndAlso? Which should I use?

Answer:
The
```
And
```
operator evaluates both sides, where
```
AndAlso
```
evaluates the right side if and only if the left side is true.
An example:
```
```
If mystring IsNot Nothing And mystring.Contains("Foo") Then
  ' bla bla
End If
```
```
The above throws an exception if
```
mystring = Nothing
```
```
```
If mystring IsNot Nothing AndAlso mystring.Contains("Foo") Then
  ' bla bla
End If
```
```
This one does not throw an exception.
So if you come from the C# world, you should use
```
AndAlso
```
like you would use
```
&&
```
.
More info here:
http://www.panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/


Question: I want to allow only users with a 3G phone to use a particular GPS function.  How do I run a check on the device before allowing that feature to be used?

Answer:
The following code with allow you to determine the exact device that is in use but I would first consider the fact that a 3G device may not actually be able to obtain a GPS lock as the process of doing so is quite slow and requires a more or less clear view of the sky.
For an iPhone 3G the result of this method will be iPhone1,2
```
```
- (NSString *)deviceModel
{
    NSString *deviceModel = nil;
    char buffer[32];
    size_t length = sizeof(buffer);
    if (sysctlbyname("hw.machine", &buffer, &length, NULL, 0) == 0) {
        deviceModel = [[NSString alloc] initWithCString:buffer encoding:NSASCIIStringEncoding];
    }
    return [deviceModel autorelease];
}
```
```


Question:
I have a generic method with this (dummy) code (yes I'm aware IList has predicates, but my code is not using IList but some other collection, anyway this is irrelevant for the question...)

    static T FindThing<T>(IList collection, int id) where T : IThing, new()
    {
        foreach (T thing in collection)
        {
            if (thing.Id == id)
                return thing;
        }
        return null;  // ERROR: Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead.
    }

This gives me a build error

"Cannot convert null to type parameter
'T' because it could be a value type.
Consider using 'default(T)' instead."

Can I avoid this error?

Answer:
```
```
return default(T);
```
```


Question:
With jQuery, how do I find out which key was pressed when I bind to the keypress event?

$('#searchbox input').bind('keypress', function(e) {});

I want to trigger a submit when ENTER is pressed.

[Update]

Even though I found the (or better: one) answer myself, there seems to be some room for variation ;)

Is there a difference between keyCode and which - especially if I'm just looking for ENTER, which will never be a unicode key?

Do some browsers provide one property and others provide the other one?

Answer:
Okay, I was blind:
```
```
e.which
```
```
will contain the ASCII code of the key.
See
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which


Question:
I'm writing a java app using eclipse which references a few external jars and requires some config files to be user accessable.

What is the best way to package it up for deployment?

My understanding is that you cant put Jars inside another jar file, is this correct?

Can I keep my config files out of the jars and still reference them in the code? Or should the path to the config file be a command line argument?

Are there any third party plugins for eclipse to help make this easier? I'm using an ant build file at the moment but I'm not sure I know what I'm doing.

Is there an equivelent of the deployment projects in Visual studio, that will figure out everything you need and just make an installer? I've used install4j before, and it was powerful if no where near as automated as  .Net deployment projects.

Cheers.

Answer:
Ant. It's not the best thing in the world, but it's standard, it's apache, and it works.
There's some good examples on the web how to make a simple build.xml for any, and it's got some features like the 'war' task that knows how to put all the basic stuff (classes, web.xml etc) in the jar file for you.
You can also tell it to pick up other config files and jars and it will happily do it.
It's also really smart about what to compile. You give it a directory, and it finds all the java files and builds them only if their classfile is out of date, so you get some of the traditional make functionality for free without much effort.


Question:
I have a base class vehicle and some children classes like car, motorbike etc.. inheriting from vehicle.
In each children class there is a function Go();
now I want to log information on every vehicle when the function Go() fires, and on that log I want to know which kind of vehicle did it.

Example:

public class vehicle
{
      public void Go()
      {
           Log("vehicle X fired");
      }
}
public class car : vehicle
{
       public void Go() : base()
       {
           // do something
       }
}

How can I know in the function Log that car called me during the base()?
Thanks,

Omri

Answer:
Calling
```
GetType()
```
from Vehicle.Go() would work - but only if Go() was actually called.
One way of enforcing this is to use the
template method pattern
:
```
```
public abstract class Vehicle
{
    public void Go()
    {
        Log("vehicle {0} fired", GetType().Name);
        GoImpl();
    }

    protected abstract void GoImpl();
}

public class Car : Vehicle
{
    protected override void GoImpl()
    {
        // do something
    }
}
```
```


Question:
I'm compiling library for a private project, which depends on a number of libraries. Specifically one of the dependencies is compiled with Fortran. On some instances, I've seen the dependency compiled with g77, on others I've seen it compiled with gfortran. My project then is ./configure'd to link with either -lg2c or -lgfortran, but so far I've been doing it by hand.

If it is possible, how can I find out, from looking into the dependent library (via e.g. nm or some other utility?), whether the used compiler was g77 (and then I'll use -lg2c in my link options) or gfortran (and then I'll use -lgfortran)?

Thanks in advance!

Answer: You might be able to figure it out by using nm, and seeing if the compiled code uses functions from one or the other, but that's quite a hack.  You may be able to figure it out based on which library is available (if there's no libg2c available, then it wasn't g77, for example), but then you still have some ambiguity if both are available.  If you can build the dependency yourself, then you can use have one part of your build process tell another part somehow (variable, file, etc.) which one you used.


Question:
I've built the x86 Boost libraries many times, but I can't seem to build x64 libraries. I start the "Visual Studio 2005 x64 Cross Tools Command Prompt" and run my usual build:

bjam --toolset=msvc --build-type=complete --build-dir=c:\build install

But it still produces x86 .lib files (I verified this with dumpbin /headers).
What am I doing wrong?

Answer:
You need to add the
```
address-model=64
```
parameter.
Look e.g.
here
.


Question: I am having problems when connecting to my SQL server 2008 and think it might be a problem related to MDAC. Is there a download to re-install these?

Answer:
MDAC 2.8 SP1
Remember, MDAC is client software that should not be installed on the server.
Your problem is more likely a protocol or firewall error.
Can you give more info please?


Question:
does anybody know how to save and retrieve files in MS SQL-Server 2000?  I guess the image data type could be used as a container.

I want to import/export the following file types: DOC, XLS, PDF, BMP, TIFF, etc.

Due to resource issues we are using MS-Access 2007 as the front end, so I am looking for VBA code.

Thanks in Advance.

Answer:
You can do this using GetChunk and AppendChunk.
From
this post
you might find
this link
helpful!
One thing to watch out for:
When using certain providers, most
  notably ODBC to SQL Server and other
  databases, you may have to take
  special care in retrieving BLOB data,
  such as placing BLOB columns at the
  end of the field list and referencing
  all non-BLOB fields prior to access
  BLOB columns.
Best of luck!


Question:
A class has a property (and instance var) of type NSMutableArray with synthesized accessors (via @property). If you observe this array using:

[myObj addObserver:self forKeyPath:@"theArray" options:0 context:NULL];

And then insert an object in the array like this:

[myObj.theArray addObject:NSString.string];

An observeValueForKeyPath... notification is not sent. However, the following does send the proper notification:

[[myObj mutableArrayValueForKey:@"theArray"] addObject:NSString.string];

This is because mutableArrayValueForKey returns a proxy object that takes care of notifying observers.

But shouldn't the synthesized accessors automatically return such a proxy object? What's the proper way to work around this--should I write a custom accessor that just invokes [super mutableArrayValueForKey...]?

Answer:
You need to wrap your
```
addObject:
```
call in
```
willChangeValueForKey:
```
and
```
didChangeValueForKey:
```
calls. As far as I know, there's no way for the NSMutableArray you're modifiying to know about any observers watching its owner.


Question: I'm just starting out with WiX as I need to be able to automate building an MSI on our CI server.  Is there anyway to automatically include all the dependencies of a project?

Answer: In my experience, Wix is a still a very manual process.  You have to add each dependency singly - I think the idea was that you would build the Wix installer at the same time you are building your project and add each item in as you are adding it in the code.  This way it seems less daunting than having to go back and do a retrospect on the project.  It certainly would be a great suggestion for an enhancement though!


Question:
Somehow my iPhone Simulator is unable to play sounds.  First an app I'm working on using AudioServicesPlaySystemSound() stopped working.. I spent a while debugging this but sound is still working on the iPhone when I run the app on the device.  I get the same results with other iPhone apps such as the sample Crash Landing app.

I can't find a sound setting anywhere in the simulator or Xcode preferences.  I've tried resetting the simulator through "Reset Content and Settings" menu item to no avail.

Answer:
I've found sound to be very inconsistent in the simulator (2.1 SDK).  Sometimes it works, sometimes it doesn't.  Even when it does work, it's usually very choppy and distorted (when playing audio files such as mp3).
A few things to remember:
call
```
AudioSessionInitialize
```
as soon as your app finishes launching
set the
```
kAudioSessionProperty_AudioCategory
```
property for the session via
```
AudioSessionSetProperty
```
(with a value such as
```
kAudioSessionCategory_MediaPlayback
```
)
call
```
AudioSessionSetActive(YES)
```
Of course when all else fails, just run it on your hardware!
EDIT: Now that the 2.2 SDK has been released, I haven't had any problems with sound in the simulator. They must have fixed the bugs! I highly recommend you upgrade to the 2.2 SDK.


Question: Delphi strings use single quotes, for example 'a valid string'. How does one specify the ' character within a literal string? How would one refer to the null byte (Unicode code point U+0000)?

Answer:
To add a single quote to a string, you include two
```
'
```
marks e.g.
```
```
str := '''test string''';
Writeln(str)
```
```
In the string above, you have the normal single quotation to start a string and then two for the single quote. Same goes for the end of the string.
You can also use
```
#
```
followed by a number for other escape character e.g.
For a new line:
```
```
str := 'Newline' + #13 + #10
```
```
or just
```
```
str := 'Newline'#13#10
```
```
Of course, using the platform-dependent constant for newline is better.


Question: I want to make my .Net application display a notification in the system tray. So I want to show an icon for that, can anyone tell how to do that?

Answer:
In .Net apps you can specify the file to use as an icon - it can be a bitmap or png etc. so just use your favourite image editing program to create you icon.
This
article
gives advice on getting your app to put an icon in the system tray.
Hope this helps.


Question:
What's the most efficient way to calculate the last day of the prior quarter?

Example:  given the date 11/19/2008, I want to return 9/30/2008.

Platform is SQL Server

Answer:
I came up with this (tested for all months):
```
```
select dateadd(dd,-1,dateadd(qq,datediff(qq,0,'11/19/2008'),0)),
       dateadd(dd,-1,dateadd(qq,datediff(qq,0,'10/19/2008'),0)),
       dateadd(dd,-1,dateadd(qq,datediff(qq,0,'12/19/2008'),0))
```
```
It might turn out to be the simplest.


Question:
About a half dozen times now, I’ve been doing a regular chore in Visual Studio – either running a unit test or simply compiling, updating something from SVN or whatever, and visual studio just disappears… it shuts down and goes away instantly… it is fine when I restart it, and I don’t see the problem again for a while… it keeps happening, and for random reasons… has anyone else experienced this?

One thought is that i'm using AnkhSVN, but if you've had this problem and don't experience this, please let me know.

Answer:
All of the devs on my team see this problem quite often. It isn't AnkhSVN because we don't use it. I believe it is C++ intellisense, but that is just a feeling. Sometimes it happens when we are not doing anything. We will go for coffee, come back and it is just gone.
It never happens to me on smaller projects, but happens frequently on our large (several million lines, dozens of projects) solution with a mix of unmanaged C++, managed C++ and C#.
We have seen it less frequently since upgrading to SP1.


Question:
I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Deque, but I am in Java 1.5.

I would like not to have to add another class to my structure but I am wondering if that is possible:

Is there any class in the Collections framework (1.5) that does the job?

If not, is there any way to turn a Queue in a LIFO Queue (aka Stack) without reimplementation?

If not, which Interface or class should I extend for this task? I guess that keep the way that the guys of Sun have made with the Deque is a good start.

Thanks a lot.

EDIT: I forgot to say about the Stack class: I have my doubts about this class when I saw that it implements the Vector class, and the Vector class is a little bit obsolete, isn't it?

Answer:
There is a
Stack class in the API
.  Will this meet your needs?


Question:
This is a followup to Avoiding @property-itis.

UIWebView has the following property declarations:

@property(nonatomic,readonly,getter=canGoBack) BOOL canGoBack;
@property(nonatomic,readonly,getter=canGoForward) BOOL canGoForward;

UIScrollView has these:

@property(nonatomic) BOOL canCancelContentTouches;

Yet, UIResponder has

- (BOOL)isFirstResponder;
- (BOOL)canBecomeFirstResponder;
- (BOOL)canResignFirstResponder;

Is the UIResponder case one where they should have been declared as properties, but, for whatever reason, were not?

Or is it a case where declaring them as properties was inappropriate? If inappropriate, why?

Answer: My best guess is that UIResponder is meant to match NSResponder, which of course was designed before Objective-C 2.0 introduced properties. Why UIWebView doesn't do the same with regard to WebView, I don't know. I'd expect properties in Cocoa to be a little schizophrenic in this way for some time, and I wouldn't think into it too much when considering your own code.


Question:
Would it be benefical to add a generic way to add info to a Throwable without creating a new Throwable?

I often see code like this:

try {
    foo();
} catch (Exception e) {
    throw new Exception(e.getMessage() + " extra info=" + blah, e);
}

Would it be better to instead add Throwable.setProperty(String key, String value) so that the code above becomes the following?

try {
    foo();
} catch(Exception e) {
    e.setProperty("extra info", blah);
    throw e;
}

The extra info could print (one per line) between the message and stack list.

Benefits:
 1. Would not require creating new Throwables just to add extra information.
 2. Stack traces would not have multiple layers of cause traces
    (and therefore be easier to read)
 3. Reduce cost of creating extra stack traces.

Answer:
In general, I think that it is better to use the standard idioms in cases like this. In this case, the standard idiom is to wrap the exception, like this:
```
```
try {
  foo();
} catch (Exception e) {
  throw new MySpecificException("extra info=" + blah, e);
}
```
```
Also, in general it is best not to catch generic Exceptions. If you want to catch and add information to RuntimeException, then do that, and create a new RuntimeException. Otherwise, think carefully about which checked exceptions you want to catch and throw.


Question: We need to get all the instances of objects that implement a given interface - can we do that, and if so how?

Answer:
I don't believe there is a way... You would have to either be able to walk the Heap, and examine every object there, or walk the stack of every active thread in the application process space, examining every stack reference variable on every thread...
The other way, (I am guessing you can't do) is intercept all Object creation activities (using a container approach) and keep a list of all objects in your application...


Question:
I would like to use ON DUPLICATE KEY UPDATE in Zend Framework 1.5, is this possible?

Example

INSERT INTO sometable (...)
VALUES (...)
ON DUPLICATE KEY UPDATE ...

Answer:
I worked for Zend and specifically worked on Zend_Db quite a bit.
No, there is no API support for the
```
ON DUPLICATE KEY UPDATE
```
syntax.  For this case, you must simply use
```
query()
```
and form the complete SQL statement yourself.
I do not recommend interpolating values into the SQL as harvejs shows.  Use query parameters.
Edit: You can avoid repeating the parameters by using
```
VALUES()
```
expressions.
```
```
$sql = "INSERT INTO sometable (id, col2, col3) VALUES (:id, :col2, :col3)
  ON DUPLICATE KEY UPDATE col2 = VALUES(col2), col3 = VALUES(col3)";

$values = array("id"=>1, "col2"=>327, "col3"=>"active");
```
```


Question:
I would like to serve a different content from a single URL depending on whether the user is a browser or a RSS reader (hence avoiding an example.com/feed URL). Thus www.example.com/posts will return an (X)HTML page to a browser and an RSS feed to a feed reader.

What the architecturally most appropriate way of accomplishing this?

PS How is that for a soft-ball question... :)

Answer:
Let me introduce you to the User-Agent
HTTP header
. It will contain an identifying string for the client accessing your page. It can be faked but you just can't be 100% sure if it's a RSS reader or a browser.
Additionally, RSS readers might send Accept headers for rss content-types, which you may use to implement
content negotiation
(
MultiViews
in Apache).
But as there is no sure fire way, you better fail on the side of serving HTML more often than RSS, or better yet, do as everybody else does and provide a different feed for RSS.


Question:
If it's harder to explain using words, let's look at an example
I have a generic function like this

void FunctionA<T>() where T : Form, new()
{
}

If I have a reflected type, how do I use it with the above function? I'm looking forward to do this

Type a = Type.GetType("System.Windows.Forms.Form");
FunctionA<a>();

Of cause the above method doesn't work.

Answer:
You can't.  Generics in .NET must be resolved at compile time.  You're trying to do something that would resolve them at runtime.
The only thing you can do is to provide an overload for FunctionA that takes a type object.
Hmmm... the commenter is right.
```
```
class Program
{
    static void Main(string[] args)
    {
        var t = typeof(Foo);
        var m = t.GetMethod("Bar");
        var hurr = m.MakeGenericMethod(typeof(string));
        var foo = new Foo();
        hurr.Invoke(foo, new string[]{"lol"});
        Console.ReadLine();
    }
}

public class Foo
{
    public void Bar<T>(T instance)
    {
        Console.WriteLine("called " + instance);
    }
}
```
```
MakeGenericMethod
.


Question:
How do I calculate the last business day of month in VBScript? It is for a Reporting Services report.

Thanks

Answer:
If you mean the last
week
day of the month (M-F), then try:
```
```
Dim d

d = DateAdd("m", 1, Now)

d = Month(d) & "/1/" & Year(d)
d = DateAdd("d", -1, d)

If Weekday(d) = 7 Then
    d = DateAdd("d", -1, d)
ElseIf Weekday(d) = 1 Then
    d = DateAdd("d", -2, d)
End If

MsgBox d
```
```


Question:
I've seen the following code to enable double buffering on a winform:

// Activates double buffering
this.SetStyle(ControlStyles.DoubleBuffer |
   ControlStyles.OptimizedDoubleBuffer |
   ControlStyles.UserPaint |
   ControlStyles.AllPaintingInWmPaint, true);
this.UpdateStyles();

Is this different in any way from simply setting Form.DoubleBuffering = true?

Answer:
Setting a form's DoubleBuffering will set double buffering for that form. It's the same as calling
```
```
form.SetStyle(ControlStyles.OptimizedDoubleBuffer, value);
```
```
The other flags like UserPaint and AllPaintingInWmPaint are styles that aren't set by simply setting control.DoubleBuffering = true


Question: Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application.

Answer:
See the
WSGI reference
implementation.


Question:
Given a java.util.Date object how do I go about finding what Quarter it's in?

Assuming Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc.

Answer:
Since Java 8, the quarter is accessible as a field using classes in the
java.time
package.
```
```
import java.time.LocalDate;
import java.time.temporal.IsoFields;

LocalDate myLocal = LocalDate.now();
quarter = myLocal.get(IsoFields.QUARTER_OF_YEAR);
```
```
In older versions of Java, you could use:
```
```
import java.util.Date;

Date myDate = new Date();
int quarter = (myDate.getMonth() / 3) + 1;
```
```
Be warned, though that
getMonth
was deprecated early on:
As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH).
Instead you could use a
```
Calendar
```
object like this:
```
```
import java.util.Calendar;
import java.util.GregorianCalendar;

Calendar myCal = new GregorianCalendar();
int quarter = (myCal.get(Calendar.MONTH) / 3) + 1;
```
```


Question:
I have a sqlite3 table that I'm trying to map to an object in objective-C. One attribute of the table is 'completed_at' which is stored as a DATETIME.

I want to create a property on my objective-C class (which inherits from NSObject) that will map well to the 'completed_at' attribute.

Objective-C has an NSDate type but I'm not sure if that will map directly?

Answer:
I have zero experience with Objective-C, but I found Apple's
NSDate Class Reference
with a google search. With the information provided on the linked page you should be able to figure out how to manipulate 32-bit epoch times in Objective-C, and this would work well in SQLite. I would probably create the completed_at column as type INTEGER for 32-bit times.
SQLite really prefers Julian dates, which are floats. I haven't found any documentation explaining how one might coerce the NSDate class into working with Julians.
timeIntervalSince1970
looks very interesting.


Question:
I'm looking to have a simple custom dialog box, like a message box, that has a label and a TextBox. If there's a simple way to do this, sorry! I'm really not well versed in the dialog stuff.

Thanks for any help, guys!

Answer:
I'm assuming you basically want a custom dialog box that returns a string entered by the user.  One way is to add a reference to Microsoft.VisualBasic to your project, which gives you access to the InputBox method, which is basically a message box with a text box on it.  But that's no fun and I'm not sure it would work on a smartphone anyway.
To roll your own, you just add a form (named CustomDialog) to your project and drag a textbox (textBox1), a label (label1), and a button (labeled "OK") onto it.
To set the label text, add a parameter to the form's constructor like this:
```
```
public CustomDialog(string textCaption)
{
    label1.Text = textCaption;
}
```
```
To expose the entered text to the caller, add this code to the form:
```
```
public override string Text
{
    get
    {
        return textBox1.Text;
    }
}
```
```
In the OK button's click event, put this code:
```
```
this.DialogResult = DialogResult.OK; // this will close the form, too
```
```
To use this dialog from your main form, you create an instance of this form, show it, check to see that the OK button was clicked, and then read its Text property (which returns what the user entered) like so:
```
```
using (CustomDialog dialog = new CustomDialog("What is your name"))
{
    if (dialog.ShowDialog(this) == DialogResult.OK)
    {
        string enteredText = dialog.Text;
    }
}
```
```
You can get fancier, but those are the basics.


Question: I'm trying to move my database.mdf file from a development environment to a SQL Server Express server that is hosted on my VPS - but I can't figure out how to attach the file to my database server. Help!

Answer:
```
sp_attach_db
```
(or CREATE DATABASE FOR ATTACH) - don't forget to bring the LDF (log) files, too.


Question:
I'm having a weird problem, where tagging works fine on my development machine, but when I deploy to the production server, I get this error in the log:

ActionView::TemplateError (undefined method `tags' for #<Person:0x98bb9d4>) on line...

There is an entry in the production.log file that states that has_many_polymorphs is loaded, so it's not like the plugin isn't available on the production machine.

My Google-fu has failed me trying to find the answer, so if anyone knows what could be wrong it would be greatly appreciated!

Edit: I should have mentioned that on both production and development I'm using the same database. I downloaded the production one, and used it on the development machine and it works fine.

Answer:
```
sp_attach_db
```
(or CREATE DATABASE FOR ATTACH) - don't forget to bring the LDF (log) files, too.


Question:
What is the difference between

if(null==object)

and

if(object==null)

Please give the advantage for using the above.

Answer:
The difference comes if you accidentally type
```
=
```
instead of
```
==
```
:
```
if (null = object)
```
- Compiler error
```
if (object = null)
```
- Bug!


Question:
I have the following string in the smarty (php templating system) variable $test:

<img height="113" width="150" alt="Sunset" src="/test.jpg"/>

I want to add "em" to the height and width like this:

{$test|replace:'" w':'em" w'|replace:'" a':'em" a'}

But this doesn't work... What's the problem and the solution?

Answer:
my regex isn't the greatest, or i'd give you a better matcher, but maybe using what you have through the regex replace would work.
```
```
{$test|regex_replace:'/".w/':'em" w'|regex_replace:'/".a/':'em" a'}
```
```
other matchers to try
```
```
'/\".w/'
'/".*w/'
'/\".*w/'
```
```
i can't play with my smarty sites at the moment, but i'd first remove the " from the replacement value, to see if the bug is there, then remove it from the matcher and just look for height/width.
otherwise i'd do the replace in PHP if you can.


Question:
I need to use C++ to read in text with spaces, followed by a numeric value.

For example, data that looks like:

text1
1.0
text two
2.1
text2 again
3.1

can't be read in with 2 "infile >>" statements. I'm not having any luck with getline
either. I ultimately want to populate a struct with these 2 data elements. Any ideas?

Answer:
If you can be sure that your input is well-formed, you can try something like this sample:
```
```
#include <iostream>
#include <sstream>

int main()
{
    std::istringstream iss("text1 1.0 text two 2.1 text2 again 3.1");

    for ( ;; )
    {
        double x;
        if ( iss >> x )
        {
            std::cout << x << std::endl;
        }
        else
        {
            iss.clear();
            std::string junk;
            if ( !(iss >> junk) )
                break;
        }
    }
}
```
```
If you do have to validate input (instead of just trying to parse anything looking like a double from it), you'll have to write some kind of parser, which is not hard but boring.


Question: We have a multi threaded java program. Multiple-threads will write to a file, and one thread will read from that file. I am looking for some design ideas. Is synchronization necessary?

Answer:
I would consider synchronization in this case. Imagine that 2 threads (t1 and t2) open the file at the same time and start writing to it. The changes performed by the first thread are overwrited by the second thread because the second thread is the last to save the changes to the file. When a thread t1 is writing to the file, t2 must wait until t1 finishes it's task before it can open it.
Also, if you care about the latest possible update of the file, you should synchronize the writing threads with the thread that reads the file so that if there's any thread writing the the file, the reading thread should wait.


Question:
I need a way of calling a web page from inside my .net appliction.

But i just want to send a request to the page and not worry about the response.

As there are times when the response can take a while so i dont want it to hang the appliction.

I have been trying in side the page_load event

WebClient webC = new WebClient();
Uri newUri = new Uri("http://localhost:49268/dosomething.aspx");
webC.UploadStringAsync(newUri, string.Empty);

Even though its set to Async, it still seams to hang as the page wont finish rendering until the threads have finsished

Answer:
Look at
```
System.Net.WebClient
```
, specifically use the
```
DownloadDataAsync()
```
method to send the request without blocking the rest of the app.


Question:
How can I accomplish this?

<% for agent in @broker.agents %>
  ...
  <% if agent.cell %><span class="cell-number">Cell: <%= agent.cell %></span><% end %>
  ...
<% end %>

I want to test to see if the agent has a cell number, and if so, display what's inside the conditional.  What I have currently doesn't seem to work; it just displays "Cell: ".

Thoughts?

Answer:
```
```
if !agent.cell.blank?
```
```
It works.


Question:
My rails model has code that is attempting to define_method(method_name) inside the model.

I keep getting:

NoMethodError: undefined method `define_method'

What am I doing wrong? Am I doing this in the wrong place. I need this method attached to this model. Where else can I define this method?

EDIT:
For those asking to see the code:

for field in rdev_fields
  next if self.attributes.include?(field)
  count = count + 1
  rdev_hash[field.to_sym] = self.attributes["attribute#{count}"]
  if !self.respond_to?(field) then
    define_method("#{field}") do
      self.send("attribute#{count}".to_sym)
    end
  end
end

Answer:
was able to cobble this together. Very little understanding of what's actually going on though.
My instance method foo is opening the class and defining bar on it so that I can then call that on my instance. More experienced folks will let us know if this is opening a can of worms at the same time.
Would be useful to know your specific use for this though.
```
```
class User < ActiveRecord::Base

  def foo
    (class << self; self; end).class_eval do
      define_method(:bar) {puts "bar"}
    end
  end
end

u = User.first
u.foo
u.bar #=> "bar"
```
```


Question:
I'm looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I've heard that delegates can be used for this, but can't figure out why they would be preferred over plain old interfaces implemented on observers. So,

Why should I use delegates instead of defining my own interfaces and passing around references to objects implementing them?

Why might I want to avoid using delegates, and go with good ol'-fashioned interfaces?

Answer:
A delegate is, in effect, passing around a reference to a method, not an object... An Interface is a reference to a subset of the methods implemented by an object...
If, in some component of your application, you need access to more than one method of an object, then define an interface representing that subset of the objects' methods, and assign and implement that interface on all classes you might need to pass to this component... Then pass the instances of these classes by that interface instead of by their concrete class..
If, otoh, in some method, or component, all you need is one of several methods, which can be in any number of different classes, but all have the same signature, then you need to use a delegate.


Question:
Anyone getting this error when using the new free chart controls MS bought from Dundas?

"Error executing child request for ChartImg.axd"

On the MSDN forum they suggested it was my web.config:
 MSDN forum post

So far that hasn't fixed the problem though.  Any other ideas?

Answer:
I posted a way I fixed this problem on the MSDN forum:
Well I still don't know why I was getting the exception but I seem to have found a workaround.  I did an experiment where I took the supposed offending web.config and copied it to a new project where I added a new web form and chart control and the chart control rendered fine with the "UseHttpHandler" option.  This led me to believe that it wasn't actually the web.config that was the problem in my case, so I went back to the original project and added a chart to another web form as an experiment, and it worked!  Even more surprising was that after that I went to the offending page and it worked too!  Then I took the new chart off the other page and checked the original offending page and it was broken again.  Then I found out if I put a chart control on any page before the offending page, it would work, otherwise it threw the exception.  These controls are so cool though that I didn't have a problem finding another page to put one on in the path of the offending page :)
This fixed the problem but if anyone has any theory why I'd be interested...maybe a bug?


Question:
I am making a mp3 id3tag editor, and a regex is not matching.
Could anyone help me please?
my code:

arquivo = "[coletanea] album [CD #] [faixa] [artista] musica.mp3"

r = New Regex("^\[(?<1>[^\]]+?)\]\s*(?<2>[\w\s]+)\s*\[CD\s*(?<3>\d+)\]\s*\[(?<4>\d+)\]\s*\[(?<5>[^\]]+)\]\s*(?<6>.+)", RegexOptions.Compiled)
m = r.Match(Mid(arquivo, 1, Len(arquivo) - 4))
        If m.Success Then
            mAuthor = Trim(m.Groups(5).ToString)
            mWM_AlbumTitle = Trim(m.Groups(2).ToString)
            mWM_TrackNumber = Trim(m.Groups(4).ToString)
            mTitle = Trim(m.Groups(6).ToString)
            mWM_PartOfSet = Trim(m.Groups(3).ToString)
            mMW_AlbumArtist = Trim(m.Groups(1).ToString)
        End If

Answer:
That's because your string will never match the regexp you are using.
The regexp expects a number instead of # and a number instead of 'faixa'
Try this, for example:
```
```
"[coletanea] album [CD 20] [89] [artista] musica.mp3"
```
```
If you wish to allow for any character instead of just numbers, replace \d for . in the groups 3 and 4


Question:
I am looking to do the following (see pseudo code); I want to select 4 rows for each gd.id (7, 11 or 9). I've incorrectly use limit because that only brings up 4 rows in total. Anyone have an idea on how to change this query to accomplish my goal?

SELECT gd.gid, gd.aid, li.ads, li.til
FROM gd
JOIN li ON li.a_id = gd.aid
WHERE gd.gid
IN (
'7', '11', '9'
)
ORDER BY li.timestamp DESC
LIMIT 4 #FOR EACH ;-)

Thank you!

Ice

p.s. Maybe sometype of group_by?

Answer:
Okay I'm posting this second answer now that I understand the relationship between your tables.
```
```
CREATE TABLE gd (
  aid INT AUTO_INCREMENT PRIMARY KEY,
  gid INT
);

INSERT INTO gd (gid) VALUES
  (7), (7), (7),                -- fewer than four rows
  (9), (9), (9), (9),           -- exactly four rows
  (11), (11), (11), (11), (11); -- greater than four rows

CREATE TABLE li (
  a_id INT AUTO_INCREMENT PRIMARY KEY,
  ads VARCHAR(10),
  til VARCHAR(10),
  `timestamp` TIMESTAMP
);

INSERT INTO li (ads, til, `timestamp`) VALUES
  ('foo1', 'bar1', '2008-01-01'),
  ('foo2', 'bar2', '2008-02-01'),
  ('foo3', 'bar3', '2008-03-01'),
  ('foo4', 'bar4', '2008-04-01'),
  ('foo5', 'bar5', '2008-05-01'),
  ('foo6', 'bar6', '2008-06-01'),
  ('foo7', 'bar7', '2008-07-01'),
  ('foo8', 'bar8', '2008-08-01'),
  ('foo9', 'bar9', '2008-09-01'),
  ('foo10', 'bar10', '2008-10-01'),
  ('foo11', 'bar11', '2008-11-01'),
  ('foo12', 'bar12', '2008-12-01');
```
```
So you want the top four rows per value of
```
gd.gid
```
, depending on the
```
timestamp
```
value in the associated table
```
li
```
.
```
```
SELECT g1.gid, g1.aid, l1.ads, l1.til, l1.`timestamp`
FROM gd AS g1
  INNER JOIN li AS l1 ON (g1.aid = l1.a_id)
  LEFT OUTER JOIN (
    gd AS g2 INNER JOIN li AS l2 ON (g2.aid = l2.a_id)
  ) ON (g1.gid = g2.gid AND l1.`timestamp` <= l2.`timestamp`)
WHERE g1.gid IN ('7', '11', '9')
GROUP BY g1.aid
HAVING COUNT(*) <= 4
ORDER BY g1.gid ASC, l1.`timestamp` DESC;
```
```
The output is the following:
```
```
+------+-----+-------+-------+---------------------+
| gid  | aid | ads   | til   | timestamp           |
+------+-----+-------+-------+---------------------+
|    7 |   3 | foo3  | bar3  | 2008-03-01 00:00:00 |
|    7 |   2 | foo2  | bar2  | 2008-02-01 00:00:00 |
|    7 |   1 | foo1  | bar1  | 2008-01-01 00:00:00 |
|    9 |   7 | foo7  | bar7  | 2008-07-01 00:00:00 |
|    9 |   6 | foo6  | bar6  | 2008-06-01 00:00:00 |
|    9 |   5 | foo5  | bar5  | 2008-05-01 00:00:00 |
|    9 |   4 | foo4  | bar4  | 2008-04-01 00:00:00 |
|   11 |  12 | foo12 | bar12 | 2008-12-01 00:00:00 |
|   11 |  11 | foo11 | bar11 | 2008-11-01 00:00:00 |
|   11 |  10 | foo10 | bar10 | 2008-10-01 00:00:00 |
|   11 |   9 | foo9  | bar9  | 2008-09-01 00:00:00 |
+------+-----+-------+-------+---------------------+
```
```


Question:
I have two classes that are associated with a one-to-one mapping:

<class name="Employee" table="Employees">
  ...
  <one-to-one name="Address" class="AddressInfo">
  ...
</class>

I would like to use a criteria expression to get only Employees where the the associated Address class is not null, something like this (which I know doesn't work):

IList employeesWithAddresses = sess.CreateCriteria(typeof(Employee))
    .Add( Expression.IsNotNull("Address") )
    .List();

I guess this is either a really difficult question or almost no one has tried to do this?

Answer:
Have you tried creating an alias for the Address property and checking if the ID/primary key of the Address is not null?
Something like:
```
```
IList employeesWithAddresses = sess.CreateCriteria(typeof(Employee))
    .CreateCriteria("Address", "address").Add( Expression.IsNotNull("Id") )
    .List();
```
```


Question:
I am a recent college graduate working for a large corporation that has an aging workforce. I am curious for peoples experiences on working with an age gap preferably from both sides.

Examples Issues I have encountered so far:

Agile practices vs Waterfall

Collaboration between programmers vs individuality

Working early in the morning vs late at night

I learned primarily agile programming in school while the project I am on (and most of the developers are used to waterfall)

I am used to collaborating with classmates and friends on projects while I tend to see older programmers like to do their own thing. I feel like I pester them asking them questions.

I find myself more of a night programmer, but most of my older colleagues are early morning (5am)

Any experiences on the age gap in the technology work is relevant.

Answer:
Waterfall
is an example of a flawed, non-working software development model.  Unfortunately, it doesn't sound like you're in a position to point this out to your aging co-workers.  :)
I recommend you keep asking questions to different people until you find someone (or a few) who seem interested in mentoring you.  No education or training that I've received in my career has ever been as valuable as the advice of a few really good mentors that I've had.
Once you find a mentor, I suggest you try to work around their schedule, at least for awhile.  Don't feel too bad about asking questions, since that's the only way you can learn (Google it, or ask your question on here first, so you don't ask them
too
many easy questions).
Good luck!
EDIT:  Since only the first two sentences of my original answer seem to be getting read, I thought I'd better provide some more links to support what I said.
The Staggered Iterative Waterfall (Anti-)Pattern
Waterfall development model considered harmful
Don’t draw diagrams of wrong practices - or: Why people still believe in the Waterfall model
Managing the development of Large Software Systems (PDF)
Note that the last one is Royce's original paper.


Question:
I've seen a couple of web pages say that a = b || 'blah' should assign 'blah' to a if b is undefined or null.  But if I type that into Firebug or use it in code, it complains that b is not defined, at the list on FF3/win.  Any hints?

Edit: I'm looking for the case where b may not exist at all.  For example, a DOM node without an id.

Answer:
If b existed, and was false, null, etc, then it works in the way that you would expect. All you'll need to do is on the line above that, put
```
var b = null
```
;
This makes sense if you think about it. It basically does something like this...
```
```
a = function(){ if(b){return b;} else{ return 'blah' } }();
```
```
Note it is checking that the value of b is truthy... if b doesn't exist, you get an exception.
Regarding Undefined variables
"Undefined" in javascript doesn't mean 'variable doesn't exist'. It means "the value of the variable is the special value of
```
undefined
```
". Example:
```
```
alert(nosuchvariable);
=> throws exception

var somevariable; // note it's never assigned
alert(somevariable);
=> This alerts with 'undefined'
```
```
Regarding Checking if variables exist.
So if we try to read
```
b
```
and there is no such variable as b, we get an exception. If we're trying to find out if b is defined, then this isn't helpful.
You can see if global variables exist by checking the top-level
```
window
```
object. All global variables are actually just fields in the
```
window
```
object. Example:
```
```
foo = 'Hello';
alert( window.foo );
=> alerts 'Hello'
```
```
Because you know the window object already exists, you can check it's fields.
Checking for fields that don't exist in javascript will give you
```
undefined
```
and won't crash, so you can then do the coalesce, or put the
```
undefined
```
in a variable or whatever
For
local
variables (things declared with
```
var
```
),
you can't check for their existence.
they don't "live" anywhere in the way that global variables "live" in the window object, and any normal attempt to reference one will cause an exception: eg:
```
```
alert(a);
=> exception because a is meaningless
alert(d45pwiu4309m9rv43);
=> exception because that is equally meaningless
```
```
There is however one exception (that I know of, thanks J c in the comments), the
```
typeof
```
operator. If you try and get the type of something that doesn't exist, it
won't
crash, it will return
the string
```
"undefined"
```
.
This gives you a way of checking for non-existent local variables. eg:
```
```
if( typeof(djfsd) === "undefined" )
  alert('no such variable');
```
```
Regarding DOM elements that don't exist
There have been several comments mentioning DOM elements without ID's and so forth...
The fact that it's a DOM element isn't really relevant. Think of the DOM as a database or a file, and an element as a row in that database or word in that file. In order to
do
anything with it, you have to go searching through the database, find the right row, and pull it's data out. The data gets put into a javascript object. You then access it by manipulating that object, and maybe putting the object in a variable if you like. Example:
```
```
document.getElementById('foo');
```
```
this goes into the dom and looks for an element with an ID of 'foo'. If it finds one, it puts some information about that element into a javascript object, and then hands that object back to you. If it can't find the element, it will hand you back
```
null
```
, but all the normal rules still apply (you can stick the
```
null
```
in a variable, or whatever).
It doesn't affect the coalesce at all.


Question:
I am working on a Perl script to read CSV file and do some calculations.
CSV file has only two columns, something like below.

One Two
1.00 44.000
3.00 55.000

Now this CSV file is very big ,can be from 10 MB to 2GB.

Currently I am taking CSV file of size  700 MB. I tried to open this file in notepad, excel but it looks like no software is going to open it.

I want to read may be last 1000 lines from CSV file and see the values.
How can I do that? I cannot open file in notepad or any other program.

If I write a Perl script then I need to process complete file to go to end of file and then read last 1000 lines.

Is there any better way to that? I am new to Perl and any suggestions will be appreciated.

I have searched net and there are some scripts available like File::Tail but I don't know they will work on windows ?

Answer:
In *nix, you can use the tail command.
```
```
tail -1000 yourfile | perl ...
```
```
That will write only the last 1000 lines to the perl program.
On Windows, there are
gnuwin32
and
unxutils
packages both have
```
tail
```
utility.


Question:
According to the adobe flex docs: http://livedocs.adobe.com/flex/3/html/help.html?content=controls_15.html

Using an image multiple times

You can use the same image multiple times in your application by using the normal image import syntax each time. Flex only loads the image once, and then references the loaded image as many times as necessary.

However, in testing we have found that if you request the same image (same url, etc.) in IE flash 9/10 a new http request will not be issued, but with Firefox, Safari (PC and MAC) a new request is always issued.

I want to prevent the image from being pulled from the server each time I try and use it anyone have any idea why this is working only in IE?

Answer:
The best way to load an image a single time and then reuse that image multiple times in a flex application is to embed the image and tie it to a class representation, then just reference that class from then on.
Example:
```
```
[Embed(source="myImage.jpg")]
[Bindable]
public var myImageClass:Class;
```
```
HTH


Question:
I am looking to find out the logic , if any , which shrinks hashtable in c# when elements are removed from it.

Regards
Harish

Answer:
The only indication of size changes for a hashtable in the documentation is when the load factor is exceeded and the size of the hashtable is increased.  There is no mention of a hastable ever shrinking.
There is some further detail of the load factor on
MSDN
.


Question: Assuming this is a multi-user system

Answer:
I don't know that it's inherently good or bad.  If there's no reason to centralize the data access from a business standpoint, having a client app talk directly to the database isn't a problem.  You'll want to build a decent data access layer regardless of whether it's done in the client or through a centralized data access server.
You mentioned multi-user, depending on the data and usage you may have transactional issues to deal with which might be an argument for centralizing things, but they can be handled from multiple clients as well.


Question: I've scoured the groovy doc and haven't found an analogue, but things there are organized a bit haphazardly. I'm switching from beanshell to groovy and was using the source("fileloc") method in beanshell to inline-include other, utility beanshell scripts for reuse. Is there a standard function to do this in groovy or a best practice?

Answer:
The reason you're not finding this is because Groovy is compiled.  Your Groovy code gets compiled into Java bytecode that gets run by the JVM right along side any Java code in your app.  This is why things like writing Groovified unit tests for large bodies of Java code requires zero extra effort.
The BeanShell is a Java-like
interpreted
language, so slurping in another got of code at run time is no big deal.
That said, you might be interested in
groovysh
and its
```
load
```
command.


Question:
A co-worker asked me how the word "Nuke" relates to CMS? To be honest I never thought about it, and there wasn't any information on the web that I could find.

Francisco Burzi wrote that his Perl script that he used to manage content was called NUKE. His knowledge of that system fueled his adaptation of thatware to phpNuke.

Does anyone know what NUKE stands for and how it is related to content management?

Answer:
From the faq (
http://www.dotnetnuke.com/Resources/Knowledge/FrequentlyAskedQuestions/tabid/546/Default.aspx
)
"The new name was chosen to reflect
  the applications .NET (DOTNET)
  framework, and coupled with the term
  “nuke” (due to *nuke’s inherent,
  industry-recognized inclusion in
  several existing open source portal
  initiatives.)"


Question:
Parameterized Queries in .Net always look like this in the examples:

SqlCommand comm = new SqlCommand(@"
   SELECT *
   FROM   Products
   WHERE  Category_ID = @categoryid
",
   conn);
comm.Parameters.Add("@categoryid", SqlDbType.Int);
comm.Parameters["@categoryid"].Value = CategoryID;

But I'm running into a brick wall trying to do the following:

SqlCommand comm = new SqlCommand(@"
   SELECT *
   FROM   Products
   WHERE  Category_ID IN (@categoryids)
      OR  name LIKE '%@name%'
",
   conn);
comm.Parameters.Add("@categoryids", SqlDbType.Int);
comm.Parameters["@categoryids"].Value = CategoryIDs;
comm.Parameters.Add("@name", SqlDbType.Int);
comm.Parameters["@name"].Value = Name;

Where

CategoryIDs is a comma separated list of numbers "123,456,789" (without quotes)

Name is a string, possibly with single quotes and other bad characters

What's the right syntax for this?

Answer:
You need "%" in value of sql parameter.
```
```
SqlCommand comm = new SqlCommand("SELECT * FROM Products WHERE Category_ID IN (@categoryid1, @categoryid2) OR name LIKE @name", conn);
comm.Parameters.Add("@categoryid1", SqlDbType.Int);
comm.Parameters["@categoryid1"].Value = CategoryID[0];
comm.Parameters.Add("@categoryid2", SqlDbType.Int);
comm.Parameters["@categoryid2"].Value = CategoryID[1];
comm.Parameters.Add("@name", SqlDbType.NVarChar);
comm.Parameters["@name"].Value = "%" + Name + "%";
```
```


Question:
I just got burned by the Cygwin X11R7.4 update and I find the official mailing lists hostile and clunky.  So I thought I'd ask here.

If you have survived the upgrade (or at least made progress on fixing things), what steps did you take to make things work?

Answer:
I ran into this same issue, I couldn't come up with an elegant solution. But the only solution I found was to either use "stitching," or to use reflection.
Stitching looks something like this.
```
```
Person existingPerson - DB.GetPerson(1);
existingPerson.BirthDate = newPerson.BirthDate;
existingPerson.JobTitle = newPerson.JobTitle;
```
```
I once read something about using a callback but I can't find it for the life of me.


Question:
Good afternoon,

I have a web query in Excel 2002 going against a web page that returns a date column.  The dates are returned as DD/MM/YYYY, as I would like to show them in my spreadsheet.  My machine running Excel has its regional settings set to en-GB, and the only language set under Internet Options is UK English.

Nevertheless, the web query pulls the dates as MM/DD/YYYY, which is misinterpreted by Excel.

How can I get the Web Query to return the dates in my regional settings, MM/DD/YYYY?

Answer:
Maybe you are lucky and Excel understands either the HTML
```
lang
```
attribute or
```
<meta http-equiv="content-language" content="...">
```
meta tag. To be honest - my guess is that it doesn't make a difference.
If you have control over the web site, you can try to add them and see if it makes a difference. OTOH - if you
had
control over the web page, you could change the date format.
The alternative would be to disable date recognition entirely and post-process it by hand after the query. To do this, recreate the web query and in the "New Web Query" dialog box, click the "Options..." button in the upper right. There is a "Disable date recognition" checkbox.


Question:
I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: os.remove("/folder_name").

What is the most effective way of removing/deleting a folder/directory that is not empty?

Answer:
```
```
import shutil

shutil.rmtree('/folder_name')
```
```
Standard Library Reference: shutil.rmtree
.
By design,
```
rmtree
```
fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then use
```
```
shutil.rmtree('/folder_name', ignore_errors=True)
```
```


Question: How can I create a method that has optional parameters in it in Visual Basic?

Answer:
Use the
```
Optional
```
keyword and supply a default value. Optional parameters must be the last parameters defined, to avoid creating ambiguous functions.
```
```
Sub MyMethod(ByVal Param1 As String, Optional ByVal FlagArgument As Boolean = True)
    If FlagArgument Then
        'Do something special
        Console.WriteLine(Param1)
    End If

End Sub
```
```
Call it like this:
```
```
MyMethod("test1")
```
```
Or like this:
```
```
MyMethod("test2", False)
```
```


Question:
I'm trying to use a break statement in a for loop, but since I'm also using strict subs in my Perl code, I'm getting an error saying:

Bareword "break" not allowed while
  "strict subs" in use at ./final.pl
  line 154.

Is there a workaround for this (besides disabling strict subs)?

My code is formatted as follows:

for my $entry (@array){
    if ($string eq "text"){
         break;
    }
}

Answer:
Oh, I found it.  You use
last
instead of
break
```
```
for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}
```
```


Question:
I was wondering if there was a way to bind an ArrayList (or any kind of List, for that matter) to a PreparedStatement which will eventually be used to access an Oracle database.  I found:

PreparedStatement IN clause alternatives?

And that seems similar to my issue, but this question is more specific: I'd like to bind an ArrayList to a PreparedStatement to be used in Oracle, if it is possible, how is this accomplished?

Answer:
Well, judging by the answer to that one, especially the comments to my wrong answer in that question, you can't.
See
https://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html#996857
.


Question: How can I prune old revisions from my development subversion repository?  I keep a subversion sandbox in which I have lots of test projects, binaries, etc.  I'd like to prune the history occasionally.

Answer:
Here's the official answer:
There are special cases where you might want to destroy all evidence of a file or commit. (Perhaps somebody accidentally committed a confidential document.) This isn't so easy, because Subversion is deliberately designed to never lose information. Revisions are immutable trees which build upon one another. Removing a revision from history would cause a domino effect, creating chaos in all subsequent revisions and possibly invalidating all working copies.
The project has plans, however, to someday implement an svnadmin obliterate command which would accomplish the task of permanently deleting information. (See issue 516.)
In the meantime, your only recourse is to svnadmin dump your repository, then pipe the dumpfile through svndumpfilter (excluding the bad path) into an svnadmin load command. See chapter 5 of the Subversion book for details about this.
Found here:
http://subversion.tigris.org/faq.html#removal


Question:
What is the proper way to load a ListBox in C# .NET 2.0 Winforms?

I thought I could just bind it to a DataTable. No such luck.

I thought I could bind it with a Dictionary. No luck.

Do I have to write an class called KeyValuePair, and then use List<KeyValuePair> just to be able to load this thing with objects? Maybe I am missing something obvious. I want my display text and values to be different values.

Answer:
Lets assume your data type is called MyDataType. Implement ToString() on that datatype to determine the display text. e.g.:
```
```
class MyDataType
{
  public string ToString()
  {
    //return the text you want to display
  }
}
```
```
Then you can take a list consisting of your datatype and cram it into the ListBox via AddRange() as follows:
```
```
ListBox l;
List<MyDataType> myItems = new List<MyDataType>(); // populate this however you like
l.AddRange(myItems.ToArray());
```
```
Let me know if you need more help - it would help to know what datatype you are trying to display in the listbox.


Question:
I have a WCF Service decorated with WebInvoke attributes and WebHttp binding for JSON enabling. The service can be accessed from JavaScript until we try to make it working cross domain. Can you please recommend how to get this to work cross domain?

We've tried to create proxy web handler but it gives "Bad Request" everytime WebHttpRequest try to access it.

Answer:
For a ridiculously short value  ( Ie: values < 64 characters ), MD5 as a hash becomes ineffective due to rainbow table attacks, and as the value you're sending will be shared over the wire, all they have to do is brute force the shared secret ( and they have a known product to work with )
As such, thats not public key private key. its mererly shared secret.
Also, keep in mind this shared secret will be in your flash file you send to the user, which these days and be trivially disassembled and then your "secret" is not a secret any more.
You want a more challenge-response mechanism with proper crypto signing, where a new sign key is assigned for every game from the server, and multiple scores cannot be submitted with the same sign key. ( For extra protection ;) )
User starts game. Sign key is requested. ( the sign key is produced from another key which they cant access ).
Score is signed with sign key, and then sent
You verify the value of the sign with the key you sent them.
You discard the sign key you sent them.
However, you
still
have the problem where you have no way to prevent the actual scoring system being tampered with. Somebody smart enough could just reverse engineer your SWF object and inject new code that just sets the score to their chosen value.


Question:
I want to index a computed column in my database table which uses a number of user defined functions. However I just learned that my column is non-deterministic.

Without indexing its going to be way to slow to run queries that I need.

What's the best way of tracing through user defined functions to determine whether they are deterministic?

Is there any kind of tool in SQL Server Management Studio that will tell me whether a user defined function is deterministic or do I just need to trace through all the system-defined functions I'm using to find out which are non-deterministic and find other ways to write my code without them?

Answer:
Try:
```
```
SELECT  *
FROM    INFORMATION_SCHEMA.ROUTINES
WHERE   IS_DETERMINISTIC = 'NO'
        AND ROUTINE_TYPE = 'FUNCTION'
```
```
or
```
```
SELECT OBJECTPROPERTY(OBJECT_ID('schemaname.functionname'), 'IsDeterministic')
```
```
Sorry, IIRC, SQL Server 2000 did not allow non-deterministic UDFs.
Indexing a column that is non-deterministic is pretty of silly - after all if its value is not strictly dependent on parameters, it's not going to be very useful if it changes on you all willy-nilly, especially if it's used in an index to find things!


Question:
I have made some changes to a site and need to re-host it as the current host is ceasing to exist.  My client has received the following from the current host:

"The best thing to tell them is that, due to the fact that we are withdrawing our service completely, we would look to fully transfer the web site address across to them rather than just "point" the web address at them. If you can forward this Email to them and ask them to
confirm their "IPS tag" (they'll know what that is), I can then arrange for it to be transferred as and when they confirm it's all ready to go."

Can anyone help me out here as i'm not too sure what they mean, nor do I know what an IPS tag is? ?

Answer:
an IPSTAG is a .uk only designation of the domain's registrar. basically, the webhost is asking you to transfer the domain name registration away from them to a new provider.
i would suggest you (or your client) find a new registrar, get their IPSTAG, and then send that to your old host, who will then be able to initiate the change.
once the IPSTAG has been updated (you can check WHOIS information for that), then your new registrar will be able to get the domain name (and thus the old host will have relinquished "control" of it)
here's an example from amazon.co.uk's WHOIS:
```
```
Domain name:
    amazon.co.uk

Registrant:
    Amazon Europe Holding Technologies SCS

Registrant type:
    Unknown

Registrant's address:
    65 boulevard G-D. Charlotte
    Luxembourg City
    Luxembourg
    LU-1311
    LU

Registrar:
    Amazon.com [Tag = AMAZON-COM]
```
```
the IPSTAG in this case is "AMAZON-COM"


Question:
I'm making heavy use of PropertySheets in my application framework's configuration editor.  I like them a lot because it's pretty easy to work with them (once you learn how) and make the editing bulletproof.

One of the things that I'm storing in my configuration are Python scripts.  It's possible to edit a Python script in a StringCollection editor, which is what I've been using, but there's a long distance between "possible" and "useable."  I'd like to have an editor that actually supported resizeable and monospace fonts, preserved blank lines, and - hey, let's go crazy with the wishlist - did syntax coloring.

I can certainly write this if I really have to, but I'd prefer not to.

I've poked around on the Google and can't find anything like what I'm describing, so I thought I'd ask here.  Is this a solved problem?  Has anyone out there already taken a crack at building a better editor?

Answer:
You would need to write your own type editor. You can think of this as a user control, in that when you write your own type editor you are providing the UI controls that appear when the property grid edits the property. As such, you can create a type editor that does anything, which means if you have a third-party editor control you can include it as part of type editor.
Some resources to get you started:
User Interface Type Editors Overview
Walkthrough: Implementing a UI Type Editor
UITypeEditor Class
How to: Implement a UI Type Editor
Rich Design Time Editing with UITypeEditors (VB.NET)
Creating Property Editors in DesignTime for VS.Net Easily (UITypeEditor Helper)
Using PropertyGrid


Question:
I've used boost serialization but this doesn't appear to allow me to generate xml that conforms to a particular schema -- it seems it's purpose was to just to persist a class's state.

Platform: linux

What do you guys use to generate NOT parse xml?

So far I'm going down Foredecker's route of just generating it myself -- it's not a large document but I really shouldn't be having this much trouble finding a decent library to generate it correctly.

As for boost, the things that I would like to be able to do is set the node names, set attributes in my nodes, and get rid of all the extra crap that comes with it as I don't really care about having to put my document back into that class.

Answer:
Some may declare me an XML heretic - but one effective way is to just generate it with your favorite string output tools (print, output streams, etc) - this can go to a buffer or a file.
Once saved - you really should then validate with a schema before committing it our shipping it off.
For one of our projects we have a very simple set of templates for managing begin/end tags and attributes.   These each have a stream output operator.   This makes it very easy to generate the source XML and debug.  This makes the structure of the XML generation code look very much like the XML itself.
One advantage of this is that you can generate large amounts of XML efficiently if streaming to a file.  You will pay the validation costs later (presumably at a better time for an expensive operation).
The downside of this technique is that it is essentially output only.   It is not suitable for creating then consuming XML dynamically.


Question:
If I have records:

Row  Date,        LocationID, Account
1    Jan 1, 2008  1           1000
2    Jan 2, 2008  1           1000
3    Jan 3, 2008  2           1001
4    Jan 3, 2008  1           1001
5    Jan 3, 2008  3           1001
6    Jan 4, 2008  3           1002

I need to get the row (date, locatinid, account) where the row has the most recent date for each distinct locationid:

4    Jan 3, 2008  1           1001
3    Jan 3, 2008  2           1001
6    Jan 4, 2008  3           1002

Answer:
Try something like:
```
```
select *
from mytable t1
where date = (select max(date) from mytable t2
              where t2.location = t1.location);
```
```


Question:
I found that SQL stored procedures are very interesting and useful. I have written stored procedures but i want to write well crafted, good performance tuned and concise SPs for any sort of requirement and also would love to learn about any tricks or good practices for stored procedures. How do i move from the beginner to the advanced stage in writing stored procedures?

Update: Found from comments that my question should be more specific.
Everyone has some tricks upon their sleeves and I was expecting such tricks and practices for SPs which they use in their code which differentiates them from others and more importantly spruce up the productivity in writing and working with stored procedures.

Answer:
The only trick I always try to use is: Always include an example usage in a comment near the top.  This is also useful for testing your SP.  I like to include the most common examples - then you don't even need SQL Prompt or a separate .sql file with your favorite invocation, since it's stored right there in the server (this is expecially useful if you have stored procs that look at sp_who output for blocks or whatever and take a bunch of parameters).
Something like:
```
```
/*
    Usage:
    EXEC usp_ThisProc @Param1 = 1, @Param2 = 2
*/
```
```
Then to test or run the SP, you simply highlight that section in your script and execute.


Question:
How would you ensure that only one user is logged in per account at a time?

Assuming cookies are persistent.

Answer:
Typically the best way is to implement a customization on the provider that checks for last login, as well as adding methods to your code to keep track of user action.
The key is that you must know at what point did the user last do something OR logout.  From there you can determine if the account is actually ready.  If you setup the tracking for these elements in code,  You can then modify the membership provider to check to ensure that the account can login.


Question:
I'm looking for material on persistent data structures that can be used to implement a relational model.

Persistence in the meaning of immutable data structures.

Anyone know of some good resources, books, papers and such?

(I already have the book Purely Functional Data Structures, which is a good example of what I'm looking for.)

Answer:
It is straightforward to modify the ubiquitous
B-tree
to be persistent. Simply always alloctate a new node whenever a node is modified, and return the new node to the recursive caller, who will insert it at that level by allocating a new node, etc. Ultimate the new root node is returned. No more than O(log N) nodes are allocated per operation.
This is the technique used in functional languages to implement, e.g, 2-3 trees.


Question: I'm working on a idea where my a:link have one state (blue, no underline etc) with a a:hover being white. I want my visited links to have the same state as a:link and a:hover. Is this possible? supported in most common browsers?

Answer:
Here's how you can style the a tags (normal and visited) and style the hover separately.
```
```
a
{
    color:#6c7492;
    font-weight:bold;
    text-decoration:none;
}
a:hover
{
    border-bottom:1px solid #6c7492;
}
```
```


Question:
When I do a cvs status, I see working revision and repository revision numbers.
What is the difference between the two, or rather, what do they mean?

Answer:
the
working revision
is just the revision you are currently using. the
repository revision
is the revision currently in the repository.
basically, if the
repository revision
is larger than your
working revision
, someone has committed changes to that file, and perhaps you should update your version, or you may end up with a conflict if you try to commit your own changes at a later time.


Question:
In through php_info() where the WSDL cache is held (/tmp), but I don't necessarily know if it is safe to delete all files starting with WSDL.

Yes, I should be able to just delete everything from /tmp, but I don't know what else this could effect if I delete any all WSDL files.

Answer:
You can safely delete the WSDL cache files. If you wish to prevent future caching, use:
```
```
ini_set("soap.wsdl_cache_enabled", 0);
```
```
or dynamically:
```
```
$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );
```
```


Question: I'm setting up CruiseControl.NET and during the build I want to modify my version.txt file and have it checked in.  When I do this, CruiseControl.NET doesn't know this checkin was done by the build and so the next time it checks sources, it sees there were modifications and rebuilds again (I have IfModificationExists set in the project build).  How do I tell CruiseControl.NET to check this file in or let it know that this one is OK so it doesn't keep re-triggering builds?

Answer:
I'm not using Subversion, i'm using TFS.
Version.txt contains "1.0.5.3" which is the current build number.  When someone checks out to build, they'll use 1.0.5.3 as their revision.  On the server, it will rev the build number, store it in version.txt and check it back in so that everyone's version is moved up to that level.  So it will be 1.0.5.4" for example.
I basicaly want a way to tell CCNet to checkin a file and ignore it when looking for future modifications.


Question:
It seems like Groovy was forgotten in this thread so I'll just ask the same question for Groovy.

Try to limit answers to Groovy core

One feature per answer

Give an example and short description of the feature, not just a link to documentation

Label the feature using bold title as the first line

See also:

Hidden features of Python

Hidden features of Ruby

Hidden features of Perl

Hidden features of Java

Answer:
Using hashes as pseudo-objects.
```
```
def x = [foo:1, bar:{-> println "Hello, world!"}]
x.foo
x.bar()
```
```
Combined with duck typing, you can go a long way with this approach.  Don't even need to whip out the "as" operator.


Question:
I recently upgraded to Delphi 2009 and was disappointed to find out that I couldn't easily replace one VCL component with another. The best answer back was that GExperts could be used to do this.

Is it worthwhile to petition Embarcadero to incorporate some or all of the capabilities of GExperts right into Delphi? Which of their "Experts" do you use most and would like to see in Delphi?

Or is GExperts best left as a community Open Source addon?

Answer:
My number one GExpert is Grep Search.
Close second is the Procedure List window.
Also very handy are the various keyboard shortcuts,
and the toolbar embedded in the editor - I have a few
buttons on there; like CPU-view, Project Manager and
the selection-tools as a dropdown (like sort selection).
Sometimes I use the Clipboard History window.
And even more rarely the ASCII windows.
Everything else I don't touch really.
I know the procedure-list could also be found in the structure-pane of Delphi 2009, but somehow the fact that I can press Ctrl+G to get a window with quick filtering and preview capabilities is more productive for me.
Same thing for grep - the GExperts' version is way more powerfull than the standard Delphi search function.
If these two (and maybe the clipboard history) where embedded in standard Delphi, I probably wouldn't install GExperts anymore.
But on the other hand : I do like the fact that these solutions are available as open source - this allowed me for example to add section-filtering to the grep-search, which otherwise wouldn't have been possible for me...


Question:
someone has an idea how can I do that ?

thanks

Answer:
If you mean "initialize a dense array of N items in a time independent of N", then it is physically impossible. A dense array has a storage space that grows linearly with the number of items, and it will take a linear amount of time to initialize this space.
You can have constant-time initialization using a sparse array. That is essentially an associative array (or hashmap, or dictionary, or table, depending on the language) which initializes items when they are first accessed.


Question:
I noticed that doxygen uses the graphviz library for creating diagrams. Have you ever used graphviz for generating documentation? Is it worth learning the graphviz for documentation purposes outside the scope of doxygen? Or am I better off to sticking with a standard data modeling package like Visio?

I understand the merits of it as a graphing library, but for trying to represent more complex UML (or similar) is it still worth looking into?

Answer: The graphviz is very very simple language/format for creating graphs. If the capabilities are enough for you I would recommend it (Its so easy, that I would estimate the time to learn with at most 1 hour).


Question:
I'm terrible with regex, but I've had a try and a Google (and even looked in reddit's source) and I'm still stuck so here goes:

My aim is to match the following 'codes' and replace them with the HTML tags. It's just the regex I'm stuck with.

**bold text**
_italic text_
~hyperlink~

Here's my attempts at the bold one:

^\*\*([.^\*]+)\*\*$

Why this isn't working? I'm using the preg syntax.

Answer:
use:
```
```
\*\*(.[^*]*)\*\*
```
```
explanation:
```
```
\*\*      // match two *'s
(.        // match any character
[^*]      // that is not a *
*)        // continuation of any character
\*\*      // match two *'s
```
```
in a character class "[ ]" "^" is only significant if it's the first character. so
```
(.*)
```
matches anything,
```
(.[^*]*)
```
is match anything until literal *
edit
: in response to comments to match asterisk within (ie
```
**bold *text**
```
), you'd have to use a non greedy match:
```
```
\*\*(.*?)\*\*
```
```
character classes are more efficient non greedy matches, but it's not possible to group within a character class (
see
"Parentheses and Backreferences...")


Question:
Our application is an Xbap running in full trust. I have a function similar to this:

private void ShowPage(Page page)
{
    NavigationWindow mainWindow = Application.Current.MainWindow as NavigationWindow;
    mainWindow.Navigate(page);
}

This works great for browsing inside an existing window. I would like to open this new page in a separate window. Is there anyway to do this?

There is an overload that takes 'extraData' but I haven't been able to determine what to pass to navigate to a new window.

Answer:
Apparently WPF is a little new for StackOverflow. Here is the function I came up with in case anyone else stumbles across this.
```
```
private void ShowPage(Page page)
{
    NavigationWindow popup = new NavigationWindow();
    popup.Height = 400;
    popup.Width = 600;
    popup.Show();
    popup.Navigate(page);
}
```
```
I have not tried this in partial trust, it is likely this only works in full trust.


Question:
I have a text area and a function to do syntax highlighting on it. Right now it reads the entire RichTextBox. How would I get a string variable containing the current line? Below is the code i currently have.

Private Sub HighLight()
    Dim rm As System.Text.RegularExpressions.MatchCollection
    Dim m As System.Text.RegularExpressions.Match
    Dim x As Integer ''lets remember where the text courser was before we mess with it

    For Each pass In FrmColors.lb1.Items
        x = rtbMain.SelectionStart
        rm = System.Text.RegularExpressions.Regex.Matches(LCase(rtbMain.Text), LCase(pass))
        For Each m In rm
            rtbMain.Select(m.Index, m.Length)
            rtbMain.SelectionColor = Color.Blue
        Next
        rtbMain.Select(x, 0)
        rtbMain.SelectionColor = Color.Black
    Next
End Sub

Answer:
Not tried it but:
```
```
rtbMain.Lines(lineNumber)
```
```
if not assign the Lines property to an array and access the array element.


Question:
In a Java application (JRE 1.5.0_12) on Windows XP, I call a native method:

public native int attachImage( ... );

... which lives in a Visual C++ 6.0 .dll. It displays an application-modal window. Problem is, the application's tray icon doesn't respond to mouseclicks while this window has focus. This is an issue because when this window is displayed, users often switch to another application to select the image to attach, then want to restore this application.

Answer:
What GUI package are you using?
You should be able to implement this without resorting to JNI calls.
For instance, in SWT, you can open an application modal shell like this:
```
```
Shell shell = new Shell(display,SWT.APPLICATION_MODAL);
```
```
For swing, this would be:
```
```
dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
```
```


Question:
My Firefox 3.0.4 does not display non-existing images at all, or it displays the image alt as plain text (if available).

This way I would have no idea that there is supposed to be an image there.

Does anyone know if there is a way to make it work like IE/Opera? (ie. display a box even if the image file doesn't exists) - plugin or anything?

Test image:

Answer:
As far as i know there is no plugin, Images should have a width and height specified like so:
```
```

or

```
```
Then firefox will reserve the appropiate space for the images.


Question:
I'm looking for something like alert(), but that doesn't "pause" the script.

I want to display an alert and allow the next command, a form submit(), to continue. So the page will be changing after the alert is displayed, but it won't wait till the user has clicked OK.

Is there something like this or is it just one of those impossible things?

Answer:
You could do the alert in a setTimeout (which a very short timeout) as setTimeout is asynchronous:
```
```
setTimeout("alert('hello world');", 1);
```
```
Or to do it properly you really show use a method rather than a string into your setTimeout:
```
```
setTimeout(function() { alert('hello world'); }, 1);
```
```
Otherwise you open yourself up to JavaScript injection attacks. When you pass a string it is run through the JavaScript
```
eval
```
function.


Question:
We have an app that monitors a folder for file drop and need to initiate a virus scan before using any incoming files.

This needs to be a part of the Delphi app and the file must pass the Virus Scan otherwise we delete the file.

I know that there are command shell options available, however this must be a direct API call to a registered AV engine installed on the PC.

We have looked at the MSOffice AntiVirus API but that only seems to be for developers wanting to make scanning apps that are triggered by hosting apps. We need the opposite.

Any suggestions on a Virus Scanning Engine and API would be greatly appreciated.

Thanks in advance.

Answer:
The procedure is described
here
, in the section entitled 'Internet Explorer 5 and Office 2000 Implementation'.
A Delphi implementation of enumerating the category is available
here
(GetRegisteredAntiviruses).  Just fill out a TMsoavinfo and call
Scan
.
Most AV programs allow you to scan a file by passing it as a single argument on the command line - I believe Windows Live Messenger uses this method.


Question:
I'm using VS 2008 to create a C++ DLL (not managed) project and I need convert a char* to a long long type. Is there an easy way to do it?

Thanks in advance :)

Answer:
Try
```
_atoi64.
```
This takes
```
char*
```
and returns
```
__int64
```
.


Question: The concept of a coroutine sounds very interesting, but I don't know, if it makes sense in a real productive environment? What are use cases for coroutines, where the coroutine implementation is more elegant, simpler or more efficient than other methods?

Answer:
True coroutines require language support.  They need to be implemented by the compiler and supported by the underlying framework.
One language-supported implementation of coroutines is the C# 2.0
```
yield return
```
keyword, which allows you to write a method that returns multiple values for looping.
The
```
yield return
```
does have limitations, however. The implementation uses a helper class to capture state, and it only supports the specific case of a coroutine as a generator (iterator).
In a more general case, an advantage of coroutines is that they make certain state-based computations easier to express and easier to understand.  For example, implementing a state machine as a set of coroutines can be more elegant than other implementations. But doing this requires language support that doesn't yet exist in C# or Java.


Question: The Drupal API has drupal_get_path($type, $name) which will give the path of any particular theme or module.  What if I want the path of the current theme?

Answer:
this should work (
doc
):
```
```
global $theme;
$path = drupal_get_path('theme', $theme);

// there's also a $theme_path global

global $theme_path;
```
```


Question: I was wondering if anyone knew of a macro or keyboard shortcut or anything really that would automate Attaching to a Process within visual studio?

Answer:
```
System.Diagnostics.Debugger.Break()
```
"If no debugger is attached, users are asked if they want to attach a debugger. If yes, the debugger is started. If a debugger is attached, the debugger is signaled with a user breakpoint event, and the debugger suspends execution of the process just as if a debugger breakpoint had been hit."
--
http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break.aspx


Question:
I need to grab the height of the window and the scrolling offset in jQuery, but I haven't had any luck finding this in the jQuery docs or Google.

I'm 90% certain there's a way to access height and scrollTop for an element (presumably including the window), but I just can't find the specific reference.

Answer:
```
```
$(window).height()

$(window).width()
```
```
There is also a plugin to jquery to determine element location and offsets
http://plugins.jquery.com/project/dimensions
scrolling offset = offsetHeight property of an element


Question:
There are multiple ways to fill an NSTableView up with data through either bindings, delegates, or data sources.

What is the best way to go about filling up the tableview with data that is changed pretty frequently from an XML-RPC server?  I'm targeting Mac OS X 10.5 only and there are lots of examples on how to do it, but nothing very definitive.

Any opinions?

Answer:
If I'm understanding correctly, it's really two separate questions. How do I fetch XML-RPC data, and how to populate a tableview?
I'm not too familiar with XML-RPC, but from doing a quick look around it seems like you can either do the parsing yourself with the NSXML* classes, or use one of several third party frameworks. I think it would be a good idea to look at the available frameworks first, even if you don't end up using one they should give you a good idea of how to go about parsing the XML data yourself if you go that route.
Once you have your data from the XML-RPC request, you'll want to store that in some sort of data structure in a controller class. You could use an array of dictionaries or basic strings, or make a custom object to represent your data, but that really depends on the complexity of what you're doing. The controller object will provide data to the table view, handle refreshing, and any other tasks you may need to do. You could make the XML-RPC request directly from the controller, or you may wish to create an additional class for this to separate the code.
Whether you use data source methods or bindings (along with an array controller) doesn't really matter, they both work fine and have their own advantages. If you're just starting with Cocoa, definitely use data source methods. Bindings requires intermediate knowledge of Objective-C and Cocoa, and will be hard to use and debug otherwise.


Question: How do you access a MySQL relation using RoR?

Answer:
Your question doesn't really make sense.
Rails works with ActiveRecord which handles all sorts of complex database relationships. Check the AR documentation for details.


Question:
I am in the process of setting up CruiseControl.NET. The problem I am having is that I am running CC as a console application and when my build completes successfully and executes (using exec) it launches it within the CruiseControl DOS prompt. I am just using simple batch files to launch my app but having it run within the same prompt as CC is causing CC to think the build continues as long as my app runs.

Are there command line parameters to cmd.exe that will spawn another separate prompt window?

Answer:
I think this works:
```
```
start cmd.exe
```
```


Question:
I am getting this warning:

Use of uninitialized value in eval \"string\" at myscript.pl line 57.

When I run this code:

eval;
{
        `$client -f $confFile -i $inputFile -o $outputFile`;
};

if( $@ )
{
        # error handling here ...
}

What is causing the error?

How can I fix the underlying cause? (Or otherwise suppress the warning?)

Answer:
There is a semicolon after
```
eval
```
.


Question:
I am considering using Maven for a Java open source project I manage.

In the past, however,  Maven has not always had the best reputation. What are your impressions of Maven, at this time?

Answer:
The JavaPosse discussed Maven quite a bit in
recent podcast #217
. The consensus was that it's very restrictive in how it allows you to structure your projects, but that its usage is growing, and that it may offer a cross-IDE standard for representing a project.
Update
—Javaposse also hosted an informative session at last spring's Java Roundup 09 entitled,
"Maven with Pain?"
I laughed (in horrified sympathy) as, toward the end of the recording, one of the participants related how a plugin update broke their build—two days before a production release.
I've steered clear of it, honestly, in large part because I find the name irritating. However, the ability to manage dependencies of third-party libraries is appealing.
Update
—for those that have an irrational disdain for my irrational opinion, let me show you what "maven" conjures up in my mind:
Yes, in my mind, Edna Mode is
the
epitome of "maven". And I don't want her in my build—too bossy!
What would be a better name? Invented words are best for their pin-point Google results. For a good impression, root them in real words with a positive connotation.


Question:
I'm wondering why styling an element within a specific class, like this:

.reddish H1 { color: red }

is shown as an example of correct syntax in the CSS1 specification under Contextual selectors:

Cascading Style Sheets, level 1

but it's not shown as an example in the CSS2 spec:

Cascading Style Sheets, Level 2

At least I can't find an example of it. Has the syntax rules for this changed in CSS2, or is it simply inferred as correct syntax?

Answer:
That syntax is correct, but the example may have changed for a couple of reasons.
Firstly it is not best practice to name classes by the description of what they do. In the case of
```
.reddish h1
```
, the example CSS shows that it is to be coloured red. However, if in a later design change the
```
h1
```
should in fact be blue then
```
```
.reddish h1 { color: blue; }
```
```
makes little sense. You should name your classes by their function or purpose on the page and not by what style they are supposed to represent.
Secondly, it isn't advised to use keywords for colours, as the colour you receive is down to browser interpretation. Instead, of 'red' you should use the hexcode '#ff0000' to get an accurate colour in all browsers. (red may not be the best example here, but there are some strange colour keywords out there).
While neither of these things is that bad, they both could add up to why the example had changed in the spec.


Question:
Is it possible using jQuery to select all <a> links which href ends with "ABC"?

For example, if I want to find this link <a href="http://server/page.aspx?id=ABC">

Answer:
```
```
$('a[href$="ABC"]')...
```
```
Selector documentation can be found at
http://docs.jquery.com/Selectors
For attributes:
```
```
= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")
```
```


Question:
I am having trouble constructing a single XPath statement to return two different sets of attributes.

For example take the following XML document:

<root>
 <line name="one" alpha="a1" beta="b1"/>
 <line name="two" alpha="a2" beta="b2"/>
 <line name="three" alpha="a3" beta="b3"/>
</root>

If I use the following XPath statement:

//@alpha

It yields the following attribute set:

alpha="a1"
alpha="a2"
alpha="a3"

What statement do I use to yield the following attribute set:

alpha="a1"
alpha="a2"
alpha="a3"
beta="b1"
beta="b2"
beta="b3"

Answer:
By using the
```
|
```
operator in an XPath expression you can select several paths:
```
```
//@alpha | //@beta
```
```


Question:
Is it possible for me to turn on audit logging on my mysql database?

I basically want to monitor all queries for an hour, and dump the log to a file.

Answer:
UPDATE: NO LONGER VALID FOR MYSQL 5.6+
Start mysql with the --log option:
```
```
mysqld --log=log_file_name
```
```
or place the following in your
```
my.cnf
```
file:
```
```
log = log_file_name
```
```
Either one will log all queries to log_file_name.
You can also log only slow queries using the
```
--log-slow-queries
```
option instead of
```
--log
```
.  By default, queries that take 10 seconds or longer are considered slow, you can change this by setting
```
long_query_time
```
to the number of seconds a query must take to execute before being logged.


Question:
I have a multi-threaded application that is hanging on a call to _dl_sysinfo_int80().  According to gdb, all threads are stuck in this call.

The top of the stack trace looks like:

#0  0x002727a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1  0x004f23de in __lll_mutex_lock_wait () from /lib/tls/libpthread.so.0
#2  0x004ef00b in _L_mutex_lock_35 () from /lib/tls/libpthread.so.0
#3  0x092828ac in construction vtable for std::ostream-in-std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> > ()

Any idea what could be causing this?

Answer:
int 80 is the software interrupt to make a kernel level system call.  My guess is that pthread is doing a call in to the kernel that is hanging.  There could be any number of reasons for why all of your threads would hang on a mutex like this:
- The mutex is locked by another thread that exited without releasing the lock
- The mutex is locked by one of the threads that is typing to lock it and wasn't declared recursive
- The mutex was never initialized at all
- The mutex has been corrupted by a bad pointer, stack problem, some other type of general memory corruption.


Question: What's the easiest way to truncate a C++ float variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?

Answer:
First it is important to know that floating point numbers are approximated.   See the link provided by @Greg Hewgill to understand why this problem is not fully solvable.
But here are a couple of solutions to the problem that will probably meet your need:
Probably the better method but less efficient:
```
```
char sz[64];
double lf = 0.600000002;
sprintf(sz, "%.4lf\n", lf); //sz contains 0.6000

double lf2 = atof(sz);

//lf == 0.600000002;
//lf2 == 0.6000

printf("%.4lf", lf2); //print 0.6000
```
```
The more efficient way, but probably less precise:
```
```
double lf = 0.600000002;
int iSigned = lf > 0? 1: -1;
unsigned int uiTemp = (lf*pow(10, 4)) * iSigned; //Note I'm using unsigned int so that I can increase the precision of the truncate
lf = (((double)uiTemp)/pow(10,4) * iSigned);
```
```


Question: I want to create a right click context menu for my textboxes to provide the typical copy/paste functionality. Any ideas on how to go about this?

Answer:
Looks like this is a
way to do this here
,
another example here
, and the
most recent one here
. Using these methods you should be able to show your own context menu. Once you have that you'll need access to the clipboard and there is an
example of this here
.
Good luck!


Question: Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?

Answer:
never used it myself, but I do follow the ipython mailing list, and there was a
thread
a couple months back.
maybe this will help
http://lists.ipython.scipy.org/pipermail/ipython-user/2008-September/005791.html
It's also a very responsive mailing list if you run into trouble.


Question:
The comment to this answer got me wondering.  I've always thought that C was a proper subset of C++, that is, any valid C code is valid C++ code by extension.  Am I wrong about that?  Is it possible to write a valid C program that is not valid C++ code?

EDIT: This is really similar to, but not an exact duplicate of this question.

Answer:
In general, yes C code is considered C++ code.
But C is not a proper subset in a strict sense.  There are a couple of exceptions.
Here are some valid things in C that are not valid in C++:
```
```
int *new;//<-- new is not a keyword in C
char *p = malloc(1024); //void * to char* without cast
```
```
There are more examples too, but you get the idea.
I previously wrote a more extensive answer in a similar question
here
.


Question:
Having the window handle for an open application, I'm able to use the GetWindowText function to retrieve the text from the title bar of the app.  I would like to take this a step farther and retrieve the icon associated with the same app.

How might I go about doing this?  I looked through what I thought would be the relevant Win32 API sections, but nothing jumped out at me.

Any pointers would be appreciated.

Thanks in advance!

Answer:
```
```
Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);
```
```
From TheSoftwareJedi
Initially this appears to be an exact duplicate of
How can I get the icon from the executable file only having an instance of it's Process in C#
but that one seems to focus largely on how to get it from within it's own self, whereas you may be asking how to get the icon using a program separate from the running process.
-Adam


Question:
How do I return a constant from an sql statement?

For example how would I change the code below so "my message" would return if my (boolean expression) was true

if (my boolean expression)
 "my message"
else
 select top 1 name from people;

I am using ms sql 2000

Answer:
Did you try:
```
```
select 'my message';
```
```