q:
void f(cli::array<PointF> ^points){
    PointF& a = points[0];
    // and so on...
}

Compile error at line 2.

.\ndPanel.cpp(52) : error C2440: 'initializing' : cannot convert from 'System::Drawing::PointF' to 'System::Drawing::PointF &'
        An object from the gc heap (element of a managed array) cannot be converted to a native reference

What is the managed way to declare a reference variable?

[A]
You need to use the
```
gcroot
```
template from
```
vcclr.h
```
file:
These are samples from MSDN:
```
```
// mcpp_gcroot.cpp
// compile with: /clr
#include <vcclr.h>
using namespace System;

class CppClass {
public:
   gcroot<String^> str;   // can use str as if it were String^
   CppClass() {}
};

int main() {
   CppClass c;
   c.str = gcnew String("hello");
   Console::WriteLine( c.str );   // no cast required
}

// mcpp_gcroot_2.cpp
// compile with: /clr
// compile with: /clr
#include <vcclr.h>
using namespace System;

struct CppClass {
   gcroot<String ^> * str;
   CppClass() : str(new gcroot<String ^>) {}

   ~CppClass() { delete str; }

};

int main() {
   CppClass c;
   *c.str = gcnew String("hello");
   Console::WriteLine( *c.str );
}

// mcpp_gcroot_3.cpp
// compile with: /clr
#include < vcclr.h >
using namespace System;

public value struct V {
   String^ str;
};

class Native {
public:
   gcroot< V^ > v_handle;
};

int main() {
   Native native;
   V v;
   native.v_handle = v;
   native.v_handle->str = "Hello";
   Console::WriteLine("String in V: {0}", native.v_handle->str);
}
```
```
You will find out more
here


q:
Like many SO people, I'm in front of a computer almost all day. I like having a dark theme for Visual Studio (easier on the eyes), but since the rest of Windows and apps (explorer, dialogs, Outlook), have the full white background, it's even harder to switch between nice dark VS and sunshine bright Windows.

I tried a UXTheme.dll patch but couldn't find any dark themes that worked across Visual Studio and Windows apps in general. Any suggestions?

Edit: To be clear, I'd like no or almost no white. No scrollbars, menus, etc.

[A]
May be not exactly what you are looking for, but
this is a dark color scheme
for visual Studio (2005 or 2008) you may use in complement of UXTheme.
Off course, they are other dar color schemes for Visual studio, like
this one
(Jeff
has one also
).
But I am not sure there is
one
tool that applies to all windows, including Visual Studio.

s: huggingface

c: devops

d: intermediate


q:
To implement "method-missing"-semantics and such in C# 4.0, you have to implement IDynamicObject:

public interface IDynamicObject
{
  MetaObject GetMetaObject(Expression parameter);
}

As far as I can figure out IDynamicObject is actually part of the DLR, so it is not new. But I have not been able to find much documentation on it.

There are some very simple example implementations out there (f.x. here and here), but could anyone point me to more complete implementations or some real documentation?

Especially, how exactly are you supposed to handle the "parameter"-parameter?

[A]
Here is what I have figured out so far:
The Dynamic Language Runtime is currently maintained as part of the
IronPython project
. So that is the best place to go for information.
The easiest way to implement a class supporting IDynamicObject seems to be to derive from
Microsoft.Scripting.Actions.Dynamic
and override the relevant methods, for instance the Call-method to implement function call semantics. It looks like Microsoft.Scripting.Actions.Dynamic hasn't been included in the CTP, but the one from IronPython 2.0 looks like it will work.
I am still unclear on the exact meaning of the "parameter"-parameter, but it seems to provide context for the binding of the dynamic-object.


q: what is the syntax for the sendkey for rightarrow  in .net?

[A]
What you are looking for is called spatial search. I'm not sure if there are extensions to  Lucene.Net to do this but you could take a look at
NHibernate Spatial
. Other than that, these queries are often done within the database. At least PostGreSQL, MySQL and SQL Server 2008 have spatial query capabilities.


q:
I'm rather confused about this.

And what's their relationship(e.g., how one can be used in the context of the other)? Much thanks!!

[A]
The concept of symbols is a little bit hard to understand. (Even I'm not sure I got it :) )
You can look at symbols as special variables which behave like constants. There is only one instance in memory, no matter how often you used it.
The benefits are conserving memory and one can see if a value is used in a constant-like manner. (Improves code readability)
You can do
similar
things in C/C++ with
```
typdef
```
, in Java with
```
static final
```
or in Delphi/Pascal/VB with
```
const
```
, but be careful, in those and many other languages "symbol" means something different.


q: I have an oc4j installation bereft of any release notes or version documentation. In the absence of such documents, how do I know for sure, which version of oc4j I am using?

[A]
Check Server header in HTTP headers. For example with wget or curl;
```
```
wget -S <url-to-server>
curl -I <url-to-server>
```
```
or with browser, which can show HTTP headers.
There should be a header something like
```
```
Server: Oracle-Application-Server-10g/10.1.3.1.0 Oracle-HTTP-Server
```
```


q: I'm using the MVP pattern in a windows form app. I need to change a radio button on the view. I can do this by exposing a Boolean property on the view, but should I be using events to manipulate the view instead?

[A]
Using "plain language" analysis, I would say that "whether or not the radio button is displayed is a
property
of the view" and therefore use an actual property to communicate this to the View.
The other (technical) possibility would be to have a event on the Presenter, i.e.
```
RadioButtonVisibilityChanged
```
, which is listened to by the View and passes the new visibility through the
```
EventArgs
```
. This runs contrary to the View being independent and ignorant of the Presenter and therefore undermines the MVP pattern. I advise against such nonsense.


q:
Actually I try to find a subclass of InputStream which is also Serializable. I think that doesn't exist. Since both Interfaces have many sublclasses it is hard to find one that is a subclass of both.

Until now I haven't found anything to help my search in Eclipse. Anyone ideas?

Edit: I understand now that serializing a Stream isn't really what one should do. But the essence of the Question is: how can I find a common subclass of two Interfaces.

[A]
Serializing an InputStream is not a very viable solution. To illustrate this, imagine if you have an InputStream from a socket and you serialize that. Before you deserialize it, the socket is closed. Now when you actually do deserialize it, the resource has vanished and you have a nasty exception in your hands.
What you should rather do, if you need to serialize a resource, is to serialize the location of it or how to obtain it. In the socket example: host name and port, for files: the file path, etc.


q:
I got this error when trying to update an image.
It was a cross-thread update, but I used .Invoke(), so that shouldn't be the problem, should it.

[A]
(Answering my own question, for others, and for future reference)
I
think
(not yet entirely sure) that this is because InvokeRequired will always return false if the control has not yet been loaded/shown. I have done a workaround which seems to work for the moment, which is to simple reference the handle of the associated control in its creator, like so:
```
```
var x = this.Handle;
```
```
(See
http://ikriv.com:8765/en/prog/info/dotnet/MysteriousHang.html
- down?
cached version
)
(Related question:
Boiler plate code replacement - is there anything bad about this code?
)


q: I know about "class having a single reason to change". Now, what is that exactly? Are there some smells/signs that could tell that class does not have a single responsibility? Or could the real answer hide in YAGNI and only refactor to a single responsibility the first time your class changes?

[A]
the methods in your class should be cohesive...they should work together and make use of the same data structures internally. If you find you have too many methods that don't seem entirely well related, or seem to operate on different things, then quite likely you don't have a good single responsibility.
Often it's hard to initially find responsibilities, and sometimes you need to use the class in several different contexts and then refactor the class into two classes as you start to see the distinctions. Sometimes you find that it's because you are mixing an abstract and concrete concept together. They tend to be harder to see, and, again, use in different contexts will help clarify.


q:
For example VK_LEFT, VK_DELETE, VK_ESCAPE, VK_RETURN, etc. How and where are they declared? Are they constants, #defines, or something else? Where do they come from?

If possible, please provide a file name/path where they are declared. Or some other info as specific as possible.

[A]
These are declared using
```
#define
```
in the file
```
winuser.h
```
in the Platform SDK. In my installation of Visual Studio 2008, the full path is
```
```
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinUser.h
```
```


q:
We are using LINQ very widely in our system. Particularly LINQ-to-objects. So in some places we end up having a LINQ query in memory build up from some huge expressions. The problem comes when there's some bug in the expressions. So we get NullReferenceException and the stack trace leads us nowhere (to [Lightweight Function]). The exception was thrown inside the dynamic method generated by LINQ.

Is there any easy way to debug such dynamic methods? Or do I have to sacrifice myself to learning WinDBG? :-)

[A]
If you're using LINQ to Objects, I wouldn't expect to see dynamic methods being created. I'd expect them with LINQ to SQL etc. Could you give an example where you're seeing this?
I don't really have any good debugging tips when it comes to LINQ, but I'm pretty sure MS know about this as a pain point. Could I suggest you try the
VS2010 CTP
and see if that's better? More for the sake of improving VS than for solving your immediate problem, admittedly.


q:
I have an Ant script that needs to checkout a directory from Subversion. This works using svnant/svnkit. However, Subversion access is authenticated, and I do not want to store my user password in a file.

Can I make svnkit pop up a password dialog?
Or even better, make it use the same credential caching that subversive/svnkit inside of Eclipse uses (the username can be read from the build.properties)?

I cannot switch to public key based authentication, as I do not control the subversion server.

Right now, it just says "svn: authentication cancelled".

[A]
To answer my own question, I can use the Ant [input] task to ask the user for a password and store it in a property that can be passed to the [svn] task.
```
```
<target name="checkout">
    <input
        message="Please enter subversion password for ${username}:"
        addproperty="password"
      />

    <svn svnkit="${svnkit}" username="${username}" password="${password}">
        <checkout url="${urlRepos}/project" destPath="web/" />
    </svn>
</target>
```
```
Unfortunately, this does not mask the password with * * * * *, and I still want to read from the credential cache...


q: Why is volatile needed in C? What is it used for? What will it do?

