q: What is the easiest way to set up an SMS alerting system so that I will receive notification if my server doesn't respond or a GET query doesn't return correct content?

[A]
You can get a service like
http://www.serviceuptime.com/
and the send an email to your-number@a-domain-your-provider-gives They usually have the exact domains for the providers on their respective websites but you could just try @t-mobile.com if your provider is t-mobile for example.
If you want to write your own tool should be pretty straightforward - send GET request if you dont get the expected response send email. You should run it from 2 different locations from 2 different ISPs tho because if there are routing problems and the request doesnt go through you'll get smsed


q: V8's documentation explains how to create a Javascript object that wraps a C++ object. The Javascript object holds on to a pointer to a C++ object instance. My question is, let's say you create the C++ object on the heap, how can you get a notification when the Javascript object is collected by the gc, so you can free the heap allocated C++ object?

[A]
In general, if a garbage-collected language can hold references to resources outside of the language engine (files, sockets, or in your case C++ objects), you should provide a 'close' method to release that resource ASAP, no point waiting until the GC thinks it's worthwhile to destroy your object.
it gets worse if your C++ object is memory-hungry and the garbage-collected object is just a reference: you might allocate thousands of objects, and the GC only sees a few KB's of tiny objects, not enough to trigger collection; while the C++ side is struggling with tens of megabytes of stale objects.

s: huggingface

c: devops

d: intermediate


q: I'm trying to use the Microsoft.Sdc.Tasks.ServiceProcess.Exists to check whether or not a service exists.  There is no example of using it in the documentation though.  Anyone have one?

[A]
I've not actually used this in production myself, and I'm not sure which version you have (I have a copy of Release 2.1.3155.0) and according to the accompanying .chm help file the Task has the following properties:
DoesExist    Returns TRUE if the service specified exists
IsDisabled   Returns TRUE if the service is disabled
ServiceName  The short name that identifies the service to the system.
The ServiceName needs to be set to "The short name that identifies the service to the system, e.g. 'W3SVC'".
You might want to give it a try with a well known service (e.g. mssqlserver) and check the result of the other two properties (DoesExist/IsDisabled).
Update: Here's a sample (works):
Import the tasks, then call (e.g.)
< Microsoft.Sdc.Tasks.ServiceProcess.Exists
       ServiceName="Server">
      < Output TaskParameter="DoesExist" PropertyName="Exists" />
< /Microsoft.Sdc.Tasks.ServiceProcess.Exists >
< Message Text="Service exists? $(Exists)" />


q:
PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array "is a list" (contains only numeric keys starting from 0)?

Basically, I want to be able to differentiate between this:

$sequentialArray = [
    'apple', 'orange', 'tomato', 'carrot'
];

and this:

$assocArray = [
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'veg1' => 'tomato',
    'veg2' => 'carrot'
];

[A]
Unless PHP has a builtin for that, you won't be able to do it in less than O(n) - enumerating over all the keys and checking for integer type. In fact, you also want to make sure there are no holes, so your algorithm might look like:
```
```
for i in 0 to len(your_array):
    if not defined(your-array[i]):
        # this is not an array array, it's an associative array :)
```
```
But why bother? Just assume the array is of the type you expect. If it isn't, it will just blow up in your face - that's dynamic programming for you! Test your code and all will be well...


q:
So I've been thinking of going for Microsoft certification and I have to make a choice (for now) between Windows Forms and WPF for developing Windows applications. I have had good exposure to Windows Forms but never tried WPF before. Furthermore, most of the job postings where I live seem to be WinForms-oriented. That might change in the next few years, so I was wondering if I should get started on learning WPF or stick to the tried and true Forms.

Any insight?

[A]
WPF leverages XAML for the design/visual experience this is the same technology that Silverlight uses and in the future will be leveraged heavily by other aspects of .NET 4.0, specifically, WCF (web services) and WF (workflow).
I would highly recommend learning it if you have the cycles, however for certification purposes it might be easier to just go ahead and do the WinForms exam as WPF is quite different and in my experience had a bit of a learning curve (because of how different it is from WinForms).


q:
I am in the position of having to make a technology choice early in a project which is targetted at mobile phones.  I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.

Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.

[A]
Have you checked out the
Mobile Python Book
?
This practical hands-on book effectively teaches how to program your own powerful and fun applications easily on Nokia smartphones based on Symbian OS and the S60 platform.
(source:
mobilenin.com
)


q:
I'd like to write some (java) code that takes a PDF document, and creates named destinations from all of the bookmarks. I think the iText API is the easiest way of doing this, but I have never used the API before.

How would you go about writing this sort of code with the iText API?  Can iText do the parsing needed to manipulate existing PDFs by itself?  The kind of manipulations I am thinking of are:

Open,

Find bookmarks,

Create destinations,

Save,

Close.

Or is there a different API that would be better?

[A]
I'll just warn you up front that you may be disappointed with this.  iText isn't really intended to be used as a parser.  It's really more for creating
entirely new
PDF documents, but you can take a whack at it.
To start, using iText, you won't be able to modify the existing PDF document.  What you
can
do, though, is to make a copy with the additional features that you want.  (If somebody else knows better,
please
let me know, this drives me crazy.)
What you will want to do is create a PdfReader object from an input stream on your source file.  Then create a PdfCopy object (which is just an extended PdfWriter that makes getting data from an existing source more convenient) for your destination.
As far as I can tell, the bookmarks cannot be obtained from iText at all.  Another library may be needed.  I think
jpedal
may have the ability to extract them (it can get them as an XML document, which you may then have to parse to get what you want.)  However you get them, you can then add them to a java.util.List, and set that list as outline on the PDFCopy.  The bookmarks themselves are just HashMaps with a particular set of keys.  I'm not sure what all of the values are, but they include "Title", "Action" (which seems to be where you'd specify that this is a named destination, though I don't know what that value would be), and "URI" (which is used if this is an external link -- I suspect that this would specify the name of the named destination that you're linking to).  Again, the specifics are hard to find.
Then iterate over the pages of the reader, importing each page to the PdfCopy.
this page
may help you.
Sorry I'm not more helpful to you.  Good luck.
P.S.  If anybody else knows of a better tool that's either (L)GPL or BSD licensed, I'd love to hear about it.


q: Am looking for C# open source NMEA parser.

[A]
Well, I'm not familiar with it myself, but some quick searches show one on
CodeProject
, which links to 2 other such,
here
and
here
. Any of those help?


q:
I've got a "little" problem with Zend Framework Zend_Pdf class. Multibyte characters are stripped from generated pdf files. E.g. when I write aąbcčdeę it becomes abcd with lithuanian letters stripped.

I'm not sure if it's particularly Zend_Pdf problem or php in general.

Source text is encoded in utf-8, as well as the php source file which does the job.

Thank you in advance for your help ;)

P.S. I run Zend Framework v. 1.6 and I use FONT_TIMES_BOLD font. FONT_TIMES_ROMAN does work

[A]
I believe Zend_Pdf got UTF-8 support in 1.5 - What version of Zend Framework are you running?
Also - what font are you trying to render with? Have you tried alternate fonts?


q:
I have some old rrdtool databases, for which the exact creation recipe has long been since lost. I need to create a new database with the same characteristics as the current ones. I've dumped a couple of old databases and pored over the contents but I'm not sure how to interpret the metadata. I think it appears in the following stanzas

<cf> AVERAGE </cf>
<pdp_per_row> 360 </pdp_per_row> <!-- 1800 seconds -->
<xff> 5.0000000000e-01 </xff>

There are four such stanzas, which correspond to the way I recall the round-robin cascading was set up. Has anyone already done this, or can give me pointers as to how to clone a new empty rrd database from an existing one? Or show me where I missed this in the documentation.

[A]
rrdtools'
rrdinfo
is your friend!
It will tell you how the rrd file's data source(s) and archive(s) were created.  Example
```
```
$ rrdtool info random.rrd
filename = "random.rrd"
rrd_version = "0001"
step = 300
last_update = 955892996
ds[a].type = "GAUGE"
ds[a].minimal_heartbeat = 600
ds[a].min = NaN
ds[a].max = NaN
ds[a].last_ds = "UNKN"
ds[a].value = 2.1824421548e+04
ds[a].unknown_sec = 0
ds[b].type = "GAUGE"
ds[b].minimal_heartbeat = 600
ds[b].min = NaN
ds[b].max = NaN
ds[b].last_ds = "UNKN"
ds[b].value = 3.9620838224e+03
ds[b].unknown_sec = 0
rra[0].cf = "AVERAGE"
rra[0].pdp_per_row = 1
rra[0].cdp_prep[0].value = nan
rra[0].cdp_prep[0].unknown_datapoints = 0
rra[0].cdp_prep[1].value = nan
rra[0].cdp_prep[1].unknown_datapoints = 0
```
```


q:
When the policy for a disk in Windows XP and Vista is set to enable write caching on the hard disk, is there a way to flush a file that has just been written, and ensure that it has been committed to disk?

I want to do this programmatically in C++.

Closing the file does perform a flush at the application level, but not at the operating system level.  If the power is removed from the PC after closing the file, but before the operating system has flushed the disk write cache, the file is lost, even though it was closed.

[A]
You haven't specified the development environment, so:
.Net
IO streams have a
```
.Flush
```
method that does what you want.
Win32 API
There is the
```
FlushFileBuffers
```
call, which takes a file handle as argument.
EDIT (based on a comment from the OA): FlushFileBuffers does not need administrative privileges; it does only if the handle passed to it is the handle for a volume, not for a single file.


q:
I've tried to override WndProc, but no message show up on paste event.

Then I tried to create custom filter and using method PreFilterMessage I was able to catch message with value 257 (KEYUP event), but that's not enough...

[A]
Use:
```
```
protected override void OnKeyDown(KeyEventArgs e)
 {
      if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
      {
            MessageBox.Show("Hello world");
      }
      base.OnKeyDown(e);
  }
```
```
Make sure your form KeyPreview = true.


q:
I am interested in seeing if I can improve the way we use NUnit in a Visual Studio solution containing 30+ projects.

First, would you have one assembly of tests for every assembly in the solution, or would you try to keep the number of test assemblies down? I started off creating many test assemblies, but I think this is costing us a lot in terms of build time.

