Question:
I've been looking at some Ruby dependency injection libraries.  In particularly, I checked out  Needle and Copland.  They've been around for quite awhile, yet not a lot of usages.

What are some of the pros and cons of using these two libraries? It sure seems like a lot of libraries / frameworks out there could make good use of these two libraries, e.g. Merb / Datamapper's Hook.

Answer:
Jamis Buck, who wrote Copland and Needle,
posted here
about Needle, dependency injection and their usefulness in a Ruby world.
It's long but worth reading, but in case you want the single paragraph most relevant to your question, I'd suggest this one, from just before the end:
DI frameworks are unnecessary. In more
  rigid environments, they have value.
  In agile environments like Ruby, not
  so much. The patterns themselves may
  still be applicable, but beware of
  falling into the trap of thinking you
  need a special tool for everything.
  Ruby is Play-Doh, remember! Let’s keep
  it that way.
HTH


Question:
In C# you can use verbatim strings like this:

@"\\server\share\file.txt"

Is there something similar in JavaScript?

Answer:
No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes.
I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method.
What I did to solve this was as follows:
```
```
public void Alert(string message)
{
    message = message.Replace("\\", "\\\\")
        .Replace("\r\n", "\n")
        .Replace("\n", "\\n")
        .Replace("\t", "\\t")
        .Replace("\"", "\\\"");

    // and now register my JavaScript with this safe string.
}
```
```


Question:
I know you can do it file by file.

Is there any way to do this in one step for all files in a project?

Answer:
Do you mean using statements? First, note that they generally do no harm other that take space.
Tools like
ReSharper
offer automated tricks to do this, however: there was a
link in the VS feed
a little while ago; it boils down to:
go to Tools -> Macros -> Macros IDE...
in the Project Explorer, Add -> Add Module... (put in a name - I've used OrganiseUsings)
paste over with the code below
File -> Save MyMacros, exit
Now if you right-click on the toolbar and Customize... - you should be able to find MyMacros.OrganiseUsings.RemoveAndSortAll - drag this somewhere handy (maybe the Tools menu; you might also want to change the name after placing it).
You can now use this option to run the Remove and Sort command for an entire solution. A big time-saver.
==== code ====
```
```
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics

Public Module OrganiseUsings

    Public Sub RemoveAndSortAll()
        On Error Resume Next
        Dim sol As Solution = DTE.Solution

        For i As Integer = 1 To sol.Projects.Count
            Dim proj As Project = sol.Projects.Item(i)
            For j As Integer = 1 To proj.ProjectItems.Count
                RemoveAndSortSome(proj.ProjectItems.Item(j))
            Next
        Next
    End Sub

    Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem)
        On Error Resume Next
        If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then
            If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then
                Dim window As Window = projectItem.Open(Constants.vsViewKindCode)

                window.Activate()

                projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort")

                window.Close(vsSaveChanges.vsSaveChangesYes)
            End If
        End If

        For i As Integer = 1 To projectItem.ProjectItems.Count
            RemoveAndSortSome(projectItem.ProjectItems.Item(i))
        Next
    End Sub

End Module
```
```


Question:
Suppose I have the following directory layout in a Maven project:

src/
|-- main
|   |-- bin
|   |   |-- run.cmd
|   |   `-- run.sh
|   |-- etc
|   |   |-- common-spring.xml
|   |   |-- log4j.xml
|   |   `-- xml-spring.xml
|   `-- java
|       `-- com
...

I would like to build a zip file that, when unzipped, produces something like this:

assembly
|-- bin
|   |-- run.cmd
|   `-- run.sh
|-- etc
|   |-- common-spring.xml
|   |-- log4j.xml
|   `-- xml-spring.xml
`-- lib
    |-- dependency1.jar
    |-- dependency2.jar
...

where `run.xx' are executable shell scripts that will call my main application and put all dependencies on the classpath.

Is this possible with some of the `official' Maven plugins, e.g. maven-assembly-plugin?

Answer:
I use the
AppAssembler plugin
to get something similar. Example:
```
```
...
<build>
<plugins>
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>appassembler-maven-plugin</artifactId>
    <configuration>
      <programs>
        <program>
          <mainClass>com.acme.MainClass</mainClass>
          <name>app</name>
        </program>
      </programs>
    </configuration>
  </plugin>
</plugins>
```
```


Question:
How can I build a native Mac OS X installer for my application, on a non-Mac platform?

For example, I have a windows pc and a Java application. I want the windows pc to build an installer (possibly inside a .dmg archive) that works with Apple installer.

Answer:
So, a couple of quick questions.
First, why do you want an installer? Most Mac users prefer apps that are just drag installed. If you are not writing Mac OS X specific code it is hard to imagine you need to place bits in special places, like Application Support or LaunchDaemons. Assuming everything you have just goes in one folder why bother with an installer at all?
Second, why would it be a problem to build the Mac installer on a Mac? Surely you have a macintosh around to test the app (you are not just blindly shipping it for Mac without testing it on a Mac, right?).
Okay, having said that, assuming you still have a good reason to actually build this on a PC, there are some bits that are not going to be easy. Basically a .pkg is a bunch of text scripts, localizations, an archive file (Archive.pax.gz), and a bill of materials (Archive.bom).
Assuming not much changes between builds, you can make the installer on a Mac, and then just rebuild the bom and the pax.gz, replace them into the existing .pkg, and batch a few pieces of metadata. The pax should be easy enough to deal with (pax is a standard archive format), but the bom file may prove a bit trickier, since I do not believe it is publicly documented, and I doubt the tools for creating them (mkbom) are part of darwin (not opensource). So you are going to need to figure that out and write a custom tool to create the bom file.
In other words, this is likely to be a large amount of work.


Question:
I just can't remember the terminology used for this and other related properties.

EDIT - Maybe such a concept doesn't exist but I remember reading something in Effective C++ (or More Effective C++) where he advocated using swaps to commit changes last in the function because the vector swap functions were guaranteed not to throw an exception.

Answer:
I think you mean to say that the function is "exception-safe". See e.g.
http://en.wikipedia.org/wiki/Exception_safety
.
The Wikipedia article further divides the safety into various levels. This is the one that is relevant here:
2. Commit or rollback semantics, also known as strong exception safety or no-change guarantee: Operations can fail, but failed operations are guaranteed to have no side effects so all data retain original values.
There's a reference to an STL design document that introduces exception safety and commit-or-rollback semantics:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1997/N1077.asc


Question: Should I use the change or textInput event to capture user input on a TextInput control? Why?

Answer:
```
textInput
```
is dispatched only when the user has
input
text into the control.
```
change
```
, on the other hand, is dispatched on every change committed by the user. So for example, if the user deletes a part of the text, only the
```
change
```
event is dispatched.
Neither of these is dispatched when the text is modified via code:
```
flash.events.TextEvent.TEXT_INPUT
```
:
"Dispatched when
the user
types, deletes, or pastes text into the
  control."
(ignore the word "delete" there -- I just tried it and this event is
not
dispatched when text is deleted by the user)
```
flash.events.Event.CHANGE
```
:
"Dispatched when text in the TextInput control changes through user
  input.
This event does not occur if
  you use data binding or ActionScript
  code to change the text
."
You can also use the
```
valueCommit
```
event, which is dispatched when the user "commits" the changes (usually by moving the focus away from the text field), but remember that this event is also dispatched when the field value is changed programmatically.


Question:
We just shifted from VB to C# and I am having some troubles..!

Why can't I create a private static const void??

why is it not working?

 private static const void MyVoid(void void)
 {
   try
   {
      this.void void = new void(void + void);
      return this.void;
   }
   catch (void)
   {
      Response.Write(void);
   }
 }

Answer:
```
void
```
is the return type of
"there is no return type"
. It is not a type in itself (as in
```
int
```
,
```
bool
```
etc.), but rather specifies it returns nothing.


Question:
This line:

strcat(query,*it);

(where *it is an iterator to a string)

Keeps giving me this error:

no matching function for call to ``strcat(char[200], const std::basic_string, std::allocator >&)`'

I guess it's because strcat takes in a char* while *it is a string.
How do I convert it from a string to a char* to make it work with strcat() ?

I've tried strcat(query,(*it).c_str()) but that just gives me a runtime error.

Edit: sorry, it should be converted to a const char*

Answer:
```
strcat(query,(*it).c_str())
```
should work. What's the runtime error? Are you sure that
```
query
```
is null-terminated before you make the call?


Question:
Given a method signature:

public bool AreTheSame<T>(Expression<Func<T, object>> exp1, Expression<Func<T, object>> exp2)

What would be the most efficient way to say if the two expressions are the same? This only needs to work for simple expressions, by this I mean all that would be "supported" would be simple MemberExpressions, eg c => c.ID.

An example call might be:

AreTheSame<User>(u1 => u1.ID, u2 => u2.ID); --> would return true

Answer:
Hmmm... I guess you'd have to parse the tree, checking the node-type and member of each. I'll knock up an example...
```
```
using System;
using System.Linq.Expressions;
class Test {
    public string Foo { get; set; }
    public string Bar { get; set; }
    static void Main()
    {
        bool test1 = FuncTest<Test>.FuncEqual(x => x.Bar, y => y.Bar),
            test2 = FuncTest<Test>.FuncEqual(x => x.Foo, y => y.Bar);
    }

}
// this only exists to make it easier to call, i.e. so that I can use FuncTest<T> with
// generic-type-inference; if you use the doubly-generic method, you need to specify
// both arguments, which is a pain...
static class FuncTest<TSource>
{
    public static bool FuncEqual<TValue>(
        Expression<Func<TSource, TValue>> x,
        Expression<Func<TSource, TValue>> y)
    {
        return FuncTest.FuncEqual<TSource, TValue>(x, y);
    }
}
static class FuncTest {
    public static bool FuncEqual<TSource, TValue>(
        Expression<Func<TSource,TValue>> x,
        Expression<Func<TSource,TValue>> y)
    {
        return ExpressionEqual(x, y);
    }
    private static bool ExpressionEqual(Expression x, Expression y)
    {
        // deal with the simple cases first...
        if (ReferenceEquals(x, y)) return true;
        if (x == null || y == null) return false;
        if (   x.NodeType != y.NodeType
            || x.Type != y.Type ) return false;

        switch (x.NodeType)
        {
            case ExpressionType.Lambda:
                return ExpressionEqual(((LambdaExpression)x).Body, ((LambdaExpression)y).Body);
            case ExpressionType.MemberAccess:
                MemberExpression mex = (MemberExpression)x, mey = (MemberExpression)y;
                return mex.Member == mey.Member; // should really test down-stream expression
            default:
                throw new NotImplementedException(x.NodeType.ToString());
        }
    }
}
```
```