[A]
```
volatile
```
tells the compiler that your variable may be changed by other means, than the code that is accessing it. e.g., it may be a I/O-mapped memory location. If this is not specified in such cases, some variable accesses can be optimised, e.g., its contents can be held in a register, and the memory location not read back in again.


q:
I'm working on a eclipse plug-in and I've tried to create another test project seperate from the plug-in. The reason I do this is to not let the plug-in depend on jUnit when it is exported. However, I can't access the Eclipse Plug-in API when I do the testing. Whenever I try to add Plug-in dependencies the import list to that is empty.

Does anyone know how to import Eclipse plug-in API to an existing project? The workspace layout looks like this at the moment:

+- com.foo.myplugin
|     |
|     +- JRE System Library
|     |
|     +- Plug-in Dependencies
|     |
|     +- src
|     |
|     +- icons, META-INF, plugin.xml, etc...
|
+- com.foo.myplugin.test
      |
      +- JRE System Library
      |
      +- JUnit 4
      |
      +- src

[A]
You could try to add the plugin nature to your new myplugin.test project.
In your .project file:
```
```
<natures>

        <nature>org.eclipse.pde.PluginNature</nature>
        [...]
</natures>
```
```
Then in the .classpath, add:
```
```
<classpath>
        [...]
        <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
        [...]
</classpath>
```
```
Delete your myplugin.test from the workspace, re-import that project and see if that does the trick...


q:
this is my old code

    protected override bool OnPreAction(string actionName, System.Reflection.MethodInfo methodInfo)
    {
        if ("|Register|RegisterPage|Login|LoginPage|Logout|Service".ToLower().Contains(actionName.ToLower()))
        {
            return base.OnPreAction(actionName, methodInfo);
        }

        Customer = CustomerHelper.GetCustomer();

        if (Customer.IsSeccessedLogin())
        {
            return base.OnPreAction(actionName, methodInfo);
        }

        Response.Redirect("Login.html");
        return false;
    }

[A]
```
```
string actionName = (string)filterContext.RouteData.Values["action"];
```
```


q:
In the recent project, we had an issue with the performance of few queries that relied heavily on ordering the results by datetime field (MSSQL 2008 database).

When we executed the queries with ORDER BY RecordDate DESC (or ASC) the queries executed 10x slower than without that. Ordering by any other field didn't produce such slow results.

We tried all the indexing options, used the tuning wizard, nothing really made any difference.

One of the suggested solutions was converting the datetime field to the integer field representing the number of seconds or miliseconds in that datetime field. It would be calculated by a simple algorithm, something like "get me the number of seconds from RecordDate to 1980-01-01". This value would be stored at insertion, and the all the sorting would be done on the integer field, and not on the datetime field.

We never tried it, but I'm curious what do you guys think?

[A]
Are the inserts coming from .Net Code...
You could store the
DateTime.Ticks
value in a bigint column on the DB and index on that.
In terms of updating your existing Database, it should be relatively trivial to write a CLR Function for converting existing DateTimes to TickCount along the lines of
```
```
ALTER TABLE dbo.MyTable ADD TickCount BigInt Null

Update dbo.MyTable Set TickCount = CLRFunction(DateTimeColumn)
```
```
It definitely feasible and would dramatically improve your sorting abilility


q:
can we output a .jpg image or .gif image in C?
I mean can we print a picture as output with the help of a C program?
Aslo can we write a script in C language for HTML pages as can be written in JavaScript?
Can the browsers operate on it?
If not possible is there any plugin for any of the browsers?

Any example code or links please?

[A]
That's a lot of questions!
You can generate JPEG and PNG files from C using
libjpeg
and
libpng
, respectively. (Yes, I'm dodging your GIF question on purpose. You don't need to do that; PNG is well-supported by mainstream browsers now and
should be preferred
. :-P)
Browsers generally only support JavaScript for client-side scripting. Using anything else will only destroy the portability of your webpages. Yes, like you say you can use plugins, but some people are averse to installing plugins, and others are behind corporate policies that don't allow such things.


q:
While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of

Name : Value
Name2 : Value2

etc.

The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though.  How would I go about writing a method that takes these sometimes-floats and makes them integers?

[A]
You can use
Math.round()
for rounding numbers to the nearest integer.
```
```
Math.round(532.24) => 532
```
```
Also, you can use
parseInt()
and
parseFloat()
to cast a variable to a certain type, in this case integer and floating point.


q:
What is the default capacity of a StringBuilder?

