q:
Basically, I have an iframe embedded in a page and the iframe has some JavaScript routines I need to invoke from the parent page.

Now the opposite is quite simple as you only need to call parent.functionName(), but unfortunately, I need exactly the opposite of that.

Please note that my problem is not changing the source URL of the iframe, but invoking a function defined in the iframe.

[A]
Quirksmode had a
post on this
.
Since the page is now broken, and only accessible via archive.org, I reproduced it here:
IFrames
On this page I give a short overview of accessing iframes from the page they’re on. Not surprisingly, there are some browser considerations.
An iframe is an inline frame, a frame that, while containing a completely separate page with its own URL, is nonetheless placed inside another HTML page. This gives very nice possibilities in web design. The problem is to access the iframe, for instance to load a new page into it. This page explains how to do it.
Frame or object?
The fundamental question is whether the iframe is seen as a frame or as an object.
As explained on the
Introduction to frames
pages, if you use frames the browser creates a frame hierarchy for you (
```
top.frames[1].frames[2]
```
and such). Does the iframe fit into this frame hierarchy?
Or does the browser see an iframe as just another object, an object that happens to have a src property? In that case we have to use a standard
DOM call
(like
```
document.getElementById('theiframe'))
```
to access it.
In general browsers allow both views on 'real' (hard-coded) iframes, but generated iframes cannot be accessed as frames.
NAME attribute
The most important rule is to give any iframe you create a
```
name
```
attribute, even if you also use an
```
id
```
.
```
```
<iframe src="iframe_page1.html"
    id="testiframe"
    name="testiframe"></iframe>
```
```
Most browsers need the
```
name
```
attribute to make the iframe part of the frame hierarchy. Some browsers (notably Mozilla) need the
```
id
```
to make the iframe accessible as an object. By assigning both attributes to the iframe you keep your options open. But
```
name
```
is far more important than
```
id
```
.
Access
Either you access the iframe as an object and change its
```
src
```
or you access the iframe as a frame and change its
```
location.href
```
.
document.getElementById('iframe_id').src = 'newpage.html';
frames['iframe_name'].location.href = 'newpage.html';
The frame syntax is slightly preferable because Opera 6 supports it but not the object syntax.
Accessing the iframe
So for a complete cross–browser experience you should give the iframe a name and use the
```
```
frames['testiframe'].location.href
```
```
syntax. As far as I know this always works.
Accessing the document
Accessing the document inside the iframe is quite simple, provided you use the
```
name
```
attribute. To count the number of links in the document in the iframe, do
```
frames['testiframe'].document.links.length
```
.
Generated iframes
When you generate an iframe through the
W3C DOM
the iframe is not immediately entered into the
```
frames
```
array, though, and the
```
frames['testiframe'].location.href
```
syntax will not work right away. The browser needs a little time before the iframe turns up in the array, time during which no script may run.
The
```
document.getElementById('testiframe').src
```
syntax works fine in all circumstances.
The
```
target
```
attribute of a link doesn't work either with generated iframes, except in Opera, even though I gave my generated iframe both a
```
name
```
and an
```
id
```
.
The lack of
```
target
```
support means that you must use JavaScript to change the content of a generated iframe, but since you need JavaScript anyway to generate it in the first place, I don't see this as much of a problem.
Text size in iframes
A curious Explorer 6 only bug:
When you change the text size through the View menu, text sizes in iframes are correctly changed. However, this browser does not change the line breaks in the original text, so that part of the text may become invisible, or line breaks may occur while the line could still hold another word.


q:
Is it possible to typedef long types that use templates?  For example:

template <typename myfloat_t>
class LongClassName
{
    // ...
};

template <typename myfloat_t>
typedef std::vector< boost::shared_ptr< LongClassName<myfloat_t> > > LongCollection;

LongCollection<float> m_foo;

This doesn't work, but is there a way to achieve a similar effect?  I just want to avoid having to type and read a type definition that covers almost the full width of my editor window.

[A]
No, that isn't possible currently. It will be made possible in C++0X AFAIK.
The best I can think of is
```
```
template<typename T> struct LongCollection {
    typedef std::vector< boost::shared_ptr< LongClassName<T> > > type;
};

LongCollection<float>::type m_foo;
```
```

s: huggingface

c: devops

d: intermediate


q:
Looking up LINQ and Or in google is proving somewhat difficult so here I am.

I want to so the following:

(from creditCard in AvailableCreditCards
where creditCard.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant())
**or creditCard.CardNumber.().Contains(txtFilter.Text)**
orderby creditCard.BillToName
select creditCard)

[A]
You can use the .Where() function to accomplish this.
```
```
var cards = AvailableCreditCards.Where(card=> card.CardNumber.Contains(txtFilter.Text) || card.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant());
```
```


q: In AJAX applications that need to poll the server in regular intervals (like a chat applications), what is the recommended minimum time between two calls, so that the update is done as quickly as possible? What times are considered as hogs for the server and the client?

[A]
The answer to this question is very much dependent on:
How much data is sent in each poll
How many users you will have online at a time
How much bandwidth your server can handle
How "fresh" the data on your client needs to be
Without knowing any of these specifics for your app, it's going to be hard to give a good recommendation. Have you looked into a method where the client connects to the server, and the server holds the connection open until there is data available? Then the server delivers the data, and the client immediately reconnects and waits again. That can be tricky to get working, but you might be able to maximize both efficiency of bandwidth AND responsiveness that way.


q:
How do I get a function's name as a string?

def foo():
    pass

>>> name_of(foo)
"foo"

[A]
```
```
my_function.func_name
```
```
There are also other fun properties of functions. Type
```
dir(func_name)
```
to list them.
```
func_name.func_code.co_code
```
is the compiled function, stored as a string.
```
```
import dis
dis.dis(my_function)
```
```
will display the code in
almost
human readable format. :)


q:
An easy jQuery question.

I have several identical forms ( except their name ) on one page with a few hidden inputs in each. I want to refer to them by using the form name and  then the input name. ( the input names are not unique in my page )

So for instance:

var xAmt = $('#xForm'+num).('#xAmt');

I really want to supply these values to an AJAX POST

    $.ajax({
      url: "X.asp",
      cache: false,
      type:  "POST",
      data:  "XID=xID&xNumber=xNum&xAmt=xAmt",

...

If I can get the values in the AJAX call even better.

[A]
Looks like you want
```
formSerialize()
```
(or even
```
ajaxSubmit()
```
) from the
jQuery forms plugin
.


q:
I would like to be able to cast a value dynamically where the type is known only at runtime. Something like this:

myvalue = CType(value, "String, Integer or Boolean")

The string that contains the type value is passed as an argument and is also read from a database, and the value is stored as string in the database.

Is this possible?

[A]
Sure, but
```
myvalue
```
will have to be defined as of type
```
Object
```
, and you don't necessarily want that. Perhaps this is a case better served by generics.
What determines what type will be used?


q:
Is there a way to dynamically invoke a method in the same class for PHP? I don't have the syntax right, but I'm looking to do something similar to this:

$this->{$methodName}($arg1, $arg2, $arg3);

[A]
Just omit the braces:
```
```
$this->$methodName($arg1, $arg2, $arg3);
```
```


q:
I have a program that will calculate the minimal area taken by fitting rectangles together.

Input: Rectangles of different height and width.

Output: One rectangle that contains all these rectangles.

Rules: One cannot turn or roll the rectangles around and they cannot overlap.

I understand that this is related or is possibly defined as a bin packing problem (NP-hard). However the algorithms i found for those often set a limit on for example width. I have no such limits, the only goal is to get the resulting area as small as possible.

Any pointers on what algorithm is appropriate to get a decent solution?

[A]
I'd start by skimming through
http://mathworld.wolfram.com
- they're awesome for stuff like this.
Second, I could envision a dopey algorithm that would put the longest (in the X dimension) box on the bottom, then the tallest (in the Y dimension) on top of it on one side or the other. Then continue stacking them in this "stair-stepped" fashion going right wards and upwards (for example go right until you can't, then go up, etc, etc).
That's probably non-ideal, and may very well give you bad results, but it's what popped to mind first.


q:
I need to echo a string containing angle brackets (< and >) to a file on a Windows machine.  Basically what I want to do is the following:

echo some string < with angle > brackets >>myfile.txt

This doesn't work since the command interpreter gets confused with the angle brackets.  I could quote the whole string like this:

echo "some string < with angle > brackets" >>myfile.txt

But then I have double quotes in my file that I don't want.

Escaping the brackets ala unix doesn't work either:

echo some string \< with angle \> brackets >>myfile.txt

Ideas?

[A]
The Windows escape character is ^, for some reason.
```
```
echo some string ^< with angle ^> brackets >>myfile.txt
```
```


q:
I'm invoking one of SharePoint's web service APIs that returns a CAML fragment. I've searched the interweb far and wide but I've been unable to figure out how to make this CAML fragment to render as "normal" HTML that I can render in a more sane environment like Plumtree, WLP, Liferay or any other portal besides SharePoint.

Without a way to do this, I'm wondering why Microsoft wrote SharePoint web service calls that return CAML in the first place. Web services are for interoperability and it seems the CAML is only valid within a WebPart running within SharePoint. [Note to Bill and Steve: that's not interoperability.]

If I can't do anything with the CAML that comes back, I'm just going to call a different web service that returns only data and then write my own UI. I was hoping for an easier path. Any suggestions would be greatly appreciated.

[A]
You could send the CAML through an XSLT stylesheet to generate HTML or XHTML.
Edit:
Considering your first question (why SharePoint returns CAML from some of its web services)... who knows?  It may be there to support authoring tools such as SharePoint designer.  But it seems clear from the dearth of documentation and tools that CAML is a more-or-less internal SharePoint thing. At present, performing CAML-to-HTML conversion would require either somehow accessing the CAML rendering engine within SharePoint, or re-implementing it. Neither option is attractive.
I think that your conclusion (calling data-returning web services and rendering the HTML yourself) is probably your best bet.


q: How do you rename a file to include the datetime using the windows command line?

[A]
Check out
StampMe.cmd
at
http://www.ss64.com/nt/syntax.html
.


q:
ExtJS has Ext.each() function, but is there a map() also hidden somewhere?

I have tried hard, but haven't found anything that could fill this role. It seems to be something simple and trivial, that a JS library so large as Ext clearly must have.

Or when Ext really doesn't include it, what would be the best way to add it to Ext. Sure, I could just write:

Ext.map = function(arr, f) { ... };

But is this really the correct way to do this?

[A]
Since
```
map
```
is more of a utility than anything, I don't see why there would be any special way of plugging it into the Ext namespace; the way you propose would work well enough, though you might want to do it thusly:
```
```
if(Ext && typeof(Ext.map) == "undefined") { // only if Ext exists & map isn't already defined
   Ext.map = function(arr, f) { ... };
}
```
```
Seems like that would be fine...but then, I don't use ExtJS, so I don't know. I did take a gander at their docs and it doesn't seem like there is anything special to do in this case.


q: Anyone know where to find a reference that describes how to output color on the Windows CLI interfaces using API and/or stdout?

[A]
At least there is the color command:
```
```
color bg fg
```
```
where:
```
```
0: Black
1: Blue
2: Green
3: Cyan
4: Red
5: Purple
6: Yellow
7: Gray
8: Silver
9: Light blue
A: Lime
B: Light cyan
C: Light red
D: Light purple
E: Light yellow
F: White
```
```
Example:
```
```
color 80
```
```
Gives a silver background with black text.


q:
I have a requirement to produce a Web User Control (in C#) which will exhibit different behaviour when clicked depending on whether the shift (or control) key is pressed at the time. The control itself will contain an ImageButton and/or Hyperlink.

Is this possible?

Basically, if the logged in user is an Admin then I need to allow them access to update the associated URL. I don't want to have a separate page for this admin as it will cause confusion.

Thanks in advance

[A]
How about
here
?
To implement the
Ctrl
/
Alt
/
Shift
detection, you can use the properties
```
event.ctrlKey
```
,
```
event.altKey
```
,
```
event.shiftKey
```
and the deprecated Navigator-specific property
```
event.modifiers
```
.


q:
Does anybody knows how can I get the max and min value of the 2nd and 3rd columns in PHP?

$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));

Output should be like:

max(12.9)
min(10)

[A]
```
```
<?php
$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));
function col($tbl,$col){
    $ret = array();
    foreach ($tbl as $row){
        $ret[count($ret)+1] = $row[$col];
    }
    return $ret;
}
print (max(col($ar,2))."\n");
print (min(col($ar,1))."\n");
?>
```
```
is this what you look for? I guess its not the most efficient way.