Question:
I'm using the ReportViewer control to display a Report within a WebForm, i've also implemented the "Export to Excel" feature, by calling the Render method of the Server Report

eg

ReportViewerControl.ServerReport.Render("Excel",etc,etc,etc);

My problem is that the exported report contains Hyperlinks that link to other reports, I wish these to appear in the webform but not appear hence be disabled in the Exported Spreadsheet (generated by the Code above).

Does anyone have a way of achieving this?

Thanks

Answer:
regarding your question about list traversal - you can start by writing a function that returns lists that represent the path - that's I think easier and it will be later easy to turn it into a function that returns a number.
This one takes a list as the first argument (path so far) and a tree and returns a list> type - that is all the possible paths from the current branch.
```
```
let rec visitor lst tree =
  match tree with
  | Branch(n, sub) -> List.collect (visitor (n::lst)) sub
  | Leaf(n) -> [List.rev (n::lst)]

// For example...
> let tr = Branch(1, [Leaf(3); Branch(2, [Leaf(4); Leaf(5)] )]);;
> visitor [] tr;;
val it : int list list = [[1; 3]; [1; 2; 4]; [1; 2; 5]]
```
```
In the 'Leaf' case, we simply add the current number to the list and return the result as a list containing single list (we have to reverse it first, because we were adding numbers to the beginning).
In the 'Branch' case, we add 'n' to the list and recursively call the visitor to process all the sub-nodes of the current branch. This returns a bunch of lists and we use 'map_concat' to turn them into a single list that contains all posble paths from the current branch.
Now, you can rewrite this to return a list of integers:
```
```
let rec visitor2 lst tree =
  match tree with
  | Branch(n, sub) -> List.collect (visitor2 (lst * 10 + n)) sub
  | Leaf(n) -> [lst * 10 + n]

// For example...
> visitor2 0 tr;;
val it : int list = [13; 124; 125]
```
```
Instead of concatenating lists, we now calculate the number.


Question:
is there a way to change an oracle user's default schema?

I found it in the FAQ that I can alter it in the session, but it's not what I want. E.G. the user at log on always sees another schema as default.

Thanks in advance.

Answer:
I believe a logon trigger should work:
```
```
CREATE OR REPLACE TRIGGER db_logon
AFTER logon ON DATABASE WHEN (USER = 'A')
BEGIN
    execute immediate 'ALTER SESSION SET CURRENT_SCHEMA = B';
END;
```
```


Question:
I have an website. When the user is logged the session details will loaded.
When the user logged out the session details will abandoned. (Log out by clicking the logout menu)
when the user simply closes the browser then how to destroy the session.

In the next time its get logging with the same session data. I need to avoid this.

Answer:
You could configure your sessions to time out quicker.
In web.config:
```
```
< sessionState ... timeout="5" />
```
```


Question: Currently, my Objective C classes use C++ objects by doing a new when the owner is created, and calling delete when it is destroyed. But is there another way? I'd like to be able to declare, say, an auto_ptr whose scope lasts the duration of the Objective C class' lifetime.

Answer:
Ok, let me assume you are using C++ and Objective-C on a Mac, if I'm right you are likely using X-code. So if you go to the properties (info) of your project. You can check the compile options (GCC's). In there, there is an option to enable C++ constructors/destructors (which is turned off by default in Cocoa projects).
Then you get default-like C++ scoping, however I haven't used it much and I've had problems with heavily template code (Boost).
Also I don't think anyone officially supports this besides some good souls working on GCC. So I'd recommend that you unit test anything like this, and keep note that anything could go wrong.
Nevertheless being able to use C++ in objective-C, for me as a C++ person, is a relief and the risks are worth the benefits :)


Question:
I have quite a large list of words in a txt file and I'm trying to do a regex find and replace in Notepad++. I need to add a string before each line and after each line.. So that:

wordone
wordtwo
wordthree

become

able:"wordone"
able:"wordtwo"
able:"wordthree"

How can I do this?

Answer:
Assuming alphanumeric words, you can use:
```
```
Search  = ^([A-Za-z0-9]+)$
Replace = able:"\1"
```
```
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
```
```
Search = ^(.+)$
```
```
```
^
```
points to the start of the line.
```
$
```
points to the end of the line.
```
\1
```
will be the source match within the parentheses.


Question:
I followed the commonly-linked tip for reducing an application to the system tray : http://www.developer.com/net/csharp/article.php/3336751 Now it works, but there is still a problem : my application is shown when it starts ; I want it to start directly in the systray. I tried to minimize and hide it in the Load event, but it does nothing.

Edit : I could, as a poster suggested, modify the shortcut properties, but I'd rather use code : I don't have complete control over every computer the soft is installed on.

I don't want to remove it completely from everywhere except the systray, I just want it to start minimized.

Any ideas ?

Thanks

Answer:
If you are using a
```
NotifyIcon
```
, try changing ShowInTaskbar to false.
To remove it from the Alt+Tab screen, try changing your window border style; I believe some of the tool-window styles don't appear...
something like:
```
```
using System;
using System.Windows.Forms;
class MyForm : Form
{
    NotifyIcon sysTray;

    MyForm()
    {
        sysTray = new NotifyIcon();
        sysTray.Icon = System.Drawing.SystemIcons.Asterisk;
        sysTray.Visible = true;
        sysTray.Text = "Hi there";
        sysTray.MouseClick += delegate { MessageBox.Show("Boo!"); };

        ShowInTaskbar = false;
        FormBorderStyle = FormBorderStyle.SizableToolWindow;
        Opacity = 0;
        WindowState = FormWindowState.Minimized;
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new MyForm());
    }
}
```
```
If it still appears in the Alt+Tab, you can change the window styles through p/invoke (a bit hackier):
```
```
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    IntPtr handle = this.Handle;
    int currentStyle = GetWindowLong(handle, GWL_EXSTYLE);
    SetWindowLong(handle, GWL_EXSTYLE, currentStyle | WS_EX_TOOLWINDOW);
}
private const int GWL_EXSTYLE = -20, WS_EX_TOOLWINDOW = 0x00000080;
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr window, int index, int value);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr window, int index);
```
```


Question:
We need to set up a secure certificate on an Apache reverse proxy.
We've been advised that we need to use a virtual host directive.

I've looked these up in the O'Reilly book bit can't find any examples that pick up https specifically.

Does anyone have any examples of config snippets to do this?

Answer:
Not sure if this is what you're after, but I used something like the following in the past:
```
```
<IfModule mod_ssl.c>
    SSLProxyEngine On
    ProxyPreserveHost On
    RewriteRule ^/whatever(.*)$       https://otherhost/whatever$1  [P]
</IfModule>
```
```
I needed to proxy secure content from another host, and that's what we ended up using. Works fine, and has for some time now. Does that sort of cover what you're looking for?


Question:
Can I utilise the new functionality provided by the new JavaFX APIs directly from Java to the same extent as I would be able to using JavaFX Script?

Are all the underlying JavaFX APIs purely Java or JavaFX Script or a mix?

Answer:
The JavaFX APIs are a mix of JavaFX and Java. The SDK comes with an archive src.zip which contains a part of the APIs (only the most basic classes are included, but things like javafx.scene are missing).
Calling JavaFX code from Java is not officially supported in JavaFX 1.x AFAIK. There's a
blog entry in the JavaFX blog
that shows you how to do anyway it using unsupported APIs, but it's complicated and won't work this way in future versions.
There are two supported ways to use JavaFX from Java. Either you use the Scripting API to invoke JavaFX code, as shown in
this article
. Or, which is the most elegant solution IMHO, write the API-accessing code using JavaFX, define Java interfaces to interact with your JavaFX code from plain Java, and then implement those interfaces in JavaFX.


Question:
I have a python list, say l

l = [1,5,8]

I want to write a sql query to get the data for all the elements of the list, say

select name from students where id = |IN THE LIST l|

How do I accomplish this?

Answer:
string.join
the list values separated by commas, and use the
format operator
to form a query string.
```
```
myquery = "select name from studens where id in (%s)" % ",".join(map(str,mylist))
```
```
(Thanks,
blair-conrad
)


Question:
I have just converted a project from Visual Studio 2003 to 2005 and although most of it 'converted' fine, I have a series of STL errors from the following line:

void SomeFn( std::vector<CSomeObject*>::iterator it,
std::vector<CSomeObject*>::iterator itBegin = NULL,
std::vector<CSomeObject*>::iterator itEnd = NULL );

The Visual Studio error is as follows:

c:\<path>\Headerfile.h(20) : error C2440: 'default argument' : cannot convert from 'int' to 'std::_Vector_iterator<_Ty,_Alloc>'
        with
        [
            _Ty=CObject *,
            _Alloc=std::allocator<CObject *>
        ]
        No constructor could take the source type, or constructor overload resolution was ambiguous

I can't see anything wrong with that code and it worked perfectly in VS 2003. Any ideas?

Answer:
In 2003,
```
std::vector<T>::iterator
```
is just
```
T *
```
. In 2005, at least in debug mode, it is a class, and hence you can't use
```
NULL
```
for its value (
```
NULL
```
resolves to
```
0
```
).
You can use a default-constructed iterator instead:
```
```
std::vector<CSomeObject*>::iterator itBegin = std::vector<CSomeObject*>::iterator()
```
```


Question:
In my Java program, I create an OtpNode and a "named" OtpMBox. Whenever a message is received via this mbox, some time-consuming operation needs to be performed after which a reply message is sent back. Since this operation is time-consuming, subsequent messages sent to the mbox won't be processed immediately.

So I want to use Java threads - one per message received. My question is should I also create a new OtpMBox for each message received or can the original OtpMBox be shared among all the threads?

Answer:
I'm not really familiar with this stuff, but I suppose you may do some calculates )
You have overhead of running OtpMBox for each java-thread and overhead of controlling system (written in java) that would ask different threads to do some work and take results from them. I believe java isn't good tool for it )
You better do java-thread 'supervisor' that will start some (may be number of CPUs) amount 'worker' java-threads with OtpMBox and send OtpMBox's pids to erlang system.
--sorry my english


Question:
What are best practices with regards to C and C++ coding standards?  Should developers be allowed to willy-nilly mix them together.  Are there any complications when linking C and C++ object files.