And when should (or shouldn't) the default be used?

[A]
[edit: at the time, the question asked about
```
StringList
```
]
Do you mean
```
StringCollection
```
? This uses an empty
```
ArrayList
```
initially, so the answer is 0. And you have no option to change it. When you first add an item, the capacity jumps to 4, then uses a doubling strategy when it fills.
If you mean
```
List<string>
```
, then it is similar (an empty
```
T[]
```
, not an
```
ArrayList
```
), but you can initialize a known size if you need (i.e. you know how much data you expect). Again, the first time you
```
Add
```
to a
```
List<T>
```
the size jumps to 4, then doubles every time it fills up.


q:
I am writing a shell script that takes file paths as input.

For this reason, I need to generate recursive file listings with full paths. For example, the file bar has the path:

/home/ken/foo/bar

but, as far as I can see, both ls and find only give relative path listings:

./foo/bar   (from the folder ken)

It seems like an obvious requirement, but I can't see anything in the find or ls man pages.

How can I generate a list of files in the shell including their absolute paths?

[A]
If you give
```
find
```
an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory:
```
```
find "$(pwd)" -name .htaccess
```
```
or if your shell expands
```
$PWD
```
to the current directory:
```
```
find "$PWD" -name .htaccess
```
```
```
find
```
simply prepends the path it was given to a relative path to the file from that path.
Greg Hewgill
also suggested using
```
pwd -P
```
if you want to resolve symlinks in your current directory.


q:
I need to create a midnight DateTime

I've just done this:

DateTime endTime = DateTime.Now;
endTime.Subtract(endTime.TimeOfDay);

Haven't test it yet, I'm assuming it works but is there a better/cleaner way?

[A]
Just use
```
foo.Date
```
, or
```
DateTime.Today
```
for today's date


q: Does anybody know about an Eclipse plug-in to analyze code coverage for TestNG unit tests?

[A]
EclEmma
can be run on TestNG test suites.  You can also run a group of test or a given TestNG class with it.  It requires the
TestNg plug-in
On EclEmma plugin, choose "coverage configuration..." and select the TestNG tab.


q: Does anyone know of a tool to take a T-SQL query and convert it into a LINQtoSQL query?

[A]
I'm sorry that I don't know of any tools to do this.  If your problem is that you just don't know Linq well enough, you may want to consider this
tool
.  It will help you learn Linq and it's free (but not open source).


q: Is there any way to add iCal event to the iPhone Calendar from the custom App?

[A]
Yes there still is no API for this (2.1). But it seemed like at WWDC a lot of people were already interested in the functionality (including myself) and the recommendation was to go to the below site and create a feature request for this. If there is enough of an interest, they might end up moving the ICal.framework to the public SDK.
https://developer.apple.com/bugreporter/


q:
I want to be able to run a function in my firefox sidebar js file when the selected tab in the main content window is reloaded or changed. So the sidebar can change depending on the site the user is looking at.

Anyone able to point me in the right direction?

[A]
My solution pilfered from somewhere but can't remember where:
```
```
//add the load eventListener to the window object
window.addEventListener("load", function() { functioname.init(); }, true);

var functionname =  {
    //add the listener for the document load event
init: function() {
    var appcontent = document.getElementById("appcontent");   // browser
    if(appcontent)
        appcontent.addEventListener("DOMContentLoaded", functionname.onPageLoad, false);
    },
    //function called on document load
    onPageLoad: function(aEvent) {
        if(aEvent.originalTarget.nodeName == "#document"){
        }
     }
}
```
```


q:
I have seen a function whose prototype is:

int myfunc(void** ppt)

This function is called in a C file as
    a = myfunc(mystruct **var1);

where mystruct is typedef for one of structure we have.

This works without any compilation errors in MSVC6.0, But when I compile it with some other C compiler, it gives an error at the place where this function is called with error message:

Argument of type mystruct ** is incompatible with parameter of type void **

The argument of myfunc() is kept as void** because it seems to be a generic malloc kind of function to be called with various structure variable types for memory allocation

Is there any type such as void ** allowed in C standard/any C compilers?

How do I fix this? [I tried casting the function call argument to mystruct**, but it didn't work]

-AD

[A]
```
void**
```
is
valid but, based on your error message, you probably have to explicitly cast the argument as follows:
```
```
mystruct **var1;
x = myfunc ((void**) var1);
```
```
That's because the
```
myfunc
```
function is expecting the
```
void**
```
type. While
```
void*
```
can be implicitly cast to any other pointer, that is not so for the double pointer - you need to explicitly cast it.


q:
I'm looking for a Report Designer that will allow me to connect to a RESTful webservice. Ideally I would like one that has a royalty-free End-User Report Designer. WE will be hosting it in an ASP.NET web site. So something compatable with that would be ideal ;)

We used to use Data Dynamics Active Reports. However this doesn't allow connections to webservices.

Any help, very much appreciated.

Thanks in advance.

Crafty

[A]
I'm not sure what you mean by asking for a report generator that can connect to a web service.
Web services aren't something you can report on. They're just a source of data. What do you want to connect to and what data are you expecting to get back?
The problem with RESTful web services is you don't know what you're going to get back (there's no schema as with a DB table).
The good thing about RESTful web services is you're probably going to get back some XML, and the Active Reports product you mention seems to do things with XML files.
"ActiveReports for .NET 3.0 supports many XML-based files for data input."
Cam you call the web services for the information you need and squirrel it away in some files (or a DB) first?
Or are you in essence asking for something that can query a RESTful web service in some reasonably complex way and return the results of the query in some structured way that a report generator can then consume?
Do you have specific RESTful web services in mind, and if so do you know what format they will return data in? Then your question is really about report generators that can handle that returned format, perhaps.
Or something else and I've missed the point?


q: How do I convert a keycode to a keychar in .NET?


q:
I want to create a trigger to check what is being deleted against business rules and then cancel the deletion if needed. Any ideas?

The solution used the Instead of Delete trigger. The Rollback tran stopped the delete. I was afraid that I would have a cascade issue when I did the delete but that didn't seem to happen. Maybe a trigger cannot trigger itself.

[A]
Use an
```
INSTEAD OF DELETE
```
(see
MSDN
) trigger and decide within the trigger what you really want to do.


q:
Here's a very simple question. I have an SP that inserts a row into a table and at the end there's the statement RETURN @@IDENTITY. What I can't seem to find is a way to retrieve this value in C#. I'm using the Enterprise library and using the method:

db.ExecuteNonQuery(cmd);

I've tried cmd.Parameters[0].Value to get the value but that returns 0 all the time. Any ideas?

[A]
```
```
Dim c as new sqlcommand("...")

Dim d As New SqlParameter()
d.Direction = ParameterDirection.ReturnValue
c.parameters.add(d)

c.executeNonQuery

(@@IDENTITY) = d.value
```
```
It is more or less like this...either this or just return the value from a stored procedure as an output parameter.


q:
This might be a naive question. I have to manually edit a .WXS file to make it support select features from command line.

For example, there are 3 features in .WXS file.

<Feature Id="AllFeature" Level='1'>

    <Feature Id="Feature1" Level='1'> </Feature>

    <Feature Id="Feature2" Level='1'> </Feature>

    <Feature Id="Feature3" Level='1'> </Feature>

</Feature>

Now, I want to select features from command line. Say, if I type "msiexec /i install.msi FEATURE=A", then "Feature1" and "Feature2" is installed; if I type "msiexec/i install.msi FEATURE=B", then "Feature1" and "Feature3" is installed. In this case, "A" maps to Feature 1 and 2; "B" maps to Feature 1 and 3.

How to accomplish this in WIX?

[A]
I would change Feature1, Feature2 and Feature3 to Components, then would declare something like this:
```
```
<Feature Id="FEATUREA" Title="Super" Level="1" >
  <ComponentRef Id="Component1" />
  <ComponentRef Id="Component2" />
</Feature>

<Feature Id="FEATUREB" Title="Super1" Level="1" >
  <ComponentRef Id="Component1" />
  <ComponentRef Id="Component3"/>
</Feature>
```
```
Then to Install either FeatureA or FeatureB
```
```
msiexec /i install.msi ADDLOCAL=[FEATUREA | FEATUREB]
```
```


q:
I am reading WIX script written by others. There are some code really confuses me.

<Custom Action='UnLoadSchedulerPerfCounters' After='InstallInitialize'>
    <![CDATA[(Installed) AND (!Scheduler = 3)]]>
</Custom>
<Custom Action='RollbackSchedulerPerfCounters' After='WriteRegistryValues'>
        <![CDATA[(&Scheduler = 3)]]>
</Custom>

So, what's the difference between !Scheduler and &Scheduler?
Is any special meaning when property is prefix-ed by & or !?

[A]
From
http://www.tramontana.co.hu/wix/lesson5.php#5.3
:
Prepending some special characters to
  the names will give them extra
  meaning:
```
```
%     environment variable (name is case insensitive)
$     action state of component
?     installed state of component
&     action state of feature
!     installed state of feature
```
```
The last four can return the following
  integer values:
```
```
-1   no action to be taken
1    advertised (only for components)
2    not present
3    on the local computer
4    run from the source
```
```


q: I'm working on a piece of library code around IDisposable. The managed path (via using) is easily testable. I'm wondering about the finalizer though: Is calling System.GC.Collect() sufficient to force the finalizer to run?

[A]
Could you mock out an
```
IDisposable
```
interface and expect a call to
```
Dispose
```
?  That would at least let you see when the object is actually disposed.


q:
My programming environment includes scripts for setting up my autobuild on a clean machine.

One step uses a vbscript to configure a website on IIS that is used to monitor the build.

On a particular machine I will be running apache on port 80 for a separate task.

I would like my vbscript to set the port to 8080 for the new site that it is adding.

How can I do this?


q:
What is the best way of working with calculated fields of Propel objects?

Say I have an object "Customer" that has a corresponding table "customers" and each column corresponds to an attribute of my object. What I would like to do is: add a calculated attribute "Number of completed orders" to my object when using it on View A but not on Views B and C.

The calculated attribute is a COUNT() of "Order" objects linked to my "Customer" object via ID.

What I can do now is to first select all Customer objects, then iteratively count Orders for all of them, but I'd think doing it in a single query would improve performance. But I cannot properly "hydrate" my Propel object since it does not contain the definition of the calculated field(s).

How would you approach it?

[A]
Add an attribute "orders_count" to a Customer, and then write something like this:
```
```
class Order {
...
  public function save($conn = null) {
    $customer = $this->getCustomer();
    $customer->setOrdersCount($customer->getOrdersCount() + 1);
    $custoner->save();
    parent::save();
  }
...
}
```
```
You can use not only the "save" method, but the idea stays the same. Unfortunately, Propel doesn't support any "magic" for such fields.


q:
Does anyone know how could I programatically disable/enable sleep mode on Windows Mobile?

Thanks!

[A]
Probably by modifying the "System Power States" as
described here
(but in c#)
That article also describes a way to prevent the mobile device to sleep (which is not exactly what you may want), by calling the native function SystemIdleTimerReset() periodically (to prevent the device from powering down).


[A]
From the Unix / cygwin command line, you can use bc.
```
```
$ bc
ibase=16
34363932353433373538323038353135353439
1164362276596472215941024063897591129839055929
```
```
There is also
an online version
.  If you want to do it in code you should use an arbitrary precision library facility, like Java's BigInteger, Perl's Math::BigInt, Tcl's  math::bignum, or of the many multiple precision arithmetic libraries that are available for C, like
GNU GMP
, or
MPI
.


q:
Possible Duplicate:

  How can I use a carriage return in a HTML tooltip?

I'd like to know if it's possible to force a newline to show in the tooltip when using title property of a TD.
something like

<td title="lineone \n linetwo \n etc...">

Can this be done?

[A]
This should be OK, but is Internet Explorer specific:
```
```
<td title="lineone
linetwo
etc...">
```
```
As others have mentioned, the only other way is to use an HTML + JavaScript based tooltip if you're only interested in the tooltip. If this is for accessibility then you will probably need to stick to just single lines for consistency.


q: I want to draw spinner controls, such as those found on a NumericUpDown, on a custom component.  If I want to draw a drop-down button, I can use ComboBoxRenderer.  Is there an equivalent of ComboBoxRenderer for NumericUpDown?

[A]
I do not think a ComboBoxRenderer exists in the Windows Forms namespace. You need to directly draw the UpDown control arrows (spin buttons) using interop and the Theme API. I don't have a complete sample for you, but you'll need
```
```
[DllImport("uxtheme.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
public static extern IntPtr OpenThemeData(IntPtr hWnd, String classList);

[DllImport("uxtheme", ExactSpelling = true)]
public extern static Int32 DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ref RECT pRect, IntPtr pClipRect);

[DllImport("uxtheme.dll", ExactSpelling = true)]
public extern static Int32 CloseThemeData(IntPtr hTheme);
```
```
and you can find the required parts and states in
this page
(look for the SPIN style class and its associated parts and states).


q:
I have a char* p, which points to a \0-terminated string. How do I create a C++ string from it in an exception-safe way?

Here is an unsafe version:

string foo()
{
  char *p = get_string();

  string str( p );
  free( p );
  return str;
}

An obvious solution would be to try-catch - any easier ways?

[A]
You can use
```
shared_ptr
```
from
C++11
or
Boost
:
```
```
string
foo()
{
    shared_ptr<char> p(get_string(), &free);
    string str(p.get());
    return str;
}
```
```
This uses a very specific feature of
```
shared_ptr
```
not available in
```
auto_ptr
```
or anything else, namely the ability to specify a custom deleter; in this case, I'm using
```
free
```
as the deleter.


q:
I am implementing replication for a project I am developing, and would like to replicate changes in the Write database to the Read database.

While this isn't a problem, I want to tune one database for reading from, and the other to writing to, so they would have different settings.

Is there any resource/guide which will tell me what concepts to look into? I'm not looking for a how to guide (then again, at this level, these tasks are very involved to have guides to).

Thanks

[A]
Index your databases differently.   You probably need different indexes (maybe fewer indexes) to suppor the process of writing to the Write database than you do with the read database.   If an index is only used for reading, then leave it off the Write database.
I'm no expert on this, and my thinking might be fuzzy, but consider the hardware/memory/and even RAID configurations.   I can't remember.... would one RAID configuration be more suited for writing and another for reading, or is that wrong...?


q:
Please give me the advantages and disadvantages of using the particular framework.

Can give me examples of successes where you have used AOP in you .net applications?


q:
In the Render method of an ASP.NET web-control, I need to alter the output of the Html based on whether JavaScript is enabled or disabled on the clients browser,

Does anyone know the right incantation to figure that out?

[A]
The
noscript
tag is used to define an alternate content (text) if a script is NOT executed.
EDIT: Hi Kieron, take a look at this link:
Creating a Server Control for JavaScript Testing
, and
Detect if JavaScript is enabled in ASPX


q: How do I convert TIS-620 (the extended ASCII Thai Character code page) string to UTF-8 string in Java?


q:
OK, I am trying to generate the rDoc for paperclip, but the rake task is choking on another plugin before it gets to it, so this is out of the question:

rake doc:plugins

I could go and fix up the broken plugin, but I'm busy and lazy, so I just want to generate the docs for paperclip. Is there any way of doing this?

[A]
Unbelievably, I've just figured it out!
```
```
rake doc:plugins:paperclip
```
```
That was simple.


q:
I'm writing a web application which uses windows authentication and I can happily get the user's login name using something like:

 string login = User.Identity.Name.ToString();

But I don't need their login name I want their DisplayName. I've been banging my head for a couple hours now...

Can I access my organisation's AD via a web application?

[A]
See related question:
Active Directory: Retrieve User information
See also:
Howto: (Almost) Everything In Active Directory via C#
and more specifically section "
Enumerate an object's properties
".
If you have a path to connect to a group in a domain, the following snippet may be helpful:
```
```
GetUserProperty("<myaccount>", "DisplayName");

public static string GetUserProperty(string accountName, string propertyName)
{
    DirectoryEntry entry = new DirectoryEntry();
    // "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."
    entry.Path = "LDAP://...";
    entry.AuthenticationType = AuthenticationTypes.Secure;

    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(SAMAccountName=" + accountName + ")";
    search.PropertiesToLoad.Add(propertyName);

    SearchResultCollection results = search.FindAll();
    if (results != null && results.Count > 0)
    {
        return results[0].Properties[propertyName][0].ToString();
    }
    else
    {
            return "Unknown User";
    }
}
```
```


q:
I'm using Python's Imaging Library and I would like to draw some bezier curves.
I guess I could calculate pixel by pixel but I'm hoping there is something simpler.

[A]
A bezier curve isn't that hard to draw yourself. Given three points
```
A
```
,
```
B
```
,
```
C
```
you require three linear interpolations in order to draw the curve. We use the scalar
```
t
```
as the parameter for the linear interpolation:
```
```
P0 = A * t + (1 - t) * B
P1 = B * t + (1 - t) * C
```
```
This interpolates between two edges we've created, edge AB and edge BC. The only thing we now have to do to calculate the point we have to draw is interpolate between P0 and P1 using the same t like so:
```
```
Pfinal = P0 * t + (1 - t) * P1
```
```
There are a couple of things that need to be done before we actually draw the curve. First off we have will walk some
```
dt
```
(delta t) and we need to be aware that
```
0 <= t <= 1
```
. As you might be able to imagine, this will not give us a smooth curve, instead it yields only a discrete set of positions at which to plot. The easiest way to solve this is to simply draw a line between the current point and the previous point.


q: Such as deleting the output file during run, directing two instances of the sw to the same IO etc ?

[A]
There isn't much you can do to prevent the user from doing that, but what you can do is to apply
defensive programming
.
In your two examples you'd have to, every time you access a resource, detect failure conditions and react appropriately either throwing exceptions and dying or continuing without access to that resource.
Never assume a resource allocation will succeed, always check what you don't control. In short,
assume as little as possible and verify everything
.
'I'm told to access this file to write to it. Is it already open? Do I have permissions? Does it have the expected format? Does the disk have enough space? etc.'
There is many more about this. Just Google for defensive programming and you'll get a lot to read about.


q:
I just posted the question how-to-determine-why-the-browser-keeps-trying-to-load-a-page and discovered that my problem is with Gravatar.

I also noticed that StackOverflow is suffering from the same outage.

Does anyone know of a graceful way to determine if Gravatar, or any third party website for that matter, is up or not, before trying to retrieve avatar icons from them?

This would eliminate the long page load and the never ending busy cursor ... I shouldn't say never ending ... it just takes a long time to go away and is very confusing to the user as they sit there and wait ... for nothing.

[A]
You can have a different process that is periodically checking the status of the site. Set a rule about what is down for you, for instance you could say: "ping time > 1500 ms = down". Have this process to leave a note in a database table or config file. Then you check this value on each page rendering at almost no cost.
Depending on how critical is this external site, you can do the check more or less often.
This process could be an out of the web stack program, or a page only accessible through localhost that gets executed via Scheduled Tasks or an ASP.NET facility like mentioned in the comments.


q:
I recently started to develop using Flex 3 and Adobe Air and I wanted to know what features you want to be in futures releases of Adobe Air ?

The ones that I miss are:

Cross-systems way of launching a local file (shellExec) right from an Air application (although you can do this using workaround at least under Windows)

Ability to setup dynamic paths for Embed statement (e.g. Embed[(variable+"/path/to/file")] ). I didn't find any way to do this properly.

Some way of setting Flex object's positions with absolute values from CSS (that sounds more Flex related by the way)

Don't hesitate to add your workarounds to theses limitations if you know somes.

[A]
Ability to call out to native code - you currently have to ship a server written in another language and make calls to that to do anything more than Air gives you.
Modal windows. There's a hack you can do which involves setting Application.application.enabled = false, setting dialog.nativeWindow.alwaysInFront = true and then re-enabling the application when the dialog closes, but this is long-winded and doesn't disable any native menus you may have! It's crazy that something so simple is made so difficult.
A usable way to set the application's icon. I spent 2 hours trying to do this the other day and gave up after persistent "303" errors that gave me no idea of what I was doing wrong. Again, really basic stuff.


q:
I want do something like this:

Result = 'MyString' in [string1, string2, string3, string4];

This can't be used with strings and I don't want to do something like this:

Result = (('MyString' = string1) or ('MyString' = string2));

Also I think that creating a StringList to do just this is too complex.

Is there some other way to achieve this?

Thanks.

[A]
Here is a function that does the job:
```
```
function StringInArray(Value: string; Strings: array of string): Boolean;
var I: Integer;
begin
  Result := False;
  for I := Low(Strings) to High(Strings) do
  Result := Result or (Value = Strings[I]);
end;
```
```
In fact, you do compare MyString with each string in Strings. As soon as you find one matching you can exit the for loop.


q:
I have client application that uses WCF service to insert some data to backend database. Client application is going to call service on per event basis (it can be every hour or every second).

I'm wondering what's the best way of calling that service.

Should I create communication channel and keep it open all the time, or should I close channel after each call and create it again?

[A]
The first question is whether your server needs to maintain any state about the client directly (i.e. are you doing session-like transactions?)  If you are, you will need to be able to manage how the server holds the information between communications.
My initial feeling of your question is that if there is no need to leave a connection open, then close it each time and recreate a new connection on demand.  This will avoid issues where a connection can be placed into a faulted state between calls.  The overhead of creating and destroying connections is minimal, and it will (probably) save you a lot of time in debugging
when
something goes wrong.


q:
Here is a simplified version of my database model.  I have two tables: "Image", and "HostingProvider" which look like this:

[Image]

id

filename

hostingprovider_id

[HostingProvider]

id

base_url

Image HostingproviderId is a many-to-one foreign key relationship to the HostingProvider table. (Each image has one hosting provider).

Essentially I want to be able to have my Image class look like this:

[Image]

Id

base_url

filename

In NHibernate, how can I create a mapping file that will combine the base_url from the HostingProvider table, into the Image class?

[A]
```
```
public class Image {
    public virtual HostingProvider HostingProvider { get; set; } // NHibernate takes care of this
    public virtual string BaseUrl { get { return HostingProvider.BaseUrl; } }
}
```
```


q:
Currently we have mutiple projects sharing a JIRA instances. We want to make it such that the users only view the projects that they are doing testing.

But however we are currently groupging these users to the standard grouping jira-users.

What is the best way to filter out JIRA project that only certain users can see and access

[A]
You should create special Groups of users for each project you have... you can have more than one group, something like "project1_developers", "project2_observers" for better organization.
You alson combine these groups with the Project Roles to define into each project what kind of access each group should have.
Make a Permission Scheme to set of permissions to one project. Something like this:
Browse Projects -> Group (project1_admins, project1_developers, project1_users, project1_observers)
Create Issues -> Group (project1_admins, project1_developers, project1_users)
Move Issues -> Group (project1_admins)
You can use your Project Roles here too... but I prefer to set everything with groups.
Finally, you can use Issue security schemes to define who can and cannot view issues. Issue security schemes implement a number of security levels which can have users/groups assigned to them.
Hope that can help.


q:
I am trying to match the folder name in a relative path using C#. I am using the expression: "/(.*)?/" and reversing the matching from left to right to right to left.
When I pass "images/gringo/" into the regular expression, it correctly gives me "gringo" in the first group - I'm only interested in what is between the brackets.
When I pass in "images/", it fails to pick up "images".
I have tried using [/^] and [/$] but neither work.

Thanks,
David

[A]
You're probably better off using the
System.IO.DirectoryInfo
class to interpret your relative path. You can then pick off folder or file names using its members:
```
```
DirectoryInfo di = new DirectoryInfo("images/gringo/");
Console.Out.WriteLine(di.Name);
```
```
This will be much safer than any regexps you could use.


q:
I have a table in Access 2007 with 11,000 rows and about 20 columns. I want to create a form button that exports the table to an Excel sheet.  The code need to be VBA.

Any Ideas?


q:
Why do database guys go on about normalisation?

What is it? How does it help?

Does it apply to anything outside of databases?

[A]
Most importantly it serves to remove duplication from the database records.
For example if you have more than one place (tables) where the name of a person could come up you move the name to a separate table and reference it everywhere else. This way if you need to change the person name later you only have to change it in one place.
It is crucial for proper database design and in theory you should use it as much as possible to keep your data integrity. However when retrieving information from many tables you're losing some performance and that's why sometimes you could see denormalised database tables (also called flattened) used in performance critical applications.
My advise is to start with good degree of normalisation and only do de-normalisation when really needed
P.S. also check this article:
http://en.wikipedia.org/wiki/Database_normalization
to read more on the subject and about so-called
normal forms


q: Which functions are available within Delphi to play a sound-file?

[A]
A full tutorial is available at:
http://sheepdogguides.com/dt3f.htm
It is a bit old. But it should work.


q:
I'm working on a report in SSRS (SQL Server Reporting Services) right now, and I'm having a problem getting a rectanlge I draw on the page in the report designer to grow.  Basically, I've got a rectangle drawn, and then I put a text field inside of it.  The contents of this text field can be either very short or very long, so I want it to grow to accomodate its contents.

But when I enter the long text, the textbox grows and then sticks outside of the lines of the rectangle.  From the SSRS documentation I read, it says rectangles should grow to contain the items within them, and that those items are "peers".

What gives?

[A]
The only way I can get a textbox to breach the border of a rectangle is if the textbox is not actually inside the rectangle, but instead is underneath it.
When the textbox is inside the rectangle, and when the textbox property
```
CanGrow = TRUE
```
then the textbox and its rectangle both grow vertically downward to accommodate large amounts of text.


q:
Is there some library for using some sort of cursor over a file? I have to read big files, but can't afford to read them all at once into memory. I'm aware of java.nio, but I want to use a higher level API.

A little backgrond: I have a tool written in GWT that analyzes submitted xml documents and then pretty prints the xml, among other things. Currently I'm writing the pretty printed xml to a temp file (my lib would throw me an OOMException if I use plain Strings), but the temp file's size are approaching 18 megs, I can't afford to respond a GWT RPC with 18 megs :)

So I can have a widget to show only a portion of the xml (check this example), but I need to read the corresponding portion of the file.

[A]
Maybe
java.io.RandomAccessFile
can be of use to you.


q:
In an UML component diagram, how does one tag or identify a component as a database, so that it's easily recognizable? In the old days there was the cylinder symbol for showing database but that's not part of the UML. Same goes for an application server for instance, how would that be shown?

Are stereotypes applicable here? Can the component symbol be enhanced with graphical elements?

[A]
You tag databases
```
<<database>>
```
and servers as (it appears)
```
<<infrastructure>>
```
according to Scott Ambler
. I pulled this information from Figure 1, but I would recommend reading this article (and his other articles - they are good reads).
Something else I want to point out - UML is just one method of modeling. In formal documentation, I try to adhere to the standard. However, when planning and documenting for the team, I use whatever makes sense and is understood by the team. For you, that might mean putting a cylinder labeled "DB" or the name of the DB in the component box.


q:
I have a PHP script that can encode a PNG image to a Base64 string.

I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.

[A]
From here
:
```
```
/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }

        output = Base64._utf8_decode(output);

        return output;
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}
```
```
Also, search for
"JavaScript base64 encoding"
turns up a lot of other options, and the above was the first one.


q: What's the best way to detect that Adobe Acrobat Reader is installed from a web browser?  I'm assuming it would have to be done on the client-side (I don't think Adobe adds any user-agent strings).  Preferably in JavaScript and in Internet Explorer, although it would be nice if it could also be done in FireFox, Safari, etc...

[A]
This article
from the Adobe website should get you what you need.
EDIT
In testing this it isn't 100% though, as I have acrobat, but it doesn't detect it in IE 6.


q:
Is there any method?
My computer is AMD64.

::std::string str;
BOOL loadU(const wchar_t* lpszPathName, int flag = 0);

When I used:

loadU(&str);

the VS2005 compiler says:

Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *'

How can I do it?

[A]
If you have a std::wstring object, you can call
```
c_str()
```
on it to get a
```
wchar_t*
```
:
```
```
std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();
```
```
Since you are operating on a narrow string, however, you would first need to widen it.  There are various options here; one is to use Windows' built-in
```
MultiByteToWideChar
```
routine.  That will give you an
```
LPWSTR
```
, which is equivalent to
```
wchar_t*
```
.


q:
I want to automate SVN adds using NAnt. I want to add to SVN all new files in a given directory. The NAnt script will successfully execute the add command, however it displays the Tortoise SVN add dialog and this is not acceptable because it will execute on a build server running CruiseControl. The build server is running Windows Server 2003.

Any ideas?

<target name="addtest">
    <exec program="c:\program files\tortoisesvn\bin\tortoiseproc.exe"
        commandline="/command:add * --force /path:C:\svn\test /notempfile /closeonend:1"
        basedir="C:\svn\test"
        failonerror="false"/>
</target>

[A]
don't use tortoise!
just drop to command line svn.
```
```
c:\>svn add ...
```
```


q:
We may tag a question with multiple tags in StackOverflow website, I'm wondering how to find out the most related questions with common tags.

Assume we have 100 questions in a database, each question has several tags. Let's say user is browsing a specific question, and we want to make the system to display the related questions on the page. The criteria for related question is they have most common tags.

For example:
Question 1 is tagged with AAA, BBB, CCC, DDD, EEE.

Question 2 is top 1 related because it also has all those 5 tags.
Question 3 is top 2 related because it has only 4 or 3 tags that Questio1 has.
......

So my question is how to design the database and find out the questions that's related to Question 1 quickly. Thank you very much.

[A]
Not entirely sure what you mean, but
the Tags page
lists tags in order of popularity (as in amount tagged).
Edit:
is this about SO or about your own application? If it is about your own app, remove the SO tag as it's kind of misleading.
Edit2:
I'd say something like:
```
```
SELECT * FROM `questions` WHERE `tag` LIKE '%tagname%' OR (looped for each tag) LIMIT 5,0
```
```
Where 5 is the maximum results you want to return (for at least some optimisation). Probably not the best solution, but I could see it working.
You might also want to try a
```
LIKE
```
match using the title.


q:
Each of my clients can have many todo items and every todo item has a due date.

What would be the query for discovering the next undone todo item by due date for each file?  In the event that a client has more than one todo, the one with the lowest id is the correct one.

Assuming the following minimal schema:

clients (id, name)

todos (id, client_id, description, timestamp_due, timestamp_completed)

Thank you.

[A]
The following should get you close, first get the min time for each client, then lookup the client/todo information
```
```
SELECT
    C.Id,
    C.Name,
    T.Id
    T.Description,
    T.timestamp_due
FROM
{
    SELECT
        client_id,
        MIN(timestamp_due) AS "DueDate"
    FROM todos
    WHERE timestamp_completed IS NULL
    GROUP BY ClientId
} AS MinValues
    INNER JOIN Clients C
    ON (MinValues.client_id = C.Id)
    INNER JOIN todos T
    ON (MinValues.client_id = T.client_id
        AND MinValues.DueDate = T.timestamp_due)
ORDER BY C.Name
```
```
NOTE:
Written assuming SQL Server


q:
A client asked me if I knew anything about the HOME development method. I, together with wikipedia and acronymfinder, drew a complete blank.

Has anyone here heard about a development method called HOME?

[A]
The closest thing I found that mentioned a HOME development model was
this document on Google Books
. Apparently, it stands for Holistic, Open Multimedia development Method. But without context, I can't be sure this is right. But my best guess is that if this isn't right, it's another acronym.


q:
$doba = explode("/", $dob);

$date = date("Y-m-d", mktime(0,0,0, $doba[0], $doba[1], $doba[2]));

The above code turns any date i pass through into 1999-11-30 and i know it was working yesterday. Date is correct when I echo $doba. Anyone have any ideas?

Cheers

[A]
What is the format of
```
$doba
```
? Remember
```
mktime
```
's syntax goes hour, minute, second,
month, day year
which can be confusing.
Here's some examples:
```
```
$doba = explode('/', '1991/08/03');
echo(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[2], $doba[0]);

$doba = explode('/', '03/08/1991');
echo(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[0], $doba[2]);
```
```


q:
Any links to a good template for a windows service?  (looking for C# code)

Something that has the basic functionality that I could extend.

[A]
It is a little clear what you are looking for.  The
Windows Service
project type in Visual Studio creates a project with the templates you need to get going with a basic windows service.
You can also look at
this article
from C# Online.  It goes over a few ideas and has a few parts to the article.
(Note; the page seems to loads a little slow so be patient)


q:
I haven´t experience in making setup, but I all ready make mine but now I need help because when I made a new version I want that the user double click the shortcut and it do the update if there are any.

The application is in c#.

Could you help?

[A]
Here's how I have implemented an updater program I wrote earlier.
First off, you grab an ini file off of your server. This file will contain information about the latest version and where the setup file is. Getting that file isn't too hard.
```
```
WebClient wc = new WebClient();
                wc.DownloadFile(UrlOfIniContainingLatestVersion, PlacetoSaveIniFile);
```
```
I also had it setup to read information from a local ini file to determine the latest version. The better way of doing this would be to read the file version directly, but I don't have the code to do that handy.
Next we do a very simple check to see how the two versions compare and download the update.
```
```
if (LatestVersion > CurrentVersion)
            {
                //Download update.
            }
```
```
Downloading the update is just as simple as downloading the original ini. You simply change change the two parameters.
```
```
wc.DownloadFile(UrlOfLatestSetupFile, PlaceToSaveSetupFile);
```
```
Now that you have the file downloaded, it's a simple matter of running the installer.
```
```
System.Diagnostics.Start(PathOfDownloadedSetupFile);
```
```
If you're not sure how to read an ini file, I found the following class somewhere over at CodeProject
```
```
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Ini
{
    /// <summary>
    /// Create a New INI file to store or load data
    /// </summary>
    public class IniFile
    {
        public string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,
            string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,
                 string key, string def, StringBuilder retVal,
            int size, string filePath);

        /// <summary>
        /// INIFile Constructor.
        /// </summary>
        /// <PARAM name="INIPath"></PARAM>
        public IniFile(string INIPath)
        {
            path = INIPath;
        }

        /// <summary>
        /// Write Data to the INI File
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// Section name
        /// <PARAM name="Key"></PARAM>
        /// Key Name
        /// <PARAM name="Value"></PARAM>
        /// Value Name
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.path);
        }

        /// <summary>
        /// Read Data Value From the Ini File
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// <PARAM name="Key"></PARAM>
        /// <PARAM name="Path"></PARAM>
        /// <returns></returns>
        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp,
                                            255, this.path);
            return temp.ToString();

        }
    }
}
```
```


