Question:
I want to create a bundle from an arbitrary bundle identifier

e.g. com.apple.iokit.IOStorageFamily

It's not an unreasonable thing to do as bundle IDs are supposed

to be unique, however the obvious code does not work:

NSString* bID = @"com.apple.iokit.IOStorageFamily";
NSBundle* bundle = [NSBundle bundleWithIdentifier:bID];

This code only works for bundles you've already loaded

(hello, chicken and egg problem), and in fact, you have

to know a little more than you'd like about the the identifier

before you can do anything. For the above style of ID

I grep out the final component and tranform it into

/System/Library/Extensions/IOStorageFamily.kext

which I then load by path.

Is this the state of the art or is there a more general way?

Answer:
Use this
```
```
NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.TextEdit"];
```
```


Question:
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion?

class MyClass(object):
    def my_function():
        """This docstring works!"""
        return True
    my_list = []
    """This docstring does not work!"""

Answer:
To my knowledge, it is not possible to assign docstrings to module data members.
PEP 224
suggests this feature, but the PEP was rejected.
I suggest you document the data members of a module in the module's docstring:
```
```
# module.py:
"""About the module.

module.data: contains the word "spam"

"""

data = "spam"
```
```


Question:
I am developing a CMS where the clients will need to upload files larger than 2mb - up to 10mb at least. I have changed the details in the php.ini file and I cannot see anywhere else that the problem might be. Any help?

Cheers

Answer:
As long as you have restarted your web service (ie apache) then the changes  should take  effect, however if you are developing for anyone other then yourself then instead of changing the php.ini I would add this to the upload script:
```
```
ini_set('upload_max_filesize', '10M');
```
```
as some people may not be able to modify php.ini this will change it just for the page it is on.


Question:
I'm a new user of Matlab, can you please help:

I have the following code in an .M file:

function f = divrat(w, C)
S=sqrt(diag(diag(C)));
s=diag(S);
f=sqrt(w'*C*w)/(w'*s);

I have stored this file (divrat.M) in the normal Matlab path, and therefore I'm assuming that Matlab will read the function when it's starting and that this function therefore should be available to use.

However, when I type

>> divrat(w, C)

I get the following error

??? Undefined function or method 'divrat' for input arguments of type 'double'.

What is the error message telling me to do, I can't see any error in the code or the function call?

Answer:
The error code indicates the function definition cannot be found. Make sure you're calling the function from the same workspace as the
```
divrat.m
```
file is stored. And make sure
```
divrat
```
function is not a subfunction, it should be first function declaration in the file. You can also try to call the function from the same
```
divrat.m
```
file in order to see if the problem is with workspace selection or the function.
By the way, why didn't you simply say
```
```
s = sqrt(diag(C));
```
```
Wouldn't it be the same?


Question:
I'm using libcurl in a Win32 C++ application.

I have the curllib.vcproj project added to my solution and set my other projects to depend on it.

How do I build it with SSL support enabled?