q:
Here is my situation: I know almost nothing about Perl but it is the only language available on a porting machine. I only have permissions to write in my local work area and not the Perl install location. I need to use the Parallel::ForkManager Perl module from CPAN

How do I use this Parallel::ForkManager without doing a central install? Is there an environment variable that I can set so it is located?

Thanks

JD

[A]
From
perlfaq8:  How do I keep my own module/library directory?
:
When you build modules, tell Perl where to install the modules.
For C-based distributions, use the INSTALL_BASE option
when generating Makefiles:
```
```
perl Makefile.PL INSTALL_BASE=/mydir/perl
```
```
You can set this in your CPAN.pm configuration so modules automatically install
in your private library directory when you use the CPAN.pm shell:
```
```
% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit
```
```
For C-based distributions, use the --install_base option:
```
```
perl Build.PL --install_base /mydir/perl
```
```
You can configure CPAN.pm to automatically use this option too:
```
```
% cpan
cpan> o conf mbuild_arg --install_base /mydir/perl
cpan> o conf commit
```
```
INSTALL_BASE tells these tools to put your modules into
F.  See L for details on how to run your newly
installed moudles.
There is one caveat with INSTALL_BASE, though, since it acts
differently than the PREFIX and LIB settings that older versions of
ExtUtils::MakeMaker advocated. INSTALL_BASE does not support
installing modules for multiple versions of Perl or different
architectures under the same directory. You should consider if you
really want that , and if you do, use the older PREFIX and LIB
settings. See the ExtUtils::Makemaker documentation for more details.


q:
We've had an ongoing need here that I can't figure out how to address using the stock Maven 2 tools and documentation.

Some of our developers have some very long running JUnit tests (usually stress tests) that under no circumstances should be run as a regular part of the build process / nightly build.

Of course we can use the surefire plugin's exclusion mechanism and just punt them from the build, but ideally we'd love something that would allow the developer to run them at will through Maven 2.

[A]
Normally you would add a profile to your maven configuration that runs a different set of tests:
run this with mvn -Pintegrationtest install
```
```
<profile>
        <id>integrationtest</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <argLine>-client -Xmx896m -XX:MaxPermSize=192m</argLine>
                        <forkMode>once</forkMode>
                        <includes>
                            <include>**/**/*Test.java</include>
                            <include>**/**/*IntTest.java</include>
                        </includes>
                        <excludes>
                            <exclude>**/**/*SeleniumTest.java</exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        <activation>
            <property>
                <name>integrationtest</name>
            </property>
        </activation>
    </profile>
```
```


q:
I want to create a class that takes string array as a constructor argument and has command line option values as members vals. Something like below, but I don't understand how the Bistate works.

import scalax.data._
import scalax.io.CommandLineParser

class TestCLI(arguments: Array[String]) extends CommandLineParser {
    private val opt1Option = new Flag("p", "print") with AllowAll
    private val opt2Option = new Flag("o", "out") with AllowAll
    private val strOption = new StringOption("v", "value") with AllowAll
    private val result = parse(arguments)
    // true or false
    val opt1 = result(opt1Option)
    val opt2 = result(opt2Option)
    val str = result(strOption)
}

[A]
I'm not personally familiar with Scalax or
```
Bistate
```
in particular, but just looking at the scaladocs, it looks like a left-right disjunction.  Scala's main library has a monad very much like this (
```
Either
```
), so I'm surprised that they didn't just use the standard one.
In essence,
```
Bistate
```
and
```
Either
```
are a bit like
```
Option
```
, except their "
```
None
```
-equivalent" can contain a value.  For example, if I were writing code using
```
Either
```
, I might do something like this:
```
```
def div(a: Int, b: Int) = if (b != 0) Left(a / b) else Right("Divide by zero")

div(4, 2) match {
  case Left(x) => println("Result: " + x)
  case Right(e) => Println("Error: " + e)
}
```
```
This would print "
```
Result: 2
```
".  In this case, we're using
```
Either
```
to simulate an exception.  We return an instance of
```
Left
```
which contains the value we want, unless that value cannot be computed for some reason, in which case we return an error message wrapped up inside an instance of
```
Right
```
.


q: Are there, in the canonical Gang of Four list, any design patterns that you often find misused, misunderstood or overused (other than the highly debated Singleton)? In other words, is there a design pattern you would advise to think twice before using? (And why?)

[A]
Factory Patterns...
I was parachuted into a project before where every single
```
MyObject
```
in the system had an equivalent
```
MyObjectFactory
```
for generating new instances. There was no concept of abstraction or extended classes... just plain old ClassX & ClassXFactory.
And no-one could explain why... "It was just the way things had always been done"


q:
I have a interface that defines some methods with attributes.  These attributes need to be accessed from the calling method, but the method I have does not pull the attributes from the interface.  What am I missing?

public class SomeClass: ISomeInterface
{
    MyAttribute GetAttribute()
    {
        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase methodBase = stackFrame.GetMethod();
        object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true);
        if (attributes.Count() == 0)
            throw new Exception("could not find MyAttribute defined for " + methodBase.Name);
        return attributes[0] as MyAttribute;
    }

    void DoSomething()
    {
        MyAttribute ma = GetAttribute();
        string s = ma.SomeProperty;
    }
}

[A]
The methodBase will be the method on the class, not the interface. You will need to look for the same method on the interface. In C# this is a little simpler (since it must be like-named), but you would need to consider things like explicit implementation. If you have VB code it will be trickier, since VB method "Foo" can implement an interface method "Bar". To do this, you would need to investigate the interface map:
```
```
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
interface IFoo
{
    void AAA(); // just to push Bar to index 1
    [Description("abc")]
    void Bar();
}
class Foo : IFoo
{
    public void AAA() { } // just to satisfy interface
    static void Main()
    {
        IFoo foo = new Foo();
        foo.Bar();
    }
    void IFoo.Bar()
    {
        GetAttribute();
    }

    void GetAttribute()
    { // simplified just to obtain the [Description]

        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase classMethod = stackFrame.GetMethod();
        InterfaceMapping map = GetType().GetInterfaceMap(typeof(IFoo));
        int index = Array.IndexOf(map.TargetMethods, classMethod);
        MethodBase iMethod = map.InterfaceMethods[index];
        string desc = ((DescriptionAttribute)Attribute.GetCustomAttribute(iMethod, typeof(DescriptionAttribute))).Description;
    }
}
```
```


q:
Given a Generic List of objects that contain a member variable that is a string, what is the best way to get the object that contains the string with the longest length?

ie.
assuming val1 is the string I'm comparing:

0 : { val1 = "a"   }
1 : { val1 = "aa"  }
2 : { val1 = "aba" }
3 : { val1 = "c"   }

what needs to be returned is object 2 because "aba" has the greatest length.

[A]
Sorry, I'll try again. You can use the following aggregation:
```
```
Dim result = elements.Aggregate(Function(a, b) If(a.val1.Length > b.val1.Length, a, b))
```
```


q:
I'm using Asp.Net 2.0. I have a scenario where i need to check a user input against any of two ranges. For e.g. I need to check a textbox value against ranges 100-200 or 500-600. I know that i can hook up 2 Asp.Net RangeValidators to the TextBox,  but that will try to validate the input against both the ranges, an AND condition,if you will. CustomValidator is an option, but how would I pass the 2 ranges values from the server-side. Is it possible to extend the RangeValidator to solve this particular problem?

[Update]
Sorry I didn't mention this, the problem for me is that range can vary. And also the different controls in the page will have different ranges based on some condition. I know i can hold these values in some js variable or hidden input element, but it won't look very elegant.

[A]
You can use the RegularExpressionValidator with the ValidationExpression property set to
Edit: (whoops, 650 and 201 etc. were valid with the old pattern)
```
```
^(1\d{2}|200|5\d{2}|600)$
```
```
This will test the entered text for 100-200 and 500-600.


q:
I am a rookie was using the Visual Studio 2008 built-in Unit Testing components, what would be the best way to record or display your results in a unit test?

I want to test my service method when it returns a System.GUID and an empty System.GUID

[TestMethod]
public void GetGUID()
{
   MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient();
   string name = "HasGuid";

   System.GUID guid = proxy.GetGUID(name);
}