q:
Is there a .net equivalent to the C++ unexpected()/set_unexpected() functionality?

Edit:  Sorry--I omitted some details previously:

Language: C# 2.0

I have some legacy apps that seem to be throwing some unhandled exception somewhere.  I just want to put something in place to stop the customer's pain until I can trace the actual source of the problem.  In C++, the function pointed at by set_unexpected() gets called, as far as I know, when an otherwise unhandled exception bubbles to the main routine.  Hence my question about a .net equivalent functionality.

[A]
There 3 possible scenarios for handling unhandled exceptions, based on the type of the application:
For windows forms application, hook an event handler to
Application.ThreadException
For commandline applications, hook an event handler to
AppDomain.UnhandledException
For ASP.NET applications, in Global.asax, create:
protected void Application_Error(Object sender, EventArgs e)
DISCLAIMER: I'm not c++ developer, but from what I read, this should answer your question.


[A]
Perhaps you can define the pagination stuff in a separate jsp, and then include it twice into your main jsp.  For example:
```
```
<jsp:include page="pagination.jsp" flush="true" />

<table>...business data...</table>

<jsp:include page="pagination.jsp" flush="true" />
```
```
This way, if you ever want to change the pagination stuff, you can just edit pagination.jsp.


q: Is Visual Studio written in .NET Windows Forms? Or is Windows Forms just too slow for a editor type application?

