q: Can I export multiple calendar events into a single iCalendar file?

[A]
You simply make an iCalendar file with multiple VEVENT sections. For example:
```
```
BEGIN:VCALENDAR
BEGIN:VEVENT
DESCRIPTION:
DTEND:20071202T220000Z
DTSTAMP:20081124T220920Z
DTSTART:20071202T200000Z
LOCATION:Wherever
STATUS:CONFIRMED
SUMMARY:An event
UID:event-the-first
END:VEVENT
BEGIN:VEVENT
DESCRIPTION:Doing whatever, because for no good reason.
DTEND:20071209T210000Z
DTSTAMP:20081124T220920Z
DTSTART:20071207T190000Z
LOCATION:A specific place
STATUS:CONFIRMED
SUMMARY:Something, somewhere
UID:event-the-second
END:VEVENT
END:VCALENDAR
```
```


q:
If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.

What's the best practice to achieve this?  Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?

[A]
```
```
Boolean a = true;
Boolean b = false;
Boolean c = null;
```
```
I would use that. It's the most straight-forward.
Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required:
```
```
public enum ThreeState {
    TRUE,
    FALSE,
    TRALSE
};
```
```
There is the advantage of the first that users of your class doesn't need to care about your three-state boolean. They can still pass
```
true
```
and
```
false
```
. If you don't like the
```
null
```
, since it's telling rather little about its meaning here, you can still make a
```
public static final Boolean tralse = null;
```
in your class.

s: huggingface

c: devops

d: intermediate


q:
I have an application in which HttpRuntime.AppDomainAppPath returns the correct path with the wrong casing.

I am then trying to use this in a String.Replace and it does not find the path in the filename due to casing.

I am aware that I can use Regex.Replace but would prefer not to.

I have this problem only on the production machine even though the folder in question has the same casing in dev.

I have just noticed that Server.MapPath also returns the wrong casing.

Any ideas?

[A]
A few things:
If you don't care about casing, use .ToUpper or .ToLower, and replace on that.
```
```
Dim path As String = HttpRuntime.AppDomainAppPath.ToUpper
Dim newpath As String = Replace(path, "fnd", "rplc")
```
```
If that is not an option try changing the compare method in your replace function.
You didn't specify a language, so I cannot give a specific example.


q:
Here's a simple (hopefully) L10N question:

Do all locales want this format:

Sunday, Nov 23, 2008

with the weekday before the date, or do some locales want it after the date like this?

Nov 23, 2008, Sunday

[A]
I can't answer for all locales, but in French, we say "dimanche 23 novembre 2008", so for us, the answer is yes.
Now, I don't know your purpose, but you probably shouldn't make any guess like that anyway...
[EDIT] Funnily, I found an example in analyzing how the zh_TW locale is setting the date/time formats in Java 1.4. I found the format for this locale to be (after decompiling it):
```
```
"ahh'\u6642'mm'\u5206'ss'\u79D2' z",
"ahh'\u6642'mm'\u5206'ss'\u79D2'",
"a hh:mm:ss",
"a h:mm",
"yyyy'\u5E74'M'\u6708'd'\u65E5' EEEE",
"yyyy'\u5E74'M'\u6708'd'\u65E5'",
"yyyy/M/d",
"yyyy/M/d",
"{1} {0}"
```
```
while default, for US (found on the Net), is:
```
```
"h:mm:ss a z", // full time pattern
"h:mm:ss a z", // long time pattern
"h:mm:ss a", // medium time pattern
"h:mm a", // short time pattern
"EEEE, MMMM d, yyyy", // full date pattern
"MMMM d, yyyy", // long date pattern
"MMM d, yyyy", // medium date pattern
"M/d/yy", // short date pattern
"{1} {0}" // date-time pattern
```
```
See the full date pattern, the EEEE (day in week) is at the end for Taiwan...


q:
I'm using shared ASP.NET hosting and I have no remote-desktop access to the web server.  I only have the ability to FTP ASP.NET related files to the server.

In this scenario, how would I see how much memory my ASP.NET application is consuming?

[A] Could you create a page that listed various performance counters in a password-protected part of the site?  That would be my suggestion, along with making sure that somewhere on the page, a machine name or IP is listed so that should the site move among various servers, this can be noted somewhere.  Another idea would be to either write to a log file or send an e-mail with various performance counters so that you could see a history of how the server is doing, but be careful on the e-mail that this could become spam-like if you do it too frequently.


q: Wanting to deploy my project on different servers I would prefer to be able to specify a connect string using a relative path. I can't seem to get that to work and want to know if there is some trick to it...?