Second, what strategy do you use for managing those tests that are long-running, or require special environment configuration? I would like to write an MSBuild script that automates the running of our unit tests, but it needs to skip over the tests that would take too long or would not work on the build machine.

[A]
To answer your first question:
You can use
categories
to keep everything organised in a single assembly if that's how you want to go. As to whether it would cut down on build time, I would hazard a guess at perhaps, I don't think it'd be a huge amount overall though.
To answer your second:
You can use
categories
and the
```
[Explicit]
```
and
```
[Ignore]
```
attribute to tell NUnit which tests to run, and which tests you have to tell it to run before it will. You might also want to look at
```
[Platform]
```
or some of the other attributes, depending on what exactly your requirements on 'environment' are.
For instance, you could add an Explicit tag to all your long running tests. Then you would have to run these tests explicitly, NUnit won't run them automatically. Or add all these tests to a category, then when you run NUnit, tell it to explicitly not run that category.


q:
I read that you could call JavaScript code from a Java Applet by calling

JApplet.getAppletContext().showDocument( "javascript:alert('Hello World');" );

However, when I do this i get the following error:

java.net.MalformedURLException: unknown protocol: javascript

How do I work around this?

[A]
```
```
try {
        this.getAppletContext().showDocument(new URL("javascript:alert('hello world');"));
    }catch(Exception e) {
        e.printStackTrace();
    }
```
```
Works !!
Maybe the browser does not have javascript enabled.. just a guess


q:
In MSVC, DebugBreak() or __debugbreak cause a debugger to break. On x86 it is equivalent to writing "_asm int 3", on x64 it is something different. When compiling with gcc (or any other standard compiler) I want to do a break into debugger, too. Is there a platform independent function or intrinsic? I saw the XCode question about that, but it doesn't seem portable enough.

Sidenote: I mainly want to implement ASSERT with that, and I understand I can use assert() for that, but I also want to write DEBUG_BREAK or something into the code.

[A]
What about defining a conditional macro based on #ifdef that expands to different constructs based on the current architecture or platform.
Something like:
```
```
#ifdef _MSC_VER
#define DEBUG_BREAK __debugbreak()
#else
...
#endif
```
```
This would be expanded by the preprocessor the correct debugger break instruction based on the platform where the code is compiled. This way you always use
```
DEBUG_BREAK
```
in your code.


q:
I only want a list of files that have been added (not ones that have been modified) since a certain date. Is there an easy way to do this?

Answer: Here's what ended up working for me, thanks guys!

svn log -v -r{2008-10-1}:HEAD svn://path.to.repo/ | grep "^   A" | grep ".java" | sort -u


q:
Good day.

I have a program thats launches an external application. That external app has a right click sub menu on it which I need to disable. Is it possible (without modifying the external app) to disable the right click? Maybe permission or group policies and etc.

Thanks.

[A]
I wasn't sure I wanted to post as I don't have a huge amount of scope on the matter, but it's definatley possible.
If you have a handle to the application (if not you can get one) you can use that to disable right click within the application.
http://www.codeguru.com/forum/showthread.php?t=190440
http://support.microsoft.com/kb/318804
seems like the most helpful links, it just goes on about how you should hook and then disregard
```
WM_RBUTTONDOWN
```
and
```
WM_RBUTTONUP
```
.
I'll try and write up a better thing later with an example.
More links/edits
This link could be useful as it explains that you're going to need to use unmanaged c/c++ to hook using setWindowsHookEx.
http://social.msdn.microsoft.com/Forums/en-US/clr/thread/8dd657b5-647b-443b-822d-ebe03ca4033c/
Hope this helps
[EDIT]
I think this can actually be done in a C# application completely. I will post a solution tonight
[/EDIT]


q:
I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.

When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:

b = wx.Button(self, 10, "Default Button", (20, 20))
        self.Bind(wx.EVT_BUTTON, self.OnClick, b)
def OnClick(self, event):
        self.log.write("Click! (%d)\n" % event.GetId())

But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value?

It would greatly reduce copy & pasting the same code but with different callers.

[A]
You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific.
```
```
b = wx.Button(self, 10, "Default Button", (20, 20))
        self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b)
def OnClick(self, event, somearg):
        self.log.write("Click! (%d)\n" % event.GetId())
```
```
If you're out to reduce the amount of code to type, you might also try a little automatism like:
```
```
class foo(whateverwxobject):
    def better_bind(self, type, instance, handler, *args, **kwargs):
        self.Bind(type, lambda event: handler(event, *args, **kwargs), instance)

    def __init__(self):
        self.better_bind(wx.EVT_BUTTON, b, self.OnClick, 'somevalue')
```
```


q: What is the easiest way to copy the all the values from a column in a table to another column in the same table?

[A]
This script will update ALL values in the field1 with the values from the field2 in the corresponding row
```
```
UPDATE table SET field1 = field2
```
```


q:
Question says it all, really.
My application is a time tracker.  It's currently written as a spreadsheet, but there's just too much data and I would like to impose a bit more structure on it.

SQLite seems like a neat way to go.

I would be open to other suggestions, too.

[A]
There are some providers available:
http://sqlite.phxsoftware.com/
http://sourceforge.net/projects/sqlite-dotnet2
And you can get up and running in just three minutes according to this chap:
http://www.mikeduncan.com/sqlite-on-dotnet-in-3-mins/
Updated Jan 5 2009:
We actually have this rolled out to our shared (partial trust) hosting environment and it works really well according to early customer feedback.


q: I'd like to get comments from people who have used or evaluated Coverity for statically analysing Java-code. I know it's popular in C/C++ world, but is it worth spending the money for Java analysis or am I better off with PMD, Findbugs and other Open Source tools?

[A]
I'll chip in with a somewhat relevant answer. I've used Klocwork for the both Java and C code. Klocwork is a close competitor of Coverity... cost-wise they are about the same ( look carefully, Klocwork looks cheaper until you actually buy what you need ), and feature-wise they fight back and forth.
For C/C++, it's great. For Java.... well, it helped find a lot of resource leaks ( #$@^#ing Java developers seem to forget that resources like file handles aren't garbage collected ), but it doesn't seem to find many "critical" bugs. It's probably because the language itself does help protect against some of the more basic but hard to find errors ( array overflows, pointer corruption, etc ).
Get Coverity in to run a demo, they are more than happy to. See what sort of things they find.


q:
If I safe an Array and reload it, is there a possibility to get the size if its unknown?
Thanks

[A]
What do you mean by "unknown"? You can get the length of any java array with the length field.
```
```
int[] myArray = deserializeSomeArray();
int size = myArray.length;
```
```


q:
A TextBox is set to AutoPostback as changing the value should cause a number of (display-only) fields to be recalculated and displayed.

That works fine.

However, when the field is tabbed out of, the focus briefly moves on to the next field, then disappears when the page is redrawn so there is no focus anywhere.

I want the focus to be on the new field, not the textbox I've just changed.
Is there a way to work out which field had the focus and force it to have it again when the page is redrawn?

[A]
This is "by design". If you are using ASP.NET 2.0+ you can try calling the Focus method of your TextBox once the postback occurs (preferably in the TextChanged event of the TextBox).
I am not sure if there is any built-in way to track focus but I found
this
article in CodeProject which should do the trick.


q:
How can ALTER be used to drop a column in a MySQL table if that column exists?

I know I can use ALTER TABLE my_table DROP COLUMN my_column, but that will throw an error if my_column does not exist. Is there alternative syntax for dropping the column conditionally?

I'm using MySQL version 4.0.18.

[A]
For MySQL, there is none:
MySQL Feature Request
.
Allowing this is arguably a really bad idea, anyway:
```
IF EXISTS
```
indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.
But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.
MariaDB also supports the following starting with 10.0.2:
```
```
DROP [COLUMN] [IF EXISTS] col_name
```
```
i. e.
```
```
ALTER TABLE my_table DROP IF EXISTS my_column;
```
```
But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.


q:
I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me?

At the moment I am doing:

SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
    qDebug("lynxThreeFile::readSlideInfoHeader");
}

but what I want is something generic:

SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
    qDebug(this.className() + "::" + this.functionName());
}

[A]
"
```
__FUNCTION__
```
" is supported by both MSVC and GCC and should give you the information you need.


q:
Given an SQLConnection object how can you get a schema for a single table?

I seemed to be able to get the schema from a DataSet which I'd gotten from running a query, but all the schema info I could get from the connection seemed to be related to what tables were available and not the actual details on the tables.

[A]
I think accessing the schema from the query (via GetSchemaTable) is the only way to do it.
You can run a query which returns no rows (select * from table where 1=2) if the schema is all you're interested in.
You should use the KeyInfo CommandBehaviour to execute the source query, as otherwise not all the information returned is guaranteed to be accurate
```
```
Command.ExecuteReader(CommandBehavior.KeyInfo)
```
```


q:
Has anyone seen a good twin slider control for .Net (Win forms or WPF).

I'm looking for something that will allow me to select a range from within a set so the first slider would be the start of the range and the second would be the end.

I remember seeing a Swing double slider but it was 6 years ago and I can't for the life of me remember who made it. It was open source though.

[A]
Devexpress have a good one:
The RangeTrackBarControl control extends the functionality provided by the TrackBarControl enabling end-users to select a range of values. Two sliders can be used to set the minimum and maximum values:
alt text http://www.devexpress.com/Help/XtraEditors/img/RangeTrackBarControl.png
you can get them free from:
http://www.devexpress.com/Products/Free/WebRegistration/
hope this helps!


q:
I'm trying to have my Struts2 app redirect to a generated URL. In this case, I want the URL to use the current date, or a date I looked up in a database. So /section/document becomes /section/document/2008-10-06

What's the best way to do this?

[A]
I ended up subclassing Struts'
```
ServletRedirectResult
```
and overriding it's
```
doExecute()
```
method to do my logic before calling
```
super.doExecute()
```
. it looks like this:
```
```
public class AppendRedirectionResult extends ServletRedirectResult {
   private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

  @Override
  protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    String date = df.format(new Date());
    String loc = "/section/document/"+date;
    super.doExecute(loc, invocation);
  }
}
```
```
I'm not sure if this is the best way to do it, but it works.