Should things like socket libraries that traditionally is written in C remain in C and kept in seperate source files? That is keeping c code in .c files and c++ code in .cpp files.
When mixing c and C++ after being parsed with g++ will there be any performance penalties, since typesafe checks are not done in C? but are in C++.  Would would be the best way to link C and C++ source code files.

Answer:
The biggest issue is calling a C function from C++ code or vice versa. In that case, you want to make sure you mark the function as having "C" linkage using
```
extern "C"
```
. You can do this in the header file directly using:
```
```
#if defined( __cplusplus )
extern "C" {
#endif

extern int myfunc( const char *param, int another_one );

#if defined( __cplusplus )
}
#endif
```
```
You need the
```
#if
```
s because C code that includes it won't understand
```
extern "C"
```
.
If you don't want to (or can't) change the header file, you can do it in the C++ code:
```
```
extern "C" {
#include "myfuncheader.h"
}
```
```
You can mark a C++ function as having C linkage the same way, and then you can call it from C code. You can't do this for overloaded functions or C++ classes.
Other than that, there should be no problem mixing C and C++. We have a number of decades-old C functions that are still being used by our C++ code.


Question:
Is there a way to find the size of a file object that is currently open?

Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size.  As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.

Answer:
If you have the file descriptor, you can use
```
fstat
```
to find out the size, if any. A more generic solution is to seek to the end of the file, and read its location there.


Question:
I need to create a BAT file to run an application through telnet, but as far as I know there is no way to do this on DOS. Telnet does not allow any command to be sent to the remote machine at the very instant of the connection, and each subsequent command in the BAT file would only be executed after telnet stops. This hypothetical piece of code illustrates what I want to do:

telnet 100.99.98.1 "C:\Application\app.exe -a -b -c"

And that would run the app.exe on the machine 100.99.98.1 with three parameters. Despite my efforts, nothing worked. Is there a way to do that?

Tks,

Pedrin Batista

Answer:
Using telnet in the way you want to is imho not possible.
You could you secure shell (ssh), but a ssh server has to run on the remote machine (100.99.98.1 in you case).
EDIT:
See
http://sshwindows.sourceforge.net/
for a ssh client and server (based on cygwin) for Windows.


Question:
I am using the Zend Framework.

I have a controller named 'UserController' that has a public function displayAction().

I would like to know how I can get that action method to use a different viewer than the default display.phtml.

Any help is appreciated.

Answer:
You can use
```
```
$this->render('actionName');
```
```
or, alternatively, you can call a view script directly by calling
```
```
$this->renderScript('path/to/viewscript.phtml');
```
```
For more information, you can take a look at
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html
, specifically the parts about the
```
render()
```
and
```
renderScript()
```
methods.


Question:
I'm automating a web application (the Mantis bug tracker) and I'm getting an interesting response header from it, called Refresh:

HTTP/1.x 200 OK
...
Refresh: 0;url=my_view_page.php

It seems to be acting the same way that meta refresh does, and the meta refresh technique implies that it is an equivalent of a header in HTTP.

Problem is, I can't find any mention of the Refresh header in the HTTP standard or any other definitive documentation on how it should be parsed and what the browser should do when it encounters it.

What's going on here?

Answer:
from the W3C HTML 4.01 specification, quote:
META and HTTP headers
The http-equiv attribute can be used in place of the name attribute and has a special significance when documents are retrieved via the Hypertext Transfer Protocol (HTTP). HTTP servers may use the property name specified by the http-equiv attribute to create an [RFC822]-style header in the HTTP response. Please see the HTTP specification ([RFC2616]) for details on valid HTTP headers.
What this means is that when you use the
```
<meta http-equiv="refresh" url="..."/>
```
tag, you are actually instructing the browser to act as if there were a
```
Refresh
```
header being sent.
a good overview of the history of it can be found at
http://www.securiteam.com/securityreviews/6Z00320HFQ.html


Question:
I'm converting my applications to Delphi 2009 and faced an intriguing issue with some calls that need to convert a string (wide) to AnsiString.

Here's an example to demonstrate the issue I'm having:

var
  s: PAnsiChar;

...

s := PAnsiChar(Application.ExeName);

With Delphi 2007 and previous versions, s := PChar(Application.ExeName) would return the application exe path.

with Delphi 2009, s := PAnsiChar(Application.ExeName) returns only 'E'.

My guess is that's because I'm converting a unicode string to an ansi string but how can I convert it so that a PAnsiChar gets the full string?

Answer:
I have no Delphi 2009 here, so I can't check it. But maybe you have to try:
```
```
s := PAnsiChar(AnsiString(Application.ExeName));
```
```
As gabr already pointed, this is not a very good practice, and you will only use it if you are 100% sure. The string only contains characters that have a direct mapping to the ANSI range.
That's why you should get a warning because you are converting Unicode to ANSI.


Question:
I am reading a .csv file and returning its lines in string array. One of the members is manufacturer, for which I have Toyota, Ford, etc.

I want to sort an array (Can be another collection) of the rows, by the value in manufacturer and alphabetical order.

So I'd have:

28437 Ford Fiesta
328   Honda Civic
34949 Toyota Yaris

and so forth...

What would be the best way to do this using C# and no database? I say no database because I could insert the csv into a table in a sql server database, and then query it and return the data. But this data is going into a html table built on the fly, which would make the database approach a little long winded.

Answer:
What version of .NET are you using? If you're using 3.5 - or can use C# 3.0 and
LINQBridge
- then I'd definitely go with LINQ. First transform each line into some appropriate object, and then use OrderBy:
```
```
var cars = lines.Select(line => Car.ParseLine(line))
                .OrderBy(car => car.Manufacturer);
```
```


Question:
In a SQL Server database, I record people's date of birth. Is there an straight-forward method of working out the person's age on a given date using SQL only?

Using DATEDIFF(YEAR, DateOfBirth, GETDATE()) does not work as this only looks at the year part of the date. For example DATEDIFF(YEAR, '31 December 2007', '01 January 2008') returns 1.

Answer:
Check out this article:
How to calculate age of a person using SQL codes
Here is the code from the article:
```
```
DECLARE @BirthDate DATETIME
DECLARE @CurrentDate DATETIME

SELECT @CurrentDate = '20070210', @BirthDate = '19790519'

SELECT DATEDIFF(YY, @BirthDate, @CurrentDate) - CASE WHEN( (MONTH(@BirthDate)*100 + DAY(@BirthDate)) > (MONTH(@CurrentDate)*100 + DAY(@CurrentDate)) ) THEN 1 ELSE 0 END
```
```


Question:
As far as Google searches tell me, the maximum allowed number of cookies depends very much on the browser, however I cannot find any recent data as to how much cookies are allowed on modern browsers.

I need to store a somewhat large number of user preferences in cookies (for not-yet-registered users), so what would be the best way of doing that? (Also, those cookies would be accessed both via javascript client-side and php server-side)

Answer:
The best way would be to not store them in a cookie at all.
Store them in a database, and store the DB key in the cookie.  If it's just a few preferences then security isn't much of an issue.
Don't forget that cookies will be sent with every request - if you have 2kb of cookie data and load 10 images on a page, that's an extra 22kb of data.


Question:
I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package.

My question is: Is there a way to access this object in the default-package from a Java-class in a named package?

Answer:
You can’t use
classes in the default package from a named package.
(
Technically
you can, as shown in Sharique Abdullah's
answer
through reflection API,
but
classes from the unnamed namespace are
not in scope
in an
import declaration
)
Prior to J2SE 1.4 you could import classes from the default package using a syntax like this:
```
```
import Unfinished;
```
```
That's
no longer allowed
. So to access a default package class from within a packaged class requires moving the default package class into a package of its own.
If you have access to the source generated by groovy, some post-processing is needed to move the file into a dedicated package and add this "package" directive at its beginning.
Update 2014:
bug 6975015
, for JDK7 and JDK8, describe an even
stricter
prohibition against import from unnamed package.
The
```
TypeName
```
must be the canonical name of a class type, interface type, enum type, or annotation type.
The type must be either a member of a
named package
, or a member of a type whose outermost lexically enclosing type is a member of a
named package
,
or a compile-time error occurs
.
Andreas
points out
in the comments
:
"why is [the default package] there in the first place? design error?"
No, it's deliberate.
JLS 7.4.2. Unnamed Packages
says: "Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development".


Question: Does anyone know if there is an implementation of javax.jms.QueueConnectionFactory for WebSphere MQ and where to get it? I Googled it and searched IBM website but couldn't find anything. I don't want to retrieve the connection or factory from Websphere MQ via JNDI, I need my own connection factory.

Answer:
I think you need three jars
```
```
com.ibm.mq.jar
com.ibm.mqbind.jar
com.ibm.mqjms.jar
```
```
You instantiate a
MQQueueConnectionFactory
and i hope you can take it from there.
And here's more info:
IBMs HOWTO
Oh, and MQ can do "real" JMS instead of MQ - only the JMS implementation seemed to have problems closing the Channel properly - at least in our environment.


Question: How can I call a C++ function from C# .NET?

Answer:
compile the C++ function into a dll and
use P/Invoke
or
compile the C++ function into a C++/CLI assembly, wrap in a managed C++ class, and then treat like any other assembly (add a reference, use a using statement and call the class)


Question:
I am trying to establish a basic .NET Remoting communication between 2x 64bit windows machines. If Machine1 is acting as client and Machine2 as server, then everything works fine. The other way around the following exception occurs:

System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 172.16.7.44:6666

The server code:

TcpChannel channel = new TcpChannel(6666);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(
  typeof(MyRemotableObject),"HelloWorld",WellKnownObjectMode.Singleton);

The client code:

TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
// Create an instance of the remote object
remoteObject = (MyRemotableObject)Activator.GetObject(
  typeof(MyRemotableObject), "tcp://172.16.7.44:6666/HelloWorld");

Any idea whats wrong with my code?