[A]
Based on my experience with the VS SDK, it looks as if it was built with C++/COM but I think that's just because the Visual Studio team decided to go with that (AND Windows Forms didn't exist as a release version when they were first developing the VS.NET IDE).
You can use Windows Forms for an editor type application. I think SharpDevelop is a WinForms app.


q: I see these two acronyms being thrown around and I was wondering if there are any differences between a GUID and a UUID?

[A]
GUID is Microsoft's implementation of the UUID standard.
Per
Wikipedia
:
The term GUID usually refers to Microsoft's implementation of the
Universally Unique Identifier
(UUID) standard.
An updated quote from that same Wikipedia article:
RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…


q:
I recently read that using flexible array members in C was poor software engineering practice. However, that statement was not backed by any argument. Is this an accepted fact?

(Flexible array members are a C feature introduced in C99 whereby one can declare the last element to be an array of unspecified size. For example: )

struct header {
    size_t len;
    unsigned char data[];
};

[A]
You meant...
```
```
struct header
{
 size_t len;
 unsigned char data[];
};
```
```
In C, that's a common idiom. I think many compilers also accept:
```
```
unsigned char data[0];
```
```
Yes, it's dangerous, but then again, it's really no more dangerous than normal C arrays  - i.e., VERY dangerous ;-) . Use it with care and only in circumstances where you truly need an array of unknown size. Make sure you malloc and free the memory correctly, using something like:-
```
```
foo = malloc(sizeof(header) + N * sizeof(data[0]));
  foo->len = N;