q: I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect SERVER['argc'], but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.

[A]
I think
```
```
$_SERVER['REMOTE_ADDR']
```
```
will not be populated from the CLI.
Also, all the HTTP_* keys in the $_SERVER superglobal won't be populated from the CLI, or do it the right way hop just mentioned :-)


q:
This is a question you can read everywhere on the web with various answers:

$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

$exts = split("[/\\.]", $filename);
$n    = count($exts)-1;
$ext  = $exts[$n];

etc.

However, there is always "the best way" and it should be on Stack Overflow.

[A]
```
pathinfo()
```
```
```
$path_info = pathinfo('/foo/bar/baz.bill');

echo $path_info['extension']; // "bill"
```
```


q:
Besides open-sourcing your project and legislation, are there ways to prevent, or at least minimize the damages of code leaking outside your company/group?

We obviously can't block Internet access (to prevent emailing the code) because programmer's need their references. We also can't block peripheral devices (USB, Firewire, etc.)

The code matters most when it has some proprietary algorithms and in-house developed knowledge (as opposed to regular routine code to draw GUIs, connect to databases, etc.), but some applications (like accounting software and CRMs) are just that: complex collections of routine code that are simple to develop in principle, but will take years to write from scratch. This is where leaked code will come in handy to competitors.

As far as I see it, preventing leakage relies almost entirely on human process. What do you think? What precautions and measures are you taking? And has code leakage affected you before?

[A]
You can't stop it getting out. So two solutions - stop people wanting to hurt you, and have legal precautions. To stop people hating you treat them right (saying more is probably off topic for stack overflow).
I'm not a lawyer, but to give yourself legal protection, if you believe in it, patent the ideas, put a copyright notice in the code, and make sure the contracts for your programmers specify carefully intellectual property rights.
But at the end of the day, the answer is run quicker than the competition.


q:
Please consider this example class:

[Serializable]
public class SomeClass
{
    private DateTime _SomeDateTime;

    public DateTime SomeDateTime
    {
        get { return _SomeDateTime; }
        set { _SomeDateTime = value; }
    }
}

I would like to alter the serialization of any DateTime declared in the class according to my own rules. The members of this class will change frequently and I don't want to maintain a custom serializer for every change. Also I would like this behaviour to be inherited by subclasses and not code a custom serializer for every one. The serialization is being output by a web service. Thanks for any help!

[A]
Have you thought about simply using a Nullable date time
```
```
public DateTime? SomeDateTime {get; set;}
```
```
This way you can actually have a null value as a legitimate value in your class. Typically you want to avoid custom serialization whenever possible. Once you do custom serialization such as implementing
ISerializable
, then you are stuck with it, and all other derived classes are stuck with it.
Remember what a pain in the butt it is to have to always override the ISerializable members for custom exceptions? This is because System.Exception implements ISerializable and therefore all derived exceptions (that means everything) must implement those members if you ever expect them to cross AppDomains.


q:
When merging topic branch "B" into "A" using git merge, I get some conflicts. I know all the conflicts can be solved using the version in "B".

I am aware of git merge -s ours. But what I want is something like git merge -s theirs.

Why doesn't it exist? How can I achieve the same result after the conflicting merge with existing git commands? (git checkout every unmerged file from B)

The "solution" of just discarding anything from branch A (the merge commit point to B version of the tree) is not what I am looking for.

[A]
I solved my problem using
```
```
git checkout -m old
git checkout -b new B
git merge -s ours old
```
```


q:
I have developed a Windows CE 4.2 Application in VS 2003. When i deploy the CAB file in the device having X86 has its processor, a short cut for the application is created in Start >> Program >> Application. But I want a short cut for the application on the
desktop.

I modified the INF file to add a new shortcut that points to the desktop folder inside windows folder but it didn't work. Also, If i replace the default shortcut created when I build the CAB file with the location of desktop it still creates a short cut in the Programs and not on the desktop.

Does anyone has a solution for this ?

[A]
I would check out the link:
http://msdn.microsoft.com/en-us/library/ms938387.aspx
That should get you well on your way. Basically shortcuts in CE are just ASCII files of the format:
21#\Windows\solitare.exe
Where 21# is the number of characters in that path. Here's another link to MSDN with more info on that:
http://msdn.microsoft.com/en-us/embedded/aa731295.aspx
Hope that helps!


q:
As a function argument I get a vector<double>& vec (an output vector, hence non-const) with unknown length and values. I want to initialise this vector to a specific length n with all zeroes.

This will work

vec.clear();
vec.resize( n, 0.0 );

And this will work as well:

vec.resize( n );
vec.assign( n, 0.0 );

Is the second more efficient (because no memory deallocation/allocation is involved)? Is there a more efficient way to do this?

[A]
```
```
std::vector<double>(n).swap(vec);
```
```
This has the advantage of actually compacting your vector too. (In your first example,
```
clear()
```
does not guarantee to compact your vector.)


q:
How do you trigger a javascript function using actionscript  in flash?

The goal is to trigger jQuery functionality from a flash movie

[A]
Take a look at the
ExternalInterface
-Class.
From the AS3-Language Reference:
The ExternalInterface class is the
  External API, an application
  programming interface that enables
  straightforward communication between
  ActionScript and the Flash Player
  container– for example, an HTML page
  with JavaScript. Adobe recommends
  using ExternalInterface for all
  JavaScript-ActionScript communication.
And it's work like this:
```
```
ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript);
ExternalInterface.call("sendToJavaScript", input.text);
```
```
You can submit parameters and recieve callbacks...pretty cool, right? ;)
As I know it will also work on AS2...


q:
Assuming I have an ArrayList

ArrayList<MyClass> myList;

And I want to call toArray, is there a performance reason to use

MyClass[] arr = myList.toArray(new MyClass[myList.size()]);

over

MyClass[] arr = myList.toArray(new MyClass[0]);

?

I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.

Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...

[A]
Using 'toArray' with the array of the correct size will perform better as the alternative will create first the zero sized array then the array of the correct size. However, as you say the difference is likely to be negligible.
Also, note that the javac compiler does not perform any optimization. These days all optimizations are performed by the JIT/HotSpot compilers at runtime. I am not aware of any optimizations around 'toArray' in any JVMs.
The answer to your question, then, is largely a matter of style but for consistency's sake should form part of any coding standards you adhere to (whether documented or otherwise).


q:
In C#, does anybody know why the following will compile:

int i = 1;
++i;
i++;

but this will not compile?

int i = 1;
++i++;

(Compiler error: The operand of an increment or decrement operator must be a variable, property or indexer.)

[A]
My guess: to avoid such ugly and unnecessary constructs. Also it would use 2 operations (2x INC) instead of one (1x ADD 2).
Yes, i know ... "but i want to increase by two and i'm a l33t g33k!"
Well, don't be a geek and write something that doesn't look like an inadvertent mistake, like this:
```
```
i += 2;
```
```


q:
Is entity framework just a fancy name for another CRUD code generator?

Or is there more to it?

[A] They changed the switch statement (from C/Java/C++) behavior for c#.  I guess the reasoning was that people forgot about the fall through and errors were caused.  One book I read said to use goto to simulate, but this doesn't sound like a good solution to me.


q:
I'm starting on a project that I expect will include a substantial amount of non-Java code (mostly shell and SQL scripts).

I would still like to manage this project with Maven. What are the best practices wrt non-Java source code and Maven? Where should the source go? What happens to them during the different lifecycle phases? Any pointers or links to more information would be greatly appreciated.

[A]
You must not put the non-Java code into resources, if you don't want to include these files into your JAR files like heckj has suggested. Everything that is located in resources is automatically copied into the JAR file and I guess you don't want shell scripts and SQL scripts be included in a JAR file, right?
So the Maven way would be to create additional folders under src/main. E.g. create a
sql
folder for your SQL scripts, an
sh
folder for your shell scripts and so on. This is the location where other Maven plugins also expect sources, e.g. for C++, Groovy and so on.


q:
Is Oracle Application Express suitable for Intranet client/server application?
If so, what should I do to enable client access to application?

Well, I am working as a PowerBuilder/Oracle developer, so I am familiar with client/server architecture. I have recently read an article about APEX so I would like to develop APEX variation of my PowerBuilder/Oracle app, which is pretty much HR app. It should not be Internet accessible app, just a couple of windows boxes in a small network. I have no problem with developing app in PL/SQL and SQL (will have to read and ask a lot, though). I would just like to know is APEX suitable for Intranet app - it should be as it is suitable for Internet app :) - and how should I enable client's browser to access an application since there would be nothing like  http:/www.appdomain.com ? I know next to nothing about win networks :)

[A]
Application Express applications are accessed via a URL in a browser, with a URL something like:
```
```
http://www.mydomain.com/pls/mydad/f?p=MYAPP
```
```
A client/server application would have to launch a browser window and pass in the appropriate URL.


q:
I have a Rails application for project management where there are Project and Task models. A project can have many tasks, but a task can also have many tasks, ad infinitum.

Using nested resources, we can have /projects/1/tasks, /projects/1/tasks/new, /projects/1/tasks/3/edit etc.

However, how do you represent the recursive nature of tasks RESTfully? I don't want go another level deep, so perhaps the following would do:

map.resources :tasks do |t|
    t.resources :tasks
end

That would give me the following urls:

/tasks/3/tasks/new
/tasks/3/tasks/45/edit

Or perhaps when it comes to an individual task I can just use /tasks/45/edit

Is this a reasonable design?

Cam

[A]
there's no reason they should have decendant URLS.
logically:
```
/projects/1  --> project 1
/projects/1/edit ( etc )
/tasks/1     --> task 1
/project/1/tasks --> task list for project 1
/project/1/tasks/new
/project/1/tasks/1/edit ->  /tasks/5/edit ( redundancy )
/project/1/tasks/1 -> redirect to /tasks/1
/tasks/1/project -> redirect to /projects/1
/tasks/3/tasks --> list of tasks that are children tasks of task 3
/tasks/3/tasks/5 -> redirect /tasks/5/    ( because you don't really need to have a recursive URL )
/tasks/5/parents -> list of tasks that are parents of tasks 3
/tasks/5/parents/3 -> redirect /tasks/3/
```
there's no reason IMHO to require the URLs be associative, you're not going to need to know that task 5 is a child of task 3 to edit task 5.