Answer:
Windows Firewall? (Question author says this is not it.)
To track down connection issues the standard approach applies (apply in any order):
ping the machine
double check if some process really is listening in port 6666 (
```
netstat -an
```
)
telnet the machine on port 6666
try to use a different service on the machine.
check if some configuration upsets the server process listening on 6666 and causes it to refuse you. (don't know if that is possible with .NET remoting)
watch communication with the machine using a packet sniffer (Packetyzer, for example) to find out what's going on at the TCP/IP level.
maybe active network infrastructure components between server and client (layer-3 switches, firewalls, NAT-routers, whatever) are interfering


Question:
I have an XML input file and I'm trying to output the result of a call like:

<xsl:value-of select="Some/Value"/>

into an attribute.

<Output Attribute="Value should be put here"/>

My problem is, since I'm outputting XML, the XSL processor won't allow me to write:

<Output Attribute="<xsl:value-of select="Some/Value"/>">

How do you accomplish this?

Answer:
You can use an xsl:attribute element:
```
```
<Output>
  <xsl:attribute name="Attribute">
    <xsl:value-of select="Some/Value"/>
  </xsl:attribute>
</Output>
```
```


Question:
I'm trying to add a new node to an jQuery SimpleTree, but all I seem to be able to get is "sTC.addNode is not a function"...

var simpleTreeCollection = $('.simpleTree').simpleTree({
    animate:true,
    drag:false,
    autoclose: false,
    afterClick:function(node){},
    afterDblClick:function(node){},
    beforeMove:function (destination, source, pos){},
    afterMove:function(destination, source, pos){},
    afterAjax:function() {},
    afterContextMenu:function(node){}
});

simpleTreeCollection.addNode('test', 'test');

Any suggestions what I might be doing wrong? Is there even the possibility to add a node?

Answer:
hmm tricky one this and I have to say I dont like the plugin as it uses numerics as id's and w3c states "The attribute's value must begin with a letter in the range A-Z or a-z and may be followed by letters......."
However to get you working u need to select one of the nodes first in order to add to it like this
```
```
//Select first child node in tree
    $('#2').click();
    //Add new node to selected node
    simpleTreeCollection.get(0).addNode(1,'A New Node')
```
```


Question:
what's the best/proper way of interacting between several windows in C# app?
Recently, I've run into a problem where one of program windows has to call method modifying main window. My solution was to create factory-like class, that would arrange all underlying model-data and organize the communication between various windows (through delegates). However, as passing one or two delegates was not a problem, I started thinking what if my other windows would need 10 delegates to interact properly with main window? Are delegates good solution? How to pass them in good way - through constructor, properties? Or maybe the need of using that many delegates is some serious design flaw itself?

Answer:
If it's only needing to interact with the main window, why not give a reference to the main window in the constructor of the others?
```
```
public class MainForm : Form
{
}

public class OtherForm : Form
{
    protected MainForm MainForm { get; set; }

    public OtherForm(MainForm mainForm) : base()
    {
        this.MainForm = mainForm;
    }
}
```
```
EDIT:
Simple and effective.
If your forms need to interact with all the other forms of the application, then a
service locator
type pattern might be better suited.


Question: I need to get an appointment into someone's Outlook calendar based on requests from their employees. The application runs in SharePoint (WSS 3.0). My first impressions are to use iCal or send meeting requests, but I haven't done either before & I'm looking for a very quick & easy way to get it done. Any ideas?

Answer:
Sorry, there's no easy answer that I know of or can find.  I'm sure you can do via code but not easily within the SharePoint point-and-click interface.
From
this thread
it seems writing an event handler on a Calendar list would be the most effective way.
So from a 10,000 ft perspective, you'd build a system or workflow in Sharepoint that results in creating calendar entries in a SharePoint calendar.  Then have an event listener whose job it is to create iCal emails when new items are created in that SP calendar.
Brian Wilson (not the Beach Boy) has a few blog posts on
getting started with event handlers in SP


Question:
I would like to create a private customized social networking for my company employees and partners so that they can collaborate, exchange messages, share experiences (events, book references, etc) and be grouped into communities. Does anybody know good Java framework for start developing this?

I would be looking for something that would contain basic components such as Profile, Friend List, Community, Events, Messages, etc. Each of this component could be extended to implement domain specific features. It would be nice if it also supports OpenSocial.

Answer:
Shindig is in incubation at Apache :
http://incubator.apache.org/projects/shindig.html
YouTube Link About Shindig :
http://www.youtube.com/watch?v=ZcWszaReqXI
A List of Open Source Social Networking >Applications< Written in Java:
http://www.manageability.org/blog/stuff/java-open-source-social-network


Question:
This may be a painfully simply question for which I will be mocked but I am having difficulty in using filepaths in master pages. I believe this is because if a page in a sub-directory to using the master page then the filepath is incorrect.

To fix this I need to get the filepath from the root but I can't seem to get it working.

I tried:

<script type="text/javascript" src="~/jQueryScripts/jquery.js"></script>

and

<script type="text/javascript" src="../jQueryScripts/jquery.js"></script>

No luck on either!

Any ideas on how I can tell it to get the filepath from the root?

Answer:
I'm just assuming by filepath, you actually mean url (or uri, I forget which one is partial).
Without the ~, the first example should work.
```
<script type="text/javascript" src="/jQueryScripts/jquery.js"></script>
```
would cause the browser to request
http://www.example.com/jQueryScripts/jquery.js
(where www.example.com is your domain).


Question:
If for example you follow the link:

data:application/octet-stream;base64,SGVsbG8=

The browser will prompt you to download a file consisting of the data held as base64 in the hyperlink itself.  Is there any way of suggesting a default name in the markup?  If not, is there a JavaScript solution?

Answer:
According to
RFC 2397
, no, there isn't.
Nor does there appear to be any
attribute
of the
```
<a>
```
element that you can use either.
However HTML5 has subsequently introduced the
```
download
```
attribute on the
```
<a>
```
element, although at the time of writing support is not universal (no MSIE support, for example)


Question: for a server based j2ee application, I need to retrieve the number of pages from word documents.. any ideas what works?

Answer:
If the documents are modern Word 2007 format you can use direct XML-based manipulation, through
OOXML
. This is by far the better long term solution, though I realize it may not be realistic for an entire organization to change overnight.
If they are older Word formats, you're probably stuck with server-side Word/Excel/Powerpoint/Outlook programmable object models, although
you're not supposed to do that on the server
..


Question:
I have a JComponent that's painting various shapes on itself.  I'm detecting whenever the mouse enters one of these shapes and changing the tooltip accordingly.

The problems I'm having are:

The tooltip doesn't follow the mouse as the user tracks the mouse across the shape. It
stays where it was first set and then only jumps whenever another shape changes the tooltip.

It takes about a second for the tooltip to appear, but I'd like it to appear immediately.

Can someone suggest a way of getting these behaviours without writing a custom tooltip mechanism?

Answer:
Take a look at the
ToolTipManager
.
You can register your component with that manager and then adjust a number of settings. Its pretty straight forward to use.
That at least can solve your initialdelay problem.
For your first problem you can overide the createTooltip command from your component to get a hold of the JTooltip instance. and then its easy make the position change whenever you move your mouse(aka follow your mouse) as its a subclass of the JComponent class.


Question: Does the C++ STL set data structure have a set difference operator?

Answer:
Yes, there is a
set_difference
function in the algorithms header.
Edits:
FYI, the set data structure is able to efficiently use that algorithm, as stated in its
documentation
.  The algorithm also works not just on sets but on any pair of iterators over sorted collections.
As others have mentioned, this is an external algorithm, not a method.  Presumably that's fine for your application.


Question: What is the best way to convert a fixed length string array to a fixed lengh integer array in C++ ?

Answer:
This will copy an array of characters into an array of ints:
```
```
#include <algorithm>
char foo[9] = "asdfasdf";
int bar[9];
std::copy(foo, foo+9, bar);
```
```
std::copy
This assigns the values of a null terminated character array {'a', 's', 'd', 'f', 'a', 's', 'd', 'f', '\0'} to an integer array, yielding {97, 115, 100, 102, 97, 115, 100, 102, 0}.  Note that this includes the null termination of the original string.
This will parse an array of strings, and put their integer values into an array of ints:
```
```
#include <algorithm>
#include <sstream>
#include <string>

template <class T>
T parse(const std::string& str)
{
    T temp;
    std::istringstream iss(str);
    iss >> temp;
    if(iss.bad() || iss.fail())
    {
        // handle conversion failure
    }
    return temp;
}

...

std::string foo[3];
int bar[3];
foo[0] = "67";
foo[1] = "11";
foo[2] = "42";

std::transform(foo, foo+3, bar, parse<int>);
```
```
std::transform
This will transform each of the strings in the array foo into ints, and place them in the array of ints, bar.


Question:
I am currently modifying some jsf application. I have two beans.

connectionBean

UIBean

When I set my connection parameters in connectionBean the first time, the UIBean is able to read my connectionBean information and display the correct UI Tree.

However when I try to set the connection parameters in the same session. My UIBean will still use the previous connectionBean information.

It only will use after I invalidate the whole httpSession.

Is there anyway I can make one session bean update another session bean?

Answer:
Sounds to me like it's some kind of problem with UIBean referencing an out-of-date version of ConnectionBean. This is one problem with JSF - if you re-create a bean, JSF will not update the references in all your other beans.
You could try getting a 'fresh' copy of the ConnectionBean each time. The following method will retrieve a backing bean by name:
```
```
protected Object getBackingBean( String name )
{
    FacesContext context = FacesContext.getCurrentInstance();

    return context
            .getApplication().createValueBinding( String.format( "#{%s}", name ) ).getValue( context );
}
```
```
Without knowing the specifics of your code and how you're using the beans it's difficult to be more specific!


Question:
If I'm writing unit tests in Python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error?

I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.

For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:

class TestBar(unittest.TestCase):
    def runTest(self):
        for t1, t2 in testdata:
            f = Foo(t1)
            self.assertEqual(f.bar(t2), 2)

If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.

Answer:
You can use simple print statements, or any other way of writing to standard output.  You can also invoke the Python debugger anywhere in your tests.
If you use
nose
to run your tests (which I recommend), it will collect the standard output for each test and only show it to you if the test failed, so you don't have to live with the cluttered output when the tests pass.
nose
also has switches to automatically show variables mentioned in asserts, or to invoke the debugger on failed tests.  For example,
```
-s
```
(
```
--nocapture
```
) prevents the capture of standard output.


Question: How do you get the current directory where your app is running?

Answer:
You could try this:
```
```
using System.IO;
using System.Reflection;

namespace Utilities
{
    static public class DirectoryHelper
    {
        static public string GetCurrentDirectory ()
        {
            return Path.GetDirectoryName (Assembly.GetExecutingAssembly ().GetName ().CodeBase);
        }
    }
}
```
```


Question: I am working on an application where I have an images folder relative to my application root. I want to be able to specify this relative path in the Properties -> Settings designer eg. "\Images\". The issue I am running into is in cases where the Environment.CurrentDirectory gets changed via an OpenFileDialog the relative path doesn't resolve to the right location. Is there a way to specifiy in the Settings file a path that will imply to always start from the application directory as opposed to the current directory? I know I can always dynamically concatenate the application path to the front of the relative path, but I would like my Settings property to be able to resolve itself.

Answer:
As far as I know, there is no built-in functionality that will allow this type of path resolution. Your best option is to dynamically determine the applications executing directory and concatenate to it your images path. You don't want to use
```
Environment.CurrentDirectory
```
specifically for the reasons you mention - the current directory may not always be correct for this situation.
The safest code I've found to find the executing assembly location is this:
```
```
public string ExecutingAssemblyPath()
{
   Assembly actualAssembly = Assembly.GetEntryAssembly();
   if (this.actualAssembly == null)
   {
      actualAssembly = Assembly.GetCallingAssembly();
   }
   return actualAssembly.Location;
}
```
```


Question:
I'm currently refactoring code to replace Convert.To's to TryParse.

I've come across the following bit of code which is creating and assigning a property to an object.

List<Person> list = new List<Person>();

foreach (DataRow row in dt.Rows)
{
     var p = new Person{ RecordID = Convert.ToInt32(row["ContactID"]) };

     list.Add(p);
}

What I've come up with as a replacement is:

var p = new Person { RecordID = Int32.TryParse(row["ContactID"].ToString(), out RecordID) ? RecordID : RecordID };

Any thoughts, opinions, alternatives to what I've done?

Answer:
Write an extension method.
```
```
public static Int32? ParseInt32(this string str) {
    Int32 k;
    if(Int32.TryParse(str, out k))
        return k;
    return null;
}
```
```


Question:
I've just been tasked with building a web application using ASP (.net) and am looking for some advice on where to start.   In a nutshell the application needs to be able to.

Handle user verification / authentication

Handle sessions

Do SOAP messaging

The application is intended to act as a front end for system functions that are accessible via web service calls.

I intend to do a lot of work on the client side using JavaScript and am thinking of using ASP solely as the framework for the 3 items I listed above.

Appreciate any suggestions you may have.

Answer:
WCF for Soap -- I would also suggest picking this up:
alt ASP.NET 3.5 http://ecx.images-amazon.com/images/I/518N8vYWf1L._SL500_AA240_.jpg
This book is in tutorial form -- and Jesse Liberty is a great teacher (as are his co-authors).


Question:
My class contains a Dictionary<T, S> dict, and I want to expose a ReadOnlyCollection<T> of the keys. How can I do this without copying the Dictionary<T, S>.KeyCollection dict.Keys to an array and then exposing the array as a ReadOnlyCollection?

I want the  ReadOnlyCollection to be a proper wrapper, ie. to reflect changes in the underlying Dictionary, and as I understand it copying the collection to an array will not do this (as well as seeming inefficient - I don't actually want a new collection, just to expose the underlying collection of keys...). Any ideas would be much appreciated!

Edit: I'm using C# 2.0, so don't have extension methods such as .ToList (easily) available.

Answer:
If you really want to use ReadOnlyCollection<T>, the issue is that the constructor of ReadOnlyCollection<T> takes an IList<T>, while the KeyCollection of the Dictionary is only a ICollection<T>.
So if you want to wrap the KeyCollection in a ReadOnlyCollection, you'll have to create an adapter (or wrapper) type, implementing IList<T>, wrapping the KeyCollection. So it would look like:
```
```
var dictionary = ...;
var readonly_keys = new ReadOnlyCollection<T> (new CollectionListWrapper<T> (dictionary.Keys)
);
```
```
Not very elegant though, especially as the KeyCollection is already a readonly collection, and that you could simply pass it around as an ICollection<T> :)


Question:
How do I build an escape sequence string in hexadecimal notation.

Example:

string s = "\x1A"; // this will create the hex-value 1A or dec-value 26

I want to be able to build strings with hex-values between 00 to FF like this (in this example 1B)

string s = "\x" + "1B"; // Unrecognized escape sequence

Maybe there's another way of making hexadecimal strings...

Answer:
You don't store hexadecimal values in strings.
You can, but it would just be that, a string, and would have to be cast to an integer or a byte to actually read its value.
You can assign a hexadecimal value as a literal to an int or a byte though:
```
```
Byte value = 0x0FF;
int value = 0x1B;
```
```
So, its easily possible to pass an hexadecimal literal into your string:
```
```
string foo = String.Format("{0} hex test", 0x0BB);
```
```
Which would create this string "126 hex test".
But I don't think that's what you wanted?


Question:
What is the best way to do cross-platform handling of hidden files?
(preferably in Python, but other solutions still appreciated)

Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?

Answer:
"Is there a standard way to deal with this?"  Yes.  Use a standard (i.e., POSIX-compliant) OS.
Since Windows is non-standard -- well -- there's no applicable standard.  Wouldn't it be great if there was?  I feel your pain.
Anything you try to do that's cross-platform like that will have Win32 oddities.
Your solution is -- for the present state of affairs -- excellent.  At some point in the future, Microsoft may elect to write a POSIX-compliant OS.  Until then, you're coping well with the situation.


Question:
I am using a Flex dataGrid, and need to sort some of my columns numerically.

Looking at the sortCompareFunction, it seems like i need to create a different function for each column that i want to sort, because my sort function has to know what field it is sorting on.

Is there any way that I can pass the field to be sorted on into the function? so that I only need one numeric sorting function.

Answer:
I did it using this function:
```
function fieldNumericSorter(field:String):Function {
    return function (obj1:Object, obj2:Object):int {
        return sign( int(obj1[field]) - int(obj2[field]) );
    }
}
```
and for each column that needed sorting set
```
colToBeSorted.sortCompareFunction = fieldNumericSorter("fieldname");
```


Question:
public class Item
{
        private int  _rowID;
        private Guid _itemGUID;

        public Item() { }

        public int Rid
        {
            get
            {
                return _rowID;
            }
            set {  }

        }

        public Guid IetmGuid
        {
            get
            {
                return _itemGuid;
            }
            set
            {
                _itemGuid= value;
            }

        }

}

The above is my custom object.

I have a list:

List<V> myList = someMethod;

where V is of type Item, my object.

I want to iterate and get the properties as such

foreach(V element in mylist)
{
   Guid test = element.IetmGuid;
}

When I debug and look at the 'element' object I can see all the properties in the 'Quickwatch' but I cannot do element.IetmGuid.

Answer:
```
```
foreach( object element in myList ) {
    Item itm = element as Item;
    if ( null == itm ) { continue; }
    Guid test = itm.ItemGuid;
}
```
```


Question:
So let's say you wanted to make a copy of a Web Form page within a .Net Project.

Is there an easier way than:

Copy Source Page

Page Source Page within project to get new page

Exclude Source Page

Rename code behind class for new page

Add Source Page Back

Sometimes I miss something obvious is there a better way to do this?  I know the next question would be "Why are you copying code within a project instead for reusing it?"  Let's just say that's a secret;).