[A]
A suggestion
You could build the absolute path in the app and pass that in the connection string.
So, if you know that the database file is in the
```
database
```
subfolder of the application folder, you could do something like this (C#):
```
```
string relativePath = @"database\myfile.s3db";
    string currentPath;
    string absolutePath;
    string connectionString;

    currentPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
    absolutePath = System.IO.Path.Combine(currentPath,relativePath);

    connectionString = string.Format("DataSource={0}", absolutePath);

    SQLiteConnection cnn = new SQLiteConnection(connectionString);
```
```
(Someone can probably correct me on how to get the current path).


q:
I have a string

var s:String = "This is a line \n This is another line.";
this.txtHolder.text = s; //.text has \n, not a new line

and i want to put it into a text area, but the new line character is ignored. How can i ensure that the text breaks where i want it to when its assigned?

[A]
Try
```
```
"This is a line {\n} This is another line."
```
```
Alternatively, use the htmlText attribute and use
```
```
"This is a line <br> This is another line."
```
```


q:
There doesn't seem to be much info on this topic so I'm going to outline my specific problem then maybe we can shape the question and the answer into something a bit more universal.

I have this rewrite rule

RewriteEngine On
RewriteBase /bookkeepers/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/?$ index.php?franchise=$1

Which is changes this URL

http://example.com/location/kings-lynn

Into this one

http://example.com/location/index.php?franchise=kings-lynn

The problem I am having is that if I add a trailing slash

http://example.com/location/kings-lynn/

then the query string is returned as

franchise=kings-lynn/

and for some reason none of my CSS and Javascript files are being loaded.

Any ideas?

[A]
It looks like the (.+) is being greedy matched.  In that case, you could try
```
```
RewriteRule ^(.+[^/])/?$ index.php?franchise=$1
```
```
This makes sure that the first group (in the brackets) doesn't end in a slash.


q: Is it possible to intercept every request made from a page using javascript? i.e. Clicking on a link, loading an image, ajax request...

[A]
In a word, no.  There's no place you can hook into to get all the requests.
Having said that, you can us javascript to place event handlers on the links, look at the src attribute of image tags and so on.  There's no "generic" way to hook into all the AJAX requests - it depends on the library you're using.
There are other things to consider, such as CSS background images, Flash (what if a flash file makes a request?).
If possible you should be using the browser itself (e.g.
Firebug
) or a proxy (e.g.
Fiddler
) or a packet sniffer (e.g. Ethereal... seems to be
WireShark
now)


q:
In the past, when I've worked on long-running C++ daemons I've had to deal with heap fragmentation issues.  Tricks like keeping a pool of my large allocations were necessary to keep from running out of contiguous heap space.

Is this still an issue with a 64 bit address space?  Perf is not a concern for me, so I would prefer to simplify my code and not deal with things like buffer pools anymore.  Does anyone have any experience or stories about this issue?  I'm using Linux, but I imagine many of the same issues apply to Windows.

[A]
If your process genuinely needs gigabytes of virtual address space, then upgrading to 64-bit really does instantly remove the need for workarounds.
But it's worth working out how much memory you expect your process to be using. If it's only in the region of a gigabyte or less, there's no way even crazy fragmentation would make you run out of 32-bit address space - memory leaks might be the problem.
(Windows is more restrictive, by the way, since it reserves an impolite amount of address space in each process for the OS).


q: Are the formulas represented in a syntax tree then recalculated using a design pattern like the Visitor pattern? How would you go about reproducing the recalculation process in code?

[A]
Probably, as you say, one guess is that Excel creates a bunch of ASTs, one for each indipendent group of cells, where the leaves are the originating, static data, and the nodes are formulas.
Then it calculates the result for each node, with a
post-order
tree traversal algorithm.
You have to take into account leaf/node cancellation, partial recalculation, ecc. If I'm not wrong, I read somewhere that Excel could benefit of multicore processors to recalculate a sheet in parallel.


q:
I know it makes little difference to a project but, assuming you use #defined header guards for your C++ code, what format do you use?  e.g. assuming a header called foo.hpp:

#ifndef __FOO_HPP__
...

#ifndef INCLUDED_FOO_HPP
...

#ifndef SOME_OTHER_FORMAT

I'm sold on the idea of upper-case #defines but cannot settle on a format for these guards.

[A]
I always use
```
INCLUDED_FOO_HPP
```
I wouldn't use the double underscore one, because starting things with double underscores is reserved.


q:
I'm reading through K&R and came to the small section on register variables, and was wondering if people here have some good examples of this put into practice.

From section 4.7 in K&R:

The register declaration looks like

       register int  x;

       register char c;

To be clear, I'm just hoping to see some cool code samples. I (am pretty sure that I) understand the subject matter so don't feel the need to type up a verbose explanation (unless you want to).

[A]
There is no good example of register usage when using modern compilers (read: last 15+ years, and note that this answer is from 2008) because it almost never does any good and can do some bad.  When you use register, you are telling the compiler "I know how to optimize my code better than you do" which is almost never the case.  One of three things can happen when you use register:
The compiler ignores it, this is most likely.  In this case the only harm is that you cannot take the address of the variable in the code.
The compiler honors your request and as a result the code runs slower.
The compiler honors your request and the code runs faster, this is the least likely scenario.
Even if one compiler produces better code when you use register, there is no reason to believe another will do the same.  If you have some critical code that the compiler is not optimizing well enough your best bet is probably to use assembler for that part anyway but of course do the appropriate profiling to verify the generated code is really a problem first.


q:
I have read around 4-5 books on design patterns, but still I don't feel I have come closer to intermediate level in design patterns?

How should I go studying design patterns?

Is there any good book for design patterns?

I know this will come only with experience but there must be some way to master these?

[A]
The best way is to begin coding with them.  Design patterns are a great concept that are hard to apply from just reading about them.  Take some sample implementations that you find online and build up around them.
A great resource is the
Data & Object Factory
page.  They go over the patterns, and give you both conceptual and real world examples.  Their reference material is great, too.


q: I am sure there are many developers out here who have team spread across different time zones. What are some of the challenges people face and whats the best way to tackle them?

[A]
In all honesty, any company that has split development of a project across time zones is out of touch with the realities of engineering.  The MBAs, in an attempt to save themselves a buck or two, foist upon their engineers the unenviable position of altering the schedules of their lives - leading to high stress, longer work hours, lower morale, and higher turnover.  Quality suffers, ship dates suffer, feature lists suffer.  The only increase you'll see in your project is the bug count.
You can have engineering projects split up like this if you don't have any need for low-latency communication between project units.  In other words - if they are working on almost entirely independent segments of the system.


q: Is there a command, or a set of tables I can look at to determine which tables, stored procedures and views in SQL Server server 2005 have a certain user defined data type?

[A]
Tables are relatively easy, sys.columns and sys.types allow you to link columns to types.  The query below will get this out.
```
```
select s.name
      ,o.name
      ,c.name
      ,t.name
  from sys.schemas s
  join sys.objects o
    on o.schema_id = s.schema_id
  join sys.columns c
    on c.object_id = o.object_id
  join sys.types t
    on c.user_type_id = t.user_type_id
 where t.name = 'Foo'
```
```
EDIT: as G Mastros has shown above, you can get parameters with a similar query.
```
```
select s.name
      ,o.name
      ,p.name
      ,t.name
  from sys.schemas s
  join sys.objects o
    on o.schema_id = s.schema_id
  join sys.parameters p
    on p.object_id = o.object_id
  join sys.types t
    on p.user_type_id = t.user_type_id
 where t.name = 'Foo'
```
```


q:
I will explain problem with an example:

There is two table in my database, named entry, tags

There is a column named ID_ENTRY in both table. When I add a record to table, entry, I have to take the ID_ENTRY of last added record and add it to table, tags. How can I do it?

[A]
I would probably do this with an INSERT trigger on the named entry table, if you have all of the data you need to push to the tags table available.  If not, then you might want to consider using a stored procedure that creates both inside a transaction.
If you want to do it in code, you'll need to be more specific about how you are managing your data.  Are you using DataAdapter, DataTables, LINQ, NHibernate, ...?  Essentially, you need to wrap both inserts inside a transaction of some sort so that either inserts get executed or neither do, but the means to doing that depend on what technology you are using to interact with the database.


q:
I have a dll that was written in c++, I need to use this dll in my c# code. After searching I found that using P/Invoke would give me access to the function I need, but these functions are defined with in a class and use non-static private member variables. So I need to be able to create an instance of this class to properly use the functions. How can I gain access to this class so that I can create an instance? I have been unable to find a way to do this.

I guess I should note that the c++ dll is not my code.

[A]
There is no way to directly use a C++ class in C# code.  You can use PInvoke in an indirect fashion to access your type.
The basic pattern is that for every member function in class Foo, create an associated non-member function which calls into the member function.
```
```
class Foo {
public:
  int Bar();
};
extern "C" Foo* Foo_Create() { return new Foo(); }
extern "C" int Foo_Bar(Foo* pFoo) { return pFoo->Bar(); }
extern "C" void Foo_Delete(Foo* pFoo) { delete pFoo; }
```
```
Now it's a matter of PInvoking these methods into your C# code
```
```
[DllImport("Foo.dll")]
public static extern IntPtr Foo_Create();

[DllImport("Foo.dll")]
public static extern int Foo_Bar(IntPtr value);

[DllImport("Foo.dll")]
public static extern void Foo_Delete(IntPtr value);
```
```
The downside is you'll have an awkward IntPtr to pass around but it's a somewhat simple matter to create a C# wrapper class around this pointer to create a more usable model.
Even if you don't own this code, you can create another DLL which wraps the original DLL and provides a small PInvoke layer.


q:
What is the most recommended/best way to stop multiple instances of a setTimeout function from being created (in javascript)?

An example (psuedo code):

function mouseClick()
{
   moveDiv("div_0001", mouseX, mouseY);
}

function moveDiv(objID, destX, destY)
{
   //some code that moves the div closer to destination
   ...
   ...
   ...

   setTimeout("moveDiv(objID, destX, destY)", 1000);
   ...
   ...
   ...
}

My issue is that if the user clicks the mouse multiple times, I have multiple instances of moveDiv() getting called.

The option I have seen is to create a flag, that only allows the timeout to be called if no other instance is available...is that the best way to go?

I hope that makes it clear....

[A]
```
```
var timeout1 = window.setTimeout('doSomething();', 1000);
var timeout2 = window.setTimeout('doSomething();', 1000);
var timeout3 = window.setTimeout('doSomething();', 1000);

// to cancel:
window.clearTimeout(timeout1);
window.clearTimeout(timeout2);
window.clearTimeout(timeout3);
```
```


q:
Suppose you have a GridView with a few columns like:

| Foo | Bar | Total |

and you use a style sheet to make the alternating rows different colors, say light blue and white.

Is there a good way to make a particular column alternate in a different color?  For example, I might want the Total column to alternate in medium and light red to bring attention to it in a large grid.

BTW, I know you can programmatically change the color of a cell.  I'd like to stick to CSS if it all possible, however, so all my style stuff is in one place.  I also don't see an easy way to tell if I'm in an alternating row when I'm inside the event handler.

[A]
If you're using jQuery, you can do it pretty easily.
```
```
$("table#myTable col:odd").css("background-color:#ffe");
```
```
the
```
:odd
```
selector is not available in most current browsers, but jQuery gives it to us today.
For rows, you can do it with the built-in AlternatingRowStyle element.
Edit: found a good resource for some different ways of doing this:
http://css-discuss.incutio.com/?page=StylingColumns


q:
I have a directory to which a process uploads some .pdf files. This process is out of my control.

I need to make those files available through the website using Tomcat.

I have a directory /var/lib/tomcat5/webapps/test1 available to the web and I can see the files in it with a browser.

So, I created a symbolic link pointing at the directory with the .pdf files:
/var/lib/tomcat5/webapps/test1/files/, but I can't see anything in that directory.

How can I enable symlinks in the test1 directory only?  I don't want to enable symlinks everywhere, just so that directory with .pdf files is available to the web.

[A]
Create a context.xml file in a
```
META-INF
```
directory in your web app containing:
```
```
<?xml version="1.0" encoding="UTF-8"?>

<Context path="/myapp" allowLinking="true">

</Context>
```
```
more here:
http://www.isocra.com/2008/01/following-symbolic-links-in-tomcat/


q:
I am a junior programmer. Since my supervisor told me to sit in with the client, I joined. I saw the unsatisfied face of the client despite the successful (from my programmer's perspective) delivery of the project!

Client: You could have included this!

Us: Was not in the specification!

Client: Common Sense!

As a programmer, how do you respond in this situation?

[A]
What you should do to avoid this situation:
Explicitly spec out what will be included and what will not be included.
The problem probably comes down to the unspecified parts of the spec:
The client thinks that unspecified stuff should be in, i.e. it was implied.
The developer thinks that unspecified stuff should not be in.
For future specs that you have, you should have a catch all statement, that explicitly states that if something is not specified in this document, it can be done after the original specification is done at an additional cost.
What you should do in the current situation:
Other than learning from your experiences, you should come to some compromise with the client.
Example: I will do this feature that you feel is common sense, but for all future additions/changes it will have to be spec'ed out explicitly.
I.e. you will have to do a little more work, but it is worth it in return for the catch all explicitly spec'ed agreement your client will enter into.
Bad spec?
Was it necessarily a bad spec? No.
It is impossible to mention everything your clients may expect, so it is critical to have this catch all statement mentioned above stated clearly and explicitly in your spec/contract.
Other ways to reduce the problem:
Involve the client early, show them early prototypes.  Even if they don't demand it.
Try not to sell the client an end product, but more of a service for working on his product.
Consider an agile development model or something similar so that tasks are well defined, small, paid for, and indisputable.


q: There might be applications that are not suited for Core Data - image manipulation programs like Photoshop or Gimp for example. But for applications that are suited for Core Data, say Address Book or iCal, what is the criteria to choose Core Data over a custom model?

[A]
I recently started a project where I decided to use Core Data for the first time in a real world application. My application is actually version 2.0 of an older app that uses a custom data model, so I spent a lot of time debating this question. Here are some of the things I asked myself.
The time to learn how Core Data works in a non-trivial application and fixing the little bugs and idiosyncrasies that pop up when you're learning a new technology. This may include a prototype or two, since you don't want to jump into using something like Core Data that will be responsible for such as large chunk of your application.
Whether or not Core Data will solve problems that are hard to address when using a custom data model, for example storing and holding in memory very large sets of data.
Whether or not you want to share code with a platform where Core Data is not available, for instance Cocoa Touch. Along the same lines, if you want the resulting data files to be compatible without having to build a separate exporter.
If learning Core Data will help improve yourself as a programmer, whether its making your more attractive to Mac development shops or just for your own use.
If your data model is simple enough that you don't really need things like undo manager support or relationships, the areas where core data really shines.
If you're using external libraries or other technologies such as Distributed Objects, where you might not want to use NSManagedObject.


q: I need to share SSO information between two different domains with a cookie, can this be done in PHP and how?

[A]
On both domains, place an image or other web element that is pulled from the other domain.  Use the URL to notify the other domain that user X is on domain A, and let domain B associate that user ID with that user on their system.
It's a little complex to carry out correctly, but if you think it through it'll work out very well.
Vinko points out in a comment (thanks!) that I shouldn't take it for granted that you understand the security risks involved.  If this information is of any value to anyone, then you should make sure you use proper encryption, authentication, etc to avoid releasing sensitive information and to avoid various attacks (replay, man in the middle, etc).  This shouldn't be too onerous since you control both websites and you can select a secure secret key for both, since the communication is only going between the two servers via this special URL.  Keep it in mind though.
-Adam


q:
I want to start using Nunit (finally), I am using Visual Studio 2008.

Is it as simple as importing Nunit into my test project?

I remember seeing a GUI for NUnit, does that do the exact same thing that a separate test project would do, except show you the pass/fail visually?

[A]
Yes, that's basically it. Personally I find the unit test runner which comes with
ReSharper
to be excellent - and the tool itself is well worth the licence feel. Alternatively there's
TestDriven.NET
.
Having a test project which runs nunit-gui or nunit-console separately is all very well, but you really want the whole unit testing experience to be as seamless as possible. The easier it is to write and run tests, the more likely you are to do it - which is a very good thing. Don't underestimate the gradual build-up of frustration due to a
slightly
poorer user experience, flipping between windows etc.


q:
Is there anything to use, to determine if a type is actually a anonymous type? For example an interface, etc?

The goal is to create something like the following...

//defined like...
public static T Get<T>(this IAnonymous obj, string prop) {
    return (T)obj.GetType().GetProperty(prop).GetValue(obj, null);
}
//...

//And then used like...
var something = new { name = "John", age = 25 };
int age = something.Get<int>("age");

Or is that just the beauty of an anonymous type? Nothing to identify it self because it takes a new shape?

Note - I realize that you can write an extension method for the object class, but that seems like a little overkill, in my opinion.

[A]
As I recall, there is a
```
[CompilerGenerated]
```
marker... 2 secs
Plus the name will be freaky, and it will be a generic type ;-p
Actually, for a "get" etc I would probably just use a static (non-extension) method.
If you just want a way to get the value from an instance of an anon-type (at a later point in time), a lambda is probably the best option - note you need a few tricks to pull this off:
```
```
static void Main()
    {
        var foo = new { name = "John", age = 25 };
        var func = Get(foo, x => x.age);
        var bar = new { name = "Marc", age = 30 };
        int age = func(bar);
    }
    // template here is just for type inference...
    static Func<TSource, TValue> Get<TSource, TValue>(
        TSource template, Func<TSource, TValue> lambda)
    {
        return lambda;
    }
```
```
(edit re the comment) There definitely
is
this attribute:
```
```
var foo = new { A = "B" };
        Type type = foo.GetType();

        CompilerGeneratedAttribute attrib = (CompilerGeneratedAttribute) Attribute.GetCustomAttribute(
            type, typeof(CompilerGeneratedAttribute)); // non-null, therefore is compiler-generated
```
```


q:
I'm trying to use the FolderBrowserDialog from my WPF application - nothing fancy. I don't much care that it has the Windows Forms look to it.

However, when I call ShowDialog, I want to pass the owner window which is an IWin32Window. How do I get this from my WPF control?

Actually, does it matter? If I run this code and use the ShowDialog overload with no parameters it works fine. Under what circumstances do I need to pass the owner window?

Thanks,

Craig

[A]
If you specify Owner, you will get a Modal dialog over the specified WPF window.
To get WinForms compatible Win32 window create a class implements IWin32Window like this
```
```
public class OldWindow : System.Windows.Forms.IWin32Window
{
    IntPtr _handle;

    public OldWindow(IntPtr handle)
    {
        _handle = handle;
    }

    #region IWin32Window Members

    IntPtr System.Windows.Forms.IWin32Window.Handle
    {
        get { return _handle; }
    }

    #endregion
}
```
```
And use an instance of this class at your WinForms
```
```
IntPtr mainWindowPtr = new WindowInteropHelper(this).Handle; // 'this' means WPF Window
        folderBrowserDialog.ShowDialog(new OldWindow(mainWindowPtr));
```
```


q:
Is it possible?
By debug I mean setting breakpoints, inspect values and advance step by step.

[A]
I haven't used web2py, but if it runs in a terminal window, you can use standard pdb stuff. Add this line somewhere in your code:
```
```
import pdb; pdb.set_trace()
```
```
This will invoke the debugger and break.  Then you can use
PDB
commands: n to step to the next line, l to list code, s to step into a function, p to print values, etc.


q: I am trying to find out which Hypervisor will allow me to grant access to specialized PCI cards (such as a telephony card) to a virtual machine. So far I have tried out VMWare ESXi server and it doesn't seem to allow me to do this. I have heard that Microsoft Virtual Server does allow this, but I haven't been able to find any supporting documentation.

[A]
I'd look into
Xen
, it appears that you can load a backend xen driver on the host OS which will then allow you to communicate directly with the hardware from the guest.
See
this link
for more information. I'm not a Xen user, but from my virtualization experience I would guess that the paravirtualization aspects of a Xen host/guess is going to be your best bet for raw device access.


q:
I have a large db with many tables and sprocs, and I want to find and see, for example, if there is a table with a name that has "setting" as part of it.  I'm not very familiar with SqlServer's System Databases like master, msdb etc., I know there is a way to query one of those dbs to get what I need back, does someone know how to do it?

Thank you,
Ray.

[A]
the table you want is sys.objects
```
```
SELECT *
FROM sys.objects
```
```


q:
I've got Postscript code/data (?) in memory (in a Java Tomcat webapp) that I'd like to send directly to a networked PS printer.  Is there an easy way (i.e. just popping open a port and sending the text) to print this, bypassing all of the O/S-specific drivers and stuff (and hopefully not even requiring extra jars)?  A link to example code showing how to do this?

Thanks,
Dave

[A]
I am not sure you can do it without extra library.
This
example
shows you how to send the file to a network printer, but requieres an adobe library (based on commercial J2EE
Livecycle ES
though, so not a generic "free" solution...).
```
```
import com.adobe.livecycle.output.client.*;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import com.adobe.idp.Document;
import com.adobe.idp.dsc.clientsdk.ServiceClientFactory;

public class SendToPrinter {

    public static void main(String[] args) {
        try{
            //Set LiveCycle ES service connection properties
            Properties ConnectionProps = new Properties();
            ConnectionProps.setProperty("DSC_DEFAULT_EJB_ENDPOINT", "jnp://localhost:1099");
            ConnectionProps.setProperty("DSC_TRANSPORT_PROTOCOL","EJB");
            ConnectionProps.setProperty("DSC_SERVER_TYPE", "JBoss");
            ConnectionProps.setProperty("DSC_CREDENTIAL_USERNAME", "administrator");
            ConnectionProps.setProperty("DSC_CREDENTIAL_PASSWORD", "password");
            //Create a ServiceClientFactory object
            ServiceClientFactory myFactory = ServiceClientFactory.createInstance(ConnectionProps);
            //Create an OutputClient object
            OutputClient outClient = new OutputClient(myFactory);
            //Reference XML data that represents form data
            FileInputStream fileInputStream = new FileInputStream("C:\\Adobe\\Loan_data.xml");
            Document inputXML = new Document(fileInputStream);
            //Set print run-time options
            PrintedOutputOptionsSpec printOptions = new PrintedOutputOptionsSpec();
            printOptions.setPrinterURI("\\\\Printer1\\Printer");
            printOptions.setCopies(2);

            //Send a PostScript print stream to printer
            OutputResult outputDocument = outClient.generatePrintedOutput(
                    PrintFormat.PostScript,
                    "Loan.xdp",
                    "C:\\Adobe",
                    "C:\\Adobe",
                    printOptions,
                    inputXML);

            //Write the results of the operation to OutputLog.xml
            Document resultData = outputDocument.getStatusDoc();
            File myFile = new File("C:\\Adobe\\OutputLog.xml");
            resultData.copyToFile(myFile);
        }
        catch (Exception ee)
        {
            ee.printStackTrace();
        }
    }
}
```
```


q:
So my goal is to be able to add a user from one Active Directory Domain to another group in a separate Active Directory Domain.

I'd like to do this in C#.  I know there is a System.DirectoryServices namespace with classes to communicate with AD, but I can't find any information on adding users across domains.

In the environment there are two domain controllers with the same parent forest.  There is a transient trust between the 2 domains, let's call them domains A and B.

I'm able to add a user from B to a Domain Local or Universal group inside of domain A with the Active Directory tool.

Does anyone know how I can do this programmatically using C#?

[A]
What worked for me when I wrote code to do this a couple years back:
Get a DirectoryEntry for the group to which you want to add a member.
Call Invoke on the group DirectoryEntry passing arguments "Add" as the method name and the
ADsPath
of the member in an array.
Some sample code off the top of my head:
```
```
DirectoryEntry group = new DirectoryEntry(@"LDAP://CN=foo,DC=domainA");
string memberADsPath = @"LDAP://CN=bar,DC=domainB";
group.Invoke("Add", new Object[] {memberADsPath});
```
```


q:
I thought I'd get myself a Subversion setup at home for my hobby projects, and I'm trying to do it right, first time (my work's source control control policies or lack of them are, well, not perfect).

The thing I'm struggling with is this:  I'd like to version entire Eclipse projects.  This will be good from Eclipse's point of view - I'll just let it do its thing, and should just mean I need to ignore a few binaries / whole build directories and set up these ignores just once when I set up the project (right?).  Anyway, I've tried it a couple of times and svn seems to get confused and ignore my ignore settings.  What should be the correct procedure?

Thanks.

PS I'm doing the svn bits from command line, trying to avoid a GUI till I'm happy with it.

[A]
If you on a linux box, you can try these steps, if on windows, pretty the installer shall do things for you.
https://help.ubuntu.com/community/Subversion
Also the subversion book might help
http://svnbook.red-bean.com/en/1.5/index.html


q: In our Flex AIR app, we have the problem that our main app window is fairly narrow. This means Alert dialog boxes are chopped on both side, while the right click menu is cropped. How can we get these windows to not get cropped by our main window?

[A]
With flex applications running inside of the flash player, windows cannot be shown outside of the stage.  So the only way to make this work would be to make your app larger.
You could though use the flex/ajax bridge and call a javascript alert box instead, they would not be bound by the stage.  But it would not be skinned like the rest of the application though and would take some more work to get hooked in, especially if you are listening for the user to click the okay button...


q:
At the moment I'm creating a DateTime for each month and formatting it to only include the month.

Is there another or any better way to do this?

[A]
You can use the following to return an array of string containing the month names
```
```
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
```
```


q:
I am very interested in learning a Ruby on Rails / Django type web technology but am currently using Windows Server 2008 (for .Net web applications.) I have read that RoR is not very performant on Windows.

Would it be unadvisable to create run a beta web application in RoR on a Windows Web server as far as performance is concerned?

Would Django or another similar technology be a better choice? Can you be a "happy, productive programmer" and still use a Windows Server?

(Note: I actually do enjoy heavily modified Asp.Net / C#. I'm looking to try some different stacks that might be fun and productive from the start.)

[A]
You can still learn a technology on Windows even if it isn't good at high performance on that platform yet.
I strongly recommend
against
trying to learn new technology at the same time as implementing an actual project you care about.  It's better to write a pretend project while learning new tools or languages.
That way you can try out features of that technology that aren't relevant to your desired project, and you aren't distracted by focus on your own project's requirements while you're trying to learn.
So go ahead and learn both, experiment with them on Windows.  There are good step-by-step tutorials available and ready-to-install bundles for both
Rails
and
Django
on Windows.


q:
What is the correct syntax for this:

IList<string> names = "Tom,Scott,Bob".Split(',').ToList<string>().Reverse();

What am I messing up?
What does TSource mean?

[A]
Try this:
```
```
List<string> names = new List<string>("Tom,Scott,Bob".Split(','));
names.Reverse();
```
```


q:
tldr:  Can someone show me how to properly format this Python iMAP example so it works?

from
https://docs.python.org/2.4/lib/imap4-example.html

import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

Assuming my email is "email@gmail.com" and the password is "password," how should this look?  I tried M.login(getpass.getuser(email@gmail.com), getpass.getpass(password))
and it timed out.  Complete newb here, so it's very likely I missed something obvious (like creating an iMAP object first?  Not sure).

[A]
Did you forget to specify the IMAP host and port? Use something to the effect of:
```
```
M = imaplib.IMAP4_SSL( 'imap.gmail.com' )
```
```
or,
```
```
M = imaplib.IMAP4_SSL()
M.open( 'imap.gmail.com' )
```
```


q: When coding, what is a good rule of thumb to keep in mind with respect to performance? There are endless ways to optimize for a specific platform and compiler, but I'm looking for answers that apply equally well (or almost) across compilers and platforms.

[A]
The number #1 performance tip is to profile your code early and often.  There are a lot of general "don't do this" tips but it's really hard to guarantee this will impact the performance of your application.  Why?  Every application is different.  It's easy to say that passing a vector by value is bad if you have a lot of elements but does your program even use a vector (you probably should but ...)?
Profiling is the only way to understand the performance of your application.  I've been in way too many situations where people "optimized" the code but didn't ever profile.  The "optimizations" turned out to introduce many bugs and not even be a hot spot in the code path.  Waste of everyones time.
EDIT:
A couple of people have commented on the "early" part of my answer.  I don't think you should be profiling from day 1.  However you should also not be waiting till 1 month from ship either.
I usually first profile once I have a couple of definitive end to end scenarios, or in a larger project, a mostly functional component.  I take a day or two (usually working with QA) to get together some large scenarios and throw it at the code.  This is a great spot check to find obvious performance problems early.  Fixing them at this point is a bit easier.
On a typical project I find that I have code meeting this criterias 30%-40% of the way through the project (100% being in customers hands).  I loosely classify this time as early.


q: I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An example would be very much appreciated. Thanks in advance.

[A]
Read about the
RE
pattern's
```
match
```
method.
Read all answers to
How do I copy files with specific file extension to a folder in my python (version 2.5) script
?
Pick one that uses
```
fnmatch
```
.  Replace
```
fnmatch
```
with
```
re.match
```
.  This requires careful thought.  It's not a cut-and-paste.
Then, ask specific questions.


q:
I am using windows authentication within an ASP.NET application. I am wondering how to best get the objectGuid from the currently logged in user?

Regards, Egil.

[A]
You can do this with the System.DirectoryServices namespace.
```
```
Dim entry As DirectoryServices.DirectoryEntry
Dim mySearcher As System.DirectoryServices.DirectorySearcher
Dim result As System.DirectoryServices.SearchResult
Dim myEntry As DirectoryEntry
Dim domainName As String
Dim userId As String
Dim objectGuid As Guid

'Split the username into domain and userid parts
domainName = Page.User.Identity.Name.Substring(0, Page.User.Identity.Name.IndexOf("\"))
userId = Page.User.Identity.Name.Substring(Page.User.Identity.Name.IndexOf("\") + 1)

'Start at the top level domain
entry = New DirectoryEntry(domainName)

mySearcher = New DirectorySearcher(entry)

'Build a filter for just the user
mySearcher.Filter = ("(&(anr=" & userId & ")(objectClass=user))")

'Get the search result ...
result = mySearcher.FindOne

'... and then get the AD entry that goes with it
myEntry = result.GetDirectoryEntry

'The Guid property is the objectGuid
objectGuid = myEntry.Guid
```
```
There might be a better way to do this, but this works!


q:
I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?

I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid in some part that should be fairly simple. So....

[A]
Reversi is an elegantly simple game. I'm going to use a psuedo C#/Java langauge to explain some concepts, but you can transpose them to Python.
To break it down into its most simple compnents, you have two basic things:
A 2 dimensional array that represents the game board:
```
```
gameBoard[10,10]
```
```
And some form of enumaration that stores the state of each tile in the gameboard:
```
```
enum tile
{
    none,
    white,
    black
}
```
```
To render the board, you loop through the gameBoard array, increasing by an offset of the piece size:
```
```
for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        // The Piece to draw would be at gameBoard[i,j];
        // Pixel locations are calculated by multiplying the array location by an offset.
        DrawPiece(gameBoard[i,j],i * Width of Tile, j * width of tile);
    }
}
```
```
Likewise, resolving a mouse click back to a location in the array would be similar, use the mouse location and offset to calculate the actual tile you are on.
Each time a tile is placed, you scan the entire array, and apply a simple rules based engine on what the new colors should be. (This is the real challenge, and I'll leave it up to you.)
The AI can take advantage of doing this array scan with hypothetical moves, have it scan 10 or so possible moves, then choose the one that produces the best outcome. Try to not make it to smart, as its easy to make an unbeatable AI when you let it play out the entire game in its head.
When there are no longer any free locations in the array, You end the game.


q:
I will have around 200,000 images as part of my website. Each image will be stored 3 times: full size, thumbnail, larger thumbnail. Full size images are around 50Kb to 500Kb.

Normal tech: Linux, Apache, MySQL, PHP on a VPS.

What is the optimum way to store these for fast retrieval and display via a browser??

Should I store everything in a single folder?
Should I store the full size images in 1 folder, the thumbails in another etc?
Should I store the images in folders of 1000, and keep an index to which folder the image is in?

Thanks for any advice.
Albert.

[A]
Depends on how you're indexing them, for how to retrieve them.
There's nothing particularly against storing them all in a single folder, but it becomes difficult to manage.  If you're storing them by filename, and the filenames are reasonably normally distributed, you might want to have subfolders separated by first letter of the name, etc.  If you're indexing by date added, you may want to segregate them by that.
As far as I know, there's no "faster" or "slower" way to store the images for browser retrieval.


q:
is there an easy way to solve the following problem.

Let's say I fetch a IList with some books in my controller from my model. Now I want to enrich the output and fetch a preview from Amazon with another model from an outside framework and get another IList.

Now I put both ILists into a property bag.

In NVelocity I use a #foreach for the BookList, but how can I access the amazonbooklist with the right preview?
I cannot use $amazonbook[index], where index would be the isbn.
Do I really need to put both lists in one big list with a simple onject containing only the two other objects?

Remember, both models are from different frameworks and cannot be placed in one framework. Both frameworks have to stay seperated. I try to solve the NVelocity problem and ofcourse, this problem is just an example, we don't sell books ;)

[A]
There may be a simpler solution, but I would create a third class like such
```
```
class BookList{
       MyBookObject     a;
       AmazonBookObject b;
}
```
```
a list of this third class could be passed to your view at once.


q:
I am currently using SQL Server Management Studio (Ver 9.00.3042.00) and click the "New Query" and wrote the following code:

Select
    colA,
    colB,
    colC
    colD
From
    table1

When I click the parse (checkbox) button to validate the SQL statement, it says "Command(s) completed successfully".  Isn't the parse button suppose to catch these simple errors...

Has anyone experienced this type of behavior from Management Studio?  This just started happening this week....

[A]
That's because that is valid SQL. You're effectively aliasing colC with the name colD. It's the same as typing:
```
```
colC as colD
```
```
Edit: For what it's worth, this is one of the reasons why people will argue that you should put the commas at the beginning of the line in cases like this. It's a lot easier to spot gotchas like this when the code is formatted as such:
```
```
Select
    colA
    , colB
    , colC
    colD
From
    table1
```
```


q:
Do you have any tricks for generating SQL statements, mainly INSERTs, in Excel for various data import scenarios?

I'm really getting tired of writing formulas with like

="INSERT INTO Table (ID, Name) VALUES (" & C2 & ", '" & D2 & "')"

[A]
The semi-colon needs to be inside the last double quote with a closing paren.  When adding single quotes around a string, remember to add them outside your selected cell.
(spaces added for visibility - remove before inserting)
```
=CONCATENATE("insert into table (id, name) values (",C2,",' ",D2," ');")
```
Here is another view:
```
=CONCATENATE("insert into table (id, date, price) values (",C3,",'",D3,"',",B3,");")
```


q:
I want to be able to take still images with a web cam, via .NET 2.0 (or 3.5 if necessary). I know I can use DirectShow but that seems like a very large learning curve.

Is there a simple to use OCX, or library that can work with most standard webcams?

[A]
The main hurdle to easily transforming your algorithm is that it doesn't result in a sequence of calls to the same function; but alternates between a few ones, each operating on the result of the other.
i'd say you have three alternatives:
totally reformulate the algorithm (that's what the Fibonacci examples do).
combine all functions into a single one with lots of cond's (ugly, and maybe won't result in a real tail-recursion, even with a single function).
turn the flow inside-out: write a single, simple tail-recursive function that transforms the input data into the sequence of operations that have to be performed, and then eval it.


q:
Here is the code currently used.

public String getStringFromDoc(org.w3c.dom.Document doc)    {
        try
        {
           DOMSource domSource = new DOMSource(doc);
           StringWriter writer = new StringWriter();
           StreamResult result = new StreamResult(writer);
           TransformerFactory tf = TransformerFactory.newInstance();
           Transformer transformer = tf.newTransformer();
           transformer.transform(domSource, result);
           writer.flush();
           return writer.toString();
        }
        catch(TransformerException ex)
        {
           ex.printStackTrace();
           return null;
        }
    }

[A]
The transformer API is the only XML-standard way to transform from a DOM object to a serialized form (String in this case). As standard I mean SUN
Java XML API for XML Processing
.
Other alternatives such as Xerces
XMLSerializer
or JDOM
XMLOutputter
are more direct methods (less code) but they are framework-specific.
In my opinion the way you have used is the most elegant and most portable of all. By using a standard XML Java API you can plug the XML-Parser or XML-Transformer of your choice without changing the code(the same as JDBC drivers). Is there anything more elegant than that?


q:
Which is better in general in terms of the ordering?  Do you put the fault condition at the top or bottom?

if (noProblems == true) {
    // do stuff
} else {
    // deal with problem
}

OR

if (noProblems == false) {
    // deal with problem
} else {
    // do stuff
}

[A]
i like to eliminate error cases first - and return from the function early so that the 'happy path' remains un-nested, e.g.
```
```
if (some error condition)
{
    //handle it
    return;
}
//implicit else for happy path
...
```
```
if it is easy to identify the conditions leading to the happy path, then by all means put that clause first (thanks Marcin!)


q:
I am trying to use ShellExecute to open a file in Excel. I was reading about the function on MSDN forums, and I found the folowing information about the handle, which is the first parameter:

"hwnd [in] A handle to the owner window used for displaying a user interface (UI) or error messages. This value can be NULL if the operation is not associated with a window."

I have also heard this referred to as the handle to the parent window. What is the parent/owner window? As you see below I am using NULL for the handle, but since the operation is indeed associated with a window, I probably need a handle, but I don't know what to use for the handle.

ShellExecute(NULL, "open" ,"Excel.exe",
    "C:\\Documents and Settings\\Lab1\\My Documents\\Test.xls",
    NULL, SW_SHOWNORMAL);

[A]
It is
usually 0
hwnd : parent window that will receive a possible messagebox. This parameter is usually 0.
It refers to the top-level window: the window you are opening does not have any parent, and is the main window for the application being executed.
When you are switching between applications (ALT-TAB), you are displaying the next top-level window (the next app with a parent handle equals to 0) in the z-order (for instance).
Of course, the parent to your app
can not be the Desktop Window itself
:
If you create a child window whose parent is GetDesktopWindow(), your window is now glued to the desktop window. If your window then calls something like MessageBox(), well that's a modal dialog, and then the rules above kick in and the desktop gets disabled and the machine is toast.
For the path, I would advice double quotes surrounding simple quotes:
```
"  ' ... ' "
```
```
```
"'C:\\Documents and Settings\\Lab1\\My Documents\\Test.xls'"
```
```
Could work also (untested) with double double quotes :
```
"  "" ... "" "
```
```
```
"""C:\\Documents and Settings\\Lab1\\My Documents\\Test.xls"""
```
```
, as illustrated by
this thread
.
Actually, as mentioned in
your other question
by
Andy
and by
Mesidin
, and in
ShellExecute Function manual
, you can open the file, and pass its path in parameter.
```
```
ShellExecute( NULL, "open",
              "Test.xls", "C:\\Documents and Settings\\Lab1\\My Documents\\",
              NULL, SW_SHOWNORMAL);
```
```
That means Excel is the default application for opening .xls extension files though.


q: Is it possible to override the background color of the minimize and maximized buttons in WinForms?

[A]
Not without writting your own NC_PAINT which is very bad practice by itself.
You never know when the user will use a new visual style never heard before. Your application will display the old ugly buttons over the existing style and everything will clash.


q: Is there a Wiki plugin for TFS 2005, ie. SharePoint Services 2.0?


q:
I want to load 52 images (deck of cards) in gif format from my recourse folder into an Image[] in c#. Any ideas?

Thanks,
Jon

[A]
You can read a Bitmap from a file like this;
```
```
public static Bitmap GetBitmap( string filename )
  {
     Bitmap retBitmap = null;
     string path = String.Concat( BitmapDir, filename );
     if ( File.Exists( path ) )
     {
        try
        {
           retBitmap = new Bitmap( path, true );
        }
        catch { }
     }
     return retBitmap;
  }
```
```
You can get a list of files in a resource directory like this;
```
```
string[] files = Directory.GetFiles( BitmapDir, "*.gif" );
```
```
Just iterate through files calling GetBitmap( file ) and populate your array. BitmapDir is obviously the directory where your GIF files live.


q: How do I extract a tar (or tar.gz, or tar.bz2) file in Java?

[A]
What about using this
API
for tar files, this
other one
included inside Ant for BZIP2 and the
standard one
for GZIP?


q:
I have a table with N rows, and I wanna select N-1 rows.

Suggestions on how to do this in one query, if it's possible..?

[A]
Does the last row have the highest ID? If so, I think this would work:
```
```
SELECT * FROM TABLE WHERE ID != (SELECT MAX(ID) FROM TABLE)
```
```
MySQL does allow subselects in the current version, right?
However, in most cases, it'd probably perform better if you selected all the rows and then filtered the unwanted data out in your application.


q:
What are release notes for and who reads them? Should/could they be automated by just spitting out bug fixes for the current release, or do they warrant careful human editing?
So, anybody with a link to best practices(reasoning behind) in regards to software release notes?

[A]
This really depends on who your application is built for and your organizations goals.  However, I tend to believe that release notes need to be a concise listing of important key additions, enhancements, or fixes that are included in the particular release.
Sometimes a simple dump of the bug tracking system information is enough, other times, I find that they need to be refined.
The key is that typically Release Notes are believed to be the "Hey look at what we did" type listing of changes.


q:
Does anyone know if there's a way to automatically expand a list in Python, separated by commas?  I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.

For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "IN" clause.

import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]

mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()

sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"

mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()

Any help would be appreciated!

[A]
try:
```
```
",".join( map(str, record_ids) )
```
```
```
",".join( list_of_strings )
```
joins a list of string by separating them with commas
if you have a list of numbers,
```
map( str, list )
```
will convert it to a list of strings


q:
I have a web application that uses Ext-JS 2.2. In a certain component, we have an empty toolbar that we are trying to add a button to using

myPanel.getTopToolbar().insertButton(0, [...array of buttons...]);

However, in IE6/7 this fails because of lines 20241-20242 in ext-all-debug.js:

var td = document.createElement("td");
this.tr.insertBefore(td, this.tr.childNodes[index]);

Since "this.tr.childNodes([0])" does not yet exist in IE, this fails with "Invalid argument".

THE REAL QUESTION:
Can I, using CSS similar to the below add a child to every toolbar <tr> so that this.tr.childNodes[0] is found:

div.x-toolbar tr:after { content: " "; }

I totally realize this is a hack, but for legal reasons I cannot change any Javascript, not even to add an empty button ({}) to each toolbar. Major kudos to anyone that can figure this out.

[A]
If all you are doing is adding to a empty panel
```
```
myPanel.getTopToolbar().add(buttons etc);
```
```
Or
```
```
myPanel.getTopToolbar().addButton(..);
```
```
Either should work.  It looks like purpose of insertButton is for putting a button within a non-empty toolbar.


q: How does one preserve the settings in the Open Dialog box?  For example, I would the Open Dialog to remember that I chose the Details view and sorted by date modified.

[A]
Microsoft didn't see fit to give us any documented way of doing this, but some people have figured out bits of the puzzle.  This link shows how to set the view, but not how to get the current setting:
http://msdn.microsoft.com/en-us/magazine/cc164009.aspx


q: When reading from a IO::Socket::INET filehandle it can not be assumed that there will always be data available on the stream. What techniques are available to either peek at the stream to check if data is available or when doing the read take no data without a valid line termination and immediately pass through the read?

[A]
Set the
```
Blocking
```
option to
```
0
```
when creating the socket:
```
```
$sock = IO::Socket::INET->new(Blocking => 0, ...);
```
```


q:
Is there any good way to convert strings like "xlSum", "xlAverage", and "xlCount" into the value they have under Microsoft.Office.Interop.Excel.XlConsolidationFunction?

I guess reflection would be slow (if its possible). There are about 10 of these constant values. I was trying to avoid a large switch statement if possible.

[A]
Instead of switch you can always use a
```
Dictionary<string, ...>
```
and fill it once when the application starts


q:
I have an after_save filter which I dont want to trigger in a specific instance.  Is there a way to do this similar to save_without_validation?

Thanks,

[A]
There is a good example of extending ActiveRecord to provide callback skipping here:
http://weareintegrum.com/?p=10
The idea is to create a method on ActiveRecord called skip_callback that accepts a block:
```
```
def self.skip_callback(callback, &block)
  method = instance_method(callback)
  remove_method(callback) if respond_to?(callback)
  define_method(callback){ true }
  begin
    result = yield
  ensure
    remove_method(callback)
    define_method(callback, method)
  end
  result
end
```
```
Then anything you do within the block does not execute the callback.


q:
I am facing a problem.
I would like to localize my action names in my project so french people can have clean urls with french names.

http://www.test.com/Home should be http://www.test.com/Accueil

It is a good thing too for google indexing.
Moreover I would like to be Restful on the application, so I would like too keep english name because developers (even frenchies) prefer to work on english names.

I don't know if it's possible and how.

My first idea should be something like get the browser language, assign it to the CurrentThread.CurrentCulture, so I can select the view name I want.

Thank you very much for your answers.

[A]
you can do this when you register the routes in global.asax.
if normally you have this:
```
```
routes.MapRoute("Catalog-Brands", "catalog/brand/", new {controller = "Brand", action = "Index", isActive = true});
```
```
you could make this one too (I don't know french, sorry)
```
```
routes.MapRoute("Catalog-Brands-French", "french-catalog/french-brand/", new {controller = "Brand", action = "Index", isActive = true});
```
```
you could either make them all available globally or have separate:
```
```
public static void RegisterUsRoutes

public static void RegisterFrenchRoutes
```
```
you'd have to make the decision at application startup though (you may or may not be able to register routes at runtime.)


q:
I have a WCF Service that should not enter the faulted state. If there's an exception, it should be logged and the service should continue uninterrupted. The service has a one-way operation contract and is reading messages from an MSMQ.

My problems are twofold:

The service appears to be swallowing
an exception/fault so I am unable to
debug it. How do I get the service
to expose the exception so that I
can log or handle it?

The service is
entering into a faulted state after
this exception is swallowed. How do
I prevent the service from entering
into a faulted state?

[A]
Exceptions will fault the proxy. You can't AFAIK do much about that: don't cause exceptions ;-p
I'm a little surprised that one-way is still causing a problem, but for swallowing
in genera
l, there are 3 aspects:
are you throwing
faults
? or exceptions? it matters (and should be "faults")
as a hack, you can enable debug exception messages - but turn it off please!!!
are you "using" the service object? I've just
blogged
on this exact subject... basically, your "using" can swallow the exception.
3 options:
don't use "using"
subclass the proxy and override Dispose()
wrap it, as per the blog


q:
I want to use this pure HTML/CSS template for my ASP.NET website:

http://sub3.tanguay.de

I copy it inside my Default.aspx page, inside the FORM element, but the form messes up the layout:

http://sub2.tanguay.de

UPDATE: this now displays correctly, thanks to Devio.

I tried altering the style of the form tag but can't get it to stop affecting the layout, I tried:

style="margin: 0px; padding: 0px; display: inline; background-color: transparent;"

Is this a common issue when copying in layout templates into ASP.NET?

Is there an easy work around, like some margin:-2px fix or something like that?

I need to keep the form tag, of course, for the ASP.NET functionality.

[A]
1) try removing the background-color attribute from the form class:
```
```
form {
    margin:10px; padding: 0;
    border: 1px solid #f2f2f2;
    background-color: #FAFAFA; /* remove this */
}
```
```
2) you cannot nest forms, but the searchform is contained inside the ASP.Net form, and ASP.Net requires exactly one form tag per page.


q:
I've been using this function but I'd like to know what's the most efficient and accurate way to get it.

function daysInMonth(iMonth, iYear) {
   return 32 - new Date(iYear, iMonth, 32).getDate();
}

[A]
```
```
function daysInMonth (month, year) { // Use 1 for January, 2 for February, etc.
  return new Date(year, month, 0).getDate();
}

console.log(daysInMonth(2, 1999)); // February in a non-leap year.
console.log(daysInMonth(2, 2000)); // February in a leap year.
```
```
Day 0 is the last day in the previous month. Because the month constructor is 0-based, this works nicely. A bit of a hack, but that's basically what you're doing by subtracting 32.
See more :
Number of days in the current month


q:
I' trying to use a Linq query to find and set the selected value in a drop down list control.

 Dim qry = From i In ddlOutcome.Items _
           Where i.Text.Contains(value)

 Dim selectedItem As ListItem = qry.First

 ddlOutcome.SelectedValue = selectedItem.Value

Even though the documentation says that the DropDownList.Items collection implements IEnumerable I get an error in the Where clause that Option Strict ON disallows late binding!

[A]
My vb.net is shaky, (c# guy) but try:
```
```
Dim qry = From DirectCast(i, ListItem) In ddlOutcome.Items ...
```
```
I may have the DirectCast syntax wrong, but you know where I'm coming from. The problem is that at compile time, Items is not verifiable as as a collection of ListItem because IEnumerable's Current property returns Object. Items is not a generic collection.
-Oisin


q: Suppose you create a generic Object variable and assign it to a specific instance. If you do GetType(), will it get type Object or the type of the original class?

[A]
Yes.
You can also do:
```
```
object c = new FooBar();
if(c is FooBar)
     Console.WriteLine("FOOBAR!!!");
```
```


q: What books would you guys recommend if one has been a java developer for years and is now trying to take the c#/asp.net route?

[A]
I find
Pro C# with .NET 3.0, Special Edition
  by Andrew Troelsen
  Apress © 2007 (1238 pages)
  ISBN:9781590598238
to be an excellent book.


q:
Is there any reason to avoid using text-align: justify;?

Does it reduce readability or cause problems?

[A] I prefer left justification (text-align: left) because it's generally more readable.  It's also quicker to read evenly-spaced words, so I hear.  Unless you have a stylistic reason for using justify, keep it left, right, or center.  Especially for body text, use left.  (Actually, you'd want something like "forward" for text in the other direction (e.g. Hebrew)...)


q:
When and why would somebody do the following:

doSomething( (MyClass) null );

Have you ever done this? Could you please share your experience?

[A]
If
```
doSomething
```
is overloaded, you need to cast the null explicitly to
```
MyClass
```
so the right overload is chosen:
```
```
public void doSomething(MyClass c) {
    // ...
}

public void doSomething(MyOtherClass c) {
    // ...
}
```
```
A non-contrived situation where you need to cast is when you call a varargs function:
```
```
class Example {
    static void test(String code, String... s) {
        System.out.println("code: " + code);
        if(s == null) {
            System.out.println("array is null");
            return;
        }
        for(String str: s) {
            if(str != null) {
                System.out.println(str);
            } else {
                System.out.println("element is null");
            }
        }
        System.out.println("---");
    }

    public static void main(String... args) {
        /* the array will contain two elements */
        test("numbers", "one", "two");
        /* the array will contain zero elements */
        test("nothing");
        /* the array will be null in test */
        test("null-array", (String[])null);
        /* first argument of the array is null */
        test("one-null-element", (String)null);
        /* will produce a warning. passes a null array */
        test("warning", null);
    }
}
```
```
The last line will produce the following warning:
Example.java:26: warning: non-varargs
  call of varargs method with inexact
  argument type for last parameter;
cast to
```
java.lang.String
```
for a varargs
  call
cast to
```
java.lang.String[]
```
for a
  non-varargs call and to suppress this
  warning


q: I want to create a Rails (2.1 and 2.2) model with ActiveRecord validations, but without a database table.  What is the most widely used approach?  I've found some plugins that claim to offer this functionality, but many of them don't appear to be widely used or maintained.  What does the community recommend I do?  Right now I am leaning toward coming up with my own solution based on this blog post.

[A]
just create a new file ending in ".rb" following the conventions you're used to (singular for file name and class name, underscored for file name, camel case for class name) on your "models/" directory. The key here is to not inherit your model from ActiveRecord (because it is AR that gives you the database functionality).
e.g.: for a new model for cars, create a file called "car.rb" in your models/ directory and inside your model:
```
```
class Car
    # here goes all your model's stuff
end
```
```
edit: btw, if you want attributes on your class, you can use here everything you use on ruby, just add a couple lines using "attr_accessor":
```
```
class Car
    attr_accessor :wheels # this will create for you the reader and writer for this attribute
    attr_accessor :doors # ya, this will do the same

    # here goes all your model's stuff
end
```
```
edit #2: after reading Mike's comment, I'd tell you to go his way if you want all of the ActiveRecord's functionality but no table on the database. If you just want an ordinary Ruby class, maybe you'll find this solution better ;)


q:
Writing a ton of web applications leveraging JSON/AJAX, I find myself returning tons literal javascript objects (JSON).  For example, I may be request all the Cats from GetCats.asp.  It would return:

[
  { 'id': 0, 'name': 'Persian' },
  { 'id': 1, 'name': 'Calico' },
  { 'id': 2, 'name': 'Tabby' }
]

Now, these are all Cat objects with behaviors.  However, if I define a Cat object, function Cat() { }, I know of no EFFICIENT way to coax these literal objects into the behaviors of a user defined object.

I can do this by brute force of iterating through them and assigning functions, but it's not going to be pretty.  Is there a nice, one line(or few), way of somehow "casting" this behavior onto these literal objects?

[A]
There's no getting around the fact that you will have to iterate through all of your simple objects and change them to a different kind of object.  You cannot avoid the loop.  That being said you could create a constructor that takes a simple object like this and copies those values into the new instance.
Like this:
```
```
function Cat(c) {
  this.id = c.id;
  this.name = c.name;
}
Cat.prototype.meow = function() {alert('meow');}
Cat.prototype.displayName= function() {alert(this.name);}

var cats = [
  { 'id': 0, 'name': 'Persian' },
  { 'id': 1, 'name': 'Calico' },
  { 'id': 2, 'name': 'Tabby' }
];

for (i=0,len=cats.length; i<len; i++) {
  cats[i] = new Cat(cats[i]);
}

cats[0].meow();  // displays "meow"
cats[0].displayName();  // display "Persian"
```
```


q:
I recently posted a question about Azure... is it really an OS?  I understand the technical details, and I got a lot of fuzzy answers... I really want to know... what do you think is the difference between an OS and a Framework?

Just for reference, Azure will be built on top of Hyper-V servers and the virtual machines will be running vanilla Windows Server 2008.  It will run services that creates a cloud on top of the many virtual machines which is called Azure.  Windows is calling Azure an OS.

I am trying to understand how to define the difference between an OS and a framework.

[A]
An OS is the thing that directly interfaces with the machine, be it virtual or real. It has to expose syscalls that handle input devices, output devices, sound, networking, and all the other things that we take for granted these days. It also often provides some kind of UI which uses these services to make it easy to use/useful for an end-user. It needs to have device drivers to work with video cards, sound cards, etc. (Once again, these can be virtualized).
A framework is... something built on top of the OS. It, too, exposes an API, but they are often not so low-level as the one the OS exposes.


q:
I have a table User which has an identity column UserID, now what is the correct Linq to Entity line of code that would return me the max UserID?

I've tried:

using (MyDBEntities db = new MyDBEntities())
{
    var User = db.Users.Last();
    // or
    var User = db.Users.Max();

    return user.UserID;
}

but Last and Max don't seem to be supported.

Any ideas?

[A]
Do that like this
```
```
db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();
```
```


q:
Is there a c++ equivalent of Java's

try {
    ...
}
catch (Throwable t) {
    ...
}

I am trying to debug Java/jni code that calls native windows functions and the virtual machine keeps crashing.  The native code appears fine in unit testing and only seems to crash when called through jni.  A generic exception catching mechanism would prove extremely useful.

[A]
```
```
try {
   // ...
} catch (...) {
   // ...
}
```
```
Note that the
```
...
```
inside the
```
catch
```
is a real ellipsis, ie. three dots.
However, because C++ exceptions are not necessarily subclasses of a base
```
Exception
```
class, there isn't any way to actually see the exception variable that is thrown when using this construct.


q: I am currently working in C#, and I need to insert a new record into one table, get the new primary key value, and then use that as a foreign key reference in inserting several more records. The Database is MS SQL Server 2003. All help is appreciated!

[A]
The best way of doing this is the use SCOPE_IDENTITY() function in TSQL.  This should be executed as part of the insert i.e.
```
```
SqlCommand cmd = new SqlCommand(@"
    INSERT INTO T (Name) VALUES(@Name)
    SELECT SCOPE_IDENTITY() As TheId", conn);
cmd.AddParameter("@Name", SqlDbType.VarChar, 50).Value = "Test";
int tId = (int)cmd.ExecuteScalar();
```
```
Alternatively you can assign SCOPE_IDENTITY() to a variable to be used in successive statements. e.g.
```
```
DECLARE @T1 int

INSERT INTO T (Name) VALUES('Test')

SELECT @T1 = SCOPE_IDENTITY()

INSERT INTO T2 (Name, TId) VALUES('Test', @T1)
```
```


q:
I'm new to using LINQ to Entities (or Entity Framework whatever they're calling it) and I'm writing a lot of code like this:

var item = (from InventoryItem item in db.Inventory
            where item.ID == id
            select item).First<InventoryItem>();

and then calling methods on that object like this:

var type = item.ItemTypeReference;

or

var orders = item.OrderLineItems.Load();

to retrieve child or related objects.

I haven't profiled the DB or dug too deeply but my guess is that when I call a .Load() or a *Reference property I'm actually making another call to the DB.  If this is the case, is there any way to get those objects in my initial LINQ expression?

[A]
You want to use the .Include(string) method references in this
"Shaping query results"
article.
```
```
var item = from InventoryItem item in
              db.Inventory.Include("ItemTypeReference").Include("OrderLineItems")
           where item.ID == id
           select item;
```
```
There is probably a "sql" style syntax for the Includes as well.
Also see this
article
about moving from LINQ-to-SQL to LINQ-to-Entities.
For others looking for a solution to this problem for
Linq to SQL
you want to do the following (Substitute DataContext and other types for whatever you have):
```
```
using (DataContext db = new DataContext())
{
    DataLoadOptions options = new DataLoadOptions();
    options.LoadWith<InventoryItem>(ii => ii.ItemTypeReference);
    options.LoadWith<InventoryItem>(ii => ii.OrderLineItems);
    db.LoadOptions = options;

    var item = from InventoryItem item in db.Inventory
               where item.ID == id
               select item;
}
```
```
This will load the properties specified in LoadWith whenever the parent item (InventoryItem) is loaded, for that particular context.
In response to some further questions from James and Jesper, check out this
question


q: I have a Gridview boundfield where i set ReadOnly to true because i don't want user to change its value. However on the objectdatasource control's update method that boundfield became null when i try to use it as parameter in update method. Is there a way to set that value during updating?

[A]
When you mark a field as read-only on the GridView it renders on the page as a span element, not an input.  Therefore the value is not available on PostBack.  If you can construct the update statement so that it doesn't expect this field, that would be the best way to deal with this.  If the update statement is autogenerated and you can't get around having the value to update, then you can either read the value from the database before doing the update (so that you have it) or include a HiddenField bound to this column and use a literal that obtains the value via Eval instead of binding (if necessary).  This will require using a template.
```
```
<asp:TemplateField>
    <InsertItemTemplate>
      <asp:TextBox runat="server" ID="itemTextBox" />
    </InsertItemTemplate>
    <EditItemTemplate>
      <asp:HiddenField runat="server" ID="itemHF" Value='<% Bind("Item") %>' />
      <asp:Label runat="server" ID="itemLabel" Text='<% Eval("Item") %>' />
    </EditItemTemplate>
    <ItemTemplate>
       <asp:Label runat="server" ID="itemLabel" Text='<% Bind("Item") %>' />
    </ItemTemplate>
</asp:TemplateField>
```
```


q:
There are a few things that I almost always do when I put a class together in C++.

1) Virtual Destructor
2) Copy constructor and assignment operator (I either implement them in terms of a private function called Copy(), or declare them private and thus explicitly disallow the compiler to auto generate them).

What things do you find are almost always useful?

[A]
Often,
```
```
operator string () const;
```
```
or
```
```
friend ostream& operator << (ostream&, const MyClass&);
```
```


q:
I'm working on something that requires traversing through the file system and for any given path, I need to know how 'deep' I am in the folder structure. Here's what I'm currently using:

int folderDepth = 0;
string tmpPath = startPath;

while (Directory.GetParent(tmpPath) != null)
{
    folderDepth++;
    tmpPath = Directory.GetParent(tmpPath).FullName;
}
return folderDepth;

This works but I suspect there's a better/faster way? Much obliged for any feedback.

[A]
Off the top of my head:
```
```
Directory.GetFullPath().Split("\\").Length;
```
```


q:
It took me some time, but I've finally managed to write down all the tasks that need to go into Version 1.0 of the software product I'm working on.

The list is almost 1000 items long.

We are a 3-person team, and we've somehow managed to get this far using MindMeister, Google Docs, @todos in the code etc. Now, I have everything neatly grouped by feature, but how do I prioritize all this and turn it into a schedule?

Any advice would be greatly appreciated - I'm not looking for software recommendations, however - I'm seeking advice on how to take this enormous bag of tasks - ranging from bug-fixes to application modules - and find out in what order I should do them.

[A]
My recommended approach will be based on Agile methodology best practices...
So, you have what in Agile terms is called a "backlog" defined- that's great - and an important first step.
A good Agile pace that is commonly used is a 2-3 week iteration length...and at the end you have a set of releasable features.  This will establish the "heartbeat" of your development process. Next, you'll decided how to organize and group the features into Stories and Tasks.
You'll want to grow the underlying architecture and let it naturally emerge based on the ordering of the Stories and Tasks that you select from your backlog.
Its important to mitigate risks early - so you'll want to select early those items that are either performance or implementation unknowns that might pose the largest risk - and could result in the largest rework impact.  For example - establishing the messaging infrastructure - might be an early architectural feature that might be included if you select a Story that required a persistent message to be delivered to complete a unit of work.
Can you group the set of features into functional categories that might naturally evolve to describe the 1.0 release as a System of Systems?  For example, the Administrative functions, the User Profile Management, Reporting, external integration layers, Database Access Objects, etc.
What are the simplest Story / Use Cases that you can write - that will map to some of the ~1,000 features / requirements you've defined?  Select a set of Stories (or individual Tasks from a Story - if the Story itself is too large to implement in a single interation).  It will take some additional effort - but recomposing your requirements into a set of Stories/Tasks is important.
You'll find that you will refactor during subsequent interations - but that your steady 2-week heartbeat iteration schedule will keep delivering real functionality.
At various points you may want to schedule an architecture iteration just to focus on some cleaning-up / refactoring - and that's ok too.


q:
I am using the date picker provided by jQuery UI to select a date range that ends up in a  single text input with something like 11/11/2008 - 12/05/2008. What would you recommend as far a validation (jQuery/JavaScript) on the client side as well as code for validation on the server side (ASP.NET/C#) to make sure the user enters valid dates?

Note I asked a question on Stack Overflow the other day about how to parse out the two dates using C# if your interested.

[A]
That tends to happen with every "next big thing." Lots of hype, followed by a slow decline in the use of the buzzword. But, even though buzzwords fade and eventually disappear, whatever good ideas were behind them tend to stick around to be absorbed into the mainstream.
[
Edit
] Okay, an example for those who think I'm "bashing" something, or claiming that aspect oriented programming is going to disappear. At one time the next big thing was structured programming. Object oriented programming grew out of that, and now nobody
talks
about doing "structured programming" any more. But, in many ways we're still using its best ideas, because OOP adopted them, improved them, and added still more new ideas.


q:
How do I hide the prev/today/next navigation in jQuery DatePicker?

I'm happy with just the Month and Year drop down boxes.

Also how do I disable the animations?

@tvanfosson - I already tried hideIfNoPrevNext but that only works if you don't have a date range that spans two months.

The duration option did the trick at turning off the animations though.

Cheers.

[A]
You can find the options for the DatePicker control at
http://docs.jquery.com/UI/Datepicker/datepicker#options
.  Specifically, I think you want to set hideIfNoPrevNext to true and set duration to ''.
```
```
$('#cal').datepicker( { hideIfNoPrevNext: true, duration: '' } );
```
```


q:
I have an nmake-based project which in turn calls the asp compiler, which can throw an error, which nmake seems to recognize:

NMAKE : fatal error U1077: 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe' : return code '0x1'

However, when I call nmake from within a batch file, the environment variable %ERRORLEVEL% remains set at zero:

nmake /NOLOGO
echo BUILD RETURNING: %ERRORLEVEL%

If I control-c the nmake task, I do end up getting a non-zero ERRORLEVEL (it's set to 2) so my assumption is that I'm able to catch errors okay, but nmake isn't bubbling up the non-zero exit code from it's task.  Or, at least, I'm mis-trapping it.  Any help would be appreciated.

[A]
First thing, please post your batch file so we can see how you trap the error.
Also comment this post so I can read it again.
As a first git, i'd guess something like:
nmakebatch.cmd
usual nmake arguments, without /NOLOGO
```
```
@echo off
rem Args[x]: nmake arguments
echo.>> %~n0.log
echo %date% %time%>> %~n0.log
echo nmake /NOLOGO %*>> %~n0.log
nmake /NOLOGO %*
echo %errorlevel%>> %~n0.log
```
```
Is a start for trapping all situations, into a incrementing log, while building.


q:
VBScript doesn't appear to have a way to include a common file of functions.

Is there a way to achieve this?

[A]
You can create a (relatively) small function in each file that you want to include other files into, as follows:
```
```
sub includeFile (fSpec)
    dim fileSys, file, fileData
    set fileSys = createObject ("Scripting.FileSystemObject")
    set file = fileSys.openTextFile (fSpec)
    fileData = file.readAll ()
    file.close
    executeGlobal fileData
    set file = nothing
    set fileSys = nothing
end sub
```
```
and then use it to include specific files - these are executed as if they were inline.
```
```
includeFile "commonapi.vbi"
includeFile "dbcalls.vbi"
```
```
It basically opens the file, reads the entire contents into a string, then executes that string. There's no error handling on the I/O calls since this sort of stuff is usually done once on program start, and you want to fail if there's a problem including it.
Note that the
```
includeFile
```
function can be compressed to:
```
```
Sub includeFile(fSpec)
    With CreateObject("Scripting.FileSystemObject")
       executeGlobal .openTextFile(fSpec).readAll()
    End With
End Sub
```
```
Or even to (if you're not adverse to long lines):
```
```
Sub includeFile(fSpec)
    executeGlobal CreateObject("Scripting.FileSystemObject").openTextFile(fSpec).readAll()
End Sub
```
```


q:
I'm trying to increase the timeout on all sessions.  The site is hosted with Godaddy, and it is written in Flash (client side of course) and asp.net on the backend.  I've added this to my web.config,

<sessionState timeout="720">

</sessionState>

Is that really all that I need to do?  I'd prefer to not let sessions expire ever, but I'm sure that the server needs to reclaim that memory at some point...I'm not storing anything in the session, really, just using it to track users' progress through the site, and if a user is logged in or not.

Thanks for any pointers...all the documentation seems deceptively simple, and it kind of makes me nervous...

[A]
Yup!
As in; Yes, that's the only thing you need to do...
To get "never ending timeouts" you'd have to create a background HTTP request (which will transmit the session cookie) back to the server every 719 minute though. Though theoretically then you'd also have to have "Out of Process" sessions using e.g. some sort of database or something...
Or you could roll your own session handler, I think APS.NET have support for this through using some sort of adapter pattern or something, but I am not sure. Then you could have a "truly" never ending session...


q:
I am trying to understand the process of declaration and assignment of a primitive type at the back stage.

int i;

i = 3;

For 1),  on the memory stack, it assigns a space for storing an int type value named i
For 2),  it assigns the value 3 to the space preserved above

Is there a memory address there?
From my impression, memory address is always associated with the objects on the heap?

Update:

Regarding the replies:

So, for every variable on the stack, they are all assigned a memory address as well just like the objects on the heap. Am I correct?

But for Java, this is not the case?

[A]
Assuming you're talking about C or C++ (I can't tell), yes. You can access the address like so:
```
```
int i = 3;

int *k = &i; // k now is a pointer to i

*k = 4; // assigns the value k points to (i) to 4, i is now 4
```
```


q: I'm kind of new to ASP.NET MVC and to the MVC pattern in general but I'm really digging the concept and the rapidity with which I can compose an app.  One thing that I'm struggling with is how to expose more than one object to a view.  I use a lot of strongly typed views, which works well but what if my view relies on more than one object?  Right now I'm doing something pretty hacky and passing a Dictionary to the view and then just keying the different objects.  Is there a better pattern for this?

[A]
You can simply store each object in the ViewData then cast the appropriate object type in your View.
Controller:
```
```
ViewData["ObjectA"] = objectA;
 ViewData["ObjectB"] = objectB;
```
```
View:
```
```
<%= ((ObjectA)ViewData["ObjectA"]).PropertyA %>
 <%= ((ObjectB)ViewData["ObjectB")).PropertyB %>
```
```
or better yet,
```
```
<%
    var objectA = (ObjectA)ViewData["ObjectA"];
    var objectB = (ObjectB)ViewData["ObjectB"];
 %>

 <%= objectA.PropertyA %>
 <%= objectB.PropertyB %>
```
```


q:
How can I use a database and PHP sessions to store a user's shopping cart? I am using CodeIgniter, if that helps.

Example code would also be nice.

[A]
I would recommend that you look at
the CodeIgnitor Session Class
.
Additionally, you could look at
Chris Shiflett's discussion
on this topic.


q:
I want to load some images into my application from the file system. There's 2 easy ways to do this:

[UIImage imageNamed:fullFileName]

or:

NSString *fileLocation = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSData *imageData = [NSData dataWithContentsOfFile:fileLocation];

[UIImage imageWithData:imageData];

I prefer the first one because it's a lot less code, but I have seen some people saying that the image is cached and that this method uses more memory? Since I don't trust people on most other forums, I thought I'd ask the question here, is there any practical difference, and if so which one is 'better'?

I have tried profiling my app using the Object Allocation instrument, and I can't see any practical difference, though I have only tried in the simulator, and not on an iPhone itself.

[A]
It depends on what you're doing with the image. The
```
imageNamed:
```
method does cache the image, but in many cases that's going to help with memory use. For example, if you load an image 10 times to display along with some text in a table view, UIImage will only keep a single representation of that image in memory instead of allocating 10 separate objects. On the other hand, if you have a very large image and you're not re-using it, you might want to load the image from a data object to make sure it's removed from memory when you're done.
If you don't have any huge images, I wouldn't worry about it. Unless you see a problem (and kudos for checking Object Allocation instead of preemptively optimizing), I would choose less lines of code over negligible memory improvements.


q:
Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first.

This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places.  So if you have a number that could have as many as 15 decimal places you need to format as Decimal("%.15f" % my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal (Decimal("%.15f" % 100000.3) == Decimal('100000.300000000002910')).

Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?

[A]
The "official" string representation of a float is given by the repr() built-in:
```
```
>>> repr(1.5)
'1.5'
>>> repr(12345.678901234567890123456789)
'12345.678901234567'
```
```
You can use repr() instead of a formatted string, the result won't contain any unnecessary garbage.


q:
How can you make the experience with Eclipse faster?

For instance: I disable all the plugins I don't need (Mylyn, Subclipse, …).

Instead of using a plugin for Mercurial, I configure TortoiseHG as an external tool.

[A]
I give it a ton of memory (add a
```
-Xmx
```
switch to the command that starts it) and try to avoid quitting and restarting it- I find the worst delays are on startup, so giving it lots of RAM lets me keep going longer before it crashes out.


q:
I'm storing a tree in a DB using nested sets.  The table's fields are id, lft, rgt, and name.

Given a node ID, I need to find all of its direct children(not grandchildren) that are themselves leaf nodes.

[A]
The article
Managing Hierarchical Data in MySQL
gives a great example of how to use Nested Sets, and gives examples of many common queries, including this one.
here's how to find the immediate children of a node:
```
```
SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth
FROM nested_category AS node,
    nested_category AS parent,
    nested_category AS sub_parent,
    (
        SELECT node.name, (COUNT(parent.name) - 1) AS depth
        FROM nested_category AS node,
        nested_category AS parent
        WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND node.name = '**[[MY NODE]]**'
        GROUP BY node.name
        ORDER BY node.lft
    )AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
    AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
    AND sub_parent.name = sub_tree.name
GROUP BY node.name
HAVING depth = 1
ORDER BY node.lft;
```
```
and then combine that with the fact that a leaf node will have
```
rgt
```
equal to
```
lft + 1
```
, and you're set.
pardon the pun.


q:
I am trying to have an element fade in, then in 5000 ms fade back out again. I know I can do something like:

setTimeout(function () { $(".notice").fadeOut(); }, 5000);

But that will only control the fade out, would I add the above on the callback?

[A]
I just figured it out below:
```
```
$(".notice")
   .fadeIn( function()
   {
      setTimeout( function()
      {
         $(".notice").fadeOut("fast");
      }, 2000);
   });
```
```
I will keep the post for other users!


q:
class A
  def initialize
    @x = do_something
  end

  def do_something
    42
  end
end

How can I stub do_something in rspec, before the original implementation is called (thus assigning 42 to @x)? And without changing the implementation, of course.

[A]
I don't know how to do that in spec's mock framework, but you can easily swap it out for mocha to do the following:
```
```
# should probably be in spec/spec_helper.rb
Spec::Runner.configure do |config|
  config.mock_with :mocha
end

describe A, " when initialized" do
  it "should set x to 42" do
    A.new.x.should == 42
  end
end

describe A, " when do_something is mocked" do
  it "should set x to 23" do
    A.any_instance.expects(:do_something).returns(23)
    A.new.x.should == 23
  end
end
```
```


q:
I have a function that exports a table to CSV and in the query I set which fields will export.

Here is the query:

SELECT lname, fname, email, address1, address2, city,
state, zip, venue_id, dtelephone, etelephone, tshirt FROM volunteers_2009

The field venue_id is the the id of the venue which is referred to in another table (venues)

So volunteers_2009.venue_id = venues.id

When I open the CSV file it displays the venue_id which I understand, but I need help modifying the query to put in the name of the venue (venues.venue_name) within the CSV file.

Any help is appreciated.

[A]
Standard SQL query for this is (assuming you want both ID and name for the venue):
```
```
SELECT a.lname as lname, a.fname as fname, a.email as email,
    a.address1 as address1, a.address2 as address2, a.city as city,
    a.state as state, a.zip as zip, a.venue_id as venue_id,
    b.venue_name as venue_name, a.dtelephone as dtelephone,
    a.etelephone as etelephone, a.tshirt as tshirt
FROM volunteers_2009 a, venues b
WHERE a.venue_id = b.id
AND a.venue_id IS NOT NULL
UNION ALL
SELECT a.lname as lname, a.fname as fname, a.email as email,
    a.address1 as address1, a.address2 as address2, a.city as city,
    a.state as state, a.zip as zip, a.venue_id as venue_id,
    '' as venue_name, a.dtelephone as dtelephone,
    a.etelephone as etelephone, a.tshirt as tshirt
FROM volunteers_2009 a
WHERE a.venue_id IS NULL
```
```


q:
From the help for the Overflow Error in VBA, there's the following examples:

Dim x As Long
x = 2000 * 365 ' gives an error

Dim x As Long
x = CLng(2000) * 365 ' fine

I would have thought that, since the Long data type is supposed to be able to hold 32-bit numbers, that the first example would work fine.

I ask this because I have some code like this:

Dim Price as Long
Price = CLng(AnnualCost * Months / 12)

and this throws an Overflow Error when AnnualCost is 5000 and Months is 12.

What am I missing?

[A]
2000 and 365 are Integer values.  In VBA, Integers are 16-bit signed types, when you perform arithmetic on 2 integers the arithmetic is carried out in 16-bits.  Since the result of multiplying these two numbers exceeds the value that can be represented with 16 bits you get an exception.  The second example works because the first number is first converted to a 32-bit type and the arithmetic is then carried out using 32-bit numbers.  In your example, the arithmetic is being performed with 16-bit integers and the result is then being converted to long but at that point it is too late, the overflow has already occurred.  The solution is to convert one of the operands in the multiplication to long first:
```
```
Dim Price as Long
Price = CLng(AnnualCost) * Months / 12
```
```


q:
Is it possible to determine whether a particular youtube video is encoded with H.264 or FLV through the YouTube data API? If so, how?

I can start a file download and check how the video stream was encoded (programmatically, of course), but I'd like to use the YouTube data API to avoid all that overhead.


q:
I ran into this bug where an element of an array, if its index is the string "0", is inaccessible.

It's not a bug with unserialize, either, as this occurred in my code without invoking it.

$arr = unserialize('a:1:{s:1:"0";i:5;}');
var_dump($arr["0"]); //should be 5, but is NULL
var_dump($arr[0]);   //maybe this would work?  no. NULL

Am I doing something wrong here?  How do I access this element of the array?

[A]
Actually, the code in your question yields
```
```
int(5)
```
```


q:
Hopefully this is a really quick one ;)  I have written a lexer / parser specification in ANTLR3, and am targeting the CSharp2 target.  The generated code works correctly, but I can't get ANTLR to put the C# output into a namespace.

The relevant section of the Grammar file is as follows:

grammar MyGrammar;

options
{
    language = CSharp2;
    output = AST;
    ASTLabelType = CommonTree;
}

To generate the correct namespace, I have tried:

@namespace { MyNamespace }

and

@lexer::namespace { MyNamespace }
@parser::namespace { MyNamespace }

but both of these generate errors, claiming that the file has no rules.

Any help is appreciated.

[A]
I use this for a combined lexer and parser (and it generates the namespace correctly):
```
```
grammar Test;

options
{
    language=CSharp2;
}

@lexer::namespace {
    My.Name.Space
}

@parser::namespace {
    My.Name.Space
}

DIGIT   :   '0'..'9';

simple  :    DIGIT EOF;
```
```
So i wonder why your version didn't work - maybe you want to try this simple example and see if it works for you.