q:
With the new approach of having the get/set within the attribut of the class like that :

public string FirstName {
        get; set;
    }

Why simply not simply put the attribute FirstName public without accessor?

[A]
Because, in the future, if you change the implementation, code using the current interface won't break.
For instance, you implement a simple class with a public field and start using your class in some external modules. A month later you discover you need to implement lazy loading in that class. You would then need to transform the field to a property. From the external module point of ciew, it might look the same syntaxicaly, but it is not. A property is a set of functions, while a field is an offset in a class instance.
By using a property, you effectively reduce the risk the interface will change.


q:
Basically I'm trying to accomplish the same thing that "mailto:bgates@microsoft.com" does in Internet Explorer Mobile.

But I want to be able to do it from a managed Windows Mobile application. I don't want to send an email pro grammatically in the background.

I want to be able to create the email in Pocket Outlook and then let the user do the rest.

Hopefully that helps you hopefully help me!

[A]
I assume you use C#. You add a reference to System.Diagnostics and then write the following code:
```
```
ProcessStartInfo psi =
  new ProcessStartInfo("mailto:bla@bla.com?subject=MySubject", "");
Process.Start(psi);
```
```
This will start the default email client on your mobile device.
The
mailto protocol definition
might come handy too.


q:
I have inherited a c# class 'Button' (which I can't change) which clashes with the BCL class 'Windows.Forms.Button'. Normally, Id be very happy to go:

MyPackage.MyClass.Button;

But there are a large number or references to this class which is a pain to have to re-type.

Is there any way to get the compiler (linker?) to default to using the customised version of Button over the BCL version?

[A]
You could remove
```
using Windows.Forms;
```
from the top of the code. That would of course mean that you would have to reference all Windows.Forms items specifically.


q:
This may be simple one, but 5 mins of Googling didn't give me the answer.
How do you save and load bitmaps using .Net librabries?

I have an Image object and I need to save it to disk in some format (preferably png) and load back in later.
A C# example would be great.

[A]
About 10 seconds of google lead me to
this example
for the save method, you can dig around a bit more for the others.


q:
I'm building an interface much like the built-in Weather application's flipside view, or the Alarms view of the Clock application in editing mode. The table view is always in editing mode, so the delete icon appears on the left side of each cell.

When the table view is in editing mode, my delegate doesn't receive didSelectRowAtIndexPath notifications. It receives accessoryButtonTappedForRowWithIndexPath notifications, but that's not what I want to do. I want my rows to stay selectable, even when the table view is in editing mode.

Any ideas on how I can accomplish this?

Thanks,

P.S. Hooray for the lifted NDA. =)

[A]
Set
```
table.allowsSelectionDuringEditing
```
to
```
YES
```
.


q:
I would like to know how much disk space a directory is going to consume before I bring it over from the Perforce server.  I don't see any way to do this other than getting the files and looking at the size of the directory in a file manager.  This, of course, defeats the purpose.

Is there a way to get file size info from Perforce without actually getting the files?


q: What are the relative merits of the xdoc and apt formats for writing websites of Maven projects? Is one more expressive than the other? Has one got better tool support than the other?

[A]
The XDOC format is definitely a richer mechanism for creating documents and is required if you want to produce documents with TOC/TOF, headers, footers or footnotes (and other document attributes), since the APT format doesn't support these.
That being said, I tend to use the APT format for almost all internal documents as I enjoy writing in the APT format.  When compared to writing XDOC (with all its XML loveliness), APT is a breeze.  By the same token, when I'm writing a plugin that generates content, I tend to use the XDOC format, since it's pretty easy to write software that creates the required XML.


q: Will content requested over https still be cached by web browsers or do they consider this insecure behaviour?  If this is the case is there anyway to tell them it's ok to cache?

[A]
By default web browsers should cache content over HTTPS the same as over HTTP, unless explicitly told otherwise via the
HTTP Headers
received.
This link
is a good introduction to setting cache setting in HTTP headers.
is there anyway to tell them it's ok to cache?
This can be achieved by setting the
```
max-age
```
value in the
```
Cache-Control
```
header to a non-zero value, e.g.
```
```
Cache-Control: max-age=3600
```
```
will tell the browser that this page can be cached for 3600 seconds (1 hour)


q:
It seems that when I use a tool (such as winmerge) to update my codebase... my Visual Studio Team System (VSTS) integration with Team Foundation Server (TFS) doesn't seem to pick it up.

How do I know which files to check out and check back in? Is there something I am missing? Is this a feature that isn't part of VSTS & TFS?

[A]
First, this is probably because the files have not yet been checked out.  If you do that first before running your update, TFS will see those changes.
Second, you can use TFS Power Tools (available from MS) to review local repository for changes that are not recognized.  If there are found differences, power toys resets the status of the file so Pending Changes window sees the change.  this does not require you to check-out the files, it will do that for you if there are differences.
Pretty nifty.
Power Tools for 2008 is here:
http://www.microsoft.com/en-us/download/details.aspx?id=15836
and you are looking for the "Online" command:
"Online Command - Use the online command to create pending edits on writable files that do not have pending edits."