Answer:
Well, since this post failed badly, I had to dig into the matter myself.
Also check out the other answers and comments for additional info regarding other versions etc.
EDIT: Since I posted this Q there seems to be ready-built binaries made available from the curl homepage. Check out
James' answer
.
So here goes:
-
Preprocessor
The following two symbols need to be fed to the preprocessor to enable SSL for libcurl:
```
```
USE_SSLEAY
USE_OPENSSL
```
```
(libcurl uses OpenSSL for SSL support)
Alternatively the symbols can be added directly to a file called setup.h in libcurl, but I'm not too happy about modifying code in 3rd party distributions unless I really have to.
Rebuilding the libcurl library, I now got some errors about OpenSSL include files not being found. Naturally, since I haven't set up the OpenSSL distribution properly yet.
Compiling OpenSSL binaries
I downloaded the OpenSSL 0.9.8 source distribution and unpacked it.
In the root of the source distribution there's a file called INSTALL.W32 which describes how to compile the OpenSSL binaries. The build chain requires perl, so I installed the latest version of ActivePerl.
I had some trouble with the build, which might not be applicable to all systems, but I'll go through it here in case somebody experiences the same.
According to INSTALL.W32:
Run the following commandline tasks with current directory set to the source distribution root:
```
```
1> perl Configure VC-WIN32 --prefix=c:/some/openssl/dir
```
```
(Where "c:/some/openssl/dir" should be replaced by the dir where OpenSSL should be installed. Don't use spaces in this path. The compilation further ahead will fail in that case)
```
```
2> ms\do_ms
```
```
For me this step was unsuccessful at first, since I lacked the environment variables OSVERSION and TARGETCPU. I set these to
5.1.2600
and
x86
respectively. You may get complaint about OSVERSION being "insane", but look closer, this error is for WinCE and doesn't affect the Win32 setup. To get hold of your OS version, run the 'ver' command from a command prompt or run winver.exe.
```
```
3> nmake -f ms\nt.mak (for static library)
```
```
or
```
```
3> nmake -f ms\ntdll.mak (for DLL)
```
```
The source now compiles. Took approx 5 minutes on my laptop.
When compilation is completed, the libs or binaries have been placed in:
distroot/out32
- for static library build
or
distroot/out32dll
- for DLL build
Building and linking
Now, back to visual studio and point out the libs and include path for headers. The include files are located in
distroot/inc32/openssl
.
Remember to add
libeay32.lib
and
ssleay32.lib
as linker input.
Rebuild the libcurl project.
Error!
Well at least for me with this version of OpenSSL.
it complained about a struct typedef in one of the OpenSSL headers. I couldn't find any info on this. After an hour of googling I broke my own principle and commented out the typedef from the OpenSSL header, and luckily libcurl wasn't using that symbol so it built fine.
Update: As pointed out by Jason, this issue seems to have dissapeared as of version 1.0.0a.
Now, for confirming that SSL support is enabled for libcurl, run the following code:
```
```
curl_version_info_data * vinfo = curl_version_info( CURLVERSION_NOW );
if( vinfo->features & CURL_VERSION_SSL )
    // SSL support enabled
else
    // No SSL
```
```
Simple as that.


Question: Someone asked me how familiar I am with VC++ and how familiar I am with C++.  What is the difference?

Answer:
C++ is the actual language, VC++ is Microsoft's Visual C++, an IDE for C++ development.
From
stason.org
:
C++ is the programming language, Visual C++ is Microsoft's implementation of it.
When people talk about learning Visual C++, it usually has more to do with learning how to use the programming environment, and how to use the Microsoft Foundation Classes (MFCs) for Windows rather than any language issues. Visual C++ can and will compile straight C and C++.


Question:
What's the best/easiest to integrate templating system for PHP, and what are the benefits of using one?

I currently don't use one at all, and am thinking that it might help to seperate content from presentation a little more.

Answer:
Smarty
I've found it to be fast, easy to use, and easy to install (even in a shared-hosting environment).  It also doesn't require that you use validating XHTML which is handy sometimes (although I think the template engines that
do
require valid XHTML are probably faster.)
It's really nice to have your content in one place and code somewhere else.
Plus you're not limited to just HTML.  I've used Smarty to generate
XML
and even
SQL
.


Question:
I'm just starting up a new ATL/WTL project and I was wondering if the global _Module variable is still required?

Back a few years when I started working with WTL it was required (at least for ATL 3.0) that you define a global variable such as:

CAppModule _Module;

To get ATL to work correctly. But recently I've read somewhere that this may not be required anymore (yet the wizard generated code still uses it). Also I did a search through the Visual C++ include directories and it only picked up _Module in a few places - most notably the ATL COM registry stuff.

So do I still need to define a global variable to use ATL these days?

Answer:
In the sample projects of the latest WTL version, this is still used.
In stdafx.h:
```
```
extern CAppModule _Module;
```
```
In implementation files:
```
```
CAppModule _Module;
```
```


Question:
What are the guidelines for when to create a new exception type instead of using one of the built-in exceptions in .Net?

The problem that got me thinking is this. I have a WCF service, which is a basic input-output service. If the service is unable to create an output, because the input is invalid, I want to throw an exception, but which one?

Right now I'm just throwing system.Exception, but this doesn't feel right to me, I don't know why, it just feels wrong.
One thing that bugs me, if I test it with a unit test and I expect the system.Exception to be thrown. The exception could as well be thrown by the framework or other code and not by the code I excepted to throw. The test would then pass, as I get the expected exception, but it should have failed.

What do you recommend?

Answer:
Avoid throwing
```
System.Exception
```
or
```
System.ApplicationException
```
yourself, as they are too general.
For WCF services there are Fault Contracts - a generic exception that you can tell subscibers to handle.
Flag the interface with:
```
```
[FaultContract( typeof( LogInFault ) )]
void LogIn( string userName, string password, bool auditLogin );
```
```
Then if there is an exception you can throw this specific fault:
```
```
throw new FaultException<LogInFault>( new LogInFault(), "message" );
```
```
Use the
```
[DataContract]
```
serialisation on your fault - this saves you from having to handle all the serialisation stuff exceptions normally require.


Question:
I am using the jQuery library to implement drag and drop.

How do I get at the element that is being dragged when it is dropped?

I want to get the id of the image inside the div. The following element is dragged:

<div class="block">
    <asp:Image ID="Image9" AlternateText="10/12/2008 - Retina" Width=81 Height=84 ImageUrl="~/uploads/ImageModifier/retina.jpg" runat=server />
</div>

I have the standard dropped function from their example:

$(".drop").droppable({
                 accept: ".block",
                 activeClass: 'droppable-active',
                 hoverClass: 'droppable-hover',
                 drop: function(ev, ui) { }
});

I have tried various ui.id etc. which doesn't seem to work.

Answer:
Is it not the ui.draggable?
If you go here (in Firefox and assuming you have firebug) and look in the firebug console youll see I am doing a console.dir of the ui.draggable object which is the div being dragged
http://jsbin.com/ixizi
Therefore the code you need in the drop function is
```
```
drop: function(ev, ui) {
                 //to get the id
                 //ui.draggable.attr('id') or ui.draggable.get(0).id or ui.draggable[0].id
                 console.dir(ui.draggable)
       }
```
```


Question:
What is the best way to determine how many window handles an application is using?  Is there a tool or a WMI performance counter that I could use?

I would like to run up an app and watch a counter of some sort and see that the number of window handles is increasing.

for (int i=0; i < 1000; i++)
{
    System.Threading.Thread.Sleep(1000);
    RichTextBox rt = new RichTextBox();
    rt.Text = "hi";
    this.Controls.Add(rt);
}

I am running the above code and watching the "Handle Count" counter on the process, and it does not seem to be increasing.  Is there something I am looking at incorrectly?

Answer:
Perfmon, which comes with your computer can do it.  You can also add a column to your task manager processes tab (Handle Count).
Instructions for Perfmon
Add a counter (click the +)
Choose Process under Performance object
Choose Handle Count under the counter list
Choose your process from the instance list
Click Add, click Close
To get the graph in range, you have to right-click it in the list, choose properties, and then choose the right scale (.1 or .01 would probably be right)
Edit (in response to added information): I think you just proved that creating RichTextBoxes doesn't result in Handles being allocated. I don't think it really needs one until you are editing the control and it might be smart enough to do that, since allocating too many resources for a control that isn't active would make it hard to have a lot of controls on a form (think about Excel, for example).


Question:
I have inherited a load of VB6 code which has tons of individual OCX files, each of which contain a single control.  I have two questions:

Firstly, Is it possible to refactor them so that I can have a single OCX file with all the OCX's in it?

Secondly, if it is possible, how do I do this?

TIA

Answer:
Yes this is possible.
You can do this by selecting
Project->Add User Control
from within an existing ActiveX User Control project. From here you can choose to add a new control to the project or add an existing user control.
Also, it can certainly make sense to group related controls together into a single project, as long as you group controls according to some kind of logic. For example, the Forms 2.0 library groups "commonly-used" controls together (Textbox, Checkbox, Combobox, Label, etc.) into a single library.


Question:
As a follow up to an earlier question that attracted a whole zero answers, I'm wondering about the possibilities of allowing a web server (apache) to write to its own document root (Linux), in order to dynamically create meta-redirect files.

Of course, this sounds incredibly dangerous, and I'm wary of going the whole hog and granting the web-server user full write-access to its own docroot. Is there a more appropriate way of achieving this?

Answer:
What's usually done is to allow writes only to subdirectories, hopefully located in a noexec mounted partition.
That said, it seems to me that you should just create a set of
RewriteMap
directives to do your dynamic redirection, there's no need to write files in the document root to accomplish that.
I answered similarly in the
other question
, just for completeness.


Question:
I'm working with embedded C for the first time. Although my C is rusty, I can read the code but I don't really have a grasp on why certain lines are the way the are. For example, I want to know if a variable is true or false and send it back to another application. Rather than setting the variable to 1 or 0, the original implementor chose 0xFF.

Is he trying to set it to an address space? or else why set a boolean variable to be 255?

Answer:
```
0xFF
```
sets all the bits in a char.
The original implementer probably decided that the standard
```
0
```
and
```
1
```
wasn't good enough and decided that if all bits
off
is
false
then all bits
on
is
true
.
That works because in C any value other than 0 is true.
Though this will set all bytes in a char, it will also work for any other variable type, since any one bit being set in a variable makes it true.


Question:
I want to do some checking in a writer accessor. My first idea was returning a boolean.

class MyClass
  def var=(var)
    @var = var
    # some checking
    return true
  end
end

m = MyClass.new
retval = (m.var = 'foo')

=> "foo"

Can I set a return value in a writer accessor? If yes, how can I get this value?

Answer:
I would use set_var(var) instead of what you are trying to do, an attribute writer is assumed to just work. What you are trying to do is nonstandard and non-obvious to the next poor person to use your code. (It may just be yourself) I would throw an exception if bad input is sent or something rather exceptional happens.
You want this behavior
```
```
Correct
>>temp = object.var = 7
=> 7

Wrong
>>temp = object.var = 7
=> false
```
```
The = operator should always return the value that was passed to it. Ruby uses implicit returns which is uncommon in programming languages. Double check the returns when you use
```
method=()
```
.


Question:
I'd like to use Rich Text Editing in place on forms in order to let admins change instructions.   What are the best options for doing this?

[To be more clear - the admins are non-technical but may want to control some formatting without using markup or with as little markup as possible.  What I'd like is for them to be able to edit inline all AJAXy with an RTE featuring some formatting controls and then submit and be able to see what the instructions will look like to the end user without changing pages.

With Regards to plugins specifically, what I'd like to know is which Rich Test Editing plugins are the best for use in Rails.  Easiest to implement, clearest API, easiest to use inline, etc... ]

Answer:
I'm not sure if I fully understand the question, but if you just ask about which editor to use, there are many options and none of them is a matter of Rails - you can use any of them just by adding a little piece of javascript into your markup. Nice and up to date overview can be found here:
http://bulletproofbox.com/web-based-rich-text-editors-compared/
.


Question:
echo "<td><a href='delete.php?id=$row[id]&&category=$a' onclick='return confirm(\'are you sure you wish to delete this record\');'>delete</a></td>";

Above is the code I am trying to use. Every time it does nothing and I cannot see how I can use 'proper' JavaScript methods. What is the reason?

Answer:
```
```
echo "delete	";
```
```
Use Firefox's HTML syntax highlighting to your advantage. :-)


Question:
I am importing the CreateICeeFileGen() function from the unmanaged DLL mscorpe.dll in a C# application, in order to  generate a PE file. This function returns a pointer to an C++ object defined here, is there any way I can access fields from this class via C# or do I need to write an unmanaged wrapper DLL?

The code I'm using currently is as follows:-

[DllImport(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorpe.dll", EntryPoint = "CreateICeeFileGen")]
static extern void CreateICeeFileGen(out IntPtr iceeFileGenPointer);
...
IntPtr filePtr;
CreateICeeFileGen(out filePtr);

N.B.: I know you can do similar things with .net libraries but I need to use unmanaged libraries for my purposes.

Answer:
You need a wrapper library to be able to use the class from C#.
The best bet would be to create the wrapper using C++/CLI, which can directly call the unmanaged function and expose the details with a managed class.  This will eliminate the need to use P/Invoke for anything.
(Well, technically if you know the class layout you could mess around with pointer arithmetic to access the fields, but this would be very fragile and messy, and trying to call virtual functions in this way would be extremely ugly).


Question:
Looking for a c# library that interfaces to multiple merchant gateways.
Should at minimum be able to handle PayPal and authorize.

Answer:
Considering that working with the gateways themselves is extremely simple, Adding support to your application for each one shouldn't be difficult.
That said, here is one that claims to have the support you want:
http://www.componentsource.com/products/ibiz-e-payment-integrator-net/index.html
Note that Payflow link and payflow pro were purchased by PayPal from verisign.


Question:
I want to create a new row in my database on a table that has a couple of foreign key relationships and I haven't been able to get a handle on what order and what calls need to be made. This is what I have so far:

db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.CustomerReference.Attach( ( from c in db.Customer where c.Id == custId select c ).First() );
db.SaveChanges();

The code is failing on the second line there, saying:

Attach is not a valid operation when
  the source object associated with this
  related end is in an added, deleted,
  or detached state. Objects loaded
  using the NoTracking merge option are
  always detached.

Any ideas?

Answer:
(Thanks John for the grammar fixes)
So I figured it out. This is what you have to do:
```
```
db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.Customer = (from c in db.Customer where c.Id == custId select c).First();
db.SaveChanges();
```
```
I hope that helps people.


Question: Anyone know a simple method to swap the background color of a webpage using JavaScript?

Answer:
Modify the JavaScript property
```
document.body.style.background
```
.
For example:
```
```
function changeBackground(color) {
   document.body.style.background = color;
}

window.addEventListener("load",function() { changeBackground('red') });
```
```
Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.


Question:
I have a bunch of XML that has lines that look like this

<_char font_name="/ITC Stone Serif Std Bold" italic="true" />

but sometimes look like this

<_char font_size="88175" italic="true" font_name="/ITC Stone Serif Std Bold" />

Here's what I need to do

Replace italic="true" with italic="false for every line that contains ITC Stone Serif Std Bold, regardless of whether it comes before OR after the italic part.

Can this be done with a single regex?

I'm not looking for a real-time solution.  I just have a ton of XML files that have this "mistake" in them and I'm trying to do a global search-and-replace with PowerGrep which would require a single regex.  If scripting's the only way to do it, then so be it.

Answer:
Well, in general, using RE for XML parsing isn't a great idea.  But if you really wanted, the easiest way would be to just do it in two lines:
```
```
if (/ITC Stone Serif Std Bold/) {
   s/italic="true"/italic="false"/g;
}
```
```


Question: I have an excel file which has more than 65536 rows. However, I can see only first 65536 of them. Is it possible to see all of them in Excel 2007?

Answer:
According to
this MSDN entry
, the limit is 1 million rows.  You could be running in compatibility mode, which would limit you to the old standard of 65k.  Does your excel say compatibility mode in the title?  If so, you can save the file as a new style file under the "save as" menu, or change your default to always use the 2007 file standard.


Question:
I am trying to open a report in Crystal Report 11 Designer (product version 11.5.8.826), but it seems to freeze up. This report use to work fine, but today the client could not load the report.

I also tried to open the report on another developer's workstation, with the same result.

Has this happened to anyone else?

Answer:
Are you sure all servers referenced in the report are still online? If you've changed database connections on the report, I've seen Crystal store a reference to the old one even when there are no active usages. If the old server is offline, Crystal still tries to connect to it when loading and will hang for a long time. We had a report that used to load in seconds start taking minutes right after an old test server was powered down. Powered it back up, it loaded instantly again, even though all the connections to it were seeming removed. We wound up totally rebuilding the report from scratch.
I found it using Sysinternals TDIMon, it showed connection attempts and timeouts coming from Crystal.


Question:
I am putting together a SVN demonstration using a WinXP Virtual PC image, and am unable to see my host machine from within the VPC guest OS.

This demo will be performed while disconnected from our LAN, so I installed the Microsoft Loopback adapter on my laptop.  In the TCP/IP settings I manually set the IP address to 192.168.3.1 to avoid conflicts with our internal network.  In the VPC image settings I set the Network Type to Microsoft Loopback Adapter and set the IP address to 192.168.3.2.

I cannot ping my host machine from the guest OS and vice versa.  I've followed through several different how-to pages on this subject but still cannot determine why this isn't working.  What am I missing here?

Answer:
So your host machine's loopback is set to 192.168.3.1 (subnet 255.255.255.0, gateway 192.168.3.1) and your VM's network adapter is set to 192.168.3.2 (subnet 255.255.255.0, gateway 192.168.3.1)?  They should be able to see each other, there's not much else to this setup.
I'd shake things up:
Install the VM additions, maybe the network driver that comes with the guest OS isn't cutting it.
Try a different subnet, maybe 192.168.22.1.
Disable your host machine's other network adapters for a bit, maybe packets are getting routed elsewhere.


Question:
I'm currently experiencing an intermediate problem with some inherited client side javascript. Every so often the users' experience a browser hang with the cursor becoming an egg timer and then the browser failing to respond.

I'm having real difficulty in determining where the issue is arising from. Short of disabling large chunks of javascript at a time is there any way to detect a hang in internet explorer and then examine the stack trace to determine the last few functions called in order to localise the problem?

Any help with this would be really appreciated.

Answer:
Update
: You can use
Web Development Helper
or
IE Dev Toolbar
to trace your Javascript calls.
Fiddler
is also a powerful web debugging proxy.
If you want to eliminate the IE part of the problem, disable all unnecessary addons loaded in Internet Explorer first. I had a big problem with skype addons.
If you want to do low level monitoring, you have to use tools like Process Explorer and Process Monitor. They have functionalities to show the stack trace, your trace of files and registries being accessed etc from your IE.
For javascript profiling, you can use a tool like
firebug
.


Question:
I start a .Net server side program on my local workstation, but soon it throws a security exception. I searched the web for answers, but no quick fix was found / worked. I just want to run my program. How do I get rid of the exception? I fully trust the program, because its mine.

Edit: Oh, yes, I do run the program from a mapped folder that is mapped to my own local drive for the sake of clarity of folder structures. Thanks for the answers, I try tomorrow to run it directly from my drive.

Edit: When I use directly my drive, it works.

Answer:
.NET 3.5 SP1 has better support for running applications on the local intranet.
If you can't target 3.5 SP1, you can map the share you're running the application from to a local drive and
use CasPol to set that mapped drive to a fully trusted location.


Question: I have 2 columns in a Grid.  When I click a button, I want the first column to animate to the left from it's current position to 0.  So, in effect, it collapses and I'm left with just viewing a single column.

Answer:
Shouldn't be too hard.  You'd need to create an EventTrigger that has a BeginStoryboard that targets the grid and uses a DoubleAnimation to shrink the column width.
The example here has a similar setup.
The EventTrigger would go on the button and the DoubleAnimation's
StoryBoard.Target
would point to the ColumnDefinition you wish to shrink.
Okay, so that doesn't work so well.  You can't shrink the column directly, but you CAN set the shrinking column to fill (width="*"), set the width of the Grid and the non-shrinking column, and then shrink the entire grid.  This does work.  The below example works:
```
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      WindowTitle="Opacity Animation Example"
      Background="White">
   <StackPanel Margin="20">
      <Grid Name="MyGrid" Width="200" HorizontalAlignment="Left">
         <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
         </Grid.RowDefinitions>
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="100"/>
         </Grid.ColumnDefinitions>
         <Rectangle HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    Grid.Column="0" Fill="Red"/>
         <Rectangle HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    Grid.Column="1" Fill="Blue"/>
      </Grid>

      <Button Name="hideButton">
         <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
               <BeginStoryboard>
                  <Storyboard>
                     <DoubleAnimation
                         Storyboard.TargetName="MyGrid"
                         Storyboard.TargetProperty="(Grid.Width)"
                         From="200" To="100"
                         Duration="0:0:2"
                         AutoReverse="True"  />
                  </Storyboard>
               </BeginStoryboard>
            </EventTrigger>
         </Button.Triggers>
      </Button>
   </StackPanel>
</Page>
```
```


Question:
OK, so instead of writing a whole bunch of access control specs, and duplicating them across many of my spec files, I'm looking to create a custom matcher. So instead of this:

describe "access control" do
  it "should prevent access by non-logged-in users"
  it "should prevent access by normal users"
  it "should prevent access by editor users"
  it "should prevent access by admin users"
  it "should allow access by super admin users"
end

I want do something like this:

lambda do
  get :index
end.should have_access_control(:allowed => [:super_admin], :disallowed => [:admin, :editor, :user])

Are there any examples or suggestions of how I can go about doing something like this?

Answer:
OK,
I have found a method of achieving this
, though it doesn't use a custom matcher. Include the following code in your spec_helper.rb:
```
```
def access_control (code, options={})
  options = {:allow => [], :disallow => []}.merge(options)

  options[:allow].each do |user|
    it "#{code} should allow #{user.to_s}" do
      login_as(user)
      eval code
      response.should_not redirect_to(login_path)
    end
  end

  options[:disallow].each do |user|
    it "#{code} should disallow #{user.to_s}" do
      login_as(user)
      eval code
      response.should redirect_to(login_path)
    end
  end
end
```
```
And call it as follows:
```
```
access_control("get :index", {:allow => [:super_admin], :disallow => [:quentin, :admin]})
```
```
You can then use it to build up a complete list of methods that should be restricted, and the users to which they are restricted to.


Question:
How do I uninstall a .NET Windows Service if the service files do not exist anymore?

I installed a .NET Windows Service using InstallUtil. I have since deleted the files but forgot to run

 InstallUtil /u

first, so the service is still listed in the Services MMC.

Do I have to go into the registry? Or is there a better way?

Answer:
From the command prompt, use the Windows "sc.exe" utility.  You will run something like this:
```
```
sc delete <service-name>
```
```
If the service name has one or more spaces, surround the name in double quotes (h/t @geoffc):
```
```
sc delete "<service-name>"
```
```


Question:
A curious thing happens in Java when you use an abstract class to implement an interface: some of the interface's methods can be completely missing (i.e. neither an abstract declaration or an actual implementation is present), but the compiler does not complain.

For example, given the interface:

public interface IAnything {
  void m1();
  void m2();
  void m3();
}

the following abstract class gets merrily compiled without a warning or an error:

public abstract class AbstractThing implements IAnything {
  public void m1() {}
  public void m3() {}
}

Can you explain why?

Answer:
That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate.  The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.
Following your example code, try making a subclass of
```
AbstractThing
```
without implementing the
```
m2
```
method and see what errors the compiler gives you.  It will force you to implement this method.


Question: Ideally, something cross-platform.

Answer:
The CPAN is probably the best way to go.  Take a look at
Term::Screen:Uni
:
```
```
require Term::Screen::Uni;
my $scr = new Term::Screen::Uni;

$scr->clrscr()
```
```


Question:
I'm trying to write a Windows cmd script to perform several tasks in series.
However, it always stops after the first command in the script.

The command it stops after is a maven build (not sure if that's relevant).

How do I make it carry on and run each task in turn please?

Installing any software or configuring the registry etc is completely out of the question - it has to work on a vanilla Windows XP installation I'm afraid.

Ideally I'd like the script to abort if any of the commands failed, but that's a "nice to have", not essential.

Thanks.

Answer:
When you call another .bat file, I think you need "call" in front of the call:
```
```
call otherCommand.bat
```
```


Question:
For example:

javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Answer:
This comes up in Java 5 and later if you're using collections without type specifiers (e.g.,
```
Arraylist()
```
instead of
```
ArrayList<String>()
```
).  It means that the compiler can't check that you're using the collection in a type-safe way, using
generics
.
To get rid of the warning, you need to be specific about what type of objects you're storing in the collection.  So, instead of
```
```
List myList = new ArrayList();
```
```
use
```
```
List<String> myList = new ArrayList<String>();
```
```
In Java 7 you can shorten generic instantiation by using
Type Inference
.
```
```
List<String> myList = new ArrayList<>();
```
```


Question:
Are there any tools to assist with the internationalization of Strings within JSP files?

Most IDEs (for example, NetBeans) offer such a feature for Java code. However, in the case of NetBeans, no such feature exists for JSP files.

With gettext, for example, there is are various tools out there that assist with extracting text Strings from code. Something similar for JSP would be great!

Answer:
I found this as a
workaround solution
to this problem. Its far from ideal, but allows you to search all Strings with an IDE. Paraphrashing the solution:
JSPs compile to servlets, so find the corresponding servlet class for each JSP on your file system. In the case of Tomcat this would be the 'work' directory.
Import the associated servlet .java file into the IDE, and then use the IDE's regular internationalization tool:
Externalize strings...
(Eclipse) /
Internationalization wizard
(NetBeans).


Question:
How do I go about doing this with jQuery?

Basically the structure:

<form id="myForm">
  <iframe>
    <!-- Normal HTML headers omitted -->
    <input type=radio name="myRadio" value=1>First
    <input type=radio name="myRadio" value=2>Second
    <input type=radio name="myRadio" value=3>Third
  </iframe>
  <input type=button value="Submit" />
</form>

I tried various examples from the net such as

$("input[@type=radio][@checked]");

But failed. Even with jQuery form plugin's .fieldValue() failed.

Answer:
Try
```
$('#myForm iframe').contents().find('input[name=myradio]').val()
```
I'll assume that the iframe contents have already been loaded and are accessible e.g same domain.


Question:
Is there a way to tell the debugger to stop just before returning, on whichever statement exits from the method, be it return, exception, or fall out the bottom? I am inspired by the fact that the Java editor shows me all the places that my method can exit - it highlights them when you click on the return type of the method declaration, (Mark Occurrences enabled).

[eclipse 3.4]

Answer:
Good question. Off the top of my head, I'd do this:
```
```
public void method(Object stuff) {
    try {
        /* normal code */
    } finally {
        int x = 0;
    }
}
```
```
You can set the breakpoint on the x = 0 line, and it will ALWAYS be executed no matter where you return. Even with an exception being thrown, it will be run.
The catch to this is scope. Unless you define variables outside of the try block, you won't be able to see their values where you get to the finally block since they will have exited scope.
Having to just place 5 breakpoints (one for each return statement, whatever) may work best.
I hope there is a better way, I'd love to know it.


Question:
I've got a spreadsheet with plenty of graphs in it and one sheet with loads of data feeding those graphs.

I've plotted the data on each graph using

=Sheet1!$C5:$C$3000

This basically just plots the values in C5 to C3000 on a graph.

Regularly though I just want to look at a subset of the data i.e. I might just want to look at the first 1000 rows for example. Currently to do this I have to modify the formula in each of my graphs which takes time.

Would you know a way to simplify this? Ideally if I could just have a cell on single sheet that it reads in the row number from and plots all the graphs from C5 to C 'row number' would be best.

Any help would be much appreciated.

Answer:
You can set the range for a chart dynamically in Excel. You can use something like the following VBA code to do it:
```
```
Private Sub Worksheet_Change(ByVal Target as Range)
    Select Case Target
    Case Cells(14, 2)
        Sheet1.ChartObjects(1).Chart.SetSourceData Range("$C5:$C$" & Cells(14,2))
    ...
    End Select
End Sub
```
```
In this case, the cell containing the number of the last row to include is B14 (remember row first when referring to the Cells object). You could also use a variable instead of the Cells reference if you wanted to do this entirely in code. (This works in both 2007 and 2003.) You can assign this procedure to a button and click it to refresh your chart once you update the cell containing the last row.
However, this may not be precisely what you want to do ... I am not aware of a way to use a formula directly within a chart to specify source data.
Edit:
And as PConroy points out in a comment, you could put this code in the Change event for that worksheet, so that neither a button nor a key combination is necessary to run the code. You can also add code so that it updates each chart only when the matching cell is edited.
I've updated the example above to reflect this.


Question:
Can anyone suggest a tutorial or sample code that implements a nested set (or similar ordered tree structure) with associated Javascript that facilitates drag and drop? I'm looking for both the display code (view) as well as the AJAX backend controller which writes the tree to the database on change.

I want it to represent a multi-layer menu where the ordering and depth of items is important.

Answer:
Something like this you really don't wanna be slapping a jquery plugin for. If you can't find anything out there it's time to make yourself an espresso and dive right into the code yourself :)
Use other -- more mature -- code out there as a sample point, but write it yourself and it will really suit your project the best. Looking for front-end and back-end code together is real tough too... unless you want something from a blog post that might be titled something like "30 jquery plugins to AJAXify your website" and you want crap PHP code. (In this case it appears that you want RoR)
This might not be of much assistance to you, but it's what I would do.
I'm particularly anti-jquery-plugins anyway... even if it does the job you want. A lot of that code is bloat. Plus I tend not to trust other people :)


Question:
I'd like to show a div that has a background-color with the height and width set to 100% but no content. Is it possible to do that without putting a &nbsp; inside?

Edit: Thanks to Mark Biek for pointing out that empty div with width and height styles shows how I'd expect. My div is in a table cell, where it does not show.

<table style="width:100%">
<tr>
<th>Header</th>
<td><div id="foo"></div></td>
</tr>
</table>

Answer:
This seems to work in Firefox, Safari, IE6, & IE7.
```
```

```
```


Question:
Greetings!

I am trying to check directory write-permissions from within a Windows MFC/ATL program using C++. My first guess is to use the C-standard _access function, e.g.:

if (_access("C:\mydir", 2) == -1)
   // Directory is not writable.

But apparently on Windows 2000 and XP, _access can't determine directory permissions. (i.e. the Security tab in the Properties dialog when you right-click on a directory in Explorer) So, is there an elegant way to determine a directory's write-permissions in Windows 2000/XP using any of the Windows C++ libraries? If so, how?

Thanks

Evan

Answer:
Use sec api.
You can ask on Adv. Win32 api newsgroup :
news://194.177.96.26/comp.os.ms-windows.programmer.win32
where it has often been discussed (C/C++ code)


Question:
Does anyone know a good resource to concisely explain the different types of lists available in C# and when their usage is appropriate?

For example, List, Hashtable, Dictionaries etc.

I'm never quite sure when I should be using what.

Answer:
If you start at the
MSDN doco for System.Collections
, you can drill down into the individual collection types for more details about those "lists" and how to use them. For example, the doco for
```
Hashtable
```
says, "Represents a collection of key/value pairs that are organized based on the hash code of the key."
There's also a nice discussion of System.Collections.Generic in
Understanding Generics
.


Question: How to find out size of session in ASP.NET from web application?

Answer:
I think you can find that information by adding
Trace="true"
to the page directive of a aspx page. Then when the page loads you can see a large number of details regarding the page request, including session information i think.
You can also enable tracing in your entire application by adding a line to your web.config file. Something like:
```
```
<trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime"
 localOnly="true"/>
```
```


Question:
We recently switched our Windows software packages from RPM (cygwin) to MSI (wix). Having a native packaging is a much welcome change and we intend to stick with it. However, MSI feels overly complicated for what it does and doesn't seem to provide some basic abilities. But I'm probably mistaken.

Is there a way to list all installed MSI from the command line ?

Answer:
Mabybe
this
is a good starting point for you example VB Script from MSDN:
```
```
strComputer = "."

Set objWMIService = GetObject("winmgmts:" & _
    "{impersonationLevel=impersonate}!\\" & _
    strComputer & _
    "\root\cimv2")

Set colSoftware = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_Product")

If colSoftware.Count > 0 Then

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objTextFile = objFSO.CreateTextFile( _
        "c:\SoftwareList.txt", True)

    For Each objSoftware in colSoftware
        objTextFile.WriteLine objSoftware.Caption & vbtab & _
        objSoftware.Version
    Next

    objTextFile.Close

Else
    WScript.Echo "Cannot retrieve software from this computer."

End If
```
```


Question:
I have a server written in Java that runs as a Windows service (thanks to Install4J).  I want this service to be able to download the latest version of the JAR file it runs from, and start running the new code.  The stitch is that I don't want the Windows service to fully exit.

Ideally, I would accomplish this by a unix-style exec() call to stop the current version and run the new one.  How can I best accomplish this?

Answer:
As far as I know, there is no way to do this in Java.
I suppose you could work around it by using the Java
```
Runtime.exec
```
or
```
ProcessBuilder
```
's start() command (which start new processes) then letting the current one end... the docs state
The subprocess is not killed when
  there are no more references to the
  Process object, but rather the
  subprocess continues executing
  asynchronously.
I'm assuming the same is true if the parent finishes and is garbage collected.
The catch is Runtime.exec's process will no longer have valid in, out, and err streams.


Question:
Inside a service, what is the best way to determine a special folder path (e.g., "My Documents") for a specific user? SHGetFolderPath allows you to pass in a token, so I am assuming there is some way to impersonate the user whose folder you are interested in.

Is there a way to do this based just on a username? If not, what is the minimum amount of information you need for the user account? I would rather not have to require the user's password.

(Here is a related question.)

Answer:
This information is stored in the registry in the key "HKEY_USERS\S-1-5-21-616815238-485949776-2992451252-3228\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders".
The "S-1-5-21-616815238-485949776-2992451252-3218" is the GUID of the user. You need to get this GUID to find the corresponding key and read it.
In
this
example they use SHGetFolderPath function you mention and there is a list with all special folders which might be helpful.
NOTE:
Microsoft discourages to use the registry key, since it is still there just for backward compatibility


Question:
Which is faster?  someCondition has the same probability of being true as it has of being false.

Insertion:

arrayList = Array("apple", "pear","grape")
if someCondition then
    ' insert "banana" element
end if

Deletion:

arrayList = Array("apple","banana","pear","grape")
if not someCondition then
    ' remove "banana" element
end if

It looks like it depends purely on the implementation of Insert and Remove.  So which, in general, is faster?  I'm leaning toward insertion because I've read that one can use CopyMemory to insert without looping.  Is this the same for deletion?  Does anyone have an example?

Edit:
This is VB6, not VB.NET.
For display reasons, I have to use insert rather than append.

Answer:
I've found an example showing that one can delete without looping as well.  It looks simpler than the code to insert.
```
```
Public Sub RemoveArrayElement_Str(AryVar() As String, ByVal _
    RemoveWhich As Long)
    '// The size of the array elements
    '// In the case of string arrays, they are
    '// simply 32 bit pointers to BSTR's.
    Dim byteLen As Byte

    '// String pointers are 4 bytes
    byteLen = 4

    '// The copymemory operation is not necessary unless
    '// we are working with an array element that is not
    '// at the end of the array
    If RemoveWhich < UBound(AryVar) Then
        '// Copy the block of string pointers starting at
        ' the position after the
        '// removed item back one spot.
        CopyMemory ByVal VarPtr(AryVar(RemoveWhich)), ByVal _
            VarPtr(AryVar(RemoveWhich + 1)), (byteLen) * _
            (UBound(AryVar) - RemoveWhich)
    End If

    '// If we are removing the last array element
    '// just deinitialize the array
    '// otherwise chop the array down by one.
    If UBound(AryVar) = LBound(AryVar) Then
        Erase AryVar
    Else
        ReDim Preserve AryVar(UBound(AryVar) - 1)
    End If
End Sub
```
```
http://www.vb-helper.com/howto_delete_from_array.html


Question:
I have a postgres table. I need to delete some data from it. I was going to create a temporary table, copy the data in, recreate the indexes and the delete the rows I need. I can't delete data from the original table, because this original table is the source of data. In one case I need to get some results that depends on deleting X, in another case, I'll need to delete Y. So I need all the original data to always be around and available.

However it seems a bit silly to recreate the table and copy it again and recreate the indexes. Is there anyway in postgres to tell it "I want a complete separate copy of this table, including structure, data and indexes"?

Unfortunately PostgreSQL does not have a "CREATE TABLE .. LIKE X INCLUDING INDEXES'

Answer:
Create a new table using a select to grab the data you want.  Then swap the old table with the new one.
```
```
create table mynewone as select * from myoldone where ...
mess (re-create) with indexes after the table swap.
```
```


Question:
<html>
    <head>
        <style type="text/css">
            div {
                border:1px solid #000;
                min-width: 50%;
            }
        </style>
    </head>
    <body>
        <div>This is some text. </div>
    </body>
</html>

I believe the div should be 50 percent of the page, unless, for some reason, the text inside the div makes it larger. However, the border around the div stretches across the entire page width. This occurs in both IE and Firefox.

Suggestions?

Answer:
If you provide
```
absolute
```
positioning to the element, it will be
```
50%
```
in Firefox.  However, IE doesn't like the
```
min-width
```
or
```
min-height
```
attributes, so you will have to define width as
```
50%
```
also for it to work in IE.


Question:
I'm trying to verify if a schema matches the objects I'm initializing.

Is there a way to get the TableName of a class other than simply reflecting the class name?

I am using some class with explicit TableNames

Edit: using Joe's solution I added the case where you don't specify the table name, it could probably use a constraint

public string find_table_name(object obj)
{
        object[] attribs = obj.GetType().GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);

        if (attribs != null)
        {
            ActiveRecordAttribute attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];
            if (attrib.Table != null)
                return attrib.Table;
            return obj.GetType().Name;
        }
    return null;
}

Answer:
If you have something like the following:
```
```
[ActiveRecord(Table = "NewsMaster")]
public class Article
{
    [PrimaryKey(Generator = PrimaryKeyType.Identity)]
    public int NewsId { get; set; }

    [Property(Column = "NewsHeadline")]
    public string Headline { get; set; }

    [Property(Column = "EffectiveStartDate")]
    public DateTime StartDate { get; set; }

    [Property(Column = "EffectiveEndDate")]
    public DateTime EndDate { get; set; }

    [Property]
    public string NewsBlurb { get; set; }
}
```
```
This will get you the table name:
```
```
[Test]
    public void Can_get_table_name()
    {
        var attribs = typeof(Article).GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false);

        if (attribs != null)
        {
            var attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0];
            Assert.AreEqual("NewsMaster", attrib.Table);
        }
    }
```
```


Question:
I'm curious to know how people are using table aliases.  The other developers where I work always use table aliases, and always use the alias of a, b, c, etc.

Here's an example:

SELECT a.TripNum, b.SegmentNum, b.StopNum, b.ArrivalTime
FROM Trip a, Segment b
WHERE a.TripNum = b.TripNum

I disagree with them, and think table aliases should be use more sparingly.

I think they should be used when including the same table twice in a query, or when the table name is very long and using a shorter name in the query will make the query easier to read.

I also think the alias should be a descriptive name rather than just a letter.  In the above example, if I felt I needed to use 1 letter table alias I would use t for the Trip table and s for the segment table.

Answer:
I feel that you should use them as often as possible but I do agree that t & s represent the entities better than a & b.
This boils down to, like everything else, preferences.  I like that you can depend on your stored procedures following the same conventions when each developer uses the alias in the same manner.
Go convince your coworkers to get on the same page as you or this is all worthless.  The alternative is you could have a table Zebra as first table and alias it as a.  That would just be cute.


Question: How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?

Answer:
```
```
#include <cstdio>
#include <cstdlib>
#include <string>

void strrev(char *str)
{
        if( str == NULL )
                return;

        char *end_ptr = &str[strlen(str) - 1];
        char temp;
        while( end_ptr > str )
        {
                temp = *str;
                *str++ = *end_ptr;
                *end_ptr-- = temp;
        }
}

int main(int argc, char *argv[])
{
        char buffer[32];

        strcpy(buffer, "testing");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "a");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "abc");
        strrev(buffer);
        printf("%s\n", buffer);

        strcpy(buffer, "");
        strrev(buffer);
        printf("%s\n", buffer);

        strrev(NULL);

        return 0;
}
```
```
This code produces this output:
```
```
gnitset
a
cba
```
```


Question:
int main()
{
    HandPhone A,B;
    A>>B;//overloading operator>> to simulate sending sms to another handphone(object)
    return 0;
}

How should I declare the istream operator to simulate sending sms to another handphone(object)?

Answer:
std::istream
is a class, not an operator.  The << and >> operators can be defined for any two types:
```
```
class A;
class B;

A operator << (A& a, const B& b)    // a << b;  sends b to a.
{
   a.sendMessage(b);
   return a;
}
```
```


Question:
I'm trying to install the .Net framework version 2.0 on embedded Windows XP SP2 (aka XPE).

I'm using the XPE specific version of the installer from Microsoft:

http://www.microsoft.com/downloads/details.aspx?familyid=c4837dad-5719-4b63-8752-cb0a65802329&displaylang=en

When the installation starts it fails with the following error:

QFE Installer -- Error
Cannot connect to the database - please check the database

How can I get .Net 2.0 installed on SPE?

Answer:
Okay, so you're running the installer that is updating your XPE development environment, right?  Or are you attempting to run that on a device before you seal it?
You need to run that installer on the workstation that has the XPE dev environment (and database) installed.  The installer is looking for a specific database on a specific instance of Sql Server, so if you have (or somebody else has) changed it, you'll need to read up on how to specify the connection string to use with the installer.
In addition, it's probably trying to connect using your windows account credentials.  Make sure you are able to log on to Sql Server, open the DB with the component definitions, and add records to it.  Alternatively, if you can specify the connection string you can set a Sql login username and password to use.
Profiler is a great tool for troubleshooting the two issues described above.
Once you have the components installed, you'll have to add them to your image, check your dependencies and then build it.
If you're trying to just install .NET 2.0 on a machine directly (before you reseal it), you will need the packages for Windows Installer on the machine first.  There might be some other dependencies; I haven't done it in a long time so I can't remember.
The best way to troubleshoot dependencies on an XPE installation is to put ProcessMonitor from Sysinternals on it.  As you run the installer, you'll see where it attempts to find stuff and fails.  Take that information back to your XPE IDE and search your components for those files.  You then have to add the packages containing those files to your image and try again.  Its an arduous process sometimes..,.


Question:
How can I make my window not have a title bar but appear in the task bar with some descriptive text?
If you set the Form's .Text property then .net gives it a title bar, which I don't want.

        this.ControlBox = false;
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.ShowInTaskbar = true;
        this.Text = "My title for task bar";

I've found a partial solution, to override CreateParams:

    protected override System.Windows.Forms.CreateParams CreateParams
    {
        get
        {
            System.Windows.Forms.CreateParams cp = base.CreateParams;
            cp.Style &= ~0x00C00000; // WS_CAPTION
            return cp;
        }
    }

However this causes my window to be resized as if they have a title bar, ie it's taller than it should be.  Is there any good solution to this?

Answer:
Just set the border style to None.
```
```
this.FormBorderStyle = FormBorderStyle.None;
```
```


Question:
I have a checkstyle suppression filter setup (e.g. ignore magic numbers in unit test code).

The suppression xml file resides in the same folder as the checkstyle xml file. However, where this file actually is varies:
on my windows dev box it is in d:\dev\shared\checkstyle\config
on the Linux CI server it will be in /root/repo/shared/checkstyle/config
on another developers box it could be anywhere (they check out their svn repo to).

The only "consistent" thing is that the suppression file is always in the same folder as the checkstyle xml file.
I cannot work out how to ensure that this file is always consistently picked up. Also I don't know why checkstyle does not support embedded suppression within the checkstyle xml file.

any help?

Answer:
I had this same problem with the Checkstyle suppression configuration when I was going back and forth between Linux and Windows. Here's how I solved it in my Ant-based build system:
Basically, I inject the proper, platform-specific directory value into the main Checkstyle configuration file by configuring a Checkstyle properties file with an Ant build script.
My main Checkstyle configuration file has a
```
SuppressionFilter
```
module declaration as shown below. The value of the
```
checkstyle-suppressions-file
```
property comes from a Checkstyle properties file:
```
```
<module name="SuppressionFilter">
    <property name="file" value="${checkstyle-suppressions-file}"/>
</module>
```
```
The Checkstyle properties file is not static, it is generated by an Ant build script from a properties file template called
```
template-checkstyle.properties
```
. Here's what the template looks like for the suppressions file property:
```
```
checkstyle-suppressions-file=@SCM_DIR@/checkstyle_suppressions.xml
```
```
My Ant build script copies this file to a file named
```
checkstyle.properties
```
. The copy has the special token replaced with the proper value of the directory in which the suppressions file is found:
```
```
<copy file="${scm.dir}/template-checkstyle.properties" tofile="${scm.dir}/checkstyle.properties">
    <filterset>
        <filter token="SCM_DIR" value="${scm.dir.unix}"/>
    </filterset>
</copy>
```
```
Now, where does the value of
```
scm.dir.unix
```
come from? Well, it's
derived
from a property of my build, read on. You'll need to specify such a value with the directory values that you mentioned.
Note that there is one slightly non-obvious issue concerning the way in which you specify this directory. I say that the
```
scm.dir.unix
```
value is derived from a build property because I observed that the main Checkstyle configuration file cannot contain backslashes, i.e. Windows path separator characters, in the value of the
```
file
```
property of the
```
SuppressionFilter
```
module. For example, specifying something like
```
C:\foo\bar\baz
```
leads to a Checkstyle error message saying that
```
C:foobarbaz
```
cannot be found. I work around this by "converting" the
```
scm.dir
```
directory build property to a "unix" format with Ant's
```
pathconvert
```
task:
```
```
<pathconvert targetos="unix" property="scm.dir.unix">
    <path location="${scm.dir}"/>
</pathconvert>
```
```
Then I call the
```
checkstyle
```
Ant task like this:
```
```
<checkstyle config="${scm.dir}/checkstyle_checks.xml"
            properties="${scm.dir}/checkstyle.properties">
    <!-- details elided -->
</checkstyle>
```
```
The call to the
```
checkstyle
```
task injects the key/value pairs contained in the
```
checkstyle.properties
```
file into the main Checkstyle configuration.
If you like, you can see the full scripts
here
Hope this helps


Question: I’m using the gcc in MinGW that comes with Strawberry Perl, on Windows XP. I’d like to have ddd (the Data Display Debugger) as well but apparently on Windows the simplest way to get ddd is by running Cygwin. So what's the bare minimum of Cygwin I can install to get ddd up and running? I'd prefer if I could run ddd natively on Win32 but that doesn't seem to be an option.

Answer:
If you're going for minimalism, you might want a smaller X server than
cygwin-x11
(though it's what I use, and I'm quite fond of it).
Starwin X-Win32
is actively maintained (though it costs $$ beyond the trial period), and avoids the overhead of installing Cygwin proper; there are other, zero-cost minimal X servers for win32 available, but I don't have linkage immediately available.
As the documentation at
x.cygwin.com
indicates, the
```
xorg-x11-base
```
package is the bare minimum needed.


Question:
Can anyone provide and example of downloading a PDF file using Watin?  I tried the SaveAsDialogHandler but I couldn't figure it out.  Perhaps a MemoryStream could be used?

Thanks,

--jb

Answer:
This code will do the trick. The UsedialogOnce class can be found in the WatiN.UnitTests code and will be part of the WatiN 1.3 release (which will probably be released tonigh 14 october).
FileDownloadHandler fileDownloadHandler = new FileDownloadHandler(file.FullName);
using (new UseDialogOnce(ie.DialogWatcher, fileDownloadHandler))
{
    ie.Button("exportPdfButtonId").ClickNoWait();
```
```
fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(30);
fileDownloadHandler.WaitUntilDownloadCompleted(200);
```
```
}
HTH,
Jeroen van Menen
Lead developer WatiN


Question:
We've all seen in-browser rich text editors, which allow you to edit colored/styled text in a WYSIWYG manner. But what about code editors, which automatically highlight code based on language rules as you type? Think Eclipse in a textarea (but without the refactoring support).

Do such things exist? I imagine scaling would be a problem - larger files would be difficult  to edit efficiently.

Answer:
The
editArea
javascript library does a pretty good job. It's used by the
OpenCMS
content management system as it's in-place JSP and JavaScript editor. The colorization gets a bit confused when the file is > 2000 lines or so.
The feature list from their page is:
Easy to integrate, only one script include and one function call
Tab support (allow to write well formated source code)
Search and replace (with regexp)
Customizable real-time syntax highlighting (currently: PHP, CSS, Javascript, Python, HTML, XML, VB, C, CPP, SQL, Pascal, Basic, Brainf*ck)
Auto-indenting new lines
Line numbering
Multilanguage support (currently: Croatian, Danish, English, French, German, Italian, Japanese, Polish, Portuguese)
Full screen mode
Can work in the same environment than "protype" and "mootools"'s like libraries.


Question:
I'm using the following code, using the SharpZipLib library, to add files to a .zip file, but each file is being stored with its full path.  I need to only store the file, in the 'root' of the .zip file.

string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
     zipFile.BeginUpdate();
     foreach (string file in files)
     {
          zipFile.Add(file);
     }
     zipFile.CommitUpdate();
}

I can't find anything about an option for this in the supplied documentation.  As this is a very popular library, I hope someone reading this may know something.

Answer:
How about using
System.IO.Path.GetFileName()
combined with the entryName parameter of ZipFile.Add()?
```
```
string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
     zipFile.BeginUpdate();
     foreach (string file in files)
     {
          zipFile.Add(file, System.IO.Path.GetFileName(file));
     }
     zipFile.CommitUpdate();
}
```
```


Question:
I'm learning how to make a firefox extension.
I have created a xul and overlay file that makes a sidebar in my browser. I'm trying to put buttons in my sidebar that load different pages within the main browser window. I'm not sure how to access the main browser window and load a new url within it. I have here a simple button and script to show you what I have so far. Any light on this subject would be greatly appreciated!

<script type="application/x-javascript">
    function loadURL(url) {

            // I know this part is wrong. How do I load url into main browser??
    window.content.open(url)
    }
</script>

<button
     id="identifier"
     class="dialog"
     label="Yahoo"
     image="images/image.jpg"
     oncommand="loadURL("http://www.yahoo.com);"/>

Answer:
You should be able to access active tab window context in the following way:
```
function loadURL(url) {
    content.wrappedJSObject.location = url;
}
```


Question:
We're working with a fixed transaction log size on our databases, and I'd like to put together an application to monitor the log sizes so we can see when things are getting too tight and we need to grow the fixed trn log.

Is there any TSQL command that I can run which will tell me the current size of the transaction log, and the fixed limit of the transaction log?

Answer:
A quick google search revealed this:
```
```
DBCC SQLPERF ( LOGSPACE )
```
```
Why aren't you using autogrowth on the transaction log?  It seems like this would be a more reliable solution.


Question:
in Config.groovy I see this:

// set per-environment serverURL stem for creating absolute links
environments {
    production {
        grails.serverURL = "http://www.changeme.com"
    }
}

what is the correct way to access that at runtime?

Answer:
here it is:
```
```
import org.codehaus.groovy.grails.commons.ConfigurationHolder
println ConfigurationHolder.config.grails.serverURL
```
```
alternatively, in controllers and tags, apparently this will work:
```
```
grailsApplication.config.grails.serverURL
```
```
I needed it in BootStrap, so option 1 was what I needed.


Question: Is there code in VBA I can wrap a function with that will let me know the time it took to run, so that I can compare the different running times of functions?

Answer:
Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is
```
QueryPerformanceCounter
```
. Google it for more info. Try pushing the following into a class, call it
```
CTimer
```
say, then you can make an instance somewhere global and just call
```
.StartCounter
```
and
```
.TimeElapsed
```
```
```
Option Explicit

Private Type LARGE_INTEGER
    lowpart As Long
    highpart As Long
End Type

Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long

Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double

Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#

Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
    Low = LI.lowpart
    If Low < 0 Then
        Low = Low + TWO_32
    End If
    LI2Double = LI.highpart * TWO_32 + Low
End Function

Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
    QueryPerformanceFrequency PerfFrequency
    m_crFrequency = LI2Double(PerfFrequency)
End Sub

Public Sub StartCounter()
    QueryPerformanceCounter m_CounterStart
End Sub

Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
    QueryPerformanceCounter m_CounterEnd
    crStart = LI2Double(m_CounterStart)
    crStop = LI2Double(m_CounterEnd)
    TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property
```
```


Question:
I'm planning on doing my next project in c# rather than c++ (using SlimDX).

All of directX uses floats, however System.Math uses doubles. This means constantly converting between floats and doubles.

So ideally I'd like to write all the code using floats, since I'm not getting any added precision converting to floats from doubles all the time anyways...

However Ive been unable to find a set of maths functions for .net that uses floats. I could of course write my own library in c#, but id rather use an existing library which has been optimised etc...

Answer:
XNA provides several math constants (including 3D specialists, like PI/2 etc.) and some advanced math functions with float precision (though not the trigonometric functions). While that is most likely not an option for you, since XNA is not as slim as SlimDX, it certainly means that System.Math is either actually missing something, or the performance hit is not that big. In my experience, you don't actually calculate that much for yourself, because most of that is handled either by the geometry classes (Matrix, Quaternion, Vector) or the GPU itself.
From that point of view, I'd have a look into SlimDX, what they are providing. Seems like the typical things like matrices, vectors, quaternions (and even 16 bit floats) are already there. If you're missing some constants with float precisions, just create them yourself (don't have the cast to be done every time, just at startup).


Question: How do I generate a random number between 0 and n?

Answer:
Well, I figured it out. Apparently there is a builtin (?) function called rand:
```
```
rand(n + 1)
```
```
If someone answers with a more detailed answer, I'll mark that as the correct answer.


Question:
Is there any way to access the file object used by a CSV writer/reader object after it has been instantiated?  I openned up the csv module, and it appears it's contest are builtin.  I also tried setting the file object as a property but I get the following error:

AttributeError: '_csv.writer' object has no attribute 'fileobj'

Answer:
```
csv.writer
```
is a "builtin" function.  That is, it is written in compiled C code rather than Python.  So its internal variables can't be accessed from Python code.
That being said, I'm not sure
why
you would need to inspect the csv.writer object to find out the file object.  That object is specified when creating the object:
```
```
w = csv.writer(fileobj, dialect, ...)
```
```
So if you need to access that object later, just save it in another variable.


Question:
I'm developing a system that needs to execute Intersystems Cache Terminal Scripts.

When I run a routine inside the regular Caché terminal or a telnet terminal, Cache executes the routine until the end with no problems. But when I try to run the same routine, but this time calling the routine within a Caché terminal Script, Caché disconnects the session after a while. There is no mention at all in the documentation of a "timeout" setting or anything realted to the "" messages i'm getting.

The script is run just like this:

Cterm.exe /console=cn_iptcp:192.168.2.13[23] c:\test.s

1) Does anybody know what may be causing Interystems Caché to disconnected the session in the middle of the run (the session isn't idle either. It regularly outputs status messages to the console)?

2) Any ideas of how to solve it?

Thanks,

Luís Fernando

Answer:
Is there a chance it's not a timeout, but some other problem?  Possibly a runtime error that's not being trapped/logged?
The main difference between running from the interactive console and as a script is that when you run interactively you're in Programmer Mode, but in the script you're in User Mode.  I can't think of any reason off-hand why that would matter, but possibly your code is sensitive to that.
Here's something to try:  Write a very simple script that does nothing except write out a character every now and then.  Maybe something like this:
F I=1:1:360 H 10 W "."  ;Write a dot every 10 seconds for 1 hour
If that gets the timeout too then you know it's the terminal, not your code.


Question: What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

Answer:
The
Clone()
method returns a new array (a shallow copy) object containing all the elements in the original array.  The
CopyTo()
method copies the elements into another existing array.  Both perform a shallow copy.  A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array.  A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.
So the difference are :
```
```
1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.
```
```
Edit:
Remove the wrong example.


Question:
How do I determine if the currency symbol is supposed to be on the left or right of a number using CFLocale / CFNumberFormatter in a Mac Carbon project?

I need to interface with a spreadsheet application which requires me to pass a number, currency symbol, currency symbol location and padding instead of a CStringRef created with CFNumberFormatter.

CFLocaleRef currentLocale = CFLocaleCopyCurrent();
CFTypeRef currencySymbol = CFLocaleGetValue (currentLocale, kCFLocaleCurrencySymbol);

provides me with the currency symbol as a string. But I'm lost on how to determine the position of the currency symbol...

Answer:
As a workaround, I have started to create a string representing a currency value and determining the position of the currency symbol by searching the string, but this sure looks fishy to me.
```
```
CFNumberFormatterRef numberFormatter = CFNumberFormatterCreate(kCFAllocatorDefault, CFLocaleCopyCurrent(), kCFNumberFormatterCurrencyStyle);
    double someNumber = 0;
    CFStringRef asString = CFNumberFormatterCreateStringWithValue(kCFAllocatorDefault, numberFormatter, kCFNumberDoubleType, &someNumber);
```
```
...
Feel free to hit me with a rolled-up newspaper and tell me the real answer...


Question:
In .NET (at least in the 2008 version, and maybe in 2005 as well), changing the BackColor property of a DateTimePicker has absolutely no affect on the appearance. How do I change the background color of the text area, not of the drop-down calendar?

Edit: I was talking about Windows forms, not ASP.

Answer:
According to
MSDN
:
Setting the
```
BackColor
```
has no effect on
  the appearance of the
```
DateTimePicker
```
.
You need to write a custom control that extends
```
DateTimePicker
```
. Override the
```
BackColor
```
property and the
```
WndProc
```
method.
Whenever you change the
```
BackColor
```
, don't forget to call the
```
myDTPicker.Invalidate()
```
method. This will force the control to redrawn using the new color specified.
```
```
const int WM_ERASEBKGND = 0x14;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if(m.Msg == WM_ERASEBKGND)
    {
        using(var g = Graphics.FromHdc(m.WParam))
        {
            using(var b = new SolidBrush(_backColor))
            {
                g.FillRectangle(b, ClientRectangle);
            }
        }
        return;
    }

    base.WndProc(ref m);
}
```
```


Question:
I have a third-party editor that basically comprises a textbox and a button (the DevExpress ButtonEdit control). I want to make a particular keystroke (Alt + Down) emulate clicking the button. In order to avoid writing this over and over, I want to make a generic KeyUp event handler that will raise the ButtonClick event. Unfortunately, there doesn't seem to be a method in the control that raises the ButtonClick event, so...

How do I raise the event from an external function via reflection?

Answer:
From
Raising an event via reflection
, although I think the answer in
VB.NET
, that is, two posts ahead of this one will provide you with the generic approach (for example, I'd look to the VB.NET one for inspiration on referencing a type not in the same class):
```
```
public event EventHandler<EventArgs> MyEventToBeFired;

    public void FireEvent(Guid instanceId, string handler)
    {

        // Note: this is being fired from a method with in the same
        //       class that defined the event (that is, "this").

        EventArgs e = new EventArgs(instanceId);

        MulticastDelegate eventDelagate =
              (MulticastDelegate)this.GetType().GetField(handler,
               System.Reflection.BindingFlags.Instance |
               System.Reflection.BindingFlags.NonPublic).GetValue(this);

        Delegate[] delegates = eventDelagate.GetInvocationList();

        foreach (Delegate dlg in delegates)
        {
            dlg.Method.Invoke(dlg.Target, new object[] { this, e });
        }
    }

    FireEvent(new Guid(),  "MyEventToBeFired");
```
```


Question: I am interacting with an Oracle DB using SQL over an ODBC connection.  Is there an SQL command I can use to get the MAC address of the server, or something that uniquely identifies the server hardware or software installation.  This is so I can be sure (or at least fairly sure) that I'm talking to the same database all the time.

Answer:
I don't know if you could get the mac address at all. But there are several informations which may help you at the v$instance view.
```
```
SELECT * FROM v$instance;
```
```


Question:
I've used a tool from Aspose (Aspose.PDF.kit) to generate a JPG thumbnail on the fly of a PDF for a .NET application.  This works great,  but what kind of other alternatives are there?  Codeproject.com has this tutorial, but it requires you to have the full version of Acrobat.

Is there an open source alternative that's geared for ASP.NET?

Answer:
I absolutely despise working with PDF documents.  But when I absolutely have to, I have been using
iTextSharp
.  It has quite a bit of functionality,
the API is fairly well documented
, and it is theoretically free.  Though to use it effectively it helps if you get the book that they push on their website.  I'm not certain if you can easily make thumbnails with it, but it has worked for me in generating and manipulating PDFs on every project I've worked on so far.


Question:
I have apache web server installed as frontend and I have j2ee SAP Netweaver Application Server installed in Intranet server. How can I configure apache to forward requests and response to/from j2ee app server.
for example, external apache server's ip is 9.20.1.1:80.
internal sap server's address is 192.168.0.1/sap/bc/gui/sap/its/webgui?sap_client=200
I want access to my sap app server for example 9.20.1.1/sapserver/sap/bc/gui/sap/its/webgui?sap_client=200

Answer:
Assuming you have mod_proxy enabled, add to you're sites-available:
```
```
ProxyRequests Off
   <Location "/sapserver">
        ProxyPass http://192.168.0.1
        ProxyPassReverse http://192.168.0.1
   </Location>
```
```
Be careful though as this does expose your internal site to the entire internet.


Question:
Is there any real practical difference between "java -server" and "java -client"?

All I can find on Sun's site is a vague

"-server starts slower but should run faster".

What are the real differences?  (Using JDK 1.6.0_07 currently.)

Answer: I've not noticed any difference in startup time between the 2, but clocked a very minimal improvement in application performance with "-server" (Solaris server, everyone using SunRays to run the app).  That was under 1.5.


Question:
Recently I've been thinking about finite state machines (FSMs), and how I would implement them in software (programming language doesn't matter).

My understanding is that deterministic state machines are in widespread use (parses/lexers, compilers and so on), but what's the matter with non-deterministic state machines?

I know that is possible to convert all non-deterministic state machines to deterministic ones (even programmatically). That's not my point. I also imagine that non-deterministic state machines are much more complicated to implement.

Anyway, does it make any sense to implement a non-deterministic state machine? Are there any special applications I don't know about?
What could be the reasons to do that? Maybe optimized and specialized non-deterministic state machines are faster?

Answer:
Most regular expression engines use
non
-deterministic automata since they offer much greater flexibility. DFAs are much more restricted. Have a look at some implementations and you'll see this. Microsoft even underlines this fact in their documentation of the .NET
Regex
class:
The .NET Framework regular expression engine is a backtracking regular expression matcher that incorporates a traditional Nondeterministic Finite Automaton (NFA) engine such as that used by Perl, Python, Emacs, and Tcl.
Matching behavior
(first paragraph) – this article also offers a rationale for the employment of an NFA rather than the more efficient DFA.


Question:
I typically use URL rewriting to pass content IDs to my website, so this

 Foo.1.aspx

rewrites to

 Foo.aspx?id=1

For a specific application I need to pass in multiple IDs to a single page, so I've rewritten things to accept this:

 Foo.1,2,3,4,5.aspx

This works fine in Cassini (the built-in ad hoc web server for Visual Studio) but gives me "Internet Explorer cannot display the webpage" when I try it on a live server running IIS. Is this an IIS limitation? Should I just use dashes or underscores instead of commas?

Answer:
The right way to
accept
multiple ids is like this:
```
```
Foo.aspx?id=1;id=2;id=3;id=4;id=5
```
```
Note that's just what the target is.  When re-writing urls, you can set your own rules to a certain extent for what you want the source to look like.
I had to learn this on StackOverflow, too.  See this question:
Split out ints from string


Question:
In asp.net, you can retrieve MULTIPLE datatables from a single call to the database.  Can you do the same thing in php?

Example:

$sql ="select * from t1; select * from t2;";
$result = SomeQueryFunc($sql);
print_r($result[0]); // dump results for t1
print_r($result[1]); // dump results for t2

Can you do something like this?

Answer:
This should be possible with newer MySQL and the mysqli (improved) php extension.
I'm not sure if any DB abstraction layers support this.
See relevant
MySQL docs
and
PHP docs
.


Question:
I'm working on a solution that contains multiple projects targeting Windows Mobile 5 and standard Windows applications.

Lately when opening up a form in designer the common UI controls (textbox, button, label, etc etc...) have vanished leaving only the controls defined within the project.

Resetting the toolbox has no effect.  A google search suggested deleting the toolbox temp files in the Local Settings\Application Data\Microsoft\VisualStudio\9.0, however this was only successful in bringing back the default controls for Windows Mobile 5.  The WinForms controls are still mysteriously missing.

Also, if I right-click and Select All on the toolbox, all of the WinForms controls do in fact come up, however they're all grayed out.

Has anyone else experienced this?

Answer:
I've noticed this exact same thing for regular WinForms as well. I can't speak to mobile applications but in regular winforms this has a tendency to happen.
I believe it's actually a bug in Visual Studio.
There are some things you can do (again, for WinForms. I'm not sure about mobile) with adding attributes to your control. Such as:
```
```
[ToolboxBitmap(typeof(MyControl), "MyControlBitmap")]
```
```
There are some other useful related things on this site:
http://en.csharp-online.net/Design-Time_Integration-Attributes


Question: I have a site that is using x509 client certificates (2 way SSL) to authenticate users and an LDAP directory that contains authorization information. I would like to use one of the certificate attributes to query the directory ( SSL_CLIENT_S_DN_CN to be exact ).  I see how to use mod_ssl to use the user's client certificates for authentication and I see how to use mod_auth_ldap and the like to use the username from basic or form based authentication to query the LDAP store for authorization. What I haven't seen a good example for is how to use an attribute of the user's client certificate in place of the username to query the LDAP. Any ideas?

Answer:
this might help:
settingcerts
+
mod_authnz_ldap
(authldapurl)


Question:
Ok, so I'm building bread crumbs and depending on the value of the breadcrumb an image will be the seperator. So "HOME" will have one image and "SEARCH" will have another.

I know I can do this programatically (at least I ASSUME) but is there an easier way to do this? Can I link an image to a node based on the value of the node? Can I do it with PathSeparatorTemplate?

Thank you.

Answer:
You can put an
```
```
<asp:Image ... />
```
```
into the PathSerparatorTemplate but you still have to set the image url from code.


Question:
After many years of using make, I've just started using jam (actually ftjam) for my projects.

In my project workspaces, I have two directories:

src where I build executables and libraries

test where my test programs are

I'm trying to set up a dependency on test programs so that each time I compile them, the libraries will be recompiled as well (if they need to).

Any suggestion on how to do it?

Answer:
Ok this seems to be not an as easy question as I thought so I worked out a solution on my own. It uses a script to achieve the end result so I still hope that a Jam guru will have a jam-only solution.
Create a Jamrules in the root directory of the project with the common definitions.
Create a Jamfile in the root directory of the project with the following content:
```
SubDir . ;
    SubInclude . src ;
    SubInclude . test ;
```
Create a Jamfile in the src directory
```
SubDir .. src ;
    Library mylib : mylib.c ;
```
Create a Jamfile in the test directory
```
SubDir .. test ;
    Main mytest : mytest.c ;
    Depends mytest :  mylib$(SUFLIB) ;
```
With this setting, as long as I am in the root directory, whenever I try to build mytest the library will also be recompiled (if needed). I found an old message on the jammer mailing list describing it.
Alas this doesn't work if I'm in the test subdirectory since jam can only look
down
into subdirectories.
So, I created a simple script called
```
jmk
```
and put it together with the
```
jam
```
executable (so that both are in the path):
```
```
if [ "$JMKROOT" = "" ] ; then
   JMKROOT=`pwd`
   export JMKROOT
fi
cd $JMKROOT
jam $*
```
```
and I set the JMKROOT environment variable to the root of my project.
For when I compile in a Windows shell (that's why I want to use Jam) I simply use this small
```
jmk.bat
```
batch file:
```
```
@echo off
if "%JMKROOT%" EQU "" set JMKROOT=%CD%

set OLDCD=%CD%
cd %JMKROOT%
jam %1 %2 %3 %4 %5 %6 %7 %8 %9

cd %OLDCD%
```
```


Question: I know there are tools to get text files to resource files for Visual Studio.  But I want to get the text from my resource files to a text file so they can be translated.  Or is there a better way to do this?

Answer:
You could use
Resx Editor
, a small translation-oriented file editor.
Target audience: translators.
Supported file format: Microsoft RESX 2.0
Here is a link to Joannès Vermoel's (the author of the free tool)
weblog entry
about it.


Question:
I am using Visual Studio 2005 to make an install.  The application has a dependency on a DLL that was built with MFC 7.1 (from Visual Studio 2003).

Are there merge modules for MFC 7.1 or other redistributables like there are for MFC 8?  Where could they be found?

Answer:
I would expect the merge modules for MFC 7.1 to be in
```
%ProgramFiles%\Microsoft Visual Studio .NET 2003\redist
```
, assuming that you have Visual Studio 2003 installed. (However, I can't verify that because I don't have Visual Studio on this PC.)


Question: How can I find out if SP1 has been installed on a server which has .NET 3.5?

Answer:
Look at
```
HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\
```
. One of these must be true:
The
```
Version
```
value in that key should be
3.5.30729.01
Or the
```
SP
```
value in the same key should be
1
In C# (taken from the first comment), you could do something along these lines:
```
```
const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);
var version = subKey.GetValue("Version").ToString();
var servicePack = subKey.GetValue("SP").ToString();
```
```


Question:
I have two users Bob and Alice in Oracle, both created by running the following commands as sysdba from sqlplus:

   create user $blah identified by $password;
   grant resource, connect, create view to $blah;

I want Bob to have complete access to Alice's schema (that is, all tables), but I'm not sure what grant to run, and whether to run it as sysdba or as Alice.

Happy to hear about any good pointers to reference material as well -- don't seem to be able to get a good answer to this from either the Internet or "Oracle Database 10g The Complete Reference", which is sitting on my desk.

Answer:
AFAIK you need to do the grants object one at a time.
Typically you'd use a script to do this, something along the lines of:
```
```
SELECT 'GRANT ALL ON '||table_name||' TO BOB;'
FROM   ALL_TABLES
WHERE  OWNER = 'ALICE';
```
```
And similar for other db objects.
You could put a package in each schema that you need to issue the grant from which will go through all call each GRANT statement via an EXECUTE IMMEDIATE.
e.g.
```
```
PROCEDURE GRANT_TABLES
   IS
   BEGIN

      FOR tab IN (SELECT table_name
                  FROM   all_tables
                  WHERE  owner = this_user) LOOP
         EXECUTE IMMEDIATE 'GRANT SELECT, INSERT, UPDATE, DELETE ON '||tab.table_name||' TO other_user';
      END LOOP;
   END;
```
```


Question: I have a fairly simple const struct in some C code that simply holds a few pointers and would like to initialize it statically if possible. Can I and, if so, how?

Answer:
You can, if the pointers point to global objects:
```
```
// In global scope
int x, y;
const struct {int *px, *py; } s = {&x, &y};
```
```


Question:
My goal is to recognize simple gestures from accelerometers mounted on a sun spot. A gesture could be as simple as rotating the device or moving the device in several different motions. The device currently only has accelerometers but we are considering adding gyroscopes if it would make it easier/more accurate.

Does anyone have recommendations for how to do this? Any available libraries in Java? Sample projects you recommend I check out? Papers you recommend?

The sun spot is a Java platform to help you make quick prototypes of systems. It is programmed using Java and can relay commands back to a base station attached to a computer. If I need to explain how the hardware works more leave a comment.

Answer:
The accelerometers will be registering a constant acceleration due to gravity, plus any acceleration the device is subjected to by the user, plus noise.
You will need to low pass filter the samples to get rid of as much irrelevant noise as you can. The worst of the noise will generally be higher frequency than any possible human-induced acceleration.
Realise that when the device is not being accelerated by the user, the only force is due to gravity, and therefore you can
deduce its attitude
in space. Moreover, when the total acceleration varies greatly from 1g, it must be due to the user accelerating the device; by subtracting last known estimate of gravity, you can roughly estimate in what direction and by how much the user is accelerating the device, and so obtain data you can begin to match against a list of known gestures.
With a single three-axis accelerometer you can detect the current pitch and roll, and also acceleration of the device in a straight line. Integrating acceleration minus gravity will give you an estimate of current velocity, but the estimate will rapidly drift away from reality due to noise; you will have to make assumptions about the user's behaviour before /  between / during gestures, and guide them through your UI, to provide points where the device is not being accelerated and you can reset your estimates and reliably estimate the direction of gravity. Integrating again to find position is unlikely to provide usable results over any useful length of time at all.
If you have two three-axis accelerometers some distance apart, or one and some gyros, you can also detect rotation of the device (by comparing the acceleration vectors, or from the gyros directly); integrating angular momentum over a couple of seconds will give you an estimate of current yaw relative to that when you started integrating, but again this will drift out of true rapidly.


Question:
I'm in need of a lightweight library for 2d & 3d vectors and 3x3 & 4x4 matrices. In basic C.
Just so I don't reinvent the wheel suboptimally.

Any suggestions?

Answer:
Assuming you're coding for x86, you might look into Intel's
Integrated Performance Primitives
(IPP) and
Math Kernel Library
(MKL).  These provide super-duper-fast libraries (probably faster than anyone else could write, since they're optimized for non-public microarchitecture details) for lots of common operations, including vectors and matrices.


Question:
It seems like Microsoft had a great idea with the ObservableCollection.  They are great for binding, and are super fast on the UI.

However, requiring a context switch to the Dispatcher Thread every time you want to tweak it seems like a bit much.  Does anyone know the best practices for using them?  Is it simply to populate an ICollection as a message object in the business layer, then create the ObservableCollection in the UI layer?  How do you then handle updates to the collection on the UI?

Answer: Is updating the ObservableCollection on the UI thread really causing that much of a bottleneck for your application? If not, stick with updating it on the UI thread. Remember, it's not really a context switch that's happening when you run something with the Dispatcher - instead, you're simply submitting a job to the UI thread, which is an already running thread, which the OS will context switch to at some point anyway. The UI thread pulls your submitted job off of an internal queue and executes it. You're not forcing the context switch yourself.


Question:
I'm looking for best practices for performing strict (whitelist) validation/filtering of user-submitted HTML.

Main purpose is to filter out XSS and similar nasties that may be entered via web forms.  Secondary purpose is to limit breakage of HTML content entered by non-technical users e.g. via WYSIWYG editor that has an HTML view.

I'm considering using HTML Purifier, or rolling my own by using an HTML DOM parser to go through a process like HTML(dirty)->DOM(dirty)->filter->DOM(clean)->HTML(clean).

Can you describe successes with these or any easier strategies that are also effective?  Any pitfalls to watch out for?

Answer:
User-submitted HTML isn't always valid, or indeed complete. Browsers will interpret a wide range of invalid HTML and you should make sure you can catch it.
Also be aware of the valid-looking:
```
```

```
```
and
```
```
click
```
```


Question: What is the difference between these three heavily related fields? Is there one specific whole they are all a part of (aside from CS)?

Answer:
Machine Learning
could
be considered a part of AI, however I would classify Machine Learning as the study of creation of semantic models and adaptive behavior with AI being the overall science of systems that intelligent-seeming behavior.
Most of what goes as "AI" is rather simplistic, but highly effective, such as heuristics and the like.
Soft Computing doesn't fell like it has many ML and AI components as it is more about analysis of complex systems.  I could be wrong though.  As with most things in computer science, the deeper you dig, the more you discover that it's all related.


Question:
I've got a file whose format I'm altering via a python script.  I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".

My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?

Answer:
You could try:
```
```
>>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord")
'Word Word Word'
```
```


Question:
I've declared Javascript arrays in such a way that I could then access them by a key, but it was a long time ago, and I've forgotten how I did it.

Basically, I have two fields I want to store, a unique key, and its value. I know there is a way to do it.. something like:

var jsArray = new {key: 'test test', value: 'value value'},
              new {key: 'test 2', value: 'value 2'};

and accessed like:

value = jsArray[key]

Can someone remind me?

Answer:
You can do it in different ways:
```
```
var a = {'a':0, 'b':1, 'c':2};

var b = new Array();
b['a'] = 0;
b['b'] = 1;
b['c'] = 2;

var c = new Object();
c.a = 0;
c.b = 1;
c.c = 2;
```
```


Question:
Is it possible to play video from data that has been embedded in a swf at compile time (with the [Embed] metatag)?

The "Import Video->Embed" feature provided by Flash CS3 etc. is not acceptable because it has many severe limitations (including sound synchronization issues, a maximum number of frames, and other caveats)

I'm interested in being able to bundle flv video data in a swf (along with other assets), which will be played by an AIR application.

I don't think it can be done. Anyone disagree?

Answer:
You can import a flv into a swf file using the Flash IDE - I've done that before. You can drop it onto the timeline of a MovieClip just like a sound and then drop that movieclip onto the stage for it to play. In Flash CS3 do File>Import>Import Video and select the flv. Choose the video and then on the next stop of the wizard choose "Embed ..... ", Here is a link to an
Adobe Developer center article on embedding flvs into swfs
.
I have not done so myself, but I can see no reason why you could access the flv from the library of a loaded swf.
FYI: It looks like this was a bug that was deferred. It doesn't look like Adobe currently allows embedding using the Embed meta tag. Here is a
forum post
on the issue and a link to the
bug tracker
.