Answer:
I do this:
Select the original ASPX file in solution explorer
Ctrl+C followed by Ctrl+V (quick copy paste)
Rename new ASPX file (let's say NewFile.aspx)
Rename code-behind class name to NewFile
Rename
```
Inherits
```
attribute of
```
Page
```
directive within HTML to end with 'NewFile'
(Optional) If you moved the page into a different folder, you'll need to update the Namespace references in the HTML's
```
Page
```
directive as well as in the code-behind.


Question:
As part of our build process I need to set the version information for all of our compiled binaries. Some of the binaries already have version information (added at compile time) and some do not.

I want to be able to apply the following information:

Company Name

Copyright Notice

Product Name

Product Description

File Version

Product Version

All of these attributes are specified by the build script and must be applied after compilation. These are standard binaries (not assemblies) compiled with C++ Builder 2007.

How can I do this?

Answer:
There is this tool
ChangeVersion
[1]
List of features (from the website):
command line interface
support for .EXE, .DLL and .RES files
update FileVersion and ProductVersion based on a version mask
add/change/remove version key strings
adjust file flags (debug, special, private etc)
update project files ( .bdsproj | .bpr | .bpk | .dproj )
add/change main application icon
use ini file with configuration
Windows Vista support (needs elevation)
easy to integrate into a continuous build environment
Full Disclosure: I know the guy who wrote this tool, I used to work with him.  But this also means that I know he makes quality software ;)
[1]
the link is dead. There seems to be mirrored version at
download.cnet.com
.


Question: If I have an xmlreader instance how can I use it to read its current node and end up with a xmlElement instance?

Answer:
Not tested, but how about via an
```
XmlDocument
```
:
```
```
XmlDocument doc = new XmlDocument();
    doc.Load(reader);
    XmlElement el = doc.DocumentElement;
```
```
Alternatively (from the cmoment), something like:
```
```
doc.LoadXml(reader.ReadOuterXml());
```
```
But actually I'm not a fan of that... it forces an additional xml-parse step (one of the more CPU-expensive operations) for no good reason. If the original is being glitchy, then perhaps consider a sub-reader:
```
```
using (XmlReader subReader = reader.ReadSubtree())
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(subReader);
        XmlElement el = doc.DocumentElement;
    }
```
```


Question:
We're using Infragistics grid (most probably, we'll have 8.2 version at the end) and we want to configure row/cells appearances "on-demand" in order to be able to provide sort of "dynamic appearance".

For example, I want some cell to be red or green, depending on its value. We might want to tweak other characteristics as well (font, size, image, etc).

A perfect place to do it would be some event, that happen before a cell gets repainted... But it seems there is no such event in Infragistics...

Or am I wrong? Any help?

Clarification: I'm talking about WinForms Infragistics UltraGrid

Answer:
There is an event.  I don't remember exactly what it's called, but it's got to be something like 'DataRowBound' or 'ItemDataBinding', etc..
Also,
this article
might help.
Not that this has anything to do with your question, but I'd stay away from heavy use of Infragistics controls - they're very heavy and will slow down the page rendering process considerably.  Just my $0.02.


Question: How can I generate valid XML in C#?

Answer:
It depends on the scenario.
```
XmlSerializer
```
is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5,
```
XDocument
```
, etc. are also very friendly. If the size is very large, then
```
XmlWriter
```
is your friend.
For an
```
XDocument
```
example:
```
```
Console.WriteLine(
    new XElement("Foo",
        new XAttribute("Bar", "some & value"),
        new XElement("Nested", "data")));