q:
I am using my own db for phpbb3 forum, and I wish to insert some data from the forum into my own tables. Now, I can make my own connection and it runs my query but in trying to use the $db variable(which I think is what you're meant to use??) it gives me an error.

I would like someone to show me the bare bones which i insert my query into to be able to run it.

[A]
Well.. You haven't given us very much information, but there are two things you need to do to connect and query to a database.
For phpbb, you may want to read the documentation they have presented:
http://wiki.phpbb.com/Database_Abstraction_Layer
Here is a general overview of how you'd execute a query:
```
```
include($phpbb_root_path . 'includes/db/mysql.' . $phpEx);

$db = new dbal_mysql();
// we're using bertie and bertiezilla as our example user credentials. You need to fill in your own ;D
$db->sql_connect('localhost', 'bertie', 'bertiezilla', 'phpbb', '', false, false);

$sql = "INSERT INTO (rest of sql statement)";

$result = $db->sql_query($sql);
```
```


q:
Within a spring webflow, i need to implement a navigation bar that will allow to "step back" or resume the flow to one of the previous view.

For example :

View 1 = login

View 2 = My informations

View 3 = My messages

View 4 = Close session

For this example, i would like to return back to view 2 from the view 4 page.

[A]
It depends how you're going about doing this.  If you're doing this within a single flow, you'll have something like this:
```
```
<view-state id="loginView" view="login.jsp">
    <action-state bean="someBean" method="login" />
    <transition on="success" to="informationView" />
</view-state>

<view-state id="informationView" view="information.jsp">
    <render-actions>
        <action-state bean="someBean" method="retrieveInformation" />
    </render-actions>
    <transition on="forward" to="messageView" />
    <transition on="back" to="loginView" />
</view-state>

<view-state id="messageView" view="message.jsp">
    <render-actions>
        <action-state bean="someBean" method="retrieveMessage" />
    </render-actions>
    <transition on="forward" to="closeView" />
    <transition on="back" to="informationView" />
</view-state>

<view-state id="closeView" view="logout.jsp">
    <transition on="jumpBack" to="informationView" />
</view-state>
```
```
The "jumpBack" transition on "closeView" will jump you back to view state #2, which is your information view.
With sub-flows it is tricky.  You'd need to chain it: call a subflow, and if an event is signaled that states you need to end your flow with a specific state, immediately do so.
For example, say that your flow chain is login->information->message->close.
On the close flow, the end-state would be "returnToInformation".
The message flow has a transition on="returnToInformation" to="returnToInformation".
"returnToInformation" is also an end-state in the message flow.
Then, the information flow has a transition on="returnToInformation" to="displayInformationPage", which would then re-display the information page.


q:
I am trying to match floating-point decimal numbers with a regular expression.  There may or may not be a number before the decimal, and the decimal may or may not be present, and if it is present it may or may not have digits after it.  (For this application, a leading +/- or a trailing "E123" is not allowed).  I have written this regex:

/^([\d]*)(\.([\d]*))?$/

Which correctly matches the following:

1
1.
1.23
.23

However, this also matches empty string or a string of just a decimal point, which I do not want.

Currently I am checking after running the regex that $1 or $3 has length greater than 0.  If not, it is not valid.  Is there a way I can do this directly in the regex?

[A]
I think this will do what you want.  It either starts with a digit, in which case the decimal point and digits after it are optional, or it starts with a decimal point, in which case at least one digit is mandatory after it.
```
```
/^\d+(\.\d*)?|\.\d+$/
```
```


q:
This PHP code...

207    if (getenv(HTTP_X_FORWARDED_FOR)) {
208        $ip   = getenv('HTTP_X_FORWARD_FOR');
209        $host = gethostbyaddr($ip);
210    } else {
211        $ip   = getenv('REMOTE_ADDR');
212        $host = gethostbyaddr($ip);
213    }

Throws this warning...

Warning: gethostbyaddr()
  [function.gethostbyaddr]: Address is
  not in a.b.c.d form in C:\inetpub...\filename.php on line 212

It seems that $ip is blank.

[A]
Why don't you use
```
```
$_SERVER['REMOTE_ADDR']
```
```
and
```
```
$_SERVER['HTTP_X_FORWARDED_FOR']
```
```


q:
In my vb.net program, I am using a webbrowser to show the user an HTML preview.  I was previously hitting a server to grab the HTML, then returning on an asynchronous thread and raising an event to populate the WebBrowser.DocumentText with the HTML string I was returning.

Now I set it up to grab all of the information on the client, without ever having to hit the server, and I'm trying to raise the same event.  I watch the code go through, and it has the HTML string correct and everything, but when I try to do

browser.DocumentText = _emailHTML

the contents of DocumentText remain as "<HTML></HTML>"

I was just wondering why the DocumentText was not being set.  Anyone have any suggestions?

[A]
Try the following:
```
```
browser.Navigate("about:blank");
HtmlDocument doc = browser.Document;
doc.Write(String.Empty);
browser.DocumentText = _emailHTML;
```
```
I've found that the
```
WebBrowser
```
control usually needs to be initialized to
```
about:blank
```
anyway. The same needs to be done between navigates to different types of content (like text/xml to text/html) because the renderer is different (mshtml for text/html, something else for text/xml).
See Also
:
C# 2.0 WebBrowser control - bug in DocumentText?


q:
I'm having trouble figuring out how to access a cookie from a compiled object. I'm trying to make a compiled (DLL) object that will check the users cookie and then compare that to a database to confirm they have the correct access.

I can pass in the cookie info fine and the component will work, but I'm trying to have the component check the users cookie as well. I'm not even sure what object to use. I've been searching all weekend and I've seen references to httprequest, httpcookie, cookie, and cookiecollection.

I can look up cookie values on the page itself using Request.Cookies("inet")("user_id") but this doesn't work in the component.

[A]
Objects (App_Code/ compiled dlls) can only access Request via the static HttpContext.Current object
```
```
HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieName"];
```
```
(If it's not called from a web app, HttpContext.Current is null, so you may want to check for that when running in unit testing)
(If this isn't App_Code, you'll need to reference System.Web)


q:
I have about 200 Excel files that are in standard Excel 2003 format.

I need them all to be saved as Excel xml - basically the same as opening each file and choosing Save As... and then choosing Save as type: XML Spreadsheet

Would you know any simple way of automating that task?

[A]
You could adapt the code I posted here:
http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/01/loading-office-documents-in-net.aspx
It shows how to save as PDF (Word is shown in the blog, but if you download the solution, it has code for Excel and PPT).
You need to find the function for saving as the new format instead of exporting (probably the easiest way is to record a macro of yourself doing it in Excel and then looking at the code).


q:
I have a table that records a sequence of actions with a field that records the sequence order:

user    data    sequence
1       foo     0
1       bar     1
1       baz     2
2       foo     0
3       bar     0
3       foo     1

Selecting the first item for each user is easy enough with WHERE sequence = '0' but is there a way to select the last item for each user in SQL?

The result I am after should look like this:

user    data    sequence
1       baz     2
2       foo     0
3       foo     1

I'm using MySQL if there are any implementation specific tricksters answering.

[A]
This sql will return the record with the highest sequence value for each user:
```
```
select a.user, a.data, a.sequence
from table as a
    inner join (
        select user, max(sequence) as 'last'
        from table
        group by user) as b
    on a.user = b.user and
       a.sequence = b.last
```
```


q: What is the simplest way (least error-prone, least lines of code, however you want to interpret it) to open a file in C and read its contents into a string (char*, char[], whatever)?

[A]
I tend to just load the entire buffer as a raw memory chunk into memory and do the parsing on my own. That way I have best control over what the standard lib does on multiple platforms.
This is a stub I use for this. you may also want to check the error-codes for fseek, ftell and fread. (omitted for clarity).
```
```
char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");

if (f)
{
  fseek (f, 0, SEEK_END);
  length = ftell (f);
  fseek (f, 0, SEEK_SET);
  buffer = malloc (length);
  if (buffer)
  {
    fread (buffer, 1, length, f);
  }
  fclose (f);
}

if (buffer)
{
  // start to process your data / extract strings here...
}
```
```


q:
I recently inherited a database on which one of the tables has the primary key composed of encoded values (Part1*1000 + Part2).

I normalized that column, but I cannot change the old values.
So now I have

select ID from table order by ID
ID
100001
100002
101001
...

I want to find the "holes" in the table (more precisely, the first "hole" after 100000) for new rows.

I'm using the following select, but is there a better way to do that?

select /* top 1 */ ID+1 as newID from table
where ID > 100000 and
ID + 1 not in (select ID from table)
order by ID

newID
100003
101029
...

The database is Microsoft SQL Server 2000. I'm ok with using SQL extensions.

[A]
```
```
SELECT (ID+1) FROM table AS t1
LEFT JOIN table as t2
ON t1.ID+1 = t2.ID
WHERE t2.ID IS NULL
```
```


q:
How can you depend on test code from another module in Maven?

Example, I have 2 modules:

Base

Main

I would like a test case in Main to extend a base test class in Base.  Is this possible?

Update: Found an acceptable answer, which involves creating a test jar.

[A]
Yep ... just include the Base module as a dependency in Main.  If you're only inheriting test code, then you can use the scope tag to make sure Maven doesn't include the code in your artifact when deployed.  Something like this should work:
```
```
<dependency>
    <groupId>BaseGroup</groupId>
    <artifactId>Base</artifactId>
    <version>0.1.0-SNAPSHOT</version>
    <scope>test</scope>
</dependency>
```
```


q:
If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that?  Or is it not possible?

This is for any database claiming to support SQL, I'm simply looking for an SQL-specific query that will work regardless of actual database implementation.

[A]
Specifically for SQL Server, use
```
sp_rename
```
```
```
USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO
```
```


q: In Eclipse, I often include all project-related material (including documents in PDF, Microsoft, and OpenDocument formats) in the project. Is this possible with Visual Studio, especially to the point where if I attempt to open the file from inside Visual Studio, it will open in the external application?

[A]
Yes, just right-click your project in the solution explorer and goto Add > Existing Item...
Though -- I'd recommend making a new folder to keep this in.
Yes, you can make sure that when you open it it opens with the correct application.  Just right-click the file once it's added into the solution explorer and select Open With... and make sure you set the default application that way from that point forward you can just double-click your files.
If you have access to use Sharepoint Services with your source control than that would also make life much easier, thanks for reminding me Chris!


q: What is the difference between ROWNUM and ROW_NUMBER  ?

[A]
ROWNUM is a "pseudocolumn" that assigns a number to each row returned by a query:
```
```
SQL> select rownum, ename, deptno
  2  from emp;

    ROWNUM ENAME          DEPTNO
---------- ---------- ----------
         1 SMITH              99
         2 ALLEN              30
         3 WARD               30
         4 JONES              20
         5 MARTIN             30
         6 BLAKE              30
         7 CLARK              10
         8 SCOTT              20
         9 KING               10
        10 TURNER             30
        11 FORD               20
        12 MILLER             10
```
```
ROW_NUMBER is an analytic function that assigns a number to each row according to its ordering within a group of rows:
```
```
SQL> select ename, deptno, row_number() over (partition by deptno order by ename) rn
  2  from emp;

ENAME          DEPTNO         RN
---------- ---------- ----------
CLARK              10          1
KING               10          2
MILLER             10          3
FORD               20          1
JONES              20          2
SCOTT              20          3
ALLEN              30          1
BLAKE              30          2
MARTIN             30          3
TURNER             30          4
WARD               30          5
SMITH              99          1
```
```


q:
I am trying to get in place editing working but I am running into this error:

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken)

I understand that rails now wants to protect against forgery and that I need to pass a form authenticity token but I am not clear on how to do this with the in_place_edit plugin.

[A]
This isn't a
complete
tested answer, but I took a look at the
plugin code
, and it looks like you could use the
```
:with
```
option to tack the authenticity token onto the end of the request parameters.  Something along the lines of:
```
```
in_place_editor("my_element", :with => "form.serialize() + '&authenticity_token=#{form_authenticity_token}';")
```
```
(I have not tested the above code).


q:
I'd like to  use the Wiimote (accelerometers, gyroscopes, infrared camera, etc, etc, etc) on various applications.

It's a bluetooth device, and I know others have connected it to their computer.

What's the easiest way to start using it in my software - are there libraries for C#, for instance?

I want my software to be usable and easily installable - what's the current easiest way to connect a wiimote to the computer?  Can I make that process part of my software installation?

-Adam

[A]
Coding4Fun had a managed C# library up that would allow you to interface with it but it seems their site is down right now.  Though I think they used the Robotics Studio so that may be a place to start.
Found it...
http://www.codeplex.com/WiimoteLib
Oh and I forgot to post a link to these videos I saw quite some time ago.
http://www.cs.cmu.edu/~johnny/projects/wii/


q:
Oracle FAQ defines temp table space as follows:

Temporary tablespaces are used to
  manage space for database sort
  operations and for storing global
  temporary tables. For example, if you
  join two large tables, and Oracle
  cannot do the sort in memory, space
  will be allocated in a temporary
  tablespace for doing the sort
  operation.

That's great, but I need more detail about what exactly is using the space. Due to quirks of the application design most queries do some kind of sorting, so I need to narrow it down to client executable, target table, or SQL statement.

Essentially, I'm looking for clues to tell me more precisely what might be wrong with this (rather large application). Any sort of clue might be useful, so long as it is more precise than "sorting".

[A]
I'm not sure exactly what information you have to hand already, but using the following query will point out which program/user/sessions etc are currently using your temp space.
```
```
SELECT   b.TABLESPACE
       , b.segfile#
       , b.segblk#
       , ROUND (  (  ( b.blocks * p.VALUE ) / 1024 / 1024 ), 2 ) size_mb
       , a.SID
       , a.serial#
       , a.username
       , a.osuser
       , a.program
       , a.status
    FROM v$session a
       , v$sort_usage b
       , v$process c
       , v$parameter p
   WHERE p.NAME = 'db_block_size'
     AND a.saddr = b.session_addr
     AND a.paddr = c.addr
ORDER BY b.TABLESPACE
       , b.segfile#
       , b.segblk#
       , b.blocks;
```
```
Once you find out which session is doing the damage, then have a look at the SQL being executed, and you should be on the right path.


q:
I have a form that I would like to style. specifcally I would like to chnage the background color of the form item's label. (the backgorundColor attribute changes both the label and the inputs background color)

i.e.

<mx:Form>
    <mx:FormItem label="username:">
        <mx:TextInput />
    </mx:FormItem>
</mx:Form>

I would like to make the label with 'username:' have a different background color, but have the text input still be the default background color.

is this possible with a FormItem ?

[A]
Try using the flex style explorers to create your desired style:
Flex 3 Style Explorer
Flex 2 Style Explorer
I used the TextArea in the style explorer and formatted the background color which gave the following css output:
```
```
TextArea {
   backgroundColor: #0000ff;
}
```
```
You can change this to the following to include in you stylesheet:
```
```
.formLabel {
   backgroundColor: #0000ff;
}
```
```
Then in the FormItem tag:
```
```
<FormItem label="Label" styleName="formLabel" />
```
```
More info on Flex Style Sheets:
Flex Style Sheets
These examples will show that you can declare styles within the mxml Style tags rather than an external style sheet if you would like.


q: just wanted to gather different ideas and perspectives as to which layer should (and why) LINQ fall into?

[A]
I think LINQ should be the very lower-level (DAL) and I think it should be wrapped into a BLL.
I know a lot of people like to use the partial accessibility of the models that LINQ to SQL generates but I think you should have clear separation of interests (see what I did there?).  I think if you're going to have business logic it needs to be decoupled completely from your data access logic.
I think what makes it tricky is the fact that you can keep chaining those LINQ extension methods anywhere you have a using System.Linq line in your code.  Again though I think LINQ belongs with the definition and should be at the lowest possible level.  It also makes TDD/Unit Testing much, much easier when you wrap the usage of LINQ in a BLL.


q: What is a typical estimate for coding unit tests given an estimate for coding new functionality? Is this different for estimates to maintain code?

[A]
My time is about equal between time for unit testing and time for functional code.
Some people would look at this and say that is a waste of time, but if your only other option is to run the app and step through all the possible paths the app can take, then the time spent on unit testing is actually less than the time you would spend on developer testing. Of course if you don't do much developer testing, then you will spend the time in fixing bugs that come back from QA.
Either way the time spent writing unit test actually saves time from the amount I would spend on the project.
When it comes time to maintain the code (slight changes, small additions in functionality), there might be a difference. If the code being changed is already fully covered and your changes do not require changes to the tests, then your time is 0. Otherwise obviously it is not, probably closer to equal again.
But, your time savings in testing time is MUCH larger; you've already created the tests to cover the rest of the code, so you would uncover any incidental changes flowing from your change without any new code or walking the app.


q:
I've got this code:

rs1 = getResults(sSQL1)
rs2 = getResults(sSQL2)

rs1 and rs2 and 2D arrays.  The first index represents the number of columns (static) and the second index represents the number of rows (dynamic).

I need to join the two arrays and store them in rs3.  I don't know what type rs1 and rs2 are though.

[A]
Are you sure that the columns will match up?  Because if that's not the case I don't know how you'd do it in a generic way in any language.  If it is the case, then you could probably do it
very
simply like this:
```
```
rs1 = getResults(sSQL1 & " UNION " sSQL2)
```
```


q:
I've discovered that cElementTree is about 30 times faster than xml.dom.minidom and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.

Can it be done?

[A]
It's not possible AFAIK... which is a pity.  Basically, ElementTree modules assume that the reader is 100% XML compliant, so it shouldn't matter if they output a section as CDATA or some other format that generates the equivalent text.
See
this thread
on the Python mailing list for more info.  Basically, they recommend some kind of DOM-based XML library instead.


q: I'm specifying my doctype as xhtml strict, but it's being sent over the wire as a content type of text/html.  I'd like to specify that the content type is application/xhtml+xm, but I can't figure out where, or if, I can configure this from within my application

[A]
You can specify it in the @ page attributes section, like this:
```
```
<%@ Page ContentType="application/xhtml+xm" %>
```
```
...more on
MSDN
.


q:
How can I get a single keyboard character from the terminal with Ruby without pressing enter?
I tried Curses::getch, but that didn't really work for me.

[A]
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/2999
```
```
#!/usr/bin/ruby

begin
  system("stty raw -echo")
  str = STDIN.getc
ensure
  system("stty -raw echo")
end
p str.chr
```
```
(Tested on my OS X system, may not be portable to all Ruby platforms). See
http://www.rubyquiz.com/quiz5.html
for some additional suggestions, including for Windows.


q:
A colleague once told me that the last option when everything has failed to debug on Linux was to use strace.

I tried to learn the science behind this strange tool, but I am not a system admin guru and I didn’t really get results.

So,

What is it exactly and what does it do?

How and in which cases should it be used?

How should the output be understood and processed?

In brief, in simple words, how does this stuff work?

[A]
strace lists all
system calls
done by the process it's applied to.  If you don't know what system calls mean, you won't be able to get much mileage from it.
Nevertheless, if your problem involves files or paths or environment values, running strace on the problematic program and redirecting the output to a file and then grepping that file for your path/file/env string may help you see what your program is
actually
attempting to do, as distinct from what you expected it to.


q: Is there any IDE for coding mono on windows platform?

[A]
SharpDevelop
and Visual Studio will both work. You can also use the Windows version of
MonoDevelop
.


q:
I create a TextArea in actionscript:

var textArea:TextArea = new TextArea();

I want it to have a black background.  I've tried

textArea.setStyle("backgroundColor", 0x000000);

and I've tried

textArea.opaqueBackground = 0x000000;

but the TextArea stays white.  What should I do?

[A]
TextArea is a UI component built from TextField and other Flash built-in classes and UIComponents. As with most of the Adobe UI components, nothing is as it seems when setting properties. To set the color of the area behind the text in the TextArea, you need to actually set the opaque background of its internal TextField using the textField property:
```
```
var textArea:TextArea = new TextArea()
textArea.textField.opaqueBackground = 0x000000;
```
```
Of course now that the background is black, the text can't also be black, so we change its color using a new TextFormat:
```
```
var myFormat:TextFormat = new TextFormat();
myFormat.color = 0xffffff;
textArea.setStyle("textFormat",myFormat);
```
```
then just set the text and add to stage:
```
```
textArea.text = "hello";
addChild(textArea);
```
```
Also, if you want a little more control, there's a nice extension class here that fixes a lot of the problems with TextArea:
http://blog.bodurov.com/Post.aspx?postID=14


q:
I have this solution for a single button:

myButton.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(myButton).ToString());