```
```
An alternative is to make data just be a pointer to the elements. You can then realloc() data to the correct size as required.
```
```
struct header
    {
     size_t len;
     unsigned char *data;
    };
```
```
Of course, if you were asking about C++, either of these would be bad practice. Then you'd typically use STL vectors instead.


q: What's the most efficient way of getting the value of the SERIAL column after the INSERT statement? I.e. I am looking for a way to replicate @@IDENTITY or SCOPE_IDENTITY functionality of MS SQL

[A]
I have seen this used.
```
```
if LOCAL_SQLCA^.sqlcode = 0 then
/* return serial */
  Result := LOCAL_SQLCA^.sqlerrd[1]
else
/* return error code */
  Result := -(Abs(LOCAL_SQLCA^.sqlcode));
```
```


q:
I have a structure like this:

<ul>
  <li>text1</li>
  <li>text2</li>
  <li>text3</li>
</ul>

How do I use javascript or jQuery to get the text as an array?

['text1', 'text2', 'text3']

My plan after this is to assemble it into a string, probably using .join(', '), and get it in a format like this:

'"text1", "text2", "text3"'

[A]
```
```
var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });
```
```
...should do the trick. To get the final output you're looking for,
```
join()
```
plus some concatenation will do nicely:
```
```
var quotedCSV = '"' + optionTexts.join('", "') + '"';
```
```


q:
On Linux, feenableexcept and fedisableexcept can be used to control the generation of SIGFPE interrupts on floating point exceptions.  How can I do this on Mac OS X Intel?

Inline assembly for enabling floating point interrupts is provided in http://developer.apple.com/documentation/Performance/Conceptual/Mac_OSX_Numerics/Mac_OSX_Numerics.pdf, pp. 7-15, but only for PowerPC assembly.

[A]
On Mac OS X this is moderately complicated. OS X uses the SSE unit for all FP math by default, not the x87 FP unit. The SSE unit does not honor the interrupt options, so that means that in addition to enabling interrupts, you need to make sure to compile all your code not to use SSE math.
You can disable the math by adding "-mno-sse -mno-sse2 -mno-sse3" to your CFLAGS. Once you do that you can use some inline assembly to configure your FP exceptions, with basically the same flags as Linux.
```
```
short fpflags = 0x1332 // Default FP flags, change this however you want.
asm("fnclex");
asm("fldcw _fpflags");
```
```
The one catch you may find is that since OS X is built entirely using sse there may be uncaught bugs. I know there used to be a big with the signal handler not passing back the proper codes, but that was a few years ago, hopefully it is fixed now.


q:
In C# there is the static property Environment.Newline that changed depending on the running platform.

Is there anything similar in Java?

[A]
As of Java 7 (and Android API level 19):
```
```
System.lineSeparator()
```
```
Documentation:
Java Platform SE 7
For older versions of Java, use:
```
```
System.getProperty("line.separator");
```
```
See
https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html
for other properties.


q:
I'm familiar with the issue behind ORA-01775: looping chain of synonyms, but is there any trick to debugging it, or do I just have to "create or replace" my way out of it?

Is there a way to query the schema or whatever to find out what the current definition of a public synonym is?

Even more awesome would be a graphical tool, but at this point, anything would be helpful.

[A]
The data dictionary table
```
DBA_SYNONYMS
```
has information about all the synonyms in a database.  So you can run the query
```
```
SELECT table_owner, table_name, db_link
  FROM dba_synonyms
 WHERE owner        = 'PUBLIC'
   AND synonym_name = <<synonym name>>
```
```
to see what the public synonym currently points at.


q:
Looking at this loop that copies one c-string to another:

void strcpyr(char *s, char *t)
{
    while(*s++=*t++)// Why does this work?
        ;
}

Why do we not check for the '\0' character in the while loop, like this?

while((*s++=*r++)!='\0')..

How does the first loop terminate?

[A]
When we hit the
```
'\0'
```
in the string initially pointed to by
```
t
```
, the
```
*s++=*t++
```
, which does the assignment, also returns the value that's assigned to the position pointed to by
```
s
```
, or
```
'\0'
```
, which evaluates to
```
false
```
and terminates the loop.
In your second example, you explicitly rely on the fact that the assignment returns the assigned character, while the first example implicitly uses this fact (and the fact that the
```
0
```
character (also written
```
'\0'
```
) is considered to be false, while all other characters evaluate to true, so the expression
```
c != '\0'
```
will yield the same result as
```
c
```
.


q:
I am writing a C# console application that takes a binary file, rips it apart, analyzes it, and stores the data into a database.

We want to use BizTalk to orchestrate watching when a new binary file is placed in a directory and calling my application with the file name/names to be parsed.

Can BizTalk run a command line program?

Can it pass command line parameters to the program?

How would I report back to BizTalk that the last run was a success or a failure?

Thank you,

Keith

[A]
Biztalk is a server product so it will always be running in the background when you set it up in a production environment.
I'd suggest that if you're wanting to use BizTalk you set it up to watch the location where the file will be dropped, rip it apart, analyze it and then write out to the database all within a BizTalk workflow. Its exactly what it's been designed to do. The workflow could also contain notifications or you could just use BizTalk tracking to confirm if the operation has been successful. The only custom code you might need to write is a disassembler for your binary file to turn it into XML. This would be done as a receive pipeline component.
If that's all your doing though, BizTalk is a heck of an expensive option for just this. I suggest you write your own Windows service and use the
FileSystemWatcher
to intercept the fact that a file has been written and then do the processing in your C# code.


q:
Possible Duplicate:

  Resizing an iframe based on content

I'm loading an iFrame and want the parent to automatically change the height based upon the height of the iFrame's content.

To simply things, all pages belong to the same domain, so I shouldn't run into cross-site scripting issues.

[A]
On any other element, I would use the
```
scrollHeight
```
of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.
Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the
```
offsetHeight
```
:
```
```
function setHeight() {
    parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}
```
```
And attach that to run with the iframe-body's
```
onLoad
```
event.


q:
I use XPather Browser to check my XPATH expressions on an HTML page.

My end goal is to use these expressions in Selenium for the testing of my user interfaces.

I got an HTML file with a content similar to this:

<tr>
  <td>abc</td>
  <td>&nbsp;</td>
</tr>

I want to select a node with a text containing the string "&nbsp;".

With a normal string like "abc" there is no problem.  I use an XPATH similar to //td[text()="abc"].

When I try with an an XPATH like //td[text()="&nbsp;"] it returns nothing.  Is there a special rule concerning texts with "&" ?

[A]
Search for
```

```
or only
```
nbsp
```
- did you try this?


q: I have an app that is failing on the install. The vendor says I probably have ini_set() disabled. How can I check this?

[A]
You might want to take a look at the CHANGEABLE directives in php.ini:
http://us3.php.net/manual/en/ini.php#ini.list
In regard to verify whether an ini_set function worked, you can check the return value to make certain that it worked:
http://us3.php.net/manual/en/function.ini-set.php
The code would look something like this:
```
```
<?php
     if(ini_set('error_reporting', 'ALL') === false)
     {
         // Perform failure handling logic
     }
?>
```
```


q:
I'm having a disagreement with someone over how best to implement a simple method that takes an array of integers, and returns the highest integer (using C# 2.0).

Below are the two implementations - I have my own opinion of which is better, and why, but I'd appreciate any impartial opinions.

Option A

public int GetLargestValue(int[] values)
{
   try  {
          Array.Sort(values);
          return values[values.Length - 1];
        }
   catch (Exception){ return -1;}
}

Option B

public int GetLargestValue(int[] values)
{
    if(values == null)
        return -1;

    if(values.Length < 1)
        return -1;

    int highestValue = values[0];

    foreach(int value in values)
        if(value > highestValue)
            highestValue = value;

    return highestValue;
}

[A]
I prefer
Option B
as it only traverses the collection exactly once.
In
Option A
, you may have to access many elements more than once (the number of times is dependant upon the implementation of the sort alogrithm).
The
Option A
is an inefficent implementation, but results in a fairly clear algorithm.  It does however use a fairly ugly Exception catch which would only ever be triggered if an empty array is passed in (so could probably be written clearer with a pre-sort check).
PS, you should never simply catch "Exception" and then correct things.  There are many types of Exceptions and generally you should catch each possible one and handle accordingly.


q: How can I transform a String value into an InputStreamReader?

[A]
Does it have to be specifically an InputStreamReader?  How about using
StringReader
?
Otherwise, you could use
StringBufferInputStream
, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).