```
```
Or the same with
```
XmlDocument
```
:
```
```
XmlDocument doc = new XmlDocument();
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo"));
el.SetAttribute("Bar", "some & value");
el.AppendChild(doc.CreateElement("Nested")).InnerText = "data";
Console.WriteLine(doc.OuterXml);
```
```
If you are writing a
large
stream of data, then any of the DOM approaches (such as
```
XmlDocument
```
/
```
XDocument
```
, etc.) will quickly take a lot of memory. So if you are writing a 100 MB XML file from
CSV
, you might consider
```
XmlWriter
```
; this is more primitive (a write-once firehose), but very efficient (imagine a big loop here):
```
```
XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteStartElement("Foo");
writer.WriteAttributeString("Bar", "Some & value");
writer.WriteElementString("Nested", "data");
writer.WriteEndElement();
```
```
Finally, via
```
XmlSerializer
```
:
```
```
[Serializable]
public class Foo
{
    [XmlAttribute]
    public string Bar { get; set; }
    public string Nested { get; set; }
}
...
Foo foo = new Foo
{
    Bar = "some & value",
    Nested = "data"
};
new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);
```
```
This is a nice model for mapping to classes, etc.; however, it might be overkill if you are doing something simple (or if the desired XML doesn't really have a direct correlation to the object model). Another issue with
```
XmlSerializer
```
is that it doesn't like to serialize immutable types : everything must have a public getter
and
setter (unless you do it all yourself by implementing
```
IXmlSerializable
```
, in which case you haven't gained much by using
```
XmlSerializer
```
).


Question:
I'm trying to bind one of my model objects to the fields of a form, using Spring-MVC. Everything works fine, except that one of the attributes of the model object is an unordered collection. Doing something like

    <c:forEach items="${m.items}" var="i" varStatus="itemsRow">
      <form:input path="items[${itemsRow.index}]"/>
    </c:forEach>
    <form:errors path="items" />

would work fine for a List-type property, but for a Set throws an error when, upon submit, it tries to bind input field content to object attributes.

Is there something in Spring that works out of the box with Sets?

Answer:
I think it has to be an ordered collection.  For example,there's
a chart
in the Spring reference that talks about how to reference properties.  It says:
account[2]    Indicates the third element
  of the indexed property account.
  Indexed properties can be of type
  array, list or other
naturally ordered
collection (emphasis theirs)
Perhaps one approach would be to add a getter to your object that, rather than returning your Set, returns Set.toArray().  Then your items attribute would reference the array.  Of course, you can't depend on the ordering.


Question:
I'm using nusoap to connect to a soap webservice. The xml that the class sends to the service is constructed from an array, ie:

$params = array("param1" => "value1", "param2" => "value1");
$client->call('HelloWorld', $params, 'namespace', 'SOAPAction');

This works fine. A multidimensional array also constructs a nice nested xml message.

I encounter a problem when i need two tags with the same name:

<items>
   <item>value 1</item>
   <item>value 2</item>
</item>

$params = array("items" => array("item" => "value 1", "item" => "value 2"));

The second item in the array overwrites the first which results in:

<items>
   <item>value 2</item>
</item>

How can achieve this?

Answer:
The problem is with the inner array()
```
```
$test_array = array("item" => "value 1", "item" => "value 2");
```
```
creates an array with a single key ("item").
Try this and see if it works:
```
```
$params = array("items" => array("item" => array("value 1", "value 2")));
```
```
No guarantees, though... I haven't used nusoap in a
long
time and don't have PHP installed here to test it.


Question:
I'm using system catalog views such as SYS.ALL_ OBJECTS, SYS.FOREIGN_KEYS etc. to get information about my database structure in MS SQL 2005.

Are there equivalent functions/views for MySQL (v. 5) servers?

Answer:
Hmm, I haven't studied everything it contains, but there's a good deal of information in the
information_schema
.  There's also the
show
command.
Still, I don't see a single command to show all the foreign keys in there.


Question:
I would like to add a backcolor for specific line depending of a Property of the object binded.

The solution I have (and it works) is to use the Event DataBindingComplete but I do not think it's the best solution.

Here is the event:

    private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {

        for (int i = 0; i < this.myGrid.Rows.Count; i++)
        {
            if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special)
            {
                this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
            }
        }
    }

Any other option that would be better?

Answer:
I don't really work with WinForms that much, but in ASP you would use the 'ItemDataBound' method.  Is there something similar in windows forms for a DataGrid?
If so, in that method, the event arguments would contain the item that was databound, along with the DataGrid row.  So the general code would look something like this (syntax is probably off):
```
```
if(((MyObject)e.Item.DataItem).Special)
   e.Item.DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
```
```


Question:
Is it possible to have two virtual directories under the same website in IIS but have the virtual directories be using different versions of the .net framework?

For example, under the default website, can I have one virtual directory targeting the 2.0 framework and a second virtual directory targeting the 1.1 framework?

This is for IIS 6, thanks!

Answer: You are not saying which version of IIS you are using, but for 6.0 and up, just assign them to different application pools, and set the pools to use the right version of .Net.


Question:
We're developing a product that relies on the Microsoft Sync Framework to keep the data on a client app and on the server in sync.  What we have noticed is when syncing about 16 tables and ~2200 records it will take about 4 minutes, which is not acceptable.

Using the SQL Server Profiler we found it is using sp_executesql to execute the queries.  when run without sp_executesql a specific query runs in <1s, but with it takes over 10s.

So the question is: What are we doing wrong and is there anything we can do to speed it up.

Answer:
sp_executesql is using dynamic sql. each row is being processed singularly.
4 minutes seems rather long, you should look at the design of your 16 tables and check the performance on them. Try using the execution plan to view where the bottleneck may be occurring.
check out this link that covers the basics:
SQL Execution Plan basics
Try scrolling down to the bottom of the article, where there are screen shots of the actual graphical interface in SQL Management Studio. There are some boring parts of the article, but you can atleast see the graphical execution plan and its benefits.


Question:
Html.TextBox("ParentPassword", "", new { @class = "required" })

what the gosh darned heck is the @ for the @class.

Answer:
```
class
```
is a reserved keyword, so you can't use this as a variable name.
The @ operator allows you to get around this rule.  The reason why its being done here is that the anonymous object is used to populate attributes on a HTML element.  A valid attribute name is "class", which lets you set the CSS class on the element.


Question:
I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do

Obj *obj = libname_newDevice();

Now, should I use delete or should I do obj->deleteMe();? I ask because I am not exactly doing new so I shouldn't be doing the delete?

I have obj->create(theType); which returns a class with the Obj interface.
My real question is do I need a libname_deleteDevice(); or is obj->deleteMe() fine since I have a deleteMe in the interface?

Answer:
Since you are abstracting the creation inside
```
libname_newDevice()
```
(which I have to say isn't a good approach), you should destroy using something like
```
libname_destroyDevice (obj)
```
.
And as the comment from Martin suggests, it's best to put them in the constructor and destructor of a custom class, that you just need to create on stack, and the compiler will take care of the rest.


Question:
I'm creating an interface wrapper for a class.  The member within the class is a reference(to avoid copying the large structure).  If I create a private constructor, what is the best way to initialize that reference to appease the compiler?

struct InterfaceWrapper {
    InterfaceWrapper( SomeHugeStructure& src ):m_internal(src){};
    int someElement(void) const { return m_internal.someElement; };
private:
    InterfaceWrapper(){}  // initialize m_internal
    SomeHugeStructure& m_internal;
};

Answer:
If you really need to construct the class without having an element, a reference is not the way to go.
If your only reason to use a reference is to avoid copying, I'd suggest using a pointer.
You can simply take the address of the passed reference in you regular constructor, and initialize it to NULL in the private constructor. When the object's lifetime ends the pointer will be a dangling pointer, but the same is true for references...
Alternatively, have the public constructor take a smart pointer and use such a smart pointer as member too, if you're concerned about lifetimes.
And of course, cope with the pointer possibly being NULL in the remainder of the class' code. (but you had to cope with the member possible being a stub in the reference case too, so that's not really an issue)


Question:
I've got a timer running in my Delphi MDI application and I'd like to use it to pop up a message if something changes in the background. But I don't want that message to pop up when the the application has a modal dialog in the foreground because the user couldn't do anything about it.

So what I'd like to know is how can I check for the existence of a modal dialog in my application?

Answer:
You could try with this code:
```
```
var
  ActForm: TCustomForm;
begin
  ActForm := Screen.ActiveForm;
  if (ActForm = nil) or not (fsModal in ActForm.FormState) then begin

  end;
end;
```
```
I tested with Delphi 4, works for me.
[EDIT]: But you should really think about whether popping up a form and stealing focus is a good idea. It depends on your application, but if a user is currently entering something into an edit field, or doing something with the mouse, then this might break their workflow.


Question:
Into some view data i have put the result of an anonymous type:

            var projectData = from p in db.Projects
                          orderby p.title
                          select new
                          {
                              Title = p.title,
                              DevURL = p.devURL ?? "N/A",
                              QAURL = p.qaURL ?? "N/A",
                              LiveURL = p.liveURL ?? "N/A",
                              Users = p.GetUsers().MakeUserList()
                          };

        ViewData["ProjectSummary"] = projectData;

How do I iterate through this view data in the MVC view on the front end to say, make a table of results?

Answer:
The problem is not that it's an anonymous type.  The problem is that it's merely a lazy-evaluated IQueryable<> object, and it hasn't been evaluated yet.
I can't answer for ASP.NET MVC, but in the very similar Monorail, you would have to convert it from an iterator into an actual collection:
```
```
var projectData = (from p in db.Projects
                      orderby p.title
                      select new
                      {
                          Title = p.title,
                          DevURL = p.devURL ?? "N/A",
                          QAURL = p.qaURL ?? "N/A",
                          LiveURL = p.liveURL ?? "N/A",
                          Users = p.GetUsers().MakeUserList()
                      }).ToList();
```
```


Question:
I have an .xsd, .vb, .xsc, and .xss file for a dataset in Visual Studio 2008 that I copied over from another Visual Studio project, however I need to make changes to the dataset. Thus I got into the XSD file, created new columns, deleted ones that aren't needed, etc., etc.  However I realized when I attempted to use the new dataset I did not have the Visual Basic code behind the scenes. This code is typically found in dataset.designer.vb. When I copied the old one over of course it was no longer valid since columns changed.

How I can force Visual Studio 2008 to use a .xsd file and to have it create/update its designer code?

Answer:
Unfortunately, this is in the gray area of things things that I can do when I need to, but I haven't needed to do enough to impart the knowledge to others.
All I know is that
```
*.designer.vb
```
means that this code was generated by Visual Studio, and if it generated it once it can do it again. Additionally, the very few times (maybe twice, both in Visual Studio 2005) that I have done this, it seemed like it was as simple as adding the  *.xsd file to Solution Explorer. If that alone doesn't do it, try showing all files or right/double clicking on the *.xsd.