Which works pretty well for one button, any ideas on how to expand this to 2 buttons?

[A]
You could add an clientside onSubmit handler, or you could do this:
```
```
myButton.Attributes.Add("onclick", "this.disabled=true; document.getElementById('"
+ button2.ClientID + "').disabled = true;"
+ GetPostBackEventReference(myButton).ToString());
```
```


q:
I could write this, but before I do, I wanted to check to see if there are existing solutions out there since it seems a lot of websites already do this, so I was wondering if there was a quick way to do this.

Also, I am talking about "popout" windows, not "popup" windows.  All JavaScript libraries support "popup" windows, but I want ones where they originally open as "popup" windows in the same browser window, but there is also a link to open them up in a brand new browser window.

[A]
Check out Cappuccino, it's more of a windowing framework than a web 2.0 framework. It's based off of Apples Cocoa, and uses a Superset of Javascript called Objective-J. Superset meaning that any JS is valid, but it extends on the language with additional syntax that is similar to Cocoa and Objetive-C.
http://cappuccino.org


q:
I'm trying to host a PHP web site that was given to me.  I see this warning:

Warning: Unknown: Your script possibly
  relies on a session side-effect which
  existed until PHP 4.2.3. Please be
  advised that the session extension
  does not consider global variables as
  a source of data, unless
  register_globals is enabled. You can
  disable this functionality and this
  warning by setting
  session.bug_compat_42 or
  session.bug_compat_warn to off,
  respectively. in Unknown on line 0

What does this mean?  How might I track down the source of this problem within the code?

[A]
basically you have a variable with the same name as your session. ex:
```
```
$_SESSION['var1'] = null;
$var1 = 'something';
```
```
which will reproduce this error. you can stop PHP from trying to find existing variables and warning you about them by adding these lines to your script:
```
```
ini_set('session.bug_compat_warn', 0);
ini_set('session.bug_compat_42', 0);
```
```
these values can be set in php.ini or .htaccess as well


q: Is there a portable way of getting thread and/or process identifier (string, int, ...) with C++?

[A]
You have a few ways, but all imply the use of an external library abstracting the thread for you.
Among the popular choices, two are:
The
Boost.Thread
library. This is the most portable but imply working with Boost, which is a HUGE library
The
Qt
library. This is less portable and imply to work with Qt, a big library.
If you already use any on these two libraries, I would recommend sticking with it. Otherwise, look at what other tools they provide and make a choice.


q:
I'm doing some research into using log4net, and I found the IObjectRenderer interface interesting.  It would allow us to control how types are logged and provide a different, possibly more user-friendly ToString() implementation.  I just started looking at log4net though, and can't seem to find a logical way to programmatically set up the association between types and renderers.

I found that this can be set up in the XML configuration file by reading the manual, but it didn't give me any hints about programmatically adding these.  It seems to me that you'd rather have a programmatic object renderer in some cases, so I'm curious how to do this.

[A]
I poked around with it some while writing the question and came up with this:
```
```
using System.IO;
using log4net;
using log4net.Config;
using log4net.ObjectRenderer;
using log4net.Util;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            BasicConfigurator.Configure();

            ILog log = LogManager.GetLogger(typeof(Program));
            var repo = LogManager.GetRepository();
            repo.RendererMap.Put(typeof(Foo), new FooRenderer());

            var fooInstance = new Foo() { Name = "Test Foo" };
            log.Info(fooInstance);
        }
    }

    internal class Foo
    {
        public string Name { get; set; }
    }

    internal class FooRenderer : log4net.ObjectRenderer.IObjectRenderer
    {
        public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer)
        {
            if (obj == null)
            {
                writer.Write(SystemInfo.NullText);
            }

            var fooInstance = obj as Foo;
            if (fooInstance != null)
            {
                writer.Write("", fooInstance.Name);
            }
            else
            {
                writer.Write(SystemInfo.NullText);
            }
        }
    }
}
```
```
I am not certain if this is the correct way to do this, but I do know that it worked.


q:
For obvious productivity reasons, I make an effort of learning and using as many of the keyboard shortcuts for the various Re# commands.

However, it seems that the unit test runner does not have any associated shortcut keys. I want to be able to select certain tests and be able to run or debug them without resorting to grabbing the mouse each time. Is using the mouse my only option?

[A]
ReSharper adds items to Visual Studio's keyboard settings dialog box.
Go to:
Tools -> Options, Environment ->
  Keyboard