q:
Looking for a bit of regex help.
I'd like to design an expression that matches a string with "foo" OR "bar", but not both "foo" AND "bar"

If I do something like...

/((foo)|(bar))/

It'll match "foobar". Not what I'm looking for. So, how can I make regex match only when one term or the other is present?

Thanks!

[A]
You can do this with a single regex but I suggest for the sake of readability you do something like...
```
```
(/foo/ and not /bar/) || (/bar/ and not /foo/)
```
```


q:
I was under the impression that I could run it on any machine, but a guy from our hosting company is saying that the csr has to be generated on the server hosting the site.

Can anyone clear this one up for me?

Thanks.

[A]
The bottom line is you do not need to generate CSRs on the server hosting an SSL certificate. A CSR is a CSR and you could actually generate it using something like OpenSSL and then import both the key and certificate once it is created into the keystore. The problem is that they probably don't understand now to get the key into the keychain. See if this
KeyTool and OpenSSL tips
helps.


q: How can I run a stored procedure from a CL program? RUNSQLSTM requires a source member, but I just want to build a command so users can pass in variables easily, so this won't work.

[A]
There may be 2 options:
In the CL program create a temporary source member. Construct the SQL statement with the supplied parameters to execute the stored procedure and write this source code to the temporary member. Then add a call to RUNSQLSTM with the generated member as parameter.
A second option is not to create a CL program but use RPG/COBOL. By using embedded SQL the stored procedure can be executed with the parameters. Their values should be passed from the command to the program.


q:
I am admin on a forum.
Earlier we had phpbb 2.0 and i made a bot that could write to the forum.
Now, we have upgraded the forum to phpbb 3.0, but i can't get my bot to write to the forum anymore.

I have looked for a solution, but now i am out of ideas.
So it would have been great if anyone have a suggestion.

i have btw used CURL and php to make this bot.

Usage of bot:
Users log in on an external website to report results of footballmatches they have played online. The bot will then automatically write a post to the forum.

So basically i need to know what $_POST[] i need to send.

[A]
I would advise looking at the source code of the 'add post' form on the site. Check the HTML; you will need to emulate each
```
input
```
or
```
select
```
element, as these are the POST values that are submitted via the form.


q:
I have a form I am submitting using jQuery's ajaxSubmit function from the Forms plugin. I'm trying to add a form name/value pair to the form data just before submission occurs. My plan is to modify the form data in the beforeSubmit event handler.

Given a function that looks like:

function handleActionFormBeforeSubmit(formData, form, options) {
    // Add a name/value pair here somehow to formData
}

How do I add a simple pair to formData? It is an array in the form of:

[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]

Thanks,
Brian

[A]
After an hour of experimentation, I figured out a solution. To append a value to the form data, the following code will work.
```
```
function handleActionFormBeforeSubmit(formData, form, options) {

    // Add a name/value pair indicating this is an asynchronous call.
    // This works with the ASP.NET MVC framework's Request.IsMvcAjaxRequest() method.
    formData[formData.length] = { "name": "__MVCASYNCPOST", "value": "true" };
}
```
```
You can also modify the data if you know the index of the value you want to change such as:
```
```
formData[0].value = 'new value';
```
```
I hope this helps someone else.


q:
Besides the syntactic sugar and expressiveness power what are the differences in runtime efficiency. I mean, plpgsql can be faster than, lets say plpythonu or pljava? Or are they all approximately equals?

We are using stored procedures for the task of detecting nearly-duplicates records of people in a moderately sized database (around 10M of records)

[A]
plpgsql provides greater type safety I believe, you have to perform explicit casts if you want to perform operations using two different columns of similar type, like varchar and text or int4 and int8. This is important because if you need to have your stored proc use indexes, postgres requires that the types match exactly between join conditions (edit: for equality checks too I think).
There may be a facility for this in the other languages though, I haven't used them. In any case, I hope this gives you a better starting point for your investigation.


q:
I am using the jQuery tableSorter plugin on a page.

Unfortunatley, the table that is being sorted is dynamically modified, and when I sort after adding an element, the  element disappears, restoring the table to the state that it was in when the tableSorter was created.

Is there any way that i can force tableSorter to rescan the page so that these new elements are sorted properly?

[A]
I believe you can trigger an update using something like:
```
```
$(table).trigger("update")
```
```


q:
If I had a phone number like this

string phone = "6365555796";

Which I store with only numeric characters in my database (as a string), is it possible to output the number like this:

"636-555-5796"

Similar to how I could if I were using a number:

long phone = 6365555796;
string output = phone.ToString("000-000-0000");

I've tried searching and all I could find online were numeric formatting documents.

The reason I ask is because I think it would be an interesting idea to be able to store only the numeric values in the DB and allow for different formatting using a Constant string value to dictate how my phone numbers are formatted. Or am I better off using a number for this?

EDIT: The question is to format a string that contains numbers, not a number itself.

[A]
Why not just do something like this?
```
```
string phoneText = "6365555796";
long phoneNum = long.Parse(phoneText);
string output = phoneNum.ToString("000-000-0000");
```
```


q:
I am implementing NHibernate into an existing web application. However, we have some other processes that do bulk inserting and updating on the database. How can I make NHibernate aware that changes are occurring on the backend db that were not initiated through NHibernate?

Most of the info that I have read around NHibernate use in asp.net have mentioned storing the Session object in the HttpContext or CallContext. This would then store the session object for the duration of the application lifecycle. This is what I have implemented. I was afraid of the costs of initializing NHibernate on each request. Isn't there a significant performance hit with this approach with initializing the Session object on each request?

Also, would it make more sense to store the SessionFactory in the the HttpContext or CallContext so that the mappings don't have to be regenerated on each request?

[A]
You shouldn't. NHibernate sessions are there to help you work in an ACID environment, which means that one transaction is not aware of any concurrent transactions. You should be using short sessions which do small sets of actions. You should not be holding sessions open for long periods of time. If you do need long periods of time for working with domain objects, then you should be detaching and then re-attaching the domain objects from and to different sessions.
Once you open a new session, any changes done to the database before the session was opened will be made available through NHibernate.


q:
I've got a Excel VSTO 2005 application I need to debug, I've tried attaching to the process EXCEL.EXE in Visual Studio 2005 to no avail.

Does anyone know what to do in order to debug managed code running in a VSTO Excel Application?

[A]
I haven't worked with Excel, but with VSTO in Word, attaching the debugger to the WINWORD process works, but makes it impossible to debug startup code, as it has already ran before you can attach.  In this case you can insert
```
```
Debugger.Launch();
```
```
which will stop your code and ask to attach a debugger.  It's about the best solution I could find.


q:
Is there a better way to implement copy construcor for matlab for a handle derived class other than adding a constructor with one input and explicitly copying its properties?

obj.property1 = from.property1;
obj.property2 = from.property2;

etc.

Thanks,
Dani

[A]
If you want a quick-and-dirty solution that assumes all properties can be copied, take a look at the PROPERTIES function.  Here's an example of a class that automatically copies all properties:
```
```
classdef Foo < handle
  properties
    a = 1;
  end
  methods
    function F=Foo(rhs)
      if nargin==0
        % default constructor
        F.a = rand(1);
      else
        % copy constructor
        fns = properties(rhs);
        for i=1:length(fns)
          F.(fns{i}) = rhs.(fns{i});
        end
      end
    end
  end
end
```
```
and some test code:
```
```
f = Foo(); [f.a Foo(f).a] % should print 2 floats with the same value.
```
```


q:
How exactly can one implement a Log off function when using ASP.NET Forms Authentication on an intranet application?

How will this work if I am an administrator and want to log in "as someone else" into the application?

Please share your ideas

[A]
```
FormsAuthentication.SignOut();
```
;)


q:
A path in Perforce contains files a.txt and b.txt. I'll refer to the main path as mainline.

I've create a branch (called initialbranch) from there which contains just a.txt. I make lots of changes to a.txt, and am very happy with it. However, it's not yet ready for submitting back to mainline. I can easily integrate any changes to a.txt that occur in mainline.

Another project comes along, which needs the changes from initialbranch. Now, say I want to make changes to b.txt, and want to be able to integrate changes that happen both in initialbranch and in mainline. At present, I'm branching from initialbranch (call this new branch secondbranch). Previously I've been adding b.txt to initialbranch, and then integrating my changes across to secondbranch. Is there a nicer way to do this?

Sorry if this question seems somewhat convoluted, I've expressed it as best I can!

Thanks,

Dom

[A]
I'm not convinced I understand your question, but I'll try to help.
If you're saying that you don't really want b.txt in initialbranch, you can define a branch specification like this:
```
```
initialbranch/a.txt secondbranch/a.txt
mainline/b.txt secondbranch/b.txt
```
```
That way, when you integrate using the "secondbranch" branch spec, your changes in secondbranch will get pushed to initialbranch or mainline.
If you don't want to push changes directly from secondbranch to mainline, then do what it sounds like you are already doing: integrate b.txt from mainline to initialbranch, then from initialbranch to secondbranch. Work on it in secondbranch, then integrate the changes successively back to initialbranch and mainline.