Question:
I'm trying to insert a comment character into a string something similar to this:

-CreateVideoTracker VT1 "vt name"

becomes

-CreateVideoTracker VT1 # "vt name"

The VT1 word can actually be anything, so I'm using the regex

$line =~ s/\-CreateVideoTracker \w/\-CreateVideoTracker \w # /g;

which gives me the result:

-CreateVideoTracker w #T1 "vt name"

Is there any way to do this with a single regex, or do I need to split up the string and insert the comment manually?

Answer:
```
```
$line =~ s/^(\-CreateVideoTracker)\s+(\w+)/$1 $2 #/;
```
```
The bracketed expressions (known as "capture buffers") in the first half of the regexp are referenced as
```
$1
```
,
```
$2
```
. etc in the second half.


Question:
What is the preferred way to insert strings that can contain both single and double quotes (",') into MySql using DBI?  For example, $val1 and $val2 can contain quotes:

my $dbh = DBI->connect( ... );
my $sql = "insert into tbl_name(col_one,col_two) values($val1, $val2)";
my $sth = $dbh->prepare($sql);
$sth->execute();

Answer:
Use a bound query using
```
```
$sth = $dbh->prepare("insert into tbl_name(col_one,col_two) values(?,?)");
$sth->execute($val1, $val2);
```
```
If you use bound variables, everything is escaped for you.
Update: Changed my example to correspond with the example edited into the question.
Update: I don't know why Adam deleted his answer, but if for some reason you can't use bound variables (aka "placeholders"), you can also use
```
$dbh->quote($var)
```
on the variable.  For example:
```
```
$sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
    $dbh->quote(q("Don't"));
```
```


Question:
I'm creating a control and need to pass it the current logon user as a parameter (declaratively)

I tried this but didn't work (I got "<%= User.Identity.Name %>" as value):

<cc1:MyControl id="myid" runat="server" User="<%= User.Identity.Name %>" />

Is there a way to do it?

Answer:
Try using:
```
```
User="<%= User.Identity.Name %>"
```
```
%= is for output
%# is for databinding.


Question: Is there any way in a Win32 environment to "tune" the timeout on a socket connect() call?  Specifically, I would like to increase the timeout length.  The sockets in use are non-blocking.  Thanks!

Answer:
Yes, this is possible.
If you're in non-blocking mode after
```
connect()
```
, you normally use
```
select()
```
to wait till I/O is ready. This function has a parameter for specifying the timeout value and will return 0 in case of a timeout.


Question: I have an implementation of default handler. When it gets to a   in the character data it stops parsing. Is there any reason that it is doing this? Are there additional properties that I need to set in order for it to deal with &nbsp?

Answer:
```

```
is not a valid xml entity. You might try replacing it with
```

```
instead, it does the same thing (non-breaking space).


Question:
I'm automating some source control software functionality using a dot bat script but given that our svn repos are hosted in a *NIX box, I'm facing the eternal case problem between these two worlds.

Is there any cmd.exe function to convert the value of the Windows system variable %USERNAME% to lower case?

Thanks much in advance!

Answer:
a quick google found
this
...
```
```
@echo off
goto :end_remarks
*************************************************************************************
*
*
*    authored:Sam Wofford
*    Returns lowercase of a string
*    12:13 PM 11/13/02
**************************************************************************************
:end_remarks
setlocal
set errorlevel=-1
if {%1}=={} echo NO ARG GIVEN&call :Help &goto :endit
if {%1}=={/?} call :Help &goto :endit
call :set_LCASE_array a b c d e f g h i j k l m n o p q r s t u v w x y z

:start
set input=%1
set input=%input:"=%
set totparams=0
call :COUNT_PARAMS %input%
call :MAKE_LOWERCASE %input%
set errorlevel=
echo %convertedstring%
endlocal
goto :eof
:endit
echo %errorlevel%
endlocal
goto :eof

:MAKE_LOWERCASE
:nextstring
if {%1}=={} goto :eof
set string=%1
set /a params+=1
set STRINGCONVERTED=
set pos=0
:NEXT_CHAR
set onechar=%%string^:^~%pos%,1%%
for /f "tokens=1,2 delims==" %%a in ('set onechar') do for /f %%c in ('echo %%b') do call :checkit %%c
if not defined STRINGCONVERTED goto :NEXT_CHAR
shift /1
if %params% LSS %totparams% set convertedstring=%convertedstring% &:add one space,but not at end
goto :nextstring
goto :eof

:Help
echo USAGE:%~n0 string OR %~n0 "with spaces"
echo function returns the lowercase of the string or -1 (error)
echo strings with embedded spaces needs to be in quotes Ex. "lower case"
echo in a batch NTscript "for /f %%%%A in ('lcase STRING') do set var=%%%%A"
set errorlevel=
goto :eof

:checkit
set LCFOUND=
if /i {%1}=={echo} set STRINGCONVERTED=Y&goto :eof
set char=%1
for /f "tokens=2 delims=_=" %%A in ('set LCASE_') do call :findit %%A %char%
:skipit
if defined LCFOUND (set convertedstring=%convertedstring%%ucletter%) else (set convertedstring=%convertedstring%%char%)
set /a pos+=1
goto :eof

:set_LCASE_array
:setit
if {%1}=={} goto :eof
set LCASE_%1_=%1
SHIFT /1
goto :setit

:findit
if defined LCFOUND goto :eof
set ucletter=%1
set lcchar=%2
if /i {%ucletter%}=={%lcchar%} set LCFOUND=yes
goto :eof

:COUNT_PARAMS
:COUNTPARAMS
if {%1}=={} goto :eof
set /a totparams+=1
shift /1
goto :COUNTPARAMS
```
```
add that as a file (lowercase.cmd) to your path and you should be able to call it as "Lowercase.cmd %Username%", you could pipe it into another command if needed.


Question:
Some databases support commands such as:

SELECT TOP 10 START AT 10 * FROM <TABLE>

Essentially I need to pull the first 10 records, then the next 10, then the next 10 etc.  Maybe there is another way to do this but in the past I've done it like the above for databases that support 'START AT'.

Answer:
```
```
SELECT Top 10 *
FROM Table
WHERE <primary key> Not IN (
    SELECT Top 10 <primaryKey>
    FROM Table
    ORDER BY <primary Key> ASC)
ORDER BY <primary Key> ASC
```
```


Question:
I have a Lotus Domino server with a truly astounding number of Domino databases on it, arranged in various folders.

Is there some means of exporting a list of all these databases, with their titles and creators' names, in a spreadsheet format of some kind? I have the Domino Admin and Domino Designer software, and I have or can get whatever access rights I'd need.

Answer:
You'd think there'd be a way in the Domino Admin, but there's no way to export the list.  So, your best bet I think is to use the Domain Catalog database.  To build it, go into the server configuration doc > Server Tasks > and turn on the Domain Catalog.  Then the catalog.nsf database will be built and will contain all the databases in your domain.  You can customize the views to include the information you need.
Then finally, you can go into a view, select all the documents and click Edit > Copy Selected As Table.  Then paste that into a spreadsheet.


Question:
For Each line As String In System.IO.File.ReadAllLines("file.txt")
'Do Something'
Next

and

Using f As System.IO.FileStream = System.IO.File.OpenRead("somefile.txt")
    Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
            While Not s.EndOfStream
                    Dim line As String = s.ReadLine

                    'put you line processing code here

            End While
    End Using
End Using

are both showing as mostly red, I'm running a clean install of MS VS2005 and these codes were both recomended to me, am I missing something else I need to install or declare?

Answer:
FROM Msdn you should do the following to read all lines
```
```
Dim Lines As String()
Lines = System.IO.File.ReadAllLines("file.txt")
```
```
For the second example something like this might work
```
```
Dim sr as New StreamReader("somefile.txt")
Dim line as String = sr.ReadLine()
Do While Not line is Nothing
    line = sr.ReadLine()
    'do something else
Loop
```
```
I just created the following VB.Net Console app and it works fine:
```
```
Imports System.IO

Module Module1

Sub Main()
    Dim sr As New StreamReader("somefile.txt")
    Dim line As String = sr.ReadLine()
    Do While Not line Is Nothing
        line = sr.ReadLine()
        'do something else
    Loop

End Sub

End Module
```
```


Question:
If you have a sequence of block elements and you wanted to place margin in between them.

Which do you prefer, margin-top or margin-bottom or both? Why?

Answer:
I always use
```
margin-bottom
```
, which means there is no unnecessary space before the first element.


Question: I'm looking for a library to read a SWF file and let me parse through its actionscript and header information. Is there anything out there that will work?

Answer:
I do not know of any libraries (including .NET) that let you read and parse (or reverse engineer) the contents of SWF's files. The ActionScript you are referring to is compiled down to byte code during compilation so you will not find the actual ActionScript source code in the SWF file.
For more information in the SWF file format I suggest you have a look at the
official specifications
.


Question:
My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be there, and I want to parse them from the file as quickly as possible.

I could store them in XML, but XML is way to complex, and it would require traversing nodes, and child nodes and so on, all I want is some class that takes a file and generates key value pairs. I want as little error handling as possible, and I want it done with as little code as possible.

I could code a class like that myself, but I'd rather learn how it's don'e in the framework than inventing the wheel twice. Are there some built in magic class in .NET (3.5) that are able to do so?

MagicClass kv = new MagicClass("Settings.ini"); // It doesn't neccesarily have to be an INI file, it can be any simple key/value pair format.
string Value1 = kv.get("Key1");
...

Answer:
I don't know of any builtin class to parse ini file. I've used
nini
when needed to do so. It's licensed under the MIT/X11 license, so doesn't have any issue to be included in a closed source program.
It's very to use. So if you have a Settings.ini file formatted this way:
```
```
[Configuration]
Name = Jb Evain
Phone = +330101010101
```
```
Using it would be as simple as:
```
```
var source = new IniConfigSource ("Settings.ini");
var config = source.Configs ["Configuration"];

string name = config.Get ("Name");
string phone = config.Get ("Phone");
```
```


Question:
I am trying to setup a failover location for MOSS. The current farm is built on 32 bit Windows 2003. The servers ar the failover location are all 64 bit Windows 2008.

Is there any way to make these two environments talk and stay in sync? I have considered a "stretched" farm configuration, but that won't work unles the bit width of both locations are the same.

The current database server for MOSS is replicated to our failover location using clustering and is visible at both locations.

Answer:
You can mix 32 bits and 64 bits in the same farm, it's fully supported.
However, it's highly recommenced to keep each tiers in the same bit width (for example all WFE 64 bits, application server 32 bits, SQL servers 64 bits).
From msdn @
http://technet.microsoft.com/en-us/library/cc261700.aspx
You can deploy an Office SharePoint Server 2007 farm on a mix of 32-bit and 64-bit servers, provided that you maintain architecture homogeneity at each topology layer. For example, you should not mix 32-bit and 64-bit Web front-end (WFE) servers, but you may use 64-bit database servers in a farm with 32-bit WFE servers and application servers.


Question:
I have a number of web apps running on several IIS6/Server 2003 boxes. They run well and are happy. They are all asp.net web apps and use .NET 3.5.

What, if any, would be valid reasons for contemplating moving the web apps to IIS7/Server 2008?

Answer:
Eventually, Microsoft will discontinue Server 2003 support. Admittedly, that won't be for several years, so it doesn't impact you today.
Improved support for ASP.NET MVC. This is probably the big one for most of us. You can get ASP.NET MVC working on IIS6, but there are
some hoops to jump through
.
I'd give you more, but I myself am not yet on Server 2008 yet, and have nothing else to give. Presumably Vista (which I do use, both at work and at home) has the "same" IIS7 as 2008 does -- the UIs certainly look very similar -- but I wouldn't consider my experience there to be useful to your question.


Question:
We have a few SGI Onyx 350 and Orgin 350 systems running IRIX 6.5.x that we would like to install Subversion on.  One of them will likely be used as a simple repository server running svnserve.  The others will only need client installs.

The Subversion webpage has links to unofficial binaries for many *NIX systems, including HP-UX, Solaris, AIX, the BSDs and Linux distros.  Unfortunately, there aren't any for IRIX.  A Google search also comes up empty.

So, is there someplace on the web that publishes IRIX binaries for Subversion?

If not, does anyone have experience compiling SVN from source on such systems?  How hard is it to track down all of the dependencies?  Are there any caveats we should be aware of?

Answer:
The guy that maintains
This website
sells secondhand SGI gear.  He sells them with CD's of contributed software.  Maybe he can do something for you.
Also,
The SGI forum on nekochan.net
has postings of contributed software.  You may be able to ask for something there.
Subversion is fairly pernickety about its dependencies (as you have probably already worked out).
This link
gives some of the dependencies for installing on Redhat 7.3, which dates back to the early 2000's (I don't know what minor release of Irix you're using).  You may find it to be a reasonable guide to the dependencies.


Question:
Let's say we have these tables;

table user:

- id

- username

- email

table user2group:

- userid

- groupid

table group:

- id

- groupname

How do I make one query that returns all users, and the groups they belong to (as an array in the resultset or something..)

Answer:
```
```
select u.id, u.username, u.email, g.groupid, g.groupname
from user u
join user2group ug on u.userid=ug.userid
join group g on g.groupid=ug.groupid
order by u.userid
```
```
As you are looping through the result set, each time you see a new userid make a new user object (or whatever) and add the groups to it.


Question: It is possible to get stacktrace using System.Diagnostics.StackTrace, but thread has to be suspended. Suspend and Resume function are obsolete, so I expect that better way exists.

Answer:
I think that if you want to do this without the cooperation of the target thread (such as by having it call a method that blocks it on a Semaphore or something while your thread does the stacktrace) you'll need to use the deprecated APIs.
A possible alternative is the use the
COM-based ICorDebug
interface that the .NET debuggers use. The MDbg codebase might give you a start:
```
http://blogs.msdn.com/jmstall/archive/2005/11/07/views_on_cordbg_and_mdbg.aspx
```
```
http://geekswithblogs.net/johnsPerfBlog/archive/2008/10/13/mdbg-a-managed-wrapper-around-icordebug.aspx
```


Question:
During undergrad i opted to take a network programming course using the POSIX sockets for linux.  As a reference we used the book Internetworking using TCP/IP (comer and stevens). 2008 its a pretty dated and still applicatable texts which takes one through several server designs.

One design that is not really featured in the book is the case there a client connects to the backend application server sends multiple requests to the server over a single TCP connection.  Since multiple requests comes via the slave socket to the server and responses send via the same slave socket.  The slave socket is becomes congested as response and requests are received via the same socket, would it be a better option to allow for a second TCP connection between the to end-points to allow full duplex communication speed?  What other architectures can be used to improve server performance?

Answer:
Since a socket is simply a number attached to a packet (call it a routing number or address), I can't imagine the socket itself getting congested.
Your code handling the socket could, but that should be pretty easily fixed by distributing packets as they arrive.
You could also code incoming and outgoing packet processing to happen on different threads, or even queue packets for distribution to many threads.
But I really don't see the original supposition as being completely accurate.  I could be wrong...


Question:
Suppose I have a python object x and a string s, how do I set the attribute s on x? So:

>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'

What's the magic? The goal of this, incidentally, is to cache calls to x.__getattr__().

Answer:
```
```
setattr(x, attr, 'magic')
```
```
For help on it:
```
```
>>> help(setattr)
Help on built-in function setattr in module __builtin__:

setattr(...)
    setattr(object, name, value)

    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ``x.y = v''.
```
```
However, you should note that you can't do that to a "pure" instance of
```
object
```
. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.


Question:
Is there a way to make OpenGL transform a general vector I give it with the current modelview matrix and get the result back?

The obvious way is to query the modelview matrix and do the multiplication myself but
I am almost sure there should be a way to make OpenGL do this for me.

Answer:
You are right, you have to get the modelview matrix and transform the vector yourself.
For a confirm, see
this link
at paragraph 9.120.


Question:
Given a week-day (1-7), how can I calculate what that week-day's last date was?

Example: Today is Wednesday, 2008/11/12, and I want to know what last Friday's date was.

Answer:
If
```
today
```
is the current day of the week, then you can use something like:
```
```
days_since_friday = (((today - 1) + 7) - (6 - 1)) % 7
```
```
This assumes that Friday is represented by day number 6 of the week (that is, 1 represents Sunday). Then subtract
```
days_since_friday
```
from the current date, and you'll get the date of the end of last week.
The above expression is slightly more complicated than it needs to be. If your day-of-week started at 0 for Sunday, it simplifies to:
```
```
days_since_friday = ((today + 7) - 5) % 7
```
```
or
```
```
days_since_friday = (today + 2) % 7
```
```


Question:
For some reason sql server 2008 is not allowing me to add columns to an existing table.

The table is empty btw.

Is there a setting that prevents modifying tables in sql 2008?

Answer:
If
```
today
```
is the current day of the week, then you can use something like:
```
```
days_since_friday = (((today - 1) + 7) - (6 - 1)) % 7
```
```
This assumes that Friday is represented by day number 6 of the week (that is, 1 represents Sunday). Then subtract
```
days_since_friday
```
from the current date, and you'll get the date of the end of last week.
The above expression is slightly more complicated than it needs to be. If your day-of-week started at 0 for Sunday, it simplifies to:
```
```
days_since_friday = ((today + 7) - 5) % 7
```
```
or
```
```
days_since_friday = (today + 2) % 7
```
```


Question:
Trying to create several layers of folders at once C:\pie\applepie\recipies\
without using several different commands, is there an easy way similar to Directory.CreateDirectory()

Answer:
Here's some code I used in one of my projects.  It requires a reference be added to the project for the file system object.
First, click Project -> References, scroll down to "Microsoft Scripting Runtime" and select it.  Then you can use this function:
```
```
Public Sub MakePath(ByVal Folder As String)

    Dim arTemp() As String
    Dim i As Long
    Dim FSO As Scripting.FileSystemObject
    Dim cFolder As String

    Set FSO = New Scripting.FileSystemObject

    arTemp = Split(Folder, "\")
    For i = LBound(arTemp) To UBound(arTemp)
        cFolder = cFolder & arTemp(i) & "\"
        If Not FSO.FolderExists(cFolder) Then
            Call FSO.CreateFolder(cFolder)
        End If
    Next

End Sub
```
```


Question:
Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc?
Eventhough I am an emacs guy, I find it much easier to create GUI with VS.

Answer:
Eclipse
has python support.
There's also
IDLE
or
Wingware
, though I'm not sure of their GUI support.
I'm sure a good
google search
would turn up more.
But in the end, I doubt it.  Python is dependent on third-party widget sets like Qt, Tk, Gtk, wxWidgets, etc for GUI support.  Each of those will have their own system for laying things out.


Question:
I'm trying to duplicate the effect used in the Firefox search box where, if the search field does not have focus ( the user has not clicked inside of it ), it just says Google in gray text. Then, when the user clicks in the box, the text is removed and they can fill in their search term.

I want to use this to provide example field data for a web form.

JQuery syntax would be preferable to plain javascript, but plain JS would be fine too.

Thanks SO Hive Mind!

Answer:
```
$(selector).text('Google');
  $(selector).click(function(){
    $(this).text('');
  });
```
There's probably a more elegant way to do it, but this assumes your box has no text in it at page load.  If it does you can remove the first line.
I haven't tested this, but it should work.


Question: I had experience with struts, and briefly experimented with tiles.  I know that within a layout each tile is a separate jsp page.  Suppose I hit a  button on each of four tiles, and each tile was (indirectly) calling a different web service.  Would the tiles refresh asynchronously as results came in at different times?

Answer:
I think it would depend on the code in the background.  You say that the tiles were indirectly calling web services.  I would think it would refresh asynchronously unless you specified in your code for it not to do so.  Say you push button 1 and then button 2.  Action 1 comes back and your code says that the screen needs to be updated and the page will refresh.  Once action 2 gets back, your code would again update the screen.  I believe this is how it works, but having never tried it, I can't be sure.
Why not just throw together a two tiled test page with buttons and try it out.  That should give you a definitive answer.


Question:
I'm mostly a .Net person at the moment, but I've been playing with Java some lately-- exploring what's out there.

Now I'm looking for the Java equivalent for WPF.  I know I could find an OpenGL library or two out there, but that's not really as rich or simple as the WPF system.

Answer:
I think a combination of JavaFX, Swing, Java2D, and Java's browser-based JRE comprise the solutions that WPF provides:
JavaFX applications (actually, any Java app) can run in the browser or on a desktop
JavaFX provides high-end video support
JavaFX provides for scripted animations and visual special effects
Swing provides UI capabilities, and can be used in both Java and JavaFX
Java2D, which provides the underpinnings for all drawing tasks (including Swing), takes advantage of hardware acceleration and DirectX support
The JRE on the desktop or the browser enable Java applications to be deployed to multiple environments (including other screens, like set-top boxes or phones)