In the search bar, type "resharper" and see the vast options that you can control with the keyboard.
Specifically, there is one to launch the unit test explorer window, and there's a couple called
ReSharper.ReSharper_UnitTest_RunSolution
ReSharper.ReSharper_UnitTest_RunContext
that are likely what you need.


q:
I am using SimpleTest, a PHP-based unit testing framework. I am testing new code that will handle storing and retrieving website comments from a database. I am at a loss for how to structure the project to test the database access code.

I am looking for any suggestions as to best practices for testing db code in a PHP application. Examples are really great. Sites for further reading are great.

Thank you kindly. :)

[A]
I had a local database dedicated to unit testing with a known name and database username/password.  The unit tests were hard-coded to that location but different developers could override those variables if they wanted.
Then before each test you
```
TRUNCATE
```
each table.  This is
much
faster than dropping/creating tables or the database itself.
Note: Do
not
truncate after the tests!  That way if a test fails you have the current state of the database which often helps diagnose the problem.


q: What function can I use in Excel VBA to slice an array?

[A]
Application.WorksheetFunction.Index(array, row, column)
If you specify a zero value for row or column, then you'll get the entire column or row that is specified.
Example:
Application.WorksheetFunction.Index(array, 0, 3)
This will give you the entire 3rd column.
If you specify both row and column as non-zero, then you'll get only the specific element.
There is no easy way to get a smaller slice than a complete row or column.
Limitation
: There is a limit to the array size that
```
WorksheetFunction.Index
```
can handle if you're using a newer version of Excel. If
```
array
```
has more than 65,536 rows or 65,536 columns, then it throws a "Type mismatch" error. If this is an issue for you, then see
this more complicated answer
which is not subject to the same limitation.
Here's the function I wrote to do all my 1D and 2D slicing:
```
```
Public Function GetArraySlice2D(Sarray As Variant, Stype As String, Sindex As Integer, Sstart As Integer, Sfinish As Integer) As Variant

' this function returns a slice of an array, Stype is either row or column
' Sstart is beginning of slice, Sfinish is end of slice (Sfinish = 0 means entire
' row or column is taken), Sindex is the row or column to be sliced
' (NOTE: 1 is always the first row or first column)
' an Sindex value of 0 means that the array is one dimensional 3/20/09 ljr

Dim vtemp() As Variant
Dim i As Integer

On Err GoTo ErrHandler

Select Case Sindex
    Case 0
        If Sfinish - Sstart = UBound(Sarray) - LBound(Sarray) Then
            vtemp = Sarray
        Else
            ReDim vtemp(1 To Sfinish - Sstart + 1)
            For i = 1 To Sfinish - Sstart + 1
                vtemp(i) = Sarray(i + Sstart - 1)
            Next i
        End If
    Case Else
        Select Case Stype
            Case "row"
                If Sfinish = 0 Or (Sstart = LBound(Sarray, 2) And Sfinish = UBound(Sarray, 2)) Then
                    vtemp = Application.WorksheetFunction.Index(Sarray, Sindex, 0)
                Else
                    ReDim vtemp(1 To Sfinish - Sstart + 1)
                    For i = 1 To Sfinish - Sstart + 1
                        vtemp(i) = Sarray(Sindex, i + Sstart - 1)
                    Next i
                End If
            Case "column"
                If Sfinish = 0 Or (Sstart = LBound(Sarray, 1) And Sfinish = UBound(Sarray, 1)) Then
                    vtemp = Application.WorksheetFunction.Index(Sarray, 0, Sindex)
                Else
                    ReDim vtemp(1 To Sfinish - Sstart + 1)
                    For i = 1 To Sfinish - Sstart + 1
                        vtemp(i) = Sarray(i + Sstart - 1, Sindex)
                    Next i
                End If
        End Select
End Select
GetArraySlice2D = vtemp
Exit Function

ErrHandler:
    Dim M As Integer
    M = MsgBox("Bad Array Input", vbOKOnly, "GetArraySlice2D")

End Function
```
```


q:
Consider the following code:

$("a").attr("disabled", "disabled");

In IE and FF, this will make anchors unclickable, but in WebKit based browsers (Google Chrome and Safari) this does nothing. The nice thing about the disabled attribute is that it is easily removed and does not effect the href and onclick attributes.

Do you have any suggestions on how to get the desired result. Answers must be:

Easily be revertable, since I want to disable form input controls while I have an AJAX call running.

Must work in IE, FF, and WebKit

[A]
I assume that you have an onclick event handler bound to these anchor elements. Just have your event handler check the "disabled" attribute and cancel the event if it is set. Your event handler would look something like this:
```
```
$("a").click(function(event){
  if (this.disabled) {
    event.preventDefault();
  } else {
    // make your AJAX call or whatever else you want
  }
});
```
```
You can also set a stylesheet rule to change the cursor.
```
```
a[disabled=disabled] { cursor: wait; }
```
```
Edit - simplified the "disabled" check as suggested in comments.


q: We are considering using ClearCase Multisite to enable the offshore development team. The other option is the ClearCase Remote Client using the local (onshore) ClearCase installation. Has anyone had experiences using Multisite? Is the synchronization and management hassle worth offshore being able to use the fat client?

[A] That is a good question.  I belive it is worth using multisite so long as you can figure out the mastership of elements.  If an element is mastered at site A  you can't edit it at site B until you have transfered the mastership.  So if each site is working on the same pieces of code then multisite is going to be more trouble than it is worth, if the coverage is disjoint then multisite is a good call.  Clearcase is very chatty on the network and keeping as much local as possible is a good idea.


q:
I use a 3rd party tool that outputs a file in Unicode format.  However, I prefer it to be in ASCII. The tool does not have settings to change the file format.

What is the best way to convert the entire file format using Python?

[A]
I think this is a deeper issue than you realize
. Simply changing the file from Unicode into ASCII is easy, however, getting all of the Unicode characters to translate into reasonable ASCII counterparts (many letters are not available in both encodings) is another.
This Python Unicode tutorial may give you a better idea of what happens to Unicode strings that are translated to ASCII:
http://www.reportlab.com/i18n/python_unicode_tutorial.html
Here's a useful quote from the site:
Python 1.6 also gets a "unicode"
  built-in function, to which you can
  specify the encoding:
```
```
> >>> unicode('hello') u'hello'
> >>> unicode('hello', 'ascii') u'hello'
> >>> unicode('hello', 'iso-8859-1') u'hello'
> >>>
```
```
All three of these return the same
  thing, since the characters in 'Hello'
  are common to all three encodings.
Now let's encode something with a
  European accent, which is outside of
  ASCII. What you see at a console may
  depend on your operating system
  locale; Windows lets me type in
  ISO-Latin-1.
```
```
> >>> a = unicode('André','latin-1')
> >>> a u'Andr\202'
```
```
If you can't type an acute letter e,
  you can enter the string 'Andr\202',
  which is unambiguous.
Unicode supports all the common
  operations such as iteration and
  splitting. We won't run over them
  here.


q:
I am trying to create a custom control that a "gridview" like control but specifcally for business objects that implement certain custom interfaces.

In doing this I have come across the following problem.