q:
I've editing this original question as I think I've narrowed down the problem...

I have one view in my site that will not let me put $document.ready within a masterpage contentplaceholder. I've stripped this page to the bare bones and the only thing that is special about it is it has a custom route in global.asax

 routes.MapRoute("Books",
                 "{controller}/{action}/{keywords}/{pageNumber}",
                  new { controller = "Books", action = "SearchResults" }
                 );

Any idea why this custom route would stop $document.ready working correctly when put in a masterpages contentplaceholder zone?

[A]
Your master page (or view page if you're not using master pages) needs to reference jquery.  This is included in the latest Beta release of the MVC framework.
Check to make sure you have jQuery included in the  tag of your page.
check the syntax as well...
```
```
$(document).ready(function() { alert('loaded'); });
```
```
these shortened versions also work:
```
```
$().ready(function() { alert('loaded'); });
$(function() { alert('loaded'); });
```
```


q: I'm trying filter the child collection of an aggregate root when loading it with Nhibernate.  Load a Customer with all their Orders that have been shipped.  Is this possible?

[A]
Well, you can expose properties that are filtered in the map, like so:
```
```
<bag name="shippedOrders" ... where="Status == 'Shipped'" >
   <key column="CustomerId" />
   <one-to-many class="Order" />
</bag>
```
```
The 'where' attribute is arbitrary SQL.
Theoretically you could have two properties of Customer, Orders and ShippedOrders.  However, I should say that I have not done this, and I would want to test how NH handles cascading in this case.  In any case, you will have to take care when new items are added/removed that they are added/removed correctly to both collections.
The fact that you want to do this makes we wonder if Order is an aggregate root.  It might be less trouble in the long run doing it like this:
```
```
orderRepository.GetOrders(int customerId, OrderStatus[] statuses)
```
```


q:
I'm trying to use xcodebuild and OCUnit with my Continuous Integration server (TeamCity).

JetBrains offers test observer implementations for boost::test and CppUnit that format test output in a way that TeamCity can interpret.  I need to do something similar for OCUnit if I want to use it.

There appears to be a SenTestObserver class in OCUnit but I'm ignorant of how exactly it should be used, and the OCUnit homepage doesn't seem to provide any documentation on the matter.

[A]
You can write your own observer by extending the SenTestObserver class and implementing the notification listeners
(void) testSuiteDidStart:(NSNotification *) aNotification
(void) testSuiteDidStop:(NSNotification *) aNotification
(void) testCaseDidStart:(NSNotification *) aNotification
(void) testCaseDidStop:(NSNotification *) aNotification
(void) testCaseDidFail:(NSNotification *) aNotification
then add an entry to the info.plist SenTestObserverClass with the name of your class.
At least in the version of OCUnit i'm familiar with SenTestObserver is equal parts useful/equal parts broken. I just skip it altogether and register for the notifications myself in my own class. (see SenTestSuiteRun.h and SenTestCaseRun.h for the defines of the notification names).
You can use the test and run properties of the notification to access the SenTestSuite and SenTestSuiteRun instances, and the run instance contains the info needed on the actual results.


q: How can I set cron to run certain commands every one and a half hours?

[A]
Is there a good reason why you can't use 1 hour or 2 hours? It would be simpler for sure.
I haven't tried this personally, but you can find some info here on getting cron to run every 90 minutes:
http://keithdevens.com/weblog/archive/2004/May/05/cron
An excert from the above link:
```
```
0 0,3,6,9,12,15,18,21 * * * <commands>
30 1,4,7,10,13,16,19,22 * * * <commands>
```
```


q: SSIS 2005/2008 does fuzzy lookups and groupings.  Is there a feature that does the same in T-SQL?

[A]
SQL Server has a SOUNDEX() function:
```
```
SELECT *
FROM Customers
WHERE SOUNDEX(Lastname) = SOUNDEX('Stonehouse')
AND SOUNDEX(Firstname) = SOUNDEX('Scott')
```
```


q:
I need to use C# programatically to append several preexisting docx files into a single, long docx file - including special markups like bullets and images.  Header and footer information will be stripped out, so those won't be around to cause any problems.

I can find plenty of information about manipulating an individual docx file with .NET Framework 3, but nothing easy or obvious about how you would merge files.  There is also a third-party program (Acronis.Words) that will do it, but it is prohibitively expensive.

Update:

Automating through Word has been suggested, but my code is going to be running on ASP.NET on an IIS web server, so going out to Word is not an option for me.  Sorry for not mentioning that in the first place.

[A]
I wrote a little test app a while ago to do this. My test app worked with Word 2003 documents (.doc) not .docx, but I imagine the process is the same - I should think all you'd have to change is to use a newer version of the Primary Interop Assembly. This code would look a lot neater with the new C# 4.0 features...
```
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Office.Interop.Word;
using Microsoft.Office.Core;
using System.Runtime.InteropServices;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            new Program().Start();
        }

        private void Start()
        {
            object fileName = Path.Combine(Environment.CurrentDirectory, @"NewDocument.doc");
            File.Delete(fileName.ToString());

            try
            {
                WordApplication = new ApplicationClass();
                var doc = WordApplication.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                try
                {
                    doc.Activate();

                    AddDocument(@"D:\Projects\WordTests\ConsoleApplication1\Documents\Doc1.doc", doc, false);
                    AddDocument(@"D:\Projects\WordTests\ConsoleApplication1\Documents\Doc2.doc", doc, true);

                    doc.SaveAs(ref fileName,
                        ref missing, ref missing, ref missing, ref missing,     ref missing,
                        ref missing, ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing, ref missing);
                }
                finally
                {
                    doc.Close(ref missing, ref missing, ref missing);
                }
            }
            finally
            {
                WordApplication.Quit(ref missing, ref missing, ref missing);
            }
        }

        private void AddDocument(string path, Document doc, bool lastDocument)
        {
            object subDocPath = path;
            var subDoc = WordApplication.Documents.Open(ref subDocPath, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing);
            try
            {

                object docStart = doc.Content.End - 1;
                object docEnd = doc.Content.End;

                object start = subDoc.Content.Start;
                object end = subDoc.Content.End;

                Range rng = doc.Range(ref docStart, ref docEnd);
                rng.FormattedText = subDoc.Range(ref start, ref end);

                if (!lastDocument)
                {
                    InsertPageBreak(doc);
                }
            }
            finally
            {
                subDoc.Close(ref missing, ref missing, ref missing);
            }
        }

        private static void InsertPageBreak(Document doc)
        {
            object docStart = doc.Content.End - 1;
            object docEnd = doc.Content.End;
            Range rng = doc.Range(ref docStart, ref docEnd);

            object pageBreak = WdBreakType.wdPageBreak;
            rng.InsertBreak(ref pageBreak);
        }

        private ApplicationClass WordApplication { get; set; }

        private object missing = Type.Missing;
    }
}
```
```


q:
While the built-in analytics of MOSS2007 are nice to have - they are inadequate at the same time. Any ideas where I can look for a more comprehensive package? Am I missing something?

Thanks,
Carl

[A]
I had similar problem, it can be done like this:
```
rm -f error_marker_file
export var=`svn ls || touch error_marker_file`

[ -f error_marker_file ] && echo "error in executing svn ls"
```


q: I am using JSF frontend for a page where an image is uploaded or deleted. Clicking on the upload or delete button causes a postback and the page to reload with the updated status. This however, resets the scroll position of the page. How should I go about retaining the scrollback of this page on the postback actions.

[A]
If you are using Apache MyFaces Tomahawk, you can set the parameter AUTOSCROLL then make sure AutoScrollPhaseListener is enabled.
I'm not sure this functionality is specified by JSF, but instead is something extra implemented by Apache MyFaces Tomahawk.
Also, be aware that prior to version 1.1.6, there is a cross-site scripting vulnerability in the AUTOSCROLL implementation.


q:
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.

How do I retrieve a module's path in python?

[A]
This was trivial.
Each module has a
```
__file__
```
variable that shows its relative path from where you are right now.
Therefore, getting a directory for the module to notify it is simple as:
```
```
os.path.dirname(__file__)
```
```


q:
I have this doubt, I've searched the web and the answers seem to be diversified. Is it better to use mysql_pconnect over mysql_connect when connecting to a database via PHP? I read that pconnect scales much better, but on the other hand, being a persistent connection... having 10 000 connections at the same time, all persistent, doesn't seem scalable to me.

Thanks in advance.

[A]
It's very unlikely that you'll reach 10000 connections. Anyhow, go to the
official source
. (Emphasis mine).
If persistent connections don't have
  any added functionality, what are
  they good for?
The answer here is extremely simple --
  efficiency. Persistent connections are
  good if the overhead to create a link
  to your SQL server is high. Whether or
  not this overhead is really high
  depends on many factors. Like, what
  kind of  database it is, whether or
  not it sits on the same computer on
  which your  web server sits, how
  loaded the machine the SQL server sits
  on is and so  forth.
The bottom line
  is that if that connection overhead is
  high,  persistent connections help you
  considerably
. They cause the child
  process  to simply connect only once
  for its entire lifespan, instead of
  every  time it processes a page that
  requires connecting to the SQL server.
  This means that for every child that
  opened a persistent connection will
  have its own open persistent
  connection to the server. For example,
  if you  had 20 different child
  processes that ran a script that made
  a persistent  connection to your SQL
  server, you'd have 20 different
  connections to  the SQL server, one
  from each child.
Note, however, that this can have some
  drawbacks if you are using a  database
  with connection limits that are
  exceeded by persistent child
  connections. If your database has a
  limit of 16 simultaneous connections,
  and in the course of a busy server
  session, 17 child threads attempt  to
  connect, one will not be able to. If
  there are bugs in your scripts  which
  do not allow the connections to shut
  down (such as infinite loops),  the
  database with only 16 connections may
  be rapidly swamped. Check your
  database documentation for information
  on handling abandoned or  idle
  connections.