[TestMethod]
public void GetEmptyGUID()
{
    MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient();
   string name = "HasEmptyGuid";

   System.GUID guid = proxy.GetGUID(name);
}

[A]
I used this for a few months last year, IIRC isn't there an
```
Assert
```
class?
```
Assert.IsTrue(...)
```
?
I've dropped VS test stuff in favor of other unit test frameworks (better IMO) so my memory is likely clouded.


q:
What commands in Emacs can I use to insert into the text buffer of a file the current date and time?

(For example, the equivalent in Notepad is simply pressing F5 which is about the only useful feature for Notepad!)

[A]
Put in your .emacs file:
```
```
;; ====================
;; insert date and time

(defvar current-date-time-format "%a %b %d %H:%M:%S %Z %Y"
  "Format of date to insert with `insert-current-date-time' func
See help of `format-time-string' for possible replacements")

(defvar current-time-format "%a %H:%M:%S"
  "Format of date to insert with `insert-current-time' func.
Note the weekly scope of the command's precision.")

(defun insert-current-date-time ()
  "insert the current date and time into current buffer.
Uses `current-date-time-format' for the formatting the date/time."
       (interactive)
       (insert "==========\n")
;       (insert (let () (comment-start)))
       (insert (format-time-string current-date-time-format (current-time)))
       (insert "\n")
       )

(defun insert-current-time ()
  "insert the current time (1-week scope) into the current buffer."
       (interactive)
       (insert (format-time-string current-time-format (current-time)))
       (insert "\n")
       )

(global-set-key "\C-c\C-d" 'insert-current-date-time)
(global-set-key "\C-c\C-t" 'insert-current-time)
```
```
Reference


q:
Lists in C# have the .ToArray() method. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but I would like a one liner to swap it back.

I am using the String.Split method in the .NET 2.0 environment, so LINQ, etc. is not available to me.

[A]
```
```
return new List<string>(stringArray);
```
```


q:
I'm in javascript, running this in the console

d = new Date();
d.setMonth(1);
d.setFullYear(2009);
d.setDate(15);
d.toString();

outputs this:

"Sun Mar 15 2009 18:05:46 GMT-0400 (EDT)"

Why would this be happening? It seems like a browser bug.

[A]
```
```
d = new Date();
d.setDate(15);
d.setMonth(1);
d.setFullYear(2009);
d.toString();
```
```
This works.


q:
I have a site that creates images for some bit of content after the content is created.  I'm trying to figure out what to do in between the time the content is created and the image is created.  My thought is that I might be able to set a custom image to display on a 404 error on the original image.  However, I'm not sure how to do this with lighttpd.  Any ideas or alternatives?

EDIT:  The issue is the user isn't the one creating the content, it's being created by a process.  Basically we are adding items to a catalog and we want to create a standardized catalog image from an image supplied by the product provider.  However, I don't want a slow server on the provider end to slow down the addition of new products.  So a separate process goes through and creates the image later, where available.  I guess I could have the system create a default image when we create the product and then overwrite it later when we create the image from the provider supplied image.

[A]
Use the
```
<object>
```
tag in HTML with a fallback to the default image.
```
```

<OBJECT title="The Earth as seen from space"
        classid="http://www.observer.mars/TheEarth.py">

  <OBJECT data="TheEarth.mpeg" type="application/mpeg">

    <OBJECT data="TheEarth.gif" type="image/gif">

     The Earth as seen from space.
    </OBJECT>
  </OBJECT>
</OBJECT>

```
```
(Example from w3.org)


q:
I often accidentally create a branch that contains more code than it needs to. When that happens, I delete the branch files, the branch tag, and then start over. The thing that stinks is having to sync the huge pile of data just so I can delete it.

Is there a way to delete server-side?

[A]
Yes, use sync -k.
Add the path you want to delete to your client, e.g.
```
```
//depot/oops/... //your-client/oops/...
```
```
Then sync that location using the -k option:
```
```
p4 sync -k oops/...
```
```
This will tell Perforce that your client has the files without actually transferring them.  Then you can do:
```
```
p4 delete oops/...
p4 submit oops/...
```
```
etc.


q:
We are developing a small in-house application that will run on monitor having multi resolutions. Now we want that the application should adjust itself and remain consistent over all monitors.

I came from a Java background too where we used different layouts to accomplish the task. I experimented in .NET with different layouts like UniGrid (which provide the consistency but very restrictive), Grid, etc. but failed in the required task.

What are some possible layout model or some other solution?

I think if we can specify percentage width or height as we do in CSS/HTML then we can adopt this cross-resolution policy. I found Infergistics have such controls, but can this can be achieved via default controls?

P.S.: I am actually trying in WPF (preferably WPF native application).

[A]
It would completely depend on the content / context of your application, but the .NET Form designer provides you with some useful tools while designing your UI.
Most controls have an
```
Anchor
```
property that allows you specify that a control should stay anchored the specified distance from the top/left/bottom/right of the form during resizing.
Likewise the form itself exposes
```
Resize
```
and
```
SizeChanged
```
events that you can use to customise the UI when the form is resized.
There's some information here as well regarding layouts,
http://msdn.microsoft.com/en-us/library/ms951306.aspx
.


q:
I have a couple of questions about generic wildcards in Java:

What is the difference between List<? extends T> and List<? super T>?

What is a bounded wildcard and what is an unbounded wildcard?

[A]
In your first question,
```
<? extends T>
```
and
```
<? super T>
```
are examples of bounded wildcards.  An unbounded wildcard looks like
```
<?>
```
, and basically means
```
<? extends Object>
```
.  It loosely means the generic can be any type.  A bounded wildcard (
```
<? extends T>
```
or
```
<? super T>
```
) places a restriction on the type by saying that it either has to
extend
a specific type (
```
<? extends T>
```
is known as an upper bound), or has to be an ancestor of a specific type (
```
<? super T>
```
is known as a lower bound).
The Java Tutorials have some pretty good explanations of generics in the articles
Wildcards
and
More Fun with Wildcards
.


q: Using .Net how do I use the Sort method to sort an Array in reverse i.e. Z to A?

[A]
You need to pass a
IComparer
object or
Comparison
delegate to the Sort function.
Here is a sample code from C# 2.0
```
```
Array.Sort(array,delegate(string a, string b)
    {
        return b.CompareTo(a);
    });
```
```
EDIT: missed the array bit.


q:
I am building a ASP.NET website, and when I click the START DEBUGGING icon, it runs Internet Explorer as the account that I ran Visual Studio with.

I would like to run IE as a different user when debugging.

[A]
You can use the runas command to run IE as a different user for running your app. Later attach to the asp.net worker process when you want to debug.
If you want to just change the credentials for Integrated Authentication, try the setting in the update below.
Update
: If you want IE to prompt for a user name and password, try this setting:
For IE 7, set this option for your zone:
Tools> Internet Options > Security > custom level (for your zone)> User Authentication> Logon > prompt for user name and password


q:
I'm trying to get my head around AMQP. It looks great for inter-machine (cluster, LAN, WAN) communication between applications but I'm not sure if it is suitable (in architectural, and current implementation terms) for use as a software bus within one machine.

Would it be worth pulling out a current high performance message passing framework to replace it with AMQP, or is this falling into the same trap as RPC by blurring the distinction between local and non-local communication?

I'm also wary of the performance impacts of using a WAN technology for intra-machine communications, although this may be more of an implementation concern than architecture.

War stories would be appreciated.

[A]
AMQP is a specification so you'd be comparing apples with oranges really. There are not that many production ready AMQP providers out there really; none of the major messaging providers or vendors support AMQP at the time of writing (e.g. IBM, Tibco, Sonic, BEA, Oracle, SwiftMQ, MS, Apache ActiveMQ, openmq from Sun) - so all the available AMQP providers are pretty new.
So I'd recommend comparing whatever AMQP provider you are interested in with your message passing framework. There's no point ripping something out that is working fine just because of the way it reads & writes bytes to a socket :)


q:
Is there any way to insert a text (string, may or may not have html tags) to a div?

It has to be a div and not a textarea.

First of all, I need to get the cursor position, then insert the text in that position. It's similar to function insertAdjacentText, but it can only insert before or after a tag, and only works in IE.

Refer to this URL: http://yart.com.au/test/iframe.aspx. Note how you can position the cursor in the div, we need to add text at the cursor location.

[A]
The Range and Selection Objects
Use the
selection
and
range objects
.  These contain all kinds of information about the current selection, and where it lies within the node tree.
Fair Warning:
It's not entirely impossible to do what you're describing, but if you get very fancy, you'll be in pretty deep water of
browser quirks and incompatibilities
.  You're going to have to do a lot of
object detection
, checking to make sure you've got consistent values and methods. Incrementally check all of your browsers as you develop.  Good luck!


q:
Is there any way to disable a system device from C#.NET.

Basically emulating when you go to Device Manager and disable a device that way?

I am assuming there is a WinAPI function that I can invoke, but I don't know which one it is?

The reason I need to do this is that I need to disable and straight after enable the device again.

I need to work in Windows XP and Vista (x86 & x64). I had a look at something called "DevCon" but it doesn't seem to work on Vista x64.

Thanks.

For the answer see here: How do I disable a system device programatically?

[A]
To futher Mel Green's answer, the hardware helper library uses interop to call the Windows API (setupapi), specifically the SetupDiSetClassInstallParams method. Of course there are other calls here which are used to look up the device details etc.
One thing to consider that if you are running as a standard user or unprivileged account you will not be able to use this to control (enable/disable etc) hardware devices.
For more details have a look at
http://www.pinvoke.net
(and for the specific call:
http://pinvoke.net/default.aspx/setupapi.SetupDiSetClassInstallParam
)


q:
What's the best way to unify several overlapping id systems into a unified one while maintaining the old id system.

I have several different ids on my website... (E.g /publisher/1234 and /designer/1234) I would like to unify the ids into a new system, but want to preserve the functionality of the older system.

[A]
You can try using
Microsoft's Sign Tool
You download it as part of the Windows SDK for Windows Server 2008 and .NET 3.5. Once downloaded you can use it from the command line like so:
signtool sign /a MyFile.exe
This signs a single executable, using the "best certificate" available. (If you have no certificate, it will show a SignTool error message.)
Or you can try:
signtool signwizard
This will launch a wizard that will walk you through signing your application. (This option is not available after Windows SDK 7.0.)
If you'd like to get a hold of certificate that you can use to test your process of signing the executable you can use the .NET tool
Makecert
.
Certificate Creation Tool (Makecert.exe)
Once you've created your own certificate and have used it to sign your executable, you'll need to manually add it as a Trusted Root CA for your machine in order for
UAC
to tell the user running it that it's from a trusted source.
Important
.
Installing a certificate as ROOT CA will endanger your users privacy. Look what happened with DELL.
You can find more information for accomplishing this both in code and through Windows in:
Stack Overflow question
Install certificates in to the Windows Local user certificate store in C#
Installing a Self-Signed Certificate as a Trusted Root CA in Windows Vista
Hopefully that provides some more information for anyone attempting to do this!


q:
is there any good Ruby audio libraries that we can build upon?

Need to manage/edit mp3 files!!!

[A]
There's an
interface
to a C++ mp3 editor, and an active
pure ruby
project.


q:
Specifically, I have a model that has a field like this

pub_date = models.DateField("date published")

I want to be able to easily grab the object with the most recent pub_date. What is the easiest/best way to do this?

Would something like the following do what I want?

Edition.objects.order_by('pub_date')[:-1]

[A]
```
```
obj = Edition.objects.latest('pub_date')
```
```
You can also simplify things by putting
```
get_latest_by
```
in the model's Meta, then you'll be able to do
```
```
obj = Edition.objects.latest()
```
```
See
the docs
for more info.  You'll probably also want to set the
```
ordering
```
Meta option.


q:
Lucene is an excellent search engine, but the .NET version is behind the official Java release (latest stable .NET release is 2.0, but the latest Java Lucene version is 2.4, which has more features).

How do you get around this?

[A]
One way I found, which was surprised could work: Create a .NET DLL from a Java .jar file! Using
IKVM
you can
download Lucene
, get the .jar file, and run:
```
```
ikvmc -target:library <path-to-lucene.jar>
```
```
which generates a .NET dll like this: lucene-core-2.4.0.dll
You can then just reference this DLL from your project and you're good to go! There are some java types you will need, so also reference IKVM.OpenJDK.ClassLibrary.dll. Your code might look a bit like this:
```
```
QueryParser parser = new QueryParser("field1", analyzer);
java.util.Map boosts = new java.util.HashMap();
boosts.put("field1", new java.lang.Float(1.0));
boosts.put("field2", new java.lang.Float(10.0));

MultiFieldQueryParser multiParser = new MultiFieldQueryParser
                      (new string[] { "field1", "field2" }, analyzer, boosts);
multiParser.setDefaultOperator(QueryParser.Operator.OR);

Query query = multiParser.parse("ABC");
Hits hits = isearcher.search(query);
```
```
I never knew you could have Java to .NET interoperability so easily. The best part is that C# and Java is "almost" source code compatible (where Lucene examples are concerned). Just replace
```
System.Out
```
with
```
Console.Writeln
```
:).
=======
Update: When building libraries like the Lucene highlighter, make sure you reference the core assembly (else you'll get warnings about missing classes). So the highlighter is built like this:
```
```
ikvmc -target:library lucene-highlighter-2.4.0.jar -r:lucene-core-2.4.0.dll
```
```


q:
Given the following markup:

<ul>
   <li>apple</li>
   <li class="highlight">orange</li>
   <li>pear</li>
</ul>

Both the uls and the lis widths appear to be 100%. If I apply a background-color to the list item, the highlight stretches the full width of the page.

I only want the background highlight to stretch as wide as the widest item (with maybe some padding). How do I constrain the lis (or perhaps the uls) width to the width of the widest item?

[A]
Can you do it like this?
```
```

apple

orange

pear

```
```


q: I have a MySQL database behind a firewall which can only be accessed via an SSH connection. Does anyone know of an implementation of java.sql.Connection which would allow me to make an SSH connection to this database?

[A]
You can use SSH's port forwarding to do this.  While not a pure java.sql.Connection, it will allow you to tunnel the connection through ssh.
```
ssh -L 3306:localhost:3306 remote.mysql.host.com
```
This will forward port 3306 on your local machine to port 3306 on remote.mysql.host.com.  This will allow you to connect to port 3306 on your local machine, and it will be tunnelled to remote.mysql.host.com.
If you're looking to do it all in Java, create the ssh connection with
JSch
.


q:
I am trying to use reflector.InvokeMethod to invoke a function with an optional parameter.
The function looks like this:

Private Function DoSomeStuff(ByVal blah1 as string, ByVal blah2 as string, Optional ByVal blah3 as string = "45") as boolean
'stuff
end function

and I'm Invoking it like this:

Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2, Param3)

This works fine, other than when I don't pass the third (optional) parameter, it dosn't hit the function.

Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2)

Is there a way I can use Reflector.invokeMethod to call this function without passing the optional parameter? or another way to achieve this?

[A]
I would overload the
DoSomeStuff
method rather than use an optional parameter...
```
```
Private Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String) As Boolean
    Return DoSomeStuff(blah1, blah2, "45")
End Function

Private Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String, ByVal blah3 As String) As Boolean
    'stuff
End Function
```
```


q:
The code at the end produces a compile error:

NotApplicable.java:7: run() in  cannot be applied to (int)
                run(42);
                ^
1 error

The question is why?  Why does javac think I am calling run(), and does not find run(int bar)?  It correctly called foo(int bar).  Why do I have to use NotApplicable.this.run(42);?  Is it a bug?

public class NotApplicable {

    public NotApplicable() {
        new Runnable() {
            public void run() {
                foo(42);
                run(42);
                // uncomment below to fix
                //NotApplicable.this.run(42);
            }
        };
    }

    private void run(int bar) {
    }

    public void foo(int bar) {
    }
}

[A]
This is because
```
run
```
is being re-declared when you enter the
```
new Runnable() {}
```
scope. All previous bindings to run become inaccessible. It's as if you were doing this:
```
```
import java.util.*;

public class tmp
{
  private int x = 20;
  public static class Inner
  {
      private List x = new ArrayList();
      public void func()
      {
          System.out.println(x + 10);
      }
  }

  public static void main(String[] args)
  {
    (new Inner()).func();
  }
}
```
```
The compiler won't look for something that matches the type of
```
x
```
all the way up the scope stack, it'll just halt when it finds the first references and sees that the types are incompatible.
NOTE:
It's not as if it
couldn't
do this... it's just that, to preserve your own sanity, it's been decided that it shouldn't.


q:
I open gmail, click on an inbox item, and look at source of the page.  It doesn't look like there isn't any proper html to relate to what is shown on the actual page.

How is the source getting processed into the actual page?  Is there some javascript processing this information?

[A]
In IE you get a blank page if you right-click and "View Source".  If you use the Page menu > View Source, you see the actual page source.  As Steve mentioned, in Firefox you see the actual source both from right-click "View Page Source" and from View menu > Page Source.
I suspect they're taking advantage of some IE-specific obfuscation to hide their secret sauce from 85% of the users.


q:
I was making the following call:

result = RegOpenKeyEx(key, s, 0, KEY_READ, &key);

(C++, Visual Studio 5, Vista 64bit).

It is failing with error code 2 ("File not found") even though "regedit" shows that the key exists.  This code has always worked on 32bit XP.  Why is it "file not found" when it clearly is there?

[A]
I discovered that I could solve my problem using the flag:
```
KEY_WOW64_64KEY
```
, as in:
```
```
result = RegOpenKeyEx(key, s, 0, KEY_READ|KEY_WOW64_64KEY, &key);
```
```
For a full explanation:
32-bit and 64-bit Application Data in the Registry


q:
In our data access layer at work we have this standard implementation where the class is accessed through a singleton public property which looks something like this:

public static CustomerController Instance
        {
            get
            {
                lock(singletonLock)
                {
                    if( _instance == null )
                    {
                        _instance = new CustomerController();
                    }
                    return _instance;
                }
            }
        }

now, I get what the code is doing, but I was wondering why you would do this over just creating an instance of the class each time it is used?

[A]
EDIT: Oh whoops I didn't catch the "Data Access Layers" part. But I have an example of that too: If your multithreaded app funnels all of its' database calls through a singleton class, only one thread will ever access the database at once, avoiding race conditions.
If you have a logging mechanism in a multi-threaded application that you use to spit out all exceptions and just write info in (especially for services, or apps that are always running, printing out statuses whenever stuff happens), you will run into file-locking issues. I use a singleton logger class, so that only one thread ever will have access to the Logger, and the rest will wait until the Logger is free to write their line in the text file.
There are lots of cool reasons to use a singleton, but I was like you and had no idea what they were FOR until I ran into this issue with file access in a multithreaded app.


q:
After I read a bunch of LINQ related stuff, I suddenly realized that no articles introduce how to write asynchronous LINQ query.

Suppose we use LINQ to SQL, below statement is clear. However, if the SQL database responds slowly, then the thread using this block of code would be hindered.

var result = from item in Products where item.Price > 3 select item.Name;
foreach (var name in result)
{
    Console.WriteLine(name);
}

Seems that current LINQ query spec doesn't provide support to this.

Is there any way to do asynchronous programming LINQ? It works like there is a callback
notification when results are ready to use without any blocking delay on I/O.

[A]
While LINQ doesn't really have this per se, the framework itself does...  You can easily roll your own asynchronous query executor in 30 lines or so...  In fact, I just threw this together for you :)
EDIT: Through writing this, I've discovered why they didn't implement it.  It cannot handle anonymous types since they are scoped local.  Thus, you have no way of defining your callback function.
This is a pretty major thing since a lot of linq to sql stuff creates them in the select clause.  Any of the below suggestions suffer the same fate, so I still think this one is the easiest to use!
EDIT: The only solution is to not use anonymous types.  You can declare the callback as just taking IEnumerable (no type args), and use reflection to access the fields (ICK!!).  Another way would be to declare the callback as "dynamic"...  oh... wait...  That's not out yet. :)  This is another decent example of how dynamic could be used.  Some may call it abuse.
Throw this in your utilities library:
```
```
public static class AsynchronousQueryExecutor
{
    public static void Call<T>(IEnumerable<T> query, Action<IEnumerable<T>> callback, Action<Exception> errorCallback)
    {
        Func<IEnumerable<T>, IEnumerable<T>> func =
            new Func<IEnumerable<T>, IEnumerable<T>>(InnerEnumerate<T>);
        IEnumerable<T> result = null;
        IAsyncResult ar = func.BeginInvoke(
                            query,
                            new AsyncCallback(delegate(IAsyncResult arr)
                            {
                                try
                                {
                                    result = ((Func<IEnumerable<T>, IEnumerable<T>>)((AsyncResult)arr).AsyncDelegate).EndInvoke(arr);
                                }
                                catch (Exception ex)
                                {
                                    if (errorCallback != null)
                                    {
                                        errorCallback(ex);
                                    }
                                    return;
                                }
                                //errors from inside here are the callbacks problem
                                //I think it would be confusing to report them
                                callback(result);
                            }),
                            null);
    }
    private static IEnumerable<T> InnerEnumerate<T>(IEnumerable<T> query)
    {
        foreach (var item in query) //the method hangs here while the query executes
        {
            yield return item;
        }
    }
}
```
```
And you could use it like this:
```
```
class Program
{

    public static void Main(string[] args)
    {
        //this could be your linq query
        var qry = TestSlowLoadingEnumerable();

        //We begin the call and give it our callback delegate
        //and a delegate to an error handler
        AsynchronousQueryExecutor.Call(qry, HandleResults, HandleError);

        Console.WriteLine("Call began on seperate thread, execution continued");
        Console.ReadLine();
    }

    public static void HandleResults(IEnumerable<int> results)
    {
        //the results are available in here
        foreach (var item in results)
        {
            Console.WriteLine(item);
        }
    }

    public static void HandleError(Exception ex)
    {
        Console.WriteLine("error");
    }

    //just a sample lazy loading enumerable
    public static IEnumerable<int> TestSlowLoadingEnumerable()
    {
        Thread.Sleep(5000);
        foreach (var i in new int[] { 1, 2, 3, 4, 5, 6 })
        {
            yield return i;
        }
    }

}
```
```
Going to go put this up on my blog now, pretty handy.


q:
Currently I have:

<system.net>
    <mailSettings>
    <smtp from="me@mydomain.com">
        <network
             host="localhost"
             port="25"
             />
      </smtp>
    </mailSettings>
  </system.net>

How can I change it so the email is sent with a name and not the email address only?

[A]
Well, in code you need to put the sender's name in quotes, followed by the e-mail address.
```
```
new SmtpClient(...).Send("\"John Smith\" jsmith@somewhere.com", ...);
```
```
And...it looks like you can encode it into the attribute too...
```
```
<smtp from=""John Smith" <jsmith@somewhere.com>">
```
```


q:
I have a dynamic Facelets page that needs to show information from database when the page loads. At this point in the flow, there have not been any form submissions. Every JSF example I can find only shows a form submission with dynamic results on the next page.

Every call I make to our database is currently takes place after an action has been triggered by a form submission. Where should this code go if there hasn't been a form submission, and how do I trigger it? A code snippet would really help me out!

[A]
You write (with my emphasis added):
Every call I make to our database is currently takes place after an action
  has been triggered by a form submission. Where should this code go
  if there
hasn't been a form submission
, and how do I trigger it? A
  code snippet would really help me out!
It sounds to me that you want to retrieve information from the database
prior
to form submission.
It seems to me that you want to make an Ajax call to query the database. The Ajax call can fire on a different event than the form submisson event. This will probably entail using Javascript rather than the Faces framework.


q:
Given a simple switch statement

switch (int)
{
    case 1 :
    {
        printf("1\n");
        break;
    }

    case 2 :
    {
        printf("2\n");
    }

    case 3 :
    {
        printf("3\n");
    }
}

The absence of a break statement in case 2, implies that execution will continue inside the code for case 3.
This is not an accident; it was designed that way. Why was this decisions made? What benefit does this provide vs. having an automatic break semantic for the blocks? What was the rationale?

[A]
If cases were designed to break implicitly then you couldn't have fallthrough.
```
```
case 0:
case 1:
case 2:
    // all do the same thing.
    break;
case 3:
case 4:
    // do something different.
    break;
default:
    // something else entirely.
```
```
If the switch was designed to break out implicitly after every case you wouldn't have a choice about it.  The switch-case structure was designed the way it is to be more flexible.


q:
What is the latest version of the Boost library that is compatible with Microsoft Visual C++ 6?  And can you provide a link to download it directly?

The Downloads link at http://www.boost.org only gives a download for version 1.36.0, and the documentation for that version lists Visual C++ 7.1 as the lowest version of Microsoft compiler tested.  Do they purge out downloads for older versions?

[A]
Boost
1.34.1
has been tested with vc6.  The old versions are still available.


q:
This is a question that's been nagging me for some time. I always thought that C++ should have been designed so that the delete operator (without brackets) works even with the new[] operator.

In my opinion, writing this:

int* p = new int;

should be equivalent to allocating an array of 1 element:

int* p = new int[1];

If this was true, the delete operator could always be deleting arrays, and we wouldn't need the delete[] operator.

Is there any reason why the delete[] operator was introduced in C++?  The only reason I can think of is that allocating arrays has a small memory footprint (you have to store the array size somewhere), so that distinguishing delete vs delete[] was a small memory optimization.

[A]
It's so that the destructors of the individual elements will be called.  Yes, for arrays of PODs, there isn't much of a difference, but in C++, you can have arrays of objects with non-trivial destructors.
Now, your question is, why not make
```
new
```
and
```
delete
```
behave like
```
new[]
```
and
```
delete[]
```
and get rid of
```
new[]
```
and
```
delete[]
```
?  I would go back Stroustrup's "Design and Evolution" book where he said that if you don't use C++ features, you shouldn't have to pay for them (at run time at least).  The way it stands now, a
```
new
```
or
```
delete
```
will behave as efficiently as
```
malloc
```
and
```
free
```
.  If
```
delete
```
had the
```
delete[]
```
meaning, there would be some extra overhead at run time (as James Curran pointed out).


q: I'm using c#, and have an open tcpip connection receiving data.  Is it possible to save the stream to an ms sql server database as I'm receiving it, instead of receiving all the data then saving it all?  If the stream could be sent to the database as it's being received, you wouldn't have to keep the entire chunk of data in memory.  Is this at all possible?

[A]
Are you writing to the DB as a BLOB, or translating the data in some form, then executing inserts for each row?
Your answer in the comments has me confused.  Writing a stream to a BLOB column is vastly different then getting the data then translating it into inserts for separate rows.
Regardless, streaming into a BLOB column is possible by first creating the row with the blob column that you need to insert into, the repeatedly calling an update statement:
```
```
update myTable set myColumn.Write(@data, @offset, @length) where someid = @someId
```
```
for chunks of bytes from the stream.
Perfect example located here.


q:
How can I calculate the number of work days between two dates in SQL Server?

Monday to Friday and it must be T-SQL.

[A]
In
Calculating Work Days
you can find a good article about this subject, but as you can see it is not that advanced.
```
```
--Changing current database to the Master database allows function to be shared by everyone.
USE MASTER
GO
--If the function already exists, drop it.
IF EXISTS
(
    SELECT *
    FROM dbo.SYSOBJECTS
    WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')
    AND XType IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_WorkDays]
GO
 CREATE FUNCTION dbo.fn_WorkDays
--Presets
--Define the input parameters (OK if reversed by mistake).
(
    @StartDate DATETIME,
    @EndDate   DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed
)

--Define the output data type.
RETURNS INT

AS
--Calculate the RETURN of the function.
BEGIN
    --Declare local variables
    --Temporarily holds @EndDate during date reversal.
    DECLARE @Swap DATETIME

    --If the Start Date is null, return a NULL and exit.
    IF @StartDate IS NULL
        RETURN NULL

    --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).
     IF @EndDate IS NULL
        SELECT @EndDate = @StartDate

    --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.
    --Usually faster than CONVERT.
    --0 is a date (01/01/1900 00:00:00.000)
     SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),
            @EndDate   = DATEADD(dd,DATEDIFF(dd,0,@EndDate)  , 0)

    --If the inputs are in the wrong order, reverse them.
     IF @StartDate > @EndDate
        SELECT @Swap      = @EndDate,
               @EndDate   = @StartDate,
               @StartDate = @Swap

    --Calculate and return the number of workdays using the input parameters.
    --This is the meat of the function.
    --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.
     RETURN (
        SELECT
        --Start with total number of days including weekends
        (DATEDIFF(dd,@StartDate, @EndDate)+1)
        --Subtact 2 days for each full weekend
        -(DATEDIFF(wk,@StartDate, @EndDate)*2)
        --If StartDate is a Sunday, Subtract 1
        -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'
            THEN 1
            ELSE 0
        END)
        --If EndDate is a Saturday, Subtract 1
        -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'
            THEN 1
            ELSE 0
        END)
        )
    END
GO
```
```
If you need to use a custom calendar, you might need to add some checks and some parameters. Hopefully it will provide a good starting point.


q:
When upgrading MySQL, I first create a backup of the database. Then I will uninstall the current version installed, and delete all the files that were left by the installer. Then I install the latest GA version, and restore the created back-up, using the MySQL Administrator.

Is there a better way of doing an upgrade of the MySQL. Because I have to create again all the users that are allowed to connect to the database.

The installation of the MySQL is used in a college enrollment system, a client server system I have developed using VB.Net and MySQL. I can only do the update at night because i know no one is connected to the database.

[A]
you can dump the
```
mysql.user
```
and
```
mysql.db
```
tables, which contains all the user info, and reimport that as well, to avoid having to recreate all that. i'd also suggest running repairs on the table after you re-import.
alternatively, you could create a listing of grants:
```
```
select concat('show grants for ',quote(user),'@',quote(host),';') from mysql.user
```
```
this will output a list of sql statements that you can then run to get specific grant statements.
ultimately though, you'll want to check out your specific version information regarding upgrades, to make sure you've considered any version specific compatibility issues.
here
is some information for a 4.1 - 5.x upgrade, for example.


q: When should unions be used? Why do we need them?

[A]
Unions allow data members which are mutually exclusive to share the same memory.  This is quite important when memory is more scarce, such as in embedded systems.
In the following example:
```
```
union {
   int a;
   int b;
   int c;
} myUnion;
```
```
This union will take up the space of a single int, rather than 3 separate int values.  If the user set the value of
a
, and then set the value of
b
, it would overwrite the value of
a
since they are both sharing the same memory location.


q: What is meant by redundant function? What is the difference between a redundant function & an inline function?

[A]
A
redundant
function is one which has potentially been superseded by another function, and shouldn't be used anymore.  I guess it can be thought of in the same way as a deprecated function.
An
inline
function, in C and C++, is one which is implemented in the header file rather than the .c or .cpp file.  The compiler will replace all calls to that function with the function body itself, rather than linking to it via the symbol table.  This will make the compiled binaries bigger, but it has the advantage that the function will run a little bit faster.


q:
On large files (~200+ MB), I get the 503 error when I read the stream.

ftp = (FtpWebRequest)WebRequest.Create(new Uri(address.AbsoluteUri + @"/" + file.Name));
ftp.Credentials = new NetworkCredential(username, password);
ftp.Method = WebRequestMethods.Ftp.DownloadFile;

response = (FtpWebResponse)ftp.GetResponse();

Any clues on what I'm doing wrong or a better practice for larger files?

[A]
Do you receive the 503 after every attempt or only subsequent attempts?
Have you tried setting the disabling KeepAlive?
```
```
ftp.KeepAlive = false;
```
```
I would try a more rubust ftp client library, a basic free one can be at
sourceforge
.


q:
In my Windows XP Task Manager, some processes display a higher value in the Mem Usage column than the VMSize. My Firefox instance, for example shows 111544 K as mem usage and 100576 K as VMSize.

According to the help file of Task Manager Mem Usage is the working set of the process and VMSize is the committed memory in the Virtual address space.

My question is, if the number of committed pages for a process is A and the number of pages in physical memory for the same process is B, shouldn't it always  be B ≤ A? Isn't the number of pages in physical memory per process a subset of the committed pages?

Or is this something to do with sharing of memory among processes? Please explain. (Perhaps my definition of 'Working Set' is off the mark).

Thanks.

[A]
You might find some explaination in
The Memory Shell Game
Working Set
(A) – This is a set of virtual memory pages (that are committed) for a process and are located in physical RAM.  These pages fully belong to the process.  A working set is like a "currently/recently working on these pages" list.
Virtual Memory
– This is a memory that an operating system can address.  Regardless of the amount of physical RAM or hard drive space, this number is limited by your processor architecture.
Committed Memory
–  When an application touches a virtual memory page (reads/write/programmatically commits) the page becomes a committed page.  It is now backed by a physical memory page.  This will usually be a physical RAM page, but could eventually be a page in the page file on the hard disk, or it could be a page in a memory mapped file on the hard disk.  The memory manager handles the translations from the virtual memory page to the physical page.   A virtual page could be in located in physical RAM, while the page next to it could be on the hard drive in the page file.
BUT: PF (Page File) Usage - This is the total number of committed pages on the system.  It does not tell you how many are actually written to the page file.  It only tells you how much of the page file would be used if all committed pages had to be written out to the page file at the same time.
Hence B > A...
If we agree that B represents "mem usage" or also PF usage, the problem comes from the fact it actually represents
potential
page usages
: in Xp, this potential file space can be used as a place to assign those virtual memory pages that programs have asked for, but never brought into use...


q:
I've got the following url route and i'm wanting to make sure that a segment of the route will only accept numbers. as such, i can provide some regex which checks the word.

/page/{currentPage}

so.. can someone give me a regex which matches when the word is a number (any int) greater than 0 (ie. 1 <-> int.max).

[A]
If you want it greater than 0, use this regex:
```
```
/([1-9][0-9]*)/
```
```
This'll work as long as the number doesn't have leading zeros (like '03').
However, I recommend just using a simple
```
[0-9]+
```
regex, and validating the number in your actual site code.


q: I am well aware that the Rest based approach is targeting HTTP.  I would love to use the REST APIs and other goodness between processes on the same computer.  Since ADO.NET data services is built on top of WCF it would seem reasonable to assume that the transport in configurable to work with any of the WCF supported transports.  Anyone know if there is a way to configure it to send traffic via namedpipes?

[A]
In .NET 3.5 there is built-in named pipe binding for WCF. See the
MSDN
for details.


q: How can I delete the session information from my browser by using javascript?  Is it possible to do?

[A]
Session information is usually stored on the server. An HTTP request to a page that destroys the session would normally do the trick (using AJAX if you wish).
For cookies you can set the cookie expiry date to the current date, this will expire the cookie and remove it.
```
```
var d = new Date();
document.cookie = "cookiename=1;expires=" + d.toGMTString() + ";" + ";";
```
```


q: I need to get all the cookies stored in my browser using JavaScript. How can it be done?

[A]
To retrieve all cookies for the current document open in the browser, you again use the
```
document.cookie
```
property.


q: Has anyone ever seen the storage class auto explicitly used in C/C++? If so, in what situation?

[A] auto is never useful in current C/C++ because all variables are implicitly auto. It is useful in C++0x, where it can replace the type declaration entirely - if you have a variable with an initial assignment, 'auto' will just make it the type of that assignment value, as in the comments.


q:
We had a performance issue with DataGridViews where the redraw was horridly slow and found the solution Here to create a derived type and enable double buffering on the control.
(Derived type is necessary since the DoubleBuffered property is protected)

It doesn't seem like there's any drawback to having the DoubleBuffered property set to true.

[A]
Double buffering by definition uses two buffers and twice the memory for rendering the view of the control into. So, there is some drawback there, however, with the amount of memory you get in a PC now, not many people probably would notice the sacrifice.
No idea why its protected. Maybe the function wasn't available in an early version of the control, and when it was introduced the designers didn't want to change the public interface of the control. Or perhaps they considered it to be an advanced feature and wanted to limit the number of methods someone new to the control would have to grok to be able to make it do something useful.


q:
I am hacking up a tagging application for emacs.  I have got a tag cloud/weighted list successfully displaying on a buffer, but i am running into a snag.  I need to be able to properly word-wrap the buffer, but I haven't a clue where to start.

The font I am using is a variable width font.  On top of that, each tag is going to be in a different size, depending on how many times it shows up on the buffer.  Finally, the window that displays the tagcloud could be in a window that is 200 pixels wide, or the full screen width.

I really have no idea where to start.  I tried longlines mode on the tagcloud buffer, but that didn't work.

Source code is at: http://emacswiki.org/cgi-bin/emacs/free-tagging.el

[A]
You probably want to track
```
posn-at-point
```
and
```
posn-at-x-y
```
as you put the tags in the buffer.


q: What's the difference between the list methods append() and extend()?

[A]
```
append
```
appends a single element.
```
extend
```
appends a list of elements.
Note that if you pass a list to append, it still adds one element:
```
```
>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]
```
```


q:
I have made a bunch of changes to a number of files in a project. Every commit (usually at the file level) was accompanied by a comment of what was changed.

Is there a way to get a list from CVS of these comments on changes since the last tagged version?

Bonus if I can do this via the eclipse CVS plugin.

UPDATE: I'd love to accept an answer here, but unfortunately none of the answers are what I am looking for. Frankly I don' think it is actually possible, which is a pity really as this could be a great way to create a change list between versions (Assuming all commits are made at a sensible granularity and contain meaningful comments).

[A]
The options for the cvs log command are available
here
. Specifically, to get all the commits since a specific tag (lets call it VERSION_1_0)
```
```
cvs log -rVERSION_1_0:
```
```
If your goal is to have a command that works without having to know the name of the last tag I believe you will need to write a script that grabs the log for the current branch, parses through to find the tag, then issues the log command against that tag, but I migrated everything off of CVS quite a while ago, so my memory might be a bit rusty.


q:
How should I use array of function pointers in C?

How can I initialize them?

[A]
You have a good example
here (Array of Function pointers)
, with the
syntax detailed
.
```
```
int sum(int a, int b);
int subtract(int a, int b);
int mul(int a, int b);
int div(int a, int b);

int (*p[4]) (int x, int y);

int main(void)
{
  int result;
  int i, j, op;

  p[0] = sum; /* address of sum() */
  p[1] = subtract; /* address of subtract() */
  p[2] = mul; /* address of mul() */
  p[3] = div; /* address of div() */
[...]
```
```
To call one of those function pointers:
```
```
result = (*p[op]) (i, j); // op being the index of one of the four functions
```
```


q: How can I add line numbers to a range of lines in a file opened in Vim? Not as in :set nu—this just displays line numbers—but actually have them be prepended to each line in the file?

[A]
```
cat -n
```
adds line numbers to its input. You can pipe the current file to
```
cat -n
```
and replace the current buffer with what it prints to stdout. Fortunately this convoluted solution is less than 10 characters in vim:
```
```
:%!cat -n
```
```
Or, if you want just a subselection, visually select the area, and type this:
```
```
:!cat -n
```
```
That will automatically put the visual selection markers in, and will look like this after you've typed it:
```
```
:'<,'>!cat -n
```
```
In order to erase the line numbers, I recommend using
```
control-v
```
, which will allow you to visually select a rectangle, you can then delete that rectangle with
```
x
```
.


q:
I have seen many programs consisting of structures like the one below

typedef struct
{
    int i;
    char k;
} elem;

elem user;

Why is it needed so often? Any specific reason or applicable area?

[A]
Using a
```
typedef
```
avoids having to write
```
struct
```
every time you declare a variable of that type:
```
```
struct elem
{
 int i;
 char k;
};
elem user; // compile error!
struct elem user; // this is correct
```
```


q: What is the purpose of the strdup() function in C?

[A]
From
strdup man
:
The
```
strdup()
```
function shall return a pointer to a new string, which is a duplicate of the string pointed to by
```
s1
```
. The returned pointer can be passed to
```
free()
```
. A null pointer is returned if the new string cannot be created.


q:
What is the difference between IQueryable<T> and IEnumerable<T>?

See also What's the difference between IQueryable and IEnumerable that overlaps with this question.

[A]
The primary difference is that the LINQ operators for
```
IQueryable<T>
```
take
```
Expression
```
objects instead of delegates, meaning the custom query logic it receives, e.g., a predicate or value selector, is in the form of an expression tree instead of a delegate to a method.
```
IEnumerable<T>
```
is great for working with sequences that are iterated in-memory, but
```
IQueryable<T>
```
allows for out-of memory things like a remote data source, such as a database or web service.
Query execution:
Where the execution of a query is going to be performed
"in process"
, typically all that's required is the code (as code) to execute each part of the query.
Where the execution will be performed
out-of-process
, the logic of the query has to be represented in data such that the LINQ provider can convert it into the appropriate form for the out-of-memory execution - whether that's an LDAP query, SQL or whatever.
More in:
LINQ :
```
IEnumerable<T>
```
and
```
IQueryable<T>
```
C# 3.0 and LINQ
.
"
Returning
```
IEnumerable<T>
```
vs
```
IQueryable<T>
```
"
Reactive Programming for .NET and C# Developers - An Introduction To
```
IEnumerable
```
,
```
IQueryable
```
,
```
IObservable
```
, and
```
IQbservable
```
2008: "
THE MOST FUNNY INTERFACE OF THE YEAR …
```
IQUERYABLE<T>
```
" from
Bart De Smet
.


q:
What is the most accurate way of timing a thread or a line of code in C# assuming the application is multithreaded?

Kind regards,

[A]
What exactly do you mean by "timing a thread"?
To just time (in wall time) how long something takes, use System.Diagnostics.Stopwatch. I don't believe there's anything to measure the processor time taken by a particular thread.  Of course, profilers will help you a lot, but they also affect the timing of the program they're examining, which makes things trickier.


q:
I have the need to display a nested set structure in HTML. I am doing it with the following partial:

<ul<%= ' id="tree"' if depth == 0 %>>
<% items.each do |item| %>
  <li id="node_<%= item.id %>"><a><%= item.name %></a>
  <% if item.has_children? %>
    <%= render :partial => 'tree_level', :locals => {:items => item.children, :depth => depth + 1} %>
  <% end %>
  </li>
<% end %>
</ul>

Is this the best place to have the code? I "feel" like there should be a to_html method on the object which dumps the entire tree structure for me, though this works.

[A]
I am not sure whether it is best practice but I used similar code for rendering project tree.
Faster alternative is to create helper method doing the same job (recursively traversing tree and adding partial strings into result string). It is a little bit PHP style :( but for such a small amount of HTML is it OK, I guess :)
Helper looks like:
```
```
def render_node(node)
  res = "<ul>"
  ...
  node.items.each {|n| res << render_node(n)}
  ...
  res << "</ul>"
  res
end
```
```
Then it is used like this:
```
```
<%=render_node ProjectTree.new%>
```
```


q:
Does anyone know of a simple method for solving this?

I have a table which consists of start times for events and the associated durations. I need to be able to split the event durations into thirty minute intervals. So for example if an event starts at 10:45:00 and the duration is 00:17:00 then the returned set should allocate 15 minutes to the 10:30:00 interval and 00:02:00 minutes to the 11:00:00 interval.

I'm sure I can figure out a clumsy approach but would like something a little simpler. This must come up quite often I'd imagine but Google is being unhelpful today.

Thanks,

Steve

[A]
You could create a lookup table with just the times (over 24 hours), and join to that table. You would need to rebase the date to that used in the lookup. Then perform a datediff on the upper and lower intervals to work out their durations. Each middle interval would be 30 minutes.
```
```
create table #interval_lookup (
  from_date datetime,
  to_date datetime
)

declare @time datetime
set @time = '00:00:00'

while @time < '2 Jan 1900'
  begin
    insert into #interval_lookup values (@time, dateadd(minute, 30, @time))
    set @time = dateadd(minute, 30, @time)
  end

declare @search_from datetime
declare @search_to datetime

set @search_from = '10:45:00'
set @search_to = dateadd(minute, 17, @search_from)

select
  from_date as interval,
  case
    when from_date <= @search_from and
         @search_from < to_date and
         from_date <= @search_to and
         @search_to < to_date
         then datediff(minute, @search_from, @search_to)
    when from_date <= @search_from and
         @search_from < to_date
         then datediff(minute, @search_from, to_date)
    when from_date <= @search_to and
         @search_to < to_date then
         datediff(minute, from_date, @search_to)
    else 30
  end as duration
from
  #interval_lookup
where
  to_date > @search_from
  and from_date <= @search_to
```
```


q: Is it possible to have something like a JTextArea which will color some keywords based on some mappings I have ?

[A]
I am not sure, because I believe
```
JTextArea
```
only directly supports a single font in a single color.
According to
```
SyntaxHighlighter
```
class
article,
```
JTextPane
```
is the way to go.


q:
I have my sources split up in several directories, so for each directory I get back a DLL. Is it possible to create a DLL from several other DLL's ?

EDIT: I'm using C++ with Windows CE Platform Builder 6.0 ( it's not managed )

[A]
Use
ILMerge
Here
you can download this.
Here
is Sample for implementation.


q:
div#thing {
  position: absolute;
  top: 0px;
  z-index: 2;
  margin: 0 auto;
}

<div id="thing">
   <p>text text text with no fixed size, variable font</p>
</div>

The div is at the top, but I can't center it with <center> or margin: 0 auto;

[A]
Your problem may be solved if you give your
```
div
```
a fixed width, as follows:
```
```
div#thing {
    position: absolute;
    top: 0px;
    z-index: 2;
    width:400px;
    margin-left:-200px;
    left:50%;
}
```
```


q:
As it seems there is no scripting language for Windows mobile devices that gives access to phone (sms, mms, make a call, take photo). I wonder how complex it would be to make a Python library that would enable that (write something in C, compile, and import in PythonCE).

Question: Where shall start to understand how to compile a PythonCE module that will give additional functionality to Python on Windows mobile. Also, what is the required toolkit. Is it at all possible on Mac (Leopard)?

[A]
As the first step, you should try to create executable programs that invoke the functions you want. For example, to send SMS, it appears you need to call MailSwitchToAccount, passing "SMS", and so on - familiarize yourself with the C API on the platform.
To create executables, you need Visual Studio, and the Windows Mobile SDK. Those run on Windows. For cross-compilation, there is CeGCC (
http://cegcc.sourceforge.net/docs/using.html
), but using it probably makes things more complicated than using the Microsoft tools.
When you have executables that perform the functions you desire, creating Python extension modules out of them should be easy. Just follow the extending-and-embedding tutorials.


q:
There are a couple of questions similar to this on stack overflow but not quite the same.

I want to open, or create, a local group on a win xp computer and add members to it, domain, local and well known accounts.  I also want to check whether a user is already a member so that I don't add the same account twice, and presumably get an exception.

So far I started using the DirectoryEntry object with the WinNT:// provider.  This is going ok but I'm stuck on how to get a list of members of a group?

Anyone know how to do this?  Or provide a better solution than using DirectoryEntry?

[A]
You should be able to find this information inside the
```
"member"
```
attribute
on the
```
DirectoryEntry
```
that represents the group.


q: Am I allowed to place <noscript> in the <head>?

[A]
According to the
XHTML Strict DTD
, no, you're allowed script, style, meta, link, object, title and base only.  Transitional allows isindex as well, but still not noscript.


q: Anyone got an idea how to get from an Xserver the list of all open windows?

[A]
From the CLI you can use
```
```
xwininfo -tree -root
```
```
If you need to do this within your own code then you need to use the
```
XQueryTree
```
function from the
```
Xlib
```
library.


q:
I have two PHP scripts, both using the same session by calling session_name('MySessID').

When the first script calls the second script using curl, the second script hangs when session_start() is called.

Why would this happend?

[A]
I don't totally understand why this happens, but I got it solved.
This
bug
describes the same problem I'm having. I have a scripts posting to another script,
both using the same session
, which apparently stalls PHP.
So, before I do the whole curl post script, I call the
```
session_commit
```
function, so ending the calling scripts session, and enabling the called script to restart the session.
Whack...


q: How to send array in Httpservice in Adobe Flex3

[A]
I am not quite sure what you mean by sending an array to a httpservice. If you mean to send an array to a httpservice with the same field name, you can pass an array as field value.
```
```
var service:HTTPService = new HTTPService();
service.useProxy = true;
service.destination = "myservicet";
service.resultFormat = HTTPService.RESULT_FORMAT_XML;

var fields:Array = ["categories", "organisation"];
var params:Object = new Object();
params.q = "stackoverflow";
params.rows = 0;
params.facet = "true";
params["facet.field"] = fields;
service.send(params);
```
```
The HTTPService will convert this to the url parameters:
```
facet=true&q=stackoverflow&facet%2Efield=categories&facet%2Efield=organisation&rows=0
```
Hope this helps!
Added for more clarity. When there is only 1 argument in the array, do not pass the fields as an array. For some reason, flex will not send this to the http service


q:
This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript.

Original string is 'original READ ONLY'

I want to replace the 'READ ONLY' with 'READ WRITE'

Any quick answer please? Possibly with a javascript code snippet...

[A]
Good
summary
. It is regexp based, if you use regexp notation you can specify the i and g modifiers (case insensitive (i), which will match regardless to case and global (g), which will replace all occurences), if you use string notation it'll get converted to a regex and you wont' be able to specify any modifier.
```
```
<script type="text/javascript">

var str1="Visit Microsoft!";
var str2 = str1.replace(/microsoft/i, "W3Schools"); //Will work, per the i modifier

var str3 = "original READ ONLY";
var str4 = str3.replace("ONLY", "WRITE"); //Will also work

</script>
```
```


q: I am creating a plugin for Eclipse 3.4.  I created a plug-in development project using the application with a view.  Now I am trying to create a TextViewer the documentation says that it is located in org.eclipse.jface.text.TextViewer.  But, this whole package is missing and eclipse cannot locate TextViewer class to import.  I want to know why is this package/class missing?  Also if it is really gone what took TextViewer's place?

[A]
in 3.4 i have it inside
eclipse-jee-ganymede-win32\plugins\org.eclipse.jface.text_3.4.0.v20080603-2000.jar


q:
Is there a way to "stream" a set of results (eg. a DataTable) from a BackgroundWorker to a DataGridView. What I want to do is to query data, and fill the results in a DataGridView as they come (like query grid results in SQL Server Management Studio). My first thought was to use a BackgroundWorker (to avoid the UI freeze effect), but there would still be a perceivable "lag" as the BackgroundWorker is loading the results.

What would be the best way to go about this?

[A]
You could:
Bind the DataGridView to an initially empty DataTable.
Then, in your worker thread, use a thread-safe collection (a synchronized queue for example) and calls to Control.BeginInvoke to pass record info over to the UI thread.
In the UI thread, you'd pull items out of the queue and add corresponding rows to the DataTable. Through the magic of data binding, these would be added to the gridview.
However, by employing multithreading you immediately make your program much more likely to be broken! I haven't tried this specific scheme, and don't know if the GridView would be rendered effectively unusable while items are being added to it. I have populated a treeview using multithreading, and it is indeed a cool effect. However, I ended up disabling the functionality, as it introduced bugs due to not being a fully correct implementation dealing with all the possible user interactions.


q: I know we can do like mget *.xml which will download all xml files. But how is it possible that we using mget with certain file name patterns. can we do something like *SS.xml which mean it will download all files ending with SS.xml?

[A]
Do you mean the
```
mget
```
command within FTP?
Yes, that should be possible, particularly if the remote server is a Unix server where file extensions have no special meaning on the server, they're just another part of the filename.


q:
We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ?

We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should compile under gcc and the Microsoft C++ compiler (of course full compliance with standards would be a plus)

[A]
Don't use
```
scanf()
```
, tokenize your input separately and then use
```
strtoull()
```
or similar.


q:
How can I use Hyperlink button in gridview. I mean when I run my program,all data is displayed in gridview,but I want hyperlink in gridview, so that when I will click in hyperlink it will show the select path which is in gridview : if there is pdf file path and I just click on this hyper link then I can see the pdf file.

Can you tell me how can I do this?

[A]
You need to use a template field. e.g. lets say you're column is called 'PdfUrl'
Then add a column to your datagrid. that looks like
```
```
<asp:TemplateField HeaderText="Link" SortExpression="PdfUrl">
    <itemtemplate>
        <asp:HyperLink runat="server" ID="hlkPDF" NavigateURL='<%# DataBinder.Eval(Container.DataItem, "PdfUrl") %>' />
    </itemtemplate>
</asp:TemplateField>
```
```


q:
I would like to hear some opinions about using the isolated storage in Silverlight for storing sensitive data. For example, is it OK to store an authentication token (some GUID that identifies a server-side session) in this storage, or is it better to use cookies?

The isolated storage gives an advantage over cookies in that it is shared across browsers, but it might be more difficult to handle expiry, and there might be some other issues (security?) that I am not aware of.

So... what are your opinions? Or do you know any great articles about the topic?

Thanks, Jacob

[A]
I have a similar situation here, though I use MySQL. Every database has a versions table that contains the version (simply an integer) and a short comment of what has changed in this version. I use a script to update the databases. Every database change can be in one function or sometimes one change is made by multiple functions. Functions contain the version number in the function name. The script looks up the highest version number in a database and applies only the functions that have a higher version number in order.
This makes it easy to update databases (just add new change functions) and allows me to quickly upgrade a recovered database if necessary (just run the script again).
Even when testing the changes before this allows for defensive changes. If you make some heavy changes on a table and you want to play it safe:
```
```
def change103(...):
    "Create new table."
def change104(...):
    """Transfer data from old table to new table and make
       complicated changes in the process.
    """
def change105(...):
    "Drop old table"
def change106(...):
    "Rename new table to old table"
```
```
if in change104() is something going wrong (and throws an exception) you can simply delete the already converted data from the new table, fix your change function and run the script again.
But I don't think that changing a database dynamically when a client connects is a good idea. Sometimes changes can take some time. And the software that accesses a database should match the schema of the database. You have somehow to keep them in sync. Maybe you could distribute a new software version and then you want to upgrade the database when a client is actually starting to use this new software. But I haven't tried that.


q:
How can I create a query for a full outer join across a M2M relationchip using the django QuerySet API?

It that is not supported, some hint about creating my own manager to do this would be welcome.

Edited to add:
@S.Lott:
Thanks for the enlightenment.
The need for the OUTER JOIN comes from the application. It has to generate a report showing the data entered, even if it still incomplete.
I was not aware of the fact that the result would be a new class/model. Your hints will help me quite a bit.

[A]
Django doesn't support "joins" in the usual SQL sense -- it supports object navigation.
Note that a relational join (inner or outer) creates a new "class" of entities.  One that doesn't have a definition in Django.  So there's no proper "result set" since there's no class definition for the things you get back.   The best you can do is define a tuple which will be packed with None's for missing combinations.
A left (or right) outer join looks like this.  It creates two disjoint subsets, those who have an associated set of related entities, and those who don't.
```
```
for obj in Model1.objects.all():
    if obj.model2_set().count() == 0:
        # process (obj, None) -- no Model2 association
    else:
        for obj2 in obj.model2_set.all():
            # process (obj, obj2) -- the "inner join" result
```
```
A "Full" outer join is a union of the remaining items that have no relationships.
```
```
for obj2 in Model2.objects.all():
    if obj2.model1_set().count() == 0:
        # process (None, obj2) -- no Model1 association
```
```
The issue is always, what processing are you doing with this weird collection of three different subsets of objects?
The point of an object database is to focus the processing on the object and it's associated objects.
The peculiar collection called a "relational join" is never in the original object model.  It's a new class of objects built from two (or more) original objects.
Worse, outer joins create a collection with multiple subclasses (inner join, left outer join and right outer join).  What does that collection of things
mean
?
Wait, it can get worse.  If the processing includes checks for the missing attributes (i.e.
```
if someObj.anObj2attribute is None
```
: we're essentially looking for
```
Model1
```
items with no
```
Model2
```
object associated.  Ummm... why did we put those in the outer join, only to filter them using an
```
if
```
statement?  Why not just do separate queries amd process each subset properly?
Edit:  When you're showing "incomplete" status, it isn't an outer-join at all.  It's much simpler.  You need to create one (or two) separate collections in your view function for your template to display.
First, you should use status codes, not the presence or absence of a foreign key.  Optional foreign keys don't have "reasons" -- they're either there or not there.  A status code can provide useful shades of meaning ("incomplete", "in error", "broken", "not applicable", "to be deleted", etc.)
```
```
errorList1 = Model1.objects.filter( status="Incomplete" )
errorList2 = Model2.objects.filter( status="Incomplete" )
```
```
These two are the two non-join parts of a full outer join.  You can then display these two error lists in your template with appropriate column titles and status codes and everything.
You can even put them into a single table to mimic the old full outer join report people used to see
```
```

Model1	Model2

    {% for e1 in errorList1 %}

e1	NULL

    {% endfor %}
    {% for e2 in errorList2 %}

NULL	e2

    {% endfor %}

```
```
Looks like a full outer join report.  Without the full outer join.


q: How to get all the database names and corresponding table names together ?

[A]
You will have to write a store procedure.
First get the database name
```
```
SELECT Name FROM master.sys.databases
```
```
For each database
```
```
SELECT %DatabaseName%, Name FROM %DatabaseName%.SysObjects WHERE type = 'U'
```
```
Edit here's the store procedure
```
```
CREATE PROCEDURE sp_GetDatabasesTables
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
CREATE TABLE #schema ( DatabaseName VarChar(50), TableName VarChar(50) );
DECLARE @DatabaseName varchar(50);
DECLARE cursorDatabase CURSOR FOR
    SELECT Name FROM master.sys.databases WHERE Name NOT IN ('tempdb'); -- add any table you want to filter here

OPEN cursorDatabase;

-- Perform the first fetch.
FETCH NEXT FROM cursorDatabase INTO @DatabaseName;

-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC ('INSERT INTO #schema (DatabaseName, TableName) SELECT ''' + @DatabaseName + ''' AS DatabaseName, Name As TableName FROM ' + @DatabaseName + '.sys.SysObjects WHERE type = ''U'';');
    FETCH NEXT FROM cursorDatabase INTO @DatabaseName;
END

CLOSE cursorDatabase;
DEALLOCATE cursorDatabase;
SELECT * FROM #schema
END
```
```


q:
In my Direct3D application, the camera can be moved using the mouse or arrow keys. But if I hard code (0,1,0) as the up direction vector in LookAtLH, the frame goes blank at some orientations of the camera.

I just learned the hard way that when looking along the Y-axis, (0,1,0) no longer works as the Up direction (seems obvious?). I am thinking of switching my up direction to something else for each of these special cases. Is there a more graceful way to handle this?

[A]
Assuming you can calculate a vector pointing forward (what you are looking at - your position) and a vector pointing right (always on the XZ-plane unless you can roll). Normalize both these vectors, then up is forward x right (where x is cross product).
In general, you can plug in your yaw, pitch and roll into a rotation matrix and rotate the axis vectors to get right, up and forward, but I guess that's what you are using LookAtLH to avoid.
See
http://en.wikipedia.org/wiki/Rotation_matrix#The_3-dimensional_rotation_matricies


q:
I used a class which derives from CListBox, and create it with following:

style:WS_CHILD|WS_VISIBLE |LBS_OWNERDRAWFIXED | WS_VSCROLL | WS_HSCROLL

I expect the ListBox's item to be have a fixed size, not affected by the size of the list box. So I override the MeasureItem() method, in which I specify the item's size like below:

void CMyListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMIS)
{
    lpMIS->itemHeight = ALBUM_ITEM_HEIGHT;
    lpMIS->itemWidth = ALBUM_ITEM_WIDTH;
}

But the item's size changes according to the List box's size changing. is there anything wrong with my approach?

[A]
If you look at the
```
MSDN
```
entry for
```
CListBox::MeasureItem
```
you'll see that it's only called once unless the
```
LBS_OWNERDRAWVARIABLE
```
(not
```
LBS_OWNERDRAWFIXED
```
) style is set. If I understand correctly then this would explain the behaviour you're seeing because
```
MeasureItem
```
would need to be called each time the control's size changes.
Also, have you considered the points made in
MFC Technical Note 14 : Custom Controls
?


q: I am generating the json from PHP.

[A]
The correct way is to use
json_encode()


q:
I've been teaching myself Objective-C over the past month or so (I'm a Java head) and I've got my brain wrapped around most of it now. One thing that's confusing me at the moment: What's the difference between importing a class via @class vs doing a #import?

Is one better than another one, or do I need to use one instead of the other in certain cases? I've been using just #import so far.

[A]
```
#import
```
brings the entire header file in question into the current file; any files that THAT file
```
#import
```
s are also included. @class, on the other hand (when used on a line by itself with some class names), just tells the compiler "Hey, you're going to see a new token soon; it's a class, so treat it that way).
This is very useful when you've got the potential for 'circular includes'; ie, Object1.h makes reference to Object2, and Object2.h makes reference to Object1. If you
```
#import
```
both files into the other, the compiler can get confused as it tries to
```
#import
```
Object1.h, looks in it and sees Object2.h; it tries to
```
#import
```
Object2.h, and sees Object1.h, etc.
If, on the other hand, each of those files has
```
@class Object1;
```
or
```
@class Object2;
```
, then there's no circular reference. Just be sure to actually
```
#import
```
the required headers into your implementation (.m) files.


q: Any ideas on how to disable, but not uninstall Resharper 4.x or above?

[A]
You can disable ReSharper 4 and lower using the Visual Studio Add-In Manager (remove the check from check box on the left).
In ReSharper 5 and above (tested up to version 7.0.1),
this is how you can suspend
ReSharper from the Tools > Options > Resharper