I have a control that I have disabled viewstate on (and I don't want to re-enable it) and it has a child control that I want viewstate enabled on.  I can't seem to get the viewstate on the child control to work since its parents is disabled.  Does anyone have any ideas of how to get that to work?

[A]
You cannot enable viewstate on a control which is within another control that has viewstate disabled.
Your only option is to enable it for the outer control, and then turn it off for all of the controls within it, except for the control you need viewstate.
EnableViewState property on any container will override the behavior of all controls within that containter.
Good Luck!
EDIT:
You may want to look at your
CreateChildContols()
method and enumerate the controls disabling viewstate from there for each of the controls within the custom control using the
EnableViewState
property.


q:
Possible Duplicate:

  Internationalization in SSRS

We use SQL Server Reporting Services for our web reports. At the moment, our clients are all in the UK, so for each report, we set the Language property for the report to "English (United Kingdom)".

But now we have US and French clients. So, we'll need to change the language and currency for the French, and the date format and currency for the Americans. We want to keep one set of reports for all our clients.

What is the best way to do this?

[A]
The report will be rendered with the web browsers language in regard to formatting of dates, currencies and so on if the report's language has not been set. See
MSDN documentation
:
If the language of the report is not set, the language of the Web browser is used. If the language of the Web browser is not set, the language of the operating system of the report server is used. For example, if you set a specific language on a text box that displays date information, then that text box is always displayed with the date format for that language even if the report, Web browser or server is set to a different language.


q:
I have a program I've written in VB.NET 2005, it saves statistics in an XML file.

I use this program on multiple computers.   I'd like to set up a webserver where I can upload my XML file, or just the data, and add it to the server ignoring duplicate entries already on the server.

What do I need for to learn for this? SQL?

Any ideas would be appriecated!

[A]
I did something like this a long time ago to send back HFNetChk XML reports from around the world back to a central server.
I set up a service endpoint on the server (webservice, TCP, whatever fits your req's), and had the client app send the finished XML back to the central server when it was done with its processing.  The webserver would send back a "data received OK" message to let the client know it could move on, and then the server would go about processing the data, and entering it from the XML into a SQL database.
So, to answer your question,
learn how to create a WCF service (aim for webservices for now - ASMX is ok if WCF seems to be too much for now), and learn how to parse the incoming XML and insert it into meaningful SQL tables.
/fark can be useful


q: What is the best way to get the names of all of the tables in a specific database on SQL Server?

[A]
```
```
exec sp_msforeachtable 'print ''?'''
```
```


q:
In few months I start a project in PHP and I am hesitating to do like usual : develop on my Windows Vista 64bits machine. Since I know few things on Linux, I think it can be a good way to learn by working on a Linux distribution.

Do you think it's a good idea or not? I would run a VirtualBox with Ubuntu (on my Vista64bits). I was thinking to install XAMPP to be able to develop in PHP.

If you think it's a good idea, feel free to suggest me some tutorial about what I should know with Virtualizing an OS, or Linux/dev.

Update
I have build many website in PHP with Windows, the question is more about if it's a good way to start learning Linux by developing on it via a Virtual machine? I have 4 gigs rams, will it be smooth if I install Eclipse in the Virtual Machine? etc.

[A]
PHP
should
be the same on any platform - so
where
you develop shouldn't matter.
However, in my experience and observation,more sites running PHP are running on Linux than Windows.
Getting Apache and PHP setup on something like Ubuntu or Fedora is a cinch, and testing everything is pretty simple, too.
Also, when you go live with your site, what platform will it be running on? I prefer to do development on the platform it will be running on whenever possible.


q:
How do you prepare your SQL deltas? do you manually save each schema-changing SQL to a delta folder, or do you have some kind of an automated diffing process?

I am interested in conventions for versioning database schema along with the source code. Perhaps a pre-commit hook that diffs the schema?

Also, what options for diffing deltas exist aside from DbDeploy?

EDIT: seeing the answers I would like to clarify that I am familiar with the standard scheme for running a database migration using deltas. My question is about creating the deltas themselves, preferably automatically.

Also, the versioning is for PHP and MySQL if it makes a difference. (No Ruby solutions please).

[A]
See
Is there a version control system for database structure changes?
How do I version my MS SQL database in SVN?
and Jeff's article
Get Your Database Under Version Control
I feel your pain, and I wish there were a better answer.  This might be closer to what you were looking for.
Mechanisms for tracking DB schema changes
Generally, I feel there is no adequate, accepted solution to this, and I roll my own in this area.


q:
What are the main reasons for having ridiculously long export times for a simple flash movie to swf? I have no unnecessary images or symbols, everything possible is set to lower than low and it still takes 10 minutes and upwards to export a 30 second animation at 24 fps. I have even created a new fla and pasted everything in there, to find out if it isn't maybe just a bug in flash. All other animations I've exported take a normal amount of time.

System specifications:
1GB DDR2 RAM
Intel Pentium D 3.4GHz

Should I upgrade my system?

Could it have something to do with having many symbols within symbols?

EDIT: Filesize of fla is 1.3 MB and swf is 500 KB. So not too big.

[A]
unfortunately this is pretty average with flash.
You can check out this post on
actionscript.org
which talks about splitting up your project so save on compile time.
Back in the AS2 days an open source compiler called
MTASC
which dramatically reduced the
compile time
.  It has since turned into
Haxe
with AS2, AS3, Javascript, PHP, and Neko virtual machine all using the same syntax. The syntax used is similar to C++.
** EDIT **
Sorry I read the above as 10 seconds, not 10 minutes... sorry. ^_^


q:
I have an application where whenever a file is uploaded to a directory, I have to call SSIS to parse the XML file.

Can I call a SSIS directly from a .NET Windows service?

[A]
Running SSIS package programmatically
.
I prefer the second method:
Start DTEXEC.EXE process. DTEXEC is command line utility for executing SSIS packages. See its command line options here:
http://msdn2.microsoft.com/en-us/library/ms162810.aspx
Benefits: running package out of process gains reliability. Can be used from any programming language (including .NET 1.1 :)). Easy to pass parameters by setting variables values.
Drawbacks: Also local only. Harder to get information about package progress (but SSIS logging can give you most functionality). Some overhead on starting new process (likely minimal compared to execution time for big packages).
ASP.NET specific: Win32 CreateProcess function ignores the thread impersonation. So if you want DTEXEC to run under account different from ASP.NET process account, you should either make user enter name/password and pass it to Process.Start, or use method described in the following KB to run child process under impersonated account
http://support.microsoft.com/kb/889251
.


q:
I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!

edit:

some clarifications-

the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times

[A]
This is an NP-complete problem, I think, so it'll be impossible to have a very fast algorithm for any large data sets.
There's also the problem where you might have a schedule that is impossible to make. Given that that's not the case, something like this pseudocode is probably your best bet:
```
```
sort players by priority, highest to lowest
start with empty schedule
for player in players:
    for timeslot in player.preferences():
        if timeslot is free:
            schedule.fillslot(timeslot, player)
            break
    else:
        #if we get here, it means this player couldn't be accomodated at all.
        #you'll have to go through the slots that were filled and move another (higher-priority) player's time slot
```
```


q:
How you fix the following Hibernate error:

What does "Use of the same entity name twice".

[A]
I think it means you have declared the same entity in more than one configuration file.
Without more information, I would try commenting out chunks of your config file so that you don't see the error, and then slowly adding sections back in until you encounter the error?
If its only a few config files, then why not post them here? When posting, if you add 4 spaces to the front of your XML, then it will be:
```
```
<xml>nicely formatted</xml>
```
```
Hope this helps.


q:
What are they and how do they work?

Context happens to be SQL Server

[A]
According to
Wikipedia
:
[...] A traditional pipe is "unnamed" because it exists anonymously and persists only for as long as the process is running. A named pipe is system-persistent and exists beyond the life of the process and must be "unlinked" or deleted once it is no longer being used. Processes generally attach to the named pipe (usually appearing as a file) to perform IPC (inter-process communication).


q:
I want completely automated integration testing for a Maven project.  The integration tests require that an external (platform-dependent) program is started before running.  Ideally, the external program would be killed after the unit tests are finished, but is not necessary.

Is there a Maven plugin to accomplish this?  Other ideas?

[A]
You could use the
antrun
plugin. Inside you would use ant's
exec
apply
task.
Something like this.
```
```
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.2</version>
    <executions>
      <execution>
        <phase> <!-- a lifecycle phase --> </phase>
        <configuration>

          <tasks>
            <apply os="unix" executable="cmd">
              <arg value="/c"/>
              <arg value="ant.bat"/>
              <arg value="-p"/>
            </apply>
            <apply os="windows" executable="cmd.exe">
              <arg value="/c"/>
              <arg value="ant.bat"/>
              <arg value="-p"/>
            </apply>
          </tasks>

        </configuration>
        <goals>
          <goal>run</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
```
```
Ant support os specific commands of course through the
condition task
.


q:
I'm working on a project where I have 2 web services that need the same entity. The 2 web services are on the same server so on the back-end, they share the same classes.

On the front-end side, my code consumes both web services and sees the entities from both services as separate (in different namespaces) so I can't use the entity across both services.

Does anyone know of a way to allow this to work in .NET 2.0?

I've done this with my entity:

[XmlType(TypeName = "Class1", Namespace = "myNamespace")]
public class Class1
{
    public int field;
}

Hoping that my IDE would somehow "know" that the class is the same on both web services so that it wouldn't create separate entities for both classes, but no luck.

Is this possible to do with .NET 2.0 web services?

[A]
I'm not sure about the implementation details with .NET 2.0, but I believe what you want to do is put the common classes in a seperate XSD file and refer to it from within your two WSDL's. This way, the common types have the same namespace between the two services.
Now, how you do this in .NET 2.0 I couldn't give you the specifics on...


q:
I have currently 200+ GB database that is using the DB2 built in backup to do a daily backup (and hopefully not restore - lol) But since that backup now takes more than 2.5 hours to complete I am looking into a Third party Backup and Restore utility.  The version is 8.2 FP 14 But I will be moving soon to 9.1 and I also have some 9.5 databases to backup and restore.  What are the best tools that you have used for this purpose?

Thanks!

[A]
It's not a "third-party" product but anyone that I have ever seen using DB2 is using
Tivoli Storage Manager
to store their database backups.
Most shops will set up archive logging to TSM so you only have to take the "big" backup every week or so.
Since it's also an IBM product you won't have to worry about it working with all the different flavors of DB2 that you have.
The downside is it's an IBM product.  :)   Not sure if that ($) makes a difference to you.


q: I know I could just ask, but that would involve bureaucratic entanglements.

[A]
I believe that on an AD network that is DNS enabled the root zone points at all the AD servers.  So, for instance, if your official AD username is joebloe@company.ad, doing an nslookup of company.ad from cmd.exe will tell you all the IPs of the controllers (and hence all the IPs you could use for LDAP).
This is edited to change the zone name, but one my work system:
```
```
C:\Documents and Settings\jj33>nslookup companyname.ad
Server:  palpatine.companyname.ad
Address:  172.19.1.3

Name:  companyname.ad
Addresses:  172.16.3.2, 172.16.6.2, 172.19.1.3, 172.16.7.9
          172.19.1.14, 172.19.1.11
C:\Documents and Settings\jj33>
```
```
On my (XP) machine, this shows me my AD domain:
Right click "My Computer"
Select "Computer Name" tab
See "Domain:" field


q:
How can I represent the following in XSD.

<price-update>
    <![CDATA[
      arbitrary data goes here
    ]]>
</price-update>

[A]
A CDATA tag is merely a means of escaping data as a text node.  Therefore you cannot stipulate that you require a CDATA node.
From a DOM perspective, the following documents are identical:
```
```
<doc>value</doc>
```
```
and
```
```
<doc><![CDATA[value]]></doc>
```
```


q: I'm looking for the class name of the popup/message windows on the iPhone (it's a blueish window that comes up when you have a missed call, or a message comes in for example.)

[A]
The class is called
```
UIAlertView
```
. From the documentation:
Use the UIAlertView class to display an alert message to the user. An alert view functions similar to but differs in appearance from an action sheet (an instance of UIActionSheet).
Use the properties and methods defined in this class to set the title, message, and delegate of an alert view and configure the buttons. You must set a delegate if you add custom buttons. The delegate should conform to the UIAlertViewDelegate protocol. Use the show method to display an alert view once it is configured.


q:
This is something that I have never fully grasped in .NET as to the correct application of the .dispose() method.

Say I have something like

Public Class someClass()
  sub someMethod
    ' do some stuff tying up resources
  end sub
End Class

public class mainApp
  dim _class as new SomeClass
  _class.someMethod()
End Class

In all cases is it good practice to implement a dispose method, and if so what should go in there?

If it is not the case that every class should have dispose method (which my gut feeling says the shouldn't) what classes should? I have always thought anything which may tie up a resource (i.e. connection, datareader etc) should have a .dispose() which would unallocate these resources.

Also how would you enforce a calling into calling the .dispose() method?

[A]
The
```
Dispose()
```
method is used for cleaning up any resources early. Although the garbage collector reclaims any unused memory for you, it's up to you to do deal with things like network/database connections and file handles. Normally, you'd want these things freed up as soon as they're no longer needed, so you implement the disposable pattern and take advantage of the
```
Using
```
statment for calling it within a try/finally block behind the scenes.