q:
What resources have to be manually cleaned up in C# and what are the consequences of not doing so?

For example, say I have the following code:

myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
// Use Brush

If I don't clean up the brush using the dispose method, I'm assuming the garbage collector frees the memory used at program termination? Is this correct?

What other resources do I need to manually clean up?

[A]
Handles to internal windows data structures.
Database connections.
File handles.
Network connections.
COM/OLE references.
The list goes on.
It's important to call
```
Dispose
```
or even better yet, use the
```
using
```
pattern.
```
```
using (SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black))
{
    // use myBrush
}
```
```
If you don't dispose something, it'll be cleaned up when the garbage collector notices that there are no more references to it, which may be after some time.
In the case of
```
System.Drawing.Brush
```
, Windows will keep internal windows structures for the brush loaded in memory until all programs release their handle.


q:
I love vim and the speed it gives me. But sometimes, my fingers are too speedy and I find myself typing :WQ instead of :wq. (On a German keyboard, you have to press Shift to get the colon :.) Vim will then complain that WQ is Not an editor command.

Is there some way to make W and Q editor commands?

[A]
Try
```
```
:command WQ wq
 :command Wq wq
 :command W w
 :command Q q
```
```
This way you can define your own commands. See
```
:help command
```
for more information.

s: huggingface

c: devops

d: intermediate


q:
When programming by contract a function or method first checks whether its preconditions are fulfilled, before starting to work on its responsibilities, right? The two most prominent ways to do these checks are by assert and by exception.

assert fails only in debug mode. To make sure it is crucial to (unit) test all separate contract preconditions to see whether they actually fail.

exception fails in debug and release mode. This has the benefit that tested debug behavior is identical to release behavior, but it incurs a runtime performance penalty.

Which one do you think is preferable?

See releated question here

[A]
Disabling assert in release builds is like saying "I will never have any issues whatsoever in a release build", which is often not the case. So assert shouldn't be disabled in a release build. But you don't want the release build crashing whenever errors occur either, do you?
So use exceptions and use them well. Use a good, solid exception hierarchy and ensure that you catch and you can put a hook on exception throwing in your debugger to catch it, and in release mode you can compensate for the error rather than a straight-up crash. It's the safer way to go.


q:
I do not currently have this issue, but you never know, and thought experiments are always fun.

Ignoring the obvious problems that you would have to have with your architecture to even be attempting this, let's assume that you had some horribly-written code of someone else's design, and you needed to do a bunch of wide and varied operations in the same code block, e.g.:

WidgetMaker.SetAlignment(57);
contactForm["Title"] = txtTitle.Text;
Casserole.Season(true, false);
((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true;

Multiplied by a hundred.  Some of these might work, others might go badly wrong.  What you need is the C# equivalent of "on error resume next", otherwise you're going to end up copying and pasting try-catches around the many lines of code.

How would you attempt to tackle this problem?

[A]
```
On Error Resume Next
```
is a really bad idea in the C# world. Nor would adding the equivalent to
```
On Error Resume Next
```
actually help you. All it would do is leave you in a bad state which could cause more subtle errors, data loss and possibly data corruption.
But to give the questioner his due, you could add a global handler and check the TargetSite to see which method borked. Then you could at least know what line it borked on. The next part would be to try and figure out how to set the "next statement" the same way the debugger does it. Hopefully your stack won't have unwound at this point or you can re-create it, but it's certainly worth a shot. However, given this approach the code would have to run in Debug mode every time so that you would have your debug symbols included.


q: If there is a cookie set for a subdomain, metric.foo.com, is there a way for me to delete the metric.foo.com cookie on a request to www.foo.com? The browser (at least Firefox) seems to ignore a Set-Cookie with a domain of metric.foo.com.

[A]
Cookies are only readable by the domain that created them, so if the cookie was created at metric.foo.com, it will have to be deleted under the same domain as it was created.  This includes sub-domains.
If you are required to delete a cookie from metric.foo.com, but are currently running a page at www.foo.com, you will not be able to.
In order to do this, you need to load the page from metric.foo.com, or create the cookie under foo.com so it can be accessable under any subdomain.  OR use this:
Response.cookies("mycookie").domain = ".foo.com"
...while creating it, AND before you delete it.
..untested - should work.


q:
MySQL's explain output is pretty straightforward. PostgreSQL's is a little more complicated. I haven't been able to find a good resource that explains it either.

Can you describe what exactly explain is saying or at least point me in the direction of a good resource?

[A]
It executes from most indented to least indented, and I believe from the bottom of the plan to the top. (So if there are two indented sections, the one farther down the page executes first, then when they meet the other executes, then the rule joining them executes.)
The idea is that at each step there are 1 or 2 datasets that arrive and get processed by some rule.  If just one dataset, that operation is done to that data set.  (For instance scan an index to figure out what rows you want, filter a dataset, or sort it.) If two, the two datasets are the two things that are indented further, and they are joined by the rule you see. The meaning of most of the rules can be reasonably easily guessed (particularly if you have read a bunch of explain plans before), however you can try to verify individual items either by looking in the documentation or (easier) by just throwing the phrase into Google along with a few keywords like
```
EXPLAIN
```
.
This is obviously not a full explanation, but it provides enough context that you can usually figure out whatever you want. For example consider this plan from an actual database:
```
```
explain analyze
select a.attributeid, a.attributevalue, b.productid
from orderitemattribute a, orderitem b
where a.orderid = b.orderid
and a.attributeid = 'display-album'
and b.productid = 'ModernBook';

------------------------------------------------------------------------------------------------------------------------------------------------------------

 Merge Join  (cost=125379.14..125775.12 rows=3311 width=29) (actual time=841.478..841.478 rows=0 loops=1)
   Merge Cond: (a.orderid = b.orderid)
   ->  Sort  (cost=109737.32..109881.89 rows=57828 width=23) (actual time=736.163..774.475 rows=16815 loops=1)
         Sort Key: a.orderid
         Sort Method:  quicksort  Memory: 1695kB
         ->  Bitmap Heap Scan on orderitemattribute a  (cost=1286.88..105163.27 rows=57828 width=23) (actual time=41.536..612.731 rows=16815 loops=1)
               Recheck Cond: ((attributeid)::text = 'display-album'::text)
               ->  Bitmap Index Scan on (cost=0.00..1272.43 rows=57828 width=0) (actual time=25.033..25.033 rows=16815 loops=1)
                     Index Cond: ((attributeid)::text = 'display-album'::text)
   ->  Sort  (cost=15641.81..15678.73 rows=14769 width=14) (actual time=14.471..16.898 rows=1109 loops=1)
         Sort Key: b.orderid
         Sort Method:  quicksort  Memory: 76kB
         ->  Bitmap Heap Scan on orderitem b  (cost=310.96..14619.03 rows=14769 width=14) (actual time=1.865..8.480 rows=1114 loops=1)
               Recheck Cond: ((productid)::text = 'ModernBook'::text)
               ->  Bitmap Index Scan on id_orderitem_productid  (cost=0.00..307.27 rows=14769 width=0) (actual time=1.431..1.431 rows=1114 loops=1)
                     Index Cond: ((productid)::text = 'ModernBook'::text)
 Total runtime: 842.134 ms
(17 rows)
```
```
Try reading it for yourself and see if it makes sense.
What I read is that the database first scans the
```
id_orderitem_productid
```
index, using that to find the rows it wants from
```
orderitem
```
, then sorts that dataset using a quicksort (the sort used will change if data doesn't fit in RAM), then sets that aside.
Next, it scans
```
orditematt_attributeid_idx
```
to find the rows it wants from
```
orderitemattribute
```
and then sorts that dataset using a quicksort.
It then takes the two datasets and merges them.  (A merge join is a sort of "zipping" operation where it walks the two sorted datasets in parallel, emitting the joined row when they match.)
As I said, you work through the plan inner part to outer part, bottom to top.


q:
How far do you go with const?  Do you just make functions const when necessary or do you go the whole hog and use it everywhere?  For example, imagine a simple mutator that takes a single boolean parameter:

void SetValue(const bool b) { my_val_ = b; }

Is that const actually useful?  Personally I opt to use it extensively, including parameters, but in this case I wonder if it's worthwhile?

I was also surprised to learn that you can omit const from parameters in a function declaration but can include it in the function definition, e.g.:

.h file

void func(int n, long l);

.cpp file

void func(const int n, const long l)

Is there a reason for this? It seems a little unusual to me.

[A]
The reason is that
```
const
```
for the parameter only applies locally within the function, since it is working on a copy of the data. This means the function signature is really the same anyways. It's probably bad style to do this a lot though.
I personally tend to not use
```
const
```
except for reference and pointer parameters. For copied objects it doesn't really matter, although it can be safer as it signals intent within the function. It's really a judgement call. I do tend to use
```
const_iterator
```
though when looping on something and I don't intend on modifying it, so I guess to each his own, as long as
```
const
```
correctness for reference types is rigorously maintained.


q: Say I have a table in a SQL 2005 database with 2,000,000+ records and a few indexes.  What advantage is there to using index hints in my queries?  Are there ever disadvantages to using index hints in queries?

[A]
First, try using SQL Profiler to generate a .trc file of activity in your database for a normal workload over a few hours.  And then use the "Database Engine Tuning Advisor" on the SQL Server Management Studio Tools menu to see if it suggests any additional indexes, composite indexes, or covering indexes that may be beneficial.
I never use query hints and mostly work with multi-million row databases.  They sometimes can affect performance negatively.


q:
I work with a bunch of sets in order to generate constrained random traffic, but I want to be able to call a Specman macro that computes the complement of a set with syntax like:

COMPLEMENT begin
   domain=[0..10,24..30],
   complementing_set=[2..3,27..30]
end

and have it generate:

[0..1,4..10,24..26]

Every time I need the complement of a set I'm using fully populated lists (e.g. {0;1;2;3....} ) and then removing elements, instead of using Specman's built-in int_range_list object.  And I'm also doing a lot of these set calculations at run-time instead of compile-time.

[A]
You can try this:
```
```
var domain: list of int = {0..10, 24..30};
var complementing_set: list of int = {2..3, 27..30};
var complement: list of int = domain.all(it in complementing set);
```
```
The
```
all
```
pseudo-method generates a sublist of the parent list of all the elements in the parent list for which the condition in the parentheses holds.


q: Let's assume that some developer in my team shelved his changes that he did in branch A. And I am working on branch B. Can I unshelve his changes into branch B? (By GUI or command prompt)

[A]
The shelf information includes the specific path it goes to.  Unfortunately I don't know of any automatic way to unshelve to any location other than the one it was shelved to.  The times I've wanted to do this I had to check out the equivalent files in the new branch, unshelve from the old branch, then manually copy the files over.
EDIT:  Well, I guess I was doing it the hard way.  I'll have to try out Curt's solution. :)


q: I'm using Express currently. What extra features do I get with the full edition?

[A]
Most of the High-Availability options are missing from the Express Edition. The Express
editions
are great for development purposes. Here's the comparison facts:
http://www.microsoft.com/sql/prodinfo/features/compare-features.mspx


q:
I've currently got multiple select's on a page that are added dynamically with ajax calls using jquery.

The problem I've had is I could not get the change event to work on the added select unless I use the onchange inside the tag e.g.

<select id="Size" size="1" onchange="onChange(this);">

This works, but I'm wondering if there's a way to get it to be assigned by jquery. I've tried using $('select').change(onChange($(this)); in the usual place of $(document).ready but that didn't work.

I've tried adding the event with bind after the ajax call but that did not work either.

Any better way to assign the event?

[A]
$('select').change(onChange($(this));
You need to understand the difference between calling a function and passing it around as an object.  Functions are first-class objects in JavaScript, they are an object just like anything else, so they can be stored in variables, passed as arguments to other functions, and so on.
The code as you have it calls the onChange function, and gives the result to jQuery's change function.  You don't want that.  The idea is to pass
the function itself
to jQuery's change function, and jQuery calls it when it is appropriate to do so.
When you have parentheses - () - after a function's name, then you are calling it.  Otherwise, you are treating it as an object.  So what you
intend
to do can be accomplished like this:
```
```
$('select').change(onChange);
```
```


q:
I have an script that receives an encrypted url and from that generates a download, the most critic par of the script is this:

$MimeType = new MimeType();
$mimetype = $MimeType->getType($filename);
$basename = basename($filename);
header("Content-type: $mimetype");
header("Content-Disposition: attachment; filename=\"$basename\"");
header('Content-Length: '. filesize($filename));
if ( @readfile($filename)===false ) {
  header("HTTP/1.0 500 Internal Server Error");
  loadErrorPage('500');
}

Downloads works as charm in any Browser except IE, I have seen problems related to 'no-cache' headers but I don't send anything like that, they talk about utf-8 characters, but there is not any utf-8 characters(and the $filename has not any utf-8 characteres neither).

[A]
This site
has a problem similar to yours in IE6. To summarize:
session_start() by default sends a cache control header including "no-store".
  Internet Explorer takes this a bit too literally, but doesn't have appropriate
  error handling for the case, and as a result explodes cryptically when you
  attempt to save the output page to disk.
Before session_start(), add "session_cache_limiter('none');", or look up that
  function and tweak the limiter as appropriate (probably 'private' is closer to
  the mark).
I realize the code snippet you posted does not include a call to
```
session_start();
```
, but I figured I'd share this possible solution in case you do have a call to it and just didn't show us.


q:
I'm successfully using VBScript within WScript to remotely read and write IIS configurations from the server. When I attempt to run these same scripts from my desk box they fail, though. Example:

Dim vdir
Set vdir = GetObject("IIS://servername/w3svc/226/root")

Error = "Invalid syntax"

The code works perfectly when run from one IIS server to another, but I'd like to run it from my XP Workstation. It would seem reasonable that there's a download of ADSI available that will make things work from my desktop, but I cannot find one. I downloaded ADAM but that only got me a small portion of the functionality I need.

Any hints out there? Thank you.

[A]
That could be tough to do what you want.  You can import a git repo into svn via something like this:
http://code.google.com/p/support/wiki/ImportingFromGit
, but I think you will have conflicts.  You could just recreate your SVN repo from scratch based on your git repo.
For future reference, it probably would've been easier to just use Git as an SVN client:
```
```
git-svn clone path/to/your/svn/repo
git-commit -a -m 'my small change'
vi some files to change.txt
git-commit -a -m 'another small change'
git-svn dcommit # sends your little changes as individual svn commits
```
```


q:
What is the best way to handle large numeric inputs in C++ (for example 10^100)?

For algorithms I usually switch over to ruby and I sometimes use strings.

Any other good methods?

[A] assuming you are talking about inputting numbers, double precision would get you up to 1.7976931348623157 x 10^308


q:
Basically what the title says. (Forgive me because I am a .NET newb)

In my department, we have a server running .net 3.5 and ever since I got into this section I have been using LINQ.  However, I am starting a personal project on a different server (obviously), so 2 questions:

What do I need to get up and running with LINQ?

What does the server need to run LINQ?

Will .net 2.0 work on the server?

The code behind would be C# if that matters.

Edit:
Would I have to compile it in 3.5 or would 2.0 work?

[A]
I'm assuming you're talking about
LINQ to SQL
specifically.
You would only need v3.5 of the framework installed on your development machine and the server.
The server doesn't run linq; linq will in the end send SQL statements to your server.
The language doesn't matter.


q:
I want alwaysPositive to be assigned a positive number with all possible values for lareValue1 and largeValue2 (these are at least 1).

The following statement causes a buffer overflow:

int alwaysPositive = (largeValue1 + largeValue2) / 2;

I know I can prevent it by substracting and adding:

int alwaysPositive = largeValue1 + ((largeValue2 - largeValue1) / 2);

But in other programming languages I can use an unsigned bitshift to do the trick:

int alwaysPositive3 = (largeValue1 + largeValue2) >>> 1;

How can I do this in C#?

The answers below all solve the problem. There are probably lots of ways to do this, but they all (including my solutions) have one thing in common: they all look obfuscated.

[A]
You could use uints:
```
```
uint alwaysPositive = (uint)(largeValue1 + largeValue2) / 2;
```
```


q:
I need to find a way to crawl one of our company's web applications and create a static site from it that can be burned to a cd and used by traveling sales people to demo the web site. The back end data store is spread across many, many systems so simply running the site on a VM on the sale person's laptop won't work. And they won't have access to the internet while at some clients (no internet, cell phone....primitive, I know).

Does anyone have any good recommendations for crawlers that can handle things like link cleanup, flash, a little ajax, css, etc? I know odds are slim, but I figured I'd throw the question out here before I jump into writing my own tool.

[A]
By using a
WebCrawler
, e.g. one of these:
DataparkSearch is a crawler and search engine released under the GNU General Public License.
GNU Wget is a command-line operated crawler written in C and released under the GPL. It is typically used to mirror web and FTP sites.
HTTrack uses a Web crawler to create a mirror of a web site for off-line viewing. It is written in C and released under the GPL.
ICDL Crawler is a cross-platform web crawler written in C++ and intended to crawl websites based on Website Parse Templates using computer's free CPU resources only.
JSpider is a highly configurable and customizable web spider engine released under the GPL.
Larbin by Sebastien Ailleret
Webtools4larbin by Andreas Beder
Methabot is a speed-optimized web crawler and command line utility written in C and released under a 2-clause BSD License. It features a wide configuration system, a module system and has support for targeted crawling through local filesystem, HTTP or FTP.
Jaeksoft WebSearch is a web crawler and indexer build over Apache Lucene. It is released under the GPL v3 license.
Nutch is a crawler written in Java and released under an Apache License. It can be used in conjunction with the Lucene text indexing package.
Pavuk is a command line web mirror tool with optional X11 GUI crawler and released under the GPL. It has bunch of advanced features compared to wget and httrack, eg. regular expression based filtering and file creation rules.
WebVac is a crawler used by the Stanford WebBase Project.
WebSPHINX (Miller and Bharat, 1998) is composed of a Java class library that implements multi-threaded web page retrieval and HTML parsing, and a graphical user interface to set the starting URLs, to extract the downloaded data and to implement a basic text-based search engine.
WIRE - Web Information Retrieval Environment [15] is a web crawler written in C++ and released under the GPL, including several policies for scheduling the page downloads and a module for generating reports and statistics on the downloaded pages so it has been used for web characterization.
LWP::RobotUA (Langheinrich , 2004) is a Perl class for implementing well-behaved parallel web robots distributed under Perl 5's license.
Web Crawler Open source web crawler class for .NET (written in C#).
Sherlock Holmes Sherlock Holmes gathers and indexes textual data (text files, web pages, ...), both locally and over the network. Holmes is sponsored and commercially used by the Czech web portal Centrum. It is also used by Onet.pl.
YaCy, a free distributed search engine, built on principles of peer-to-peer networks (licensed under GPL).
Ruya Ruya is an Open Source, high performance breadth-first, level-based web crawler. It is used to crawl English and Japanese websites in a well-behaved manner. It is released under the GPL and is written entirely in the Python language. A SingleDomainDelayCrawler implementation obeys robots.txt with a crawl delay.
Universal Information Crawler Fast developing web crawler. Crawls Saves and analyzes the data.
Agent Kernel A Java framework for schedule, thread, and storage management when crawling.
Spider News, Information regarding building a spider in perl.
Arachnode.NET, is an open source promiscuous Web crawler for downloading, indexing and storing Internet content including e-mail addresses, files, hyperlinks, images, and Web pages. Arachnode.net is written in C# using SQL Server 2005 and is released under the GPL.
dine is a multithreaded Java HTTP client/crawler that can be programmed in JavaScript released under the LGPL.
Crawljax is an Ajax crawler based on a method which dynamically builds a `state-flow graph' modeling the various navigation paths and states within an Ajax application. Crawljax is written in Java and released under the BSD License.


q:
From time to time, I need to dump USB traffic under Windows, mostly to support hardware under Linux, so my primary goal is to produce dump files for protocol analysis.

For USB traffic, it seems that SniffUsb is the clear winner... It works under Windows XP (but not later) and has a much nicer GUI than earlier versions. It produces huge dump files, but everything is there.

However, my device is in fact a USB serial device, so I turned to Portmon which can sniff serial port traffic without the USB overhead.

[A]
Personally, I'd use
QEMU
or
KVM
and instrument their USB passthrough code, and then use
libusb
to prototype the replacement driver in user space (this latter bit I've done before;
writing USB device drivers in Python
is fun!).


q:
At work I'm using Perl 5.8.0 on Windows.

When I first put Perl on, I went to CPAN, downloaded all the sources, made a few changes (in the .MAK file(?) to support threads, or things like that), and did nmake / nmake test / nmake install. Then, bit by bit, I've downloaded individual modules from CPAN and done the nmake dance.

So, I'd like to upgrade to a more recent version, but the new one must not break any existing scripts. Notably, a bunch of "use" modules that I've installed must be installed in the new version.

What's the most reliable (and easiest) way to update my current version, ensuring that everything I've done with the nmake dance will still be there after updating?

[A]
When I did it I installed the newer one into a separate directory.  There's a bit of added confusion running two versions, but it definitely helps make sure everything's working first, and provides a quick way of switching back to the old one in a pinch.  I also set up Apache to run two separate services, so I could monkey around with the newer Perl in one service without touching the production one on the old Perl.
It's probably a lot wiser, in hindsight, to install on a separate computer, and do your testing there. Record every configuration change you need to make.
I am not sure about building it yourself—I always just used prepackaged binaries for Windows.
I'm not sure I understand exactly what you're asking. Do you have a list of changes you made to the 5.8 makefile? Or is the question how to obtain such a list? Are you also asking how to find out which packages above the base install you've obtained from CPAN? Are you also asking how to test that your custom changes won't break those packages if you get them from CPAN again?


q:
Just a small SVN "problem" here.

I setup my own SVN server Setting up Subversion on Windows

Now I made a rep in which all my projects will go.

Now, I checked the rep out in a folder called "Projects".

Now If I make a project and check it in, that project is revision 1. If I make a second project, and check it in, that Project is at revision 2. Thus, if I make a change to Project 1, that project will then be at Revision 3.

What I would really want is for each project to have its own revision scheme. How do I do this?

[A]
The only way is to have each project in a completely separate repository.  Items within the same repository will always exhibit the behavior you mentioned in your question.
From Here
Unlike those of many other version control systems, Subversion's revision numbers apply to entire trees, not individual files. Each revision number selects an entire tree, a particular state of the repository after some committed change.


q:
We have been using GenuineChannels in our product for the last 4 years. GenuineChannels now appears to have become unsupported and the main developer guy Dmitri has I think joined Microsoft. I have the source as part of the product but not the networking / .net knowledge to support it.

Has anyone found a good alternative to GenuineChannels for good .net remoting? I need our software product to run on top of some supported software!

[A]
WCF (Windows Communication Foundation) is the way to go - much more scalable, easily swappable to other technologies (if you need in the future), and builtin to .NET 3.0.
A lot of other nice stuff there, too...
http://msdn.microsoft.com/en-us/netframework/aa663324.aspx


q: Like the title says, how do you create custom code snippets in Visual Studio 2008?

[A]
Here's a link to a utility for Creating/editing Snippets. It works for more languages than just VB despite the classification in the link.
http://msdn.microsoft.com/en-us/vbasic/bb973770.aspx


q:
Documentation can be found here

It says in the example:

onDrop:
Called whenever a Draggable is released over the Droppable and the Droppable is accepts it. The callback gets three parameters: the Draggable element, the Droppable element and the Event. You can extract additional information about the drop – like if the Ctrl or Shift keys were pressed – from the Event object.

Then it gives some code

Droppables.add('shopping_cart', {
  accept: 'products',
  onDrop: function(element) {
    $('shopping_cart_text').update('Dropped the ' + element.alt + ' on me.');
  }
});

It uses the ambiguous word 'element' in the code.  My question is, does anyone have a good example on how to reference the draggable element and the droppable element in this callback javascript function?

[A]
Going by the example further down the page, the callback function can take as many of the parameters as you need:
```
```
onDrop: function() { $('droppable_demo').highlight(); }
```
```
In this case, they have used none of the callback parameters.  To this end, presumably to access all three as mentioned in the paragraph you quoted, you can define:
```
```
onDrop: function(dragged, dropped, event) {  }
```
```


q:
My website makes a lot of requests. I often need to cancel all current requests, so that the browser is not blocking relevant new requests.

I have 3 kinds of requests:

Ajax

inserted script-tags (which do JSONP-Communication)

inserted image-tags (which cause the browser to request data from various servers)

For Ajax its no problem as the XMLHttpRequest object supports canceling.
What I need is a way to make any browser stop loading resources, from DOM-Objects.

Looks like simply removing an object (eg. an image-tag) from the DOM only helps avoiding an request, if the request is not already running.

UPDATE: a way to cancel all requests, which are irrelevant, instead of really any request would be perfect.

[A]
I think
```
document.close()
```
stops all requests, but I'm not so sure about it.


q:
I am re-designing an application for a ASP.NET CMS that I really don't like. I have made som improvements in performance only to discover that not only does this CMS use MS SQL but some users "simply" use MS Access database.

The problem is that I have some tables which I inner join, that with the MS Access version are in two different files. I am not allowed to simply move the tables to the other mdb file.

I am now trying to figure out a good way to "inner join" across multiple access db files?

It would really be a pity if I have fetch all the data and the do it programmatically!

Thanks

[A]
If you have access to the MDBs, and are able to change them, you might consider using Linked Tables. Access provides the ability to link to external data (in other MDBs, in Excel files, even in SQL Server or Oracle), and then you can perform your joins against the links.
I'd strongly encourage performance testing such an option. If it's feasible to migrate users of the Access databases to another system (even SQL Express), that would also be preferable -- last I checked, there are no 64-bit JET drivers for ODBC anymore, so if the app is ever hosted in a 64-bit environment, these users will be hosed.


q:
Does anyone have a good guide to capabilities of Windows Services under XP? In particular, I am trying to find out what happens when a program being run as a service tries to open windows, but hasn't been given permission to interact with the desktop.

Basically, I have a program that is/was a GUI application, that should be able to run as a service for long term background processing. Rewriting the program to not display the GUI elements when doing background processing is a major effort, so I'd like to see if there is just a way to ignore the UI elements. It is sort of working now, as long as too many windows aren't opened. I'm trying to figure out what limits I might be running into. Ideally, there would be an MSDN page that discusses this, but I've had no luck finding one yet.

[A]
A
service
in Microsoft Windows is a program that runs whenever the computer is running the operating system. It does not require a user to be logged on. Services are needed to perform user-independent tasks such as directory replication, process monitoring, or services to other machines on a network, such as support for the Internet HTTP protocol
Usually it is implemented as a console application that runs in the background and performs tasks that don't require user interaction.
The installed services can be configured through the Services applet, available from
```
Control Panel --> Administrative Tools
```
in Windows 2000/XP.
Services can be configured to start automatically when operating system starts, so you dont have to start each of them manually after a system reboot.
Creating a Simple Service - MSDN Article
Writing Windows Services Made easy - Code Project Article
Five Steps to Writing Windows Services in C - DevX Article


q:
I know this is probably the dumbest question ever, however I am a total beginner when it comes to CSS; how do you hyperlink an image on a webpage using an image which is sourced from CSS? I am trying to set the title image on my website linkable to the frontpage. Thanks!

Edit: Just to make it clear, I'm sourcing my image from CSS, the CSS code for the header div is as follows:-

#header
{
    width: 1000px;
    margin: 0px auto;
    padding: 0px 15px 0px 15px;
    border: none;
    background: url(images/title.png) no-repeat bottom;
    width: 1000px;
    height: 100px;
}

I want to know how to make this div hyperlinked on my webpage without having to make it an anchor rather than a div.

[A]
That's really not a CSS thing. You still need your A tag to make that work. (But use CSS to make sure the image border is either removed, or designed to your required spec.)
```
```

```
```
EDIT: Taking original intent (updated question) into account, a new code sample is below:
```
```

```
```
You're still in an HTML world for links, as described by other answers on this question.


q:
Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as:

$numbers = array(1,3,4,5,6,8,11,12,14,15,16);

The ranges would be:

 1,3-6,8,11-12,14-16

[A]
Here's a python implementation, it should be easy enough to follow
```
```
numbers = [1,3,4,5,6,8,11,12,14,15,16];

def is_predecessor(i1, i2):
    if i1 == i2 - 1:
        return True;
    else:
        return False;

def make_range(i1, i2):
    if i1 == i2:
        return str(i1);
    else:
        return str(i1) + "-" + str(i2);

previous_element = None;
current_start_element = None;

for number in numbers:
    if not is_predecessor(previous_element, number):
        if current_start_element is not None:
            print make_range(current_start_element, previous_element);
        current_start_element = number;
    previous_element = number;

# handle last pair
if current_start_element is not None:
    print make_range(current_start_element, previous_element);
```
```
This outputs:
```
```
1
3-6
8
11-12
14-16
```
```
I know, I know, it isn't an
algorithm
, but I found it harder to actually explain it without having indentation problems than to just implement a solution for it.


q:
Here's the code I want to speed up.   It's getting a value from an ADO recordset and converting it to a char*.   But this is slow.    Can I skip the creation of the _bstr_t?

                _variant_t var = pRs->Fields->GetItem(i)->GetValue();

                if (V_VT(&var) == VT_BSTR)
                {
                    char* p = (const char*) (_bstr_t) var;

[A]
This creates a temporary on the stack:
```
```
USES_CONVERSION;
char *p=W2A(var.bstrVal);
```
```
This uses a slightly newer syntax and is probably more robust. It has a configurable size, beyond which it will use the heap so it avoids putting massive strings onto the stack:
```
```
char *p=CW2AEX<>(var.bstrVal);
```
```


q:
I'm trying to use the page-break-inside CSS directive, the class of which is to be attached to a div tag or a table tag (I think this may only work on block elements, in which case it would have to be the table).

I've tried all the tutorials that supposedly describe exactly how to do this, but nothing works. Is this an issue of browser support or has anyone actually gotten this working, the exact bit of CSS looks like this:

@media print {

  .noPageBreak {
     page-break-inside : avoid;
  }
}

[A]
Safari
1.3+
,
Opera
9.2+
,
Konquerer
, and
IE8
all support it, at least to some degree.
Firefox
apparently still does not.


q: For our Django App, we'd like to get an AutoField to start at a number other than 1.  There doesn't seem to be an obvious way to do this.  Any ideas?

[A]
A quick peek at the
source
shows that there doesn't seem to be any option for this, probably because it doesn't always increment by one; it picks the next available key: "An IntegerField that automatically increments according to available IDs" —
djangoproject.com


q: I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?

[A]
You can use strtol
```
```
char string[] = "1101110100110100100000";
char * end;
long int value = strtol (string,&end,2);
```
```


q:
For example if I'm working on Visual Studio 2008, I want the values devenv and 2008 or 9.

The version number is very important...

[A]
This
project
demonstrates the two functions you need:
EnumWindows
and
GetWindowtext


q: I am writing a .NET wrapper class for an existing native class which throws exceptions. What are the best practices for translating between native C++ exceptions and Managed exceptions? Catch and re-throw on a one-to-one basis (e.g. std::invalid_argument -> System.System.ArgumentException)? Is there a mapping already drawn up somewhere?

[A]
There is no standard mapping that I know of.  What I've done in the past is translate the ones I know about, and a catch block for System.Runtime.InteropServices.SEHException.  All non-translated exceptions will be turned into that exception.  As long as you have a debug build of the code that is throwing the exception, you should get a nice stack trace.  Then you can go and look at the exception and write the wrapper.
But on the last project I had to do this on, I went with something much more simple, I ended up writing a couple of System.Exception derivatives for logic_error and runtime_error.  Then I would catch those 2 base classes and use typeid(err) to write the .NET message that got thrown.  This way I didn't "lose" what was being thrown from the C++ but didn't have to map everything except the most important ones.


q:
Is anyone aware of a (preferablly free) webservice that would accept a SOAP or REST request.

This request would contain an IP address, and the service would return an approximation of that IP's location.

EDIT: I need resolution down to the city of possible.

[A]
MaxMind
do a fairly cheap one. You send the IP as a query string parameter, then it sends you back either a 2 letter code or an error code. We used it for quite a while before moving to our own lookup tables, and it's quick and reliable.
Found the link:
http://www.maxmind.com/app/web_services#country
- it's $20 for 200,000 lookups which isn't bad value at all.
EDIT: MaxMind also do a service with resolution down to the city:
http://www.maxmind.com/app/web_services#city
. It's a bit more expensive at $20 for 50,000 queries but that still isn't too bad. I can't vouch for the accuracy of this service though as I have only used the country resolution one, as that's all we need.


q:
I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect.

For example:

           <-----row 1 interval------->
<---find this--> <--and this--> <--and this-->

Please phrase your answer in the form of a SQL WHERE-clause, AND consider the case where the end time in the second table may be NULL.

Target platform is SQL Server 2005, but solutions from other platforms may be of interest also.

[A]
```
```
SELECT *
FROM table1,table2
WHERE table2.start <= table1.end
AND (table2.end IS NULL OR table2.end >= table1.start)
```
```


q:
I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields.

Something like firefox live headers, but for the server side.

[A]
That shouldn't be too hard to write yourself as long as you only need the headers.  Try that:
```
```
import sys

def log_headers(app, stream=None):
    if stream is None:
        stream = sys.stdout
    def proxy(environ, start_response):
        for key, value in environ.iteritems():
            if key.startswith('HTTP_'):
                stream.write('%s: %s\n' % (key[5:].title().replace('_', '-'), value))
        return app(environ, start_response)
    return proxy
```
```


q:
In PHP, replace one URL with another within a string e.g.

New post on the site <a href="http://stackoverflow.com/xyz1">http://stackoverflow.com/xyz1</a></p>

becomes:

New post on the site <a href="http://yahoo.com/abc1">http://yahoo.com/abc1</a></p>

Must work for repeating strings as above. Appreciate this is simple but struggling!

[A]
Use
str_replace()
:
```
```
$text = str_replace('http://stackoverflow.com/xyz1', 'http://yahoo.com/abc1', $text);
```
```
That will replace the first URL with the second URL in $text.


q: How do I totally disable caching in nHibernate?

[A]
Use the IStatelessSession to bypass the first level cache:
http://darioquintana.com.ar/blogging/?p=4
In order to use the second level cache you must explicitly configure it.  You will not use it if you don't.
You can also turn off lazy loading in your mappings. lazy=false.


q:
Not a competition, it is instead me trying to find why a certain regex works in one but not the other.

(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

That's my Regex and I'm trying to run it on

127.255.0.0

Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.

re.findall(regex, string)
preg_match_all($regex, $string, $matches);

Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated.


q: What's the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don't know how large the table is (it is constantly growing). The table does have a column that is automatically incremented and used as a unique identifier for each row.

[A]
```
```
SELECT * FROM table_name ORDER BY auto_incremented_id DESC LIMIT n
```
```


q:
I have been interested in database developing for some time now and decided that MS SQL has a lot to offer in terms of T-SQL and generally much more functionality (not saying that Oracle or Postgres don't have that).

I would like to know:

What are the big paradigm changes I
should expect to see?

How much effort do "regular" companies put
into developing their database (for
transactions, triggers, events, data
cleansing, ETL)?

What can I expect
    from the inner-workings of MS SQL
    developer teams and how they
    interact with the .NET application
    developers?

I hope I have phrased my question correctly. I am not very clued-up about the whole .NET scene.

[A]
Can't answer #1 as I've never worked with mysql but I'll take a shot at #2 and #3.
This tends to depend on the size of the database and/or the size (or professionalism) of the company. Companies with large databases with many users spend a great deal of time indeed making sure that the database both has integrity and is performance tuned. They woudl lose customers if they did not. We have 6 people who do nothing but ETL work and 5 dbas who tune and manage the databases and database servers as well as many many developers who write t-sql code.
As far as #3, in good companies these people work together very well as a team. In bad companies, there is often tension between the two groups and each uses the other group as a scapegaoat for whatever problems occur. I work with a bunch of great .net developers. They respect my database expertise as I respect their .net expertise and we caonsult each other on design issues and tuning issues and in general any issue that needs input from both sides.


q: I have a SQL script that creates a package with a comment containing an ampersand (&). When I run the script from SQL Plus, I am prompted to enter a substitute value for the string starting with &. How do I disable this feature so that SQL Plus ignores the ampersand?

[A]
This may work for you:
```
```
set define off
```
```
Otherwise the ampersand needs to be at the end of a string,
```
```
'StackOverflow &' || ' you'
```
```
EDIT:  I was click-happy when saving...  This was referenced from a
blog
.


q:
I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change?
I don't have any syncronization or Mutual exclusion system in place... but should this code work all the time (imagine a global bool named dataUpdated):

Thread 1:

while(1) {
    if (dataUpdated)
        updateScreen();
    doSomethingElse();
}

Thread 2:

while(1) {
    if (doSomething())
        dataUpdated = TRUE;
}

Does a compiler like gcc optimize this code in a way that it doesn't check for the global value, only considering it value at compile time (because it nevers get changed at the same thred)?

PS: Being this for a game-like application, it really doen't matter if there will be a read while the value is being written... all that matters is that the change gets noticed by the other thread.

[A]
Use the
volatile
keyword to hint to the compiler that the value can change at any time.
```
```
volatile int myInteger;
```
```


q:
When you use the WebBrowser control in .NET you can "embed" an instance of IE in your application, essentially making your own IE-based Web Browser.

Does anyone know how to make any new windows created (like when the user selects "Open in New Window" from the context menu) open up in another Window of Your Web Browser Application, instead of the computers default browser??

[A]
Maybe the Source Code from this CodeProject article can help:
Extended .NET 2.0 WebBrowser Control


q:
I need to allow other Python applications to register callback functions for events in my application.  These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher.

These are all lightweight callbacks running in the same process, so I don't need to send signals across process boundaries.

Is there a good Python library to handle this, or do I need to write my own?

[A]
Are these other applications running in another address space? If so, you'll need to use an interprocess communication library like
D-BUS
.
If you're just sending signals in the same process, try
PyDispatcher


q:
I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?

If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting Unicode and different type sizes (and all browsers for that matter).

[A]
Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.
```
```
var fontSize = 12;
var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px"

console.log(height, width);
```
```
```
```
#Test
{
    position: absolute;
    visibility: hidden;
    height: auto;
    width: auto;
    white-space: nowrap; /* Thanks to Herb Caudill comment */
}
```
```
```
```
<div id="Test">
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</div>
```
```


q:
How can I open multiple Eclipse workspaces at the same time on the Mac?

On other platforms, I can just launch extra Eclipse instances, but the Mac will not let me open the same application twice. Is there a better way than keeping two copies of Eclipse?

[A]
EDIT:
Milhous's answer
seems to be the officially supported way to do this as of 10.5. Earlier version of OS X and even 10.5 and up should still work using the following instructions though.
Open the
command line
(Terminal)
Navigate to your Eclipse installation folder, for instance:
```
cd /Applications/eclipse/
```
```
cd /Developer/Eclipse/Eclipse.app/Contents/MacOS/eclipse
```
```
cd /Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse
```
```
cd /Users/<usernamehere>/eclipse/jee-neon/Eclipse.app/Contents/MacOS
```
Launch Eclipse:
```
./eclipse &
```
This last command will launch eclipse and immediately background the process.
Rinse and repeat to open as many unique instances of Eclipse as you want.
Warning
You might have to
change the Tomcat
server ports in order to run your project in
different/multiple Tomcat instances
, see
Tomcat Server Error - Port 8080 already in use


q:
I'm trying to teach Komodo to fire up IDLE when I hit the right keystrokes.  I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well.  But, giving this path to Komodo causes it to say that 1 is returned.  This appears to be a failure as IDLE doesn't start up.

I thought I'd avoid the shortcut and just use the exact path.  I go to the start menu, find the shortcut for IDLE, right click to look at the properties.  The target is grayed out, but says "Python 2.5.2".  The "Start in" is set to, "C:\Python25\".  The "Open File Location" button is also grayed out.

How do I find out where this shortcut is really pointing?  I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.

[A]
There's a file called
```
idle.py
```
in your Python installation directory in
```
Lib\idlelib\idle.py
```
.
If you run that file with Python, then IDLE should start.
c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py


q:
(Java question)

If I reference a field in an inner class, does this cause a circular dependency between the enclosing class and the inner class?

How can I avoid this?

Here is an example:

public class Outer {

  private Other o;
  private Inner i;

  public Outer() {
    o = new Other();

    i = new Inner() {
      public void doSomething() {
        o.foo();
      }
    };

  }
}

[A]
The syntax you're using in the example is a little off there is no declaration of the class or interface Inner. But there isn't anything wrong with the concept of the example. In Java it will work fine.
I'm not sure what you're doing here, but you may want to consider a more simple design for maintainability etc.
It's a common pattern for anonymous event handlers to reference elements of their parent class, so no reason to avoid it if that's the case, that's how Java was designed instead of having function pointers.


q:
So I was writing some code today that basically looks like this:

string returnString = s.Replace("!", " ")
            .Replace("@", " ")
            .Replace("#", " ")
            .Replace("$", " ")
            .Replace("%", " ")
            .Replace("^", " ")
            .Replace("*", " ")
            .Replace("_", " ")
            .Replace("+", " ")
            .Replace("=", " ")
            .Replace("\", " ")

Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the Replace() function?

[A]
You can use
Regex.Replace()
. All of the characters can be placed between square brackets, which matches any character between the square brackets. Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. The first parameter is the input string and the last parameter is the replacement string.
```
```
var returnString = Regex.Replace(s,@"[!@#\$%\^*_\+=\\]"," ");
```
```


q:
How can UTF-8 strings (i.e. 8-bit string) be converted to/from XML-compatible 7-bit strings (i.e. printable ASCII with numeric entities)?

i.e. an encode() function such that:

encode("“£”") -> "&#8220;&#163;&#8221;"

decode() would also be useful:

decode("&#8220;&#163;&#8221;") -> "“£”"

PHP's htmlenties()/html_entity_decode() pair does not do the right thing:

htmlentities(html_entity_decode("&#8220;&#163;&#8221;")) ->
  "&amp;#8220;&pound;&amp;#8221;"

Laboriously specifying types helps a little, but still returns XML-incompatible named entities, not numeric ones:

htmlentities(html_entity_decode("&#8220;&#163;&#8221;", ENT_QUOTES, "UTF-8"), ENT_QUOTES, "UTF-8") ->
  "&ldquo;&pound;&rdquo;"

[A]
It's a bit of a workaround, but I read a bit about
```
iconv()
```
and i don't think it'll give you numeric entities (not put to the test)
```
```
function decode( $string )
{
  $doc = new DOMDocument( "1.0", "UTF-8" );
  $doc->LoadXML( '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<x />', LIBXML_NOENT );
  $doc->documentElement->appendChild( $doc->createTextNode( $string ) );
  $output = $doc->saveXML( $doc );
  $output = preg_replace( '/<\?([^>]+)\?>/', '', $output );
  $output = str_replace( array( '<x>', '</x>' ), array( '', '' ), $output );
  return trim( $output );
}
```
```
This however, I have put to the test. I might do the reverse later, just don't hold your breath ;-)


q: This came up in  Hidden features of Python, but I can't see good documentation or examples that explain how the feature works.

[A]
```
Ellipsis
```
, or
```
...
```
is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it.
So the syntax for it depends entirely on you, or someone else, having written code to understand it.
Numpy uses it, as stated in the
documentation
. Some examples
here
.
In your own class, you'd use it like this:
```
```
>>> class TestEllipsis(object):
...     def __getitem__(self, item):
...         if item is Ellipsis:
...             return "Returning all items"
...         else:
...             return "return %r items" % item
...
>>> x = TestEllipsis()
>>> print x[2]
return 2 items
>>> print x[...]
Returning all items
```
```
Of course, there is the
python documentation
, and
language reference
. But those aren't very helpful.


q:
I have Drupal 5 site where a button is clicked and it calls a JavaScript function. The function basically builds a string, and then redirects to another page on our site. After clicking the button, sometimes the user gets logged out and sees the "Access Denied" screen, even though they were previously logged in. The page where they are being redirected has the same access restrictions as the previous page, but regardless of that, they shouldn't be getting logged out.

One user has this happen about half the time (the other half it works as it should), and another user has reported always being logged out when clicking that button. However, I'm always able to run it without a hitch on the machines I use, and I suspect it has to do with them using IE6. Has anyone run across this issue before, or have any ideas on what could be causing this? I've searched and posted in the Drupal forum, and searched in this forum, and have had no luck yet.

[A]
Many things come to mind.
Is the page being redirected to on the same domain?  domain.com and www.domain.com are NOT the same as far as cookies are concerned (depending on how they are set)..
Can you reproduce it 100% reliably in any browser? No offense to your users, but users are liars (or at least bad at reporting technical bugs). I wouldn't trust something a user told me as fact ("oh, well, yeah, I was closing the browser between tries. but that shouldn't matter.").
Is there something running on the server that is clearing out session, or is the session expiration limit set too loo?
Moral: go try and reproduce the issue first, so you can narrow down exactly what it is. I suggest Firebug + Firecookie for debugging Firefox and general cookie problems, and Fiddler2 (a proxy) for debugging IE.


q:
Along the lines of my previous question, how can i join a list of strings into a string such that values get quoted cleanly. Something like:

['a', 'one "two" three', 'foo, bar', """both"'"""]

into:

a, 'one "two" three', "foo, bar", "both\"'"

I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.

[A]
Using the
```
csv
```
module you can do that way:
```
```
import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)
```
```
If you need a string just use
```
StringIO
```
instance as a file:
```
```
f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()
```
```
The output:
```
a,"one ""two"" three","foo, bar","both""'"
```
```
csv
```
will write in a way it can read back later.
You can fine-tune its output by defining a
```
dialect
```
, just set
```
quotechar
```
,
```
escapechar
```
, etc, as needed:
```
```
class SomeDialect(csv.excel):
    delimiter = ','
    quotechar = '"'
    escapechar = "\\"
    doublequote = False
    lineterminator = '\n'
    quoting = csv.QUOTE_MINIMAL

f = cStringIO.StringIO()
writer = csv.writer(f, dialect=SomeDialect)
writer.writerow(the_list)
print f.getvalue()
```
```
The output:
```
a,one \"two\" three,"foo, bar",both\"'
```
The same dialect can be used with csv module to read the string back later to a list.


q:
We are looking to do some heavy security requirements on our project, and we need to do a lot of encryption that is highly performant.

I think that I know that PKI is much slower and more complex than symmetric encryption, but I can't find the numbers to back up my feelings.

[A]
Use the OpenSSL
```
speed
```
subcommand to benchmark the algorithms and see for yourself.
```
```
[dave@hal9000 ~]$ openssl speed aes-128-cbc
Doing aes-128 cbc for 3s on 16 size blocks: 26126940 aes-128 cbc's in 3.00s
Doing aes-128 cbc for 3s on 64 size blocks: 7160075 aes-128 cbc's in 3.00s
...
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
aes-128 cbc     139343.68k   152748.27k   155215.70k   155745.61k   157196.29k

[dave@hal9000 ~]$ openssl speed rsa2048
Doing 2048 bit private rsa's for 10s: 9267 2048 bit private RSA's in 9.99s
Doing 2048 bit public rsa's for 10s: 299665 2048 bit public RSA's in 9.99s
...
                  sign    verify    sign/s verify/s
rsa 2048 bits 0.001078s 0.000033s    927.6  29996.5
```
```


q:
Sorry the title isn't more help. I have a database of media-file URLs that came from two sources:

(1) RSS feeds and (2) manual entries.

I want to find the ten most-recently added URLs, but a maximum of one from any feed. To simplify, table 'urls' has columns 'url, feed_id, timestamp'.

feed_id='' for any URL that was entered manually.

How would I write the query? Remember, I want the ten most-recent urls, but only one from any single feed_id.

[A]
You probably want a
union
. Something like this should work:
```
```
(SELECT
        url, feed_id, timestamp
    FROM rss_items
    GROUP BY feed_id
    ORDER BY timestamp DESC
    LIMIT 10)
UNION
    (SELECT
        url, feed_id, timestamp
    FROM manual_items
    GROUP BY feed_id
    ORDER BY timestamp DESC
    LIMIT 10)
ORDER BY timestamp DESC
LIMIT 10
```
```


q:
Can anyone recommend a cheap and good RTF control for .Net 1.1 Windows development. It needs to be able to do print/preview and some basic text formatting, fonts etc but nothing too advanced.

Cheers

Andreas


q:
The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots.

I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedures with MySQL and PHP5? My version of MySQL supports Stored Procedures.

[A]
You'll need to use
MySQLI
(MySQL Improved Extension) to call stored procedures. Here's how you would call an
SP
:
```
```
$mysqli = new MySQLI(user,pass,db);

$result = $mysqli->query("CALL sp_mysp()");
```
```
When using SPs you'll need close first resultset or you'll receive an error. Here's some more information :
http://blog.rvdavid.net/using-stored-procedures-mysqli-in-php-5/
(broken link)
Alternatively, you can use
Prepared Statements
, which I find very straight-forward:
```
```
$stmt = $mysqli->prepare("SELECT Phone FROM MyTable WHERE Name=?");

  $stmt->bind_param("s", $myName);

  $stmt->execute();
```
```
MySQLI Documentation:
http://no.php.net/manual/en/book.mysqli.php


q: How do you support optimistic / pessimistic concurrency using NHibernate?

[A]
NHibernate, by default, supports optimistic concurrency. Pessimistic concurrency, on the other hand, can be accomplished through the
```
ISession.Lock()
```
method.
These issues are discussed in detail in
this document
.


q:
What is the best way to test my webforms applications?

Looks like people are loving Watin, and selenium.

[A]
UPDATE
:
Given WatiN has been stagnant for over a year now, I would direct anyone that needs web ui tests towards
selenium
, it is in continuous use & development by many contributors, and is actively used by Google.
WatiN
is the best that I've found.  It integrates into Visual Studio unit testing or nunit & you can do pretty much anything you need in the browser (click links, submit forms, look for text/images, etc.)
See the following questions for similar answers:
What is the best way to do unit testing for ASP web pages (C#)?
Web Application Testing for .Net (watin Test Recorder)
How do you programmatically fill in a form and ‘POST’ a web page?


q: Is there a way to manipulate the speed of the video playback? I'm especially interested in a way to slow down with frame blending, exactly like the function in Final Cut Pro.

[A]
Interpolation should be able to help you. There's an example included with Quartz Composer (Interpolation Modes.qtz) and a beginning tutorial
here
that breifly mentions it (step 5).
this wiki article
also discusses it and talks about the different types.
Note: I don't actually have a Mac that can run QC, so this is just what I've been able to find through Google, but it sounds like it should get you on the right track.


q:
Say I have a web service http://www.example.com/webservice.pl?q=google which returns text "google.com". I need to call this web service (http://www.example.com/webservice.pl) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing.

What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated.

[A]
Take a look at one of the many javascript libraries out there. I'd recommend
jQuery
, personally. Aside from all the fancy UI stuff they can do, it has really good
cross-browser AJAX libraries
.
```
```
$.get(
    "http://xyz.com/webservice.pl",
    { q : "google" },
    function(data) {
        alert(data);  // "google.com"
    }
);
```
```


q:
I had assumed that the canonical form for operator+, assuming the existence of an overloaded operator+= member function, was like this:

const T operator+(const T& lhs, const T& rhs)
{
    return T(lhs) +=rhs;
}

But it was pointed out to me that this would also work:

const T operator+ (T lhs, const T& rhs)
{
    return lhs+=rhs;
}

In essence, this form transfers creation of the temporary from the body of the implementation to the function call.

It seems a little awkward to have different types for the two parameters, but is there anything wrong with the second form?  Is there a reason to prefer one over the other?

[A]
With the edited question, the first form would be preferred.  The compiler will more likely optimize the return value (you could verify this by placing a breakpoint in the constructor for T).  The first form also takes both parameters as const, which would be more desirable.
Research on the topic of
return value optimization
, such as this link as a quick example:
http://www.cs.cmu.edu/~gilpin/c++/performance.html


q:
I need to layout a html datatable with CSS.

The actual content of the table can differ, but there is always one main column and 2 or more other columns. I'd like to make the main column take up as MUCH width as possible, regardless of its contents, while the other columns take up as little width as possible. I can't specify exact widths for any of the columns because their contents can change.

How can I do this using a simple semantically valid html table and css only?

For example:

| Main column                           | Col 2 | Column 3 |
 <------------------ fixed width in px ------------------->
 <------- as wide as possible --------->
 Thin as possible depending on contents: <-----> <-------->

[A]
I'm far from being a CSS expert but this works for me (in IE, FF, Safari and Chrome):
```
```
td.zero_width {
    width: 1%;
}
```
```
Then in your HTML:
```
```
...
```
```


q: I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?

[A]
I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is this way, whitespace delimited.
I've never actually thought about that as an accessibility issue however. Maybe it's something to put forward as a bug report to Python?
I'd assume that you use a screen reader here however for the output? So the tabs would seem "invisible" to you? With a Braille output, it might be easier to read, but I can understand exactly how confusing this could be.
In fact, this is very interesting to me. I wish that I knew enough to be able to write an app that will do this for you.
I think it's definately something that I'll put in a bug report for, unless you've already done so yourself, or want to.
Edit: Also, as
noted
by
John Millikin
There is also
PyBraces
Which might be a viable solution to you, and may be possible to be hacked together dependant on your coding skills to be exactly what you need (and I hope that if that's the case, you release it out for others like yourself to use)
Edit 2: I've just
reported this
to the python bug tracker


q:
I am building a physics simulation engine and editor in Windows. I want to build the editor part using Qt and I want to run the engine using SDL with OpenGL.

My first idea was to build the editor using only Qt and share as much code with the engine (the resource manager, the renderer, the maths). But, I would also like to be able to run the simulation inside the editor. This means I also have to share the simulation code which uses SDL threads.

So, my question is this: Is there a way to have an the render OpenGL to a Qt window by using SDL?

I have read on the web that it might be possible to supply SDL with a window handle in which to render. Anybody has experience dong that?

Also, the threaded part of the simulator might pose a problem since it uses SDL threads.

[A]
Rendering onto opengl from QT is trivial (and works very well)
No direct experience of SDL but there is an example app here about mixing them.
http://www.devolution.com/pipermail/sdl/2003-January/051805.html
There is a good article about mixing QT widgewts directly with the opengl here
http://doc.trolltech.com/qq/qq26-openglcanvas.html
a bit beyond what you strictly need but rather clever!


q: I have an Events list in sharepoint and need to disallow users from having the ability to create meeting workspaces in the new event form.  Shy of customizing the new event form (which breaks attachment support), how can this be done?

[A]
By default, in order for users to create a meeting workspace, they will need to be an administrator or Site Owner (specifically they will need the Create Sites permission).  If you don't give them this permission, they won't be able to create a meeting workspace.
This will disallow the user to create any site under the site where these permissions are set.  I'm not aware of a way to restrict access to a specific site definition but still allow users to create a different one.


q:
I'm using GDI+ in C++.  (This issue might exist in C# too).

I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right.

For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150.  I would expect a monospace font to give exactly double the width for "PP".

My question is:  is this intended or documented behaviour, and how do I disable this?

RectF Rect(0,0,32767,32767);
RectF Bounds1, Bounds2;
graphics->MeasureString(L"PP", 1, font, Rect, &Bounds1);
graphics->MeasureString(L"PP", 2, font, Rect, &Bounds2);
margin = Bounds1.Width * 2 - Bounds2.Width;

[A]
It's by design, that method doesn't use the actual glyphs to measure the width and so adds a little padding in the case of overhangs.
MSDN
suggests using a different method if you need more accuracy:
To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the
MeasureCharacterRanges
method or one of the
MeasureString
methods that takes a
StringFormat
, and pass
GenericTypographic
. Also, ensure the
TextRenderingHint
for the
Graphics
is
AntiAlias
.


q:
Dynamically creating a radio button using eg

var radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);

works in Firefox but not in IE. Why not?

[A]
Based on this post and its comments:
http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html
the following works. Apparently the problem is that you can't dynamically set the name property in IE. I also found that you can't dynamically set the checked attribute either.
```
```
function createRadioElement( name, checked ) {
    var radioInput;
    try {
        var radioHtml = '<input type="radio" name="' + name + '"';
        if ( checked ) {
            radioHtml += ' checked="checked"';
        }
        radioHtml += '/>';
        radioInput = document.createElement(radioHtml);
    } catch( err ) {
        radioInput = document.createElement('input');
        radioInput.setAttribute('type', 'radio');
        radioInput.setAttribute('name', name);
        if ( checked ) {
            radioInput.setAttribute('checked', 'checked');
        }
    }

    return radioInput;
}
```
```


q:
Usecase: The user makes font customizations to an object on the design surface, that I need to load/save to my datastore. I.e. settings like Bold, Italics, Size, Font Name need to persisted.

Is there some easy (and reliable) mechanism to convert/read back from a string representation of the font object (in which case I would need just one attribute)? Or is multiple properties combined with custom logic the right option?

[A]
Use
TypeConverter
:
```
```
Font font = new Font("Arial", 12, GraphicsUnit.Pixel);

TypeConverter converter = TypeDescriptor.GetConverter(typeof (Font));

string fontStr = converter.ConvertToInvariantString(font);

Font font2 = (Font) converter.ConvertFromString(fontStr);

Console.WriteLine(font.Name == font2.Name); // prints True
```
```
If you want to use XML serialization you can create Font class wrapper which will store some subset of Font properties.
Note(Gishu) - Never access a type converter directly. Instead, access the appropriate converter by using TypeDescriptor. Very important :)


q:
I have done some searches looking for information about how to do logging with the Spring Framework.

We currently have an application that has no logging in it except for system.out statements (very bad way).

What I would like to do, is add logging, but also want to be able to control the logging at run time, with say JMX.

We are using Rad 7.0 / WebSphere 6.1

I am interesting to find out what is the best way(s) to accomplish this (I figure there may be several).

Update:  Thoughts on the following Spring AOP Logging Good ideal or not.  This is in reference to a question posted here on logging:  Conditional Logging.  Does this improve things or just makes it more difficult in the area of logging?

[A]
I would use
Commons Logging
and
Log4j
.  This is not really a question for Spring, however the Springframework source does uses Commons Logging as well. If you create a log4j logger and appender in log4j, you can enable logging within the Springframework classes too.  There are a few ways to control logging at runtime.  The Log4j sandbox has a JSP, that you can drop into your webapp, that will allow you to control the log levels of all of the loggers within your application.


q:
I find the autoindent style of Notepad++ a little weird: when I am typing on an indented line, I do want it to indent the next line after I press Enter (this it does properly). However, when I am on an empty line (no indentation, no characters) and I press Enter, it indents the next line, using the same indentation as the last non-empty line. I find this extremely annoying; have you ever encountered this problem and do you know how to fix it?

(Note: I'm editing HTML/PHP files.)

[A]
To be honest, this to me seems expected behaviour. Blank lines are used a lot by myself to break up the code to make it more readable, having the program make me have to tab out again would be VERY annoying.
I can understand this as a frustration with something like Python, but not with PHP... Though, before braces etc etc this might be annoying.
Try out
Komodo Edit
however, it's free, and I've found that it generally has been the best for auto-indenting for me. It seems to have learnt my coding style (or have the options in it for all coding styles and it picks up what you're using) and automatically indents everything correctly.
Edit: As you've noted in your reply, the issue is with "trailing whitespace" - I don't know Notepad++ too well, but most modern editors designed for coding have a "strip trailing whitespace on save" option (I know Komodo does!)


q:
Does anyone know how I can get rid of the following assembler warning?

Code is x86, 32 bit:

int test (int x)
{
  int y;
  // do a bit-rotate by 8 on the lower word. leave upper word intact.
  asm ("rorw $8, %0\n\t": "=q"(y) :"0"(x));
  return y;
}

If I compile it I get the following (very valid) warning:

Warning: using `%ax' instead of `%eax' due to `w' suffix

What I'm looking for is a way to tell the compiler/assembler that I want to access the lower 16 bit sub-register of %0. Accessing the byte sub-registers (in this case AL and AH) would be nice to know as well.

I've already chosen the "q" modifier, so the compiler is forced to use EAX, EBX, ECX or EDX. I've made sure the compiler has to pick a register that has sub-registers.

I know that I can force the asm-code to use a specific register (and its sub-registers), but I want to leave the register-allocation job up to the compiler.

[A]
You can use
```
%w0
```
if I remember right. I just tested it, too. :-)
```
```
int
test(int x)
{
    int y;
    asm ("rorw $8, %w0" : "=q" (y) : "0" (x));
    return y;
}
```
```
Edit: In response to the OP, yes, you can do the following too:
```
```
int
test(int x)
{
    int y;
    asm ("xchg %b0, %h0" : "=Q" (y) : "0" (x));
    return y;
}
```
```
For x86 it's documented in the
x86 Operand Modifiers section
of the Extended Asm part of the manual.
For non-x86 instruction sets, you may have to dig through their
```
.md
```
files in the GCC source. For example,
```
gcc/config/i386/i386.md
```
was the only place to find this before it was officially documented.
(Related:
In GNU C inline asm, what are the size-override modifiers for xmm/ymm/zmm for a single operand?
for vector registers.)


q:
How do I open multiple pages in Internet Explorer 7 with a single DOS command? Is a batch file the only way to do this?

Thanks!

[A]
Unfortunately, there is no way to include multiple URLs as command-line parameters.  Here is a a
blog post
which details another (fairly convoluted) way to do it via Javascript.


q:
Deep down in WinDef.h there's this relic from the segmented memory era:

#define far
#define near

This obviously causes problems if you attempt to use near or far as variable names.  Any clean workarounds? Other then renaming my variables?

[A]
maybe:
```
```
#undef near
#undef far
```
```
could be dangerous though...


q: I want to use the macports version of python instead of the one that comes with Leopard.

[A]
I have both installed:
```
```
$ which python
/usr/bin/python
$ which python2.5
/opt/local/bin/python2.5
```
```
I also added the following line to my
```
.profile
```
:
```
```
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
```
```


q:
I would like to replace only the group in parenthesis in this expression :

my_string.gsub(/<--MARKER_START-->(.)*<--MARKER_END-->/, 'replace_text')

so that I get : <--MARKER_START-->replace_text<--MARKER_END-->

I know I could repeat the whole MARKER_START and MARKER_END blocks in the substitution expression but I thought there should be a more simple way to do this.

[A]
You could do something like this:
```
```
my_string.gsub(/(<--MARKER_START-->)(.*)(<--MARKER_END-->)/, '\1replace_text\3')
```
```


q: How can I start a project in CodePlex.com?

[A]
Try going to CodePlex and
reading how to do this
there.
Register


q:
I've been trying to figure out how to print in Adobe AIR. I know the standard javascript functions don't work. The AIRforJSDev guide says:
"The window.print() method is not supported within Adobe
AIR 1.0. There are other methods available via the exposed AIRAPIs that give you access to printing within the runtime"

But I can't find those functions. I've looked in the language reference but can't find them there anywhere. Where are they and what are they ?

[A]
What you need to do is access the AS3
flash.printing.PrintJob
API. Here's a page on
accessing flash API from javascript
(basically you just do window.runtime.XYZ where XYZ is the flash API).
You should look up tutorials on printing in flash, just need minor tweaks to do it from JS. Here's two random tutorials on printing in flash I found:
one
,
two


q:
I recently installed MySQL 5 on Windows 2003 and tried configuring an instance. Everything worked fine until I got to "Applying Security settings", at which point it gave me the above error (Can't connect to MySQL server on 'localhost' (10061)).

I do have a port 3306 exception in my firewall for 'MySQL Server'.

[A]
You'll probably have to grant 'localhost' privileges to on the table to the user.  See the
```
'GRANT'
```
syntax documentation.  Here's an example (from some C source).
"GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' IDENTIFIED BY '%s'";
That's the most common access problem with MySQL.
Other than that, you might check that the user you have defined to create your instance has full privileges, else the user cannot grant privileges.
Also, make sure the mysql service is started.
Make sure you don't have a third party firewall or Internet security service turned on.
Beyond that, there's several pages of the MySQL forum devoted to this:
http://forums.mysql.com/read.php?11,9293,9609#msg-9609
Try reading that.


q:
In our Java applications we typically use the maven conventions (docs, src/java, test, etc.).  For Perl we follow similar conventions only using a top level 'lib' which is easy to add to Perl's @INC.

I'm about to embark on creating a service written in Erlang, what's a good source layout for Erlang applications?

[A]
The Erlang recommended standard directory structure can be
found here
.
In addition you may need a few more directories depending on your project, common ones are (credit to Vance Shipley):
```
lib:        OS driver libraries
    bin:        OS executables
    c_src:      C language source files (e.g. for drivers)
    java_src:   Java language source files
    examples:   Example code
    mibs:       SNMP MIBs
```
Other projects such as
Mochiweb
have their own structures, Mochiweb even have a script to create it all for you. Other projects such as
Erlware
overlay on the standard structure.


q:
Can anyone suggest a good way of detecting if a database is empty from Java (needs to support at least Microsoft SQL Server, Derby and Oracle)?

By empty I mean in the state it would be if the database were freshly created with a new create database statement, though the check need not be 100% perfect if covers 99% of cases.

My first thought was to do something like this...

tables = metadata.getTables(null, null, null, null);
Boolean isEmpty = !tables.next();
return isEmpty;

...but unfortunately that gives me a bunch of underlying system tables (at least in Microsoft SQL Server).

[A]
Are you always checking databases created in the same way?  If so you might be able to simply select from a subset of tables that you are familiar with to look for data.
You also might need to be concerned about static data perhaps added to a lookup table that looks like 'data' from a cursory glance, but might in fact not really be 'data' in an interesting sense of the term.
Can you provide any more information about the specific problem you are trying to tackle?  I wonder if with more data a simpler and more reliable answer might be provided.
Are you creating these databases?
Are you creating them with roughly the same constructor each time?
What kind of process leaves these guys hanging around, and can that constructor destruct?
There is certainly a meta data process to loop through tables, just through something a little more custom might exist.


q: Any useful metrics will be fine

[A] One of the things that I look for in a code is unit test. This will give the freedom to refactor it. So if the code does not have tests I consider it a legacy code.


q:
It seems that anyone can snoop on incoming/outgoing .NET web service SOAP messages just by dropping in a simple SoapExtension into the bin folder and then plumbing it in using:

<soapExtensionTypes>
  <add type="MyLoggingSoapExtension, SoapLoggingTools" priority="0" group="High" />
<soapExtensionTypes>

Is there a way to prevent SOAP extensions from loading or to be asked in my app (through an event or some such mechanism) whether it's ok to load ?

@Hurst: thanks for the answer. I know about message level encryption/WS-Security and was hoping not to have to go that road. We have classic ASP clients using the service and that opens a small world of pain. There are SSL certs on the site running the web service but I was kinda hoping that I could discourage the client from tinkering with soap extensions as they have developers who have some ability to 'play'.

[A]
I am not sure what you mean by extensions and bin folders (I would guess you are using .NET), so I can't answer about them being loaded etc.
However, note that SOAP is designed to allow intermediaries to read the headers and even to modify them. (Do a search for "SOAP Active Intermediaries").
Judging by that, I expect there to be no reason for a technology to avoid snooping by preventing code from reading the SOAP
.
The proper way to protect yourself is to use "
message-level security
". (This is in contrast to
transport-level security
, such as SSL, which does not protect from intermediaries).
In other words, encrypt your own messages before sending.
One available standard used to implement message-level security mechanisms is the
WS-Security
protocol. This allows you to target the encryption to the payload and relevant headers regardless of transport. It is more complex, but that is how you would go about restricting access.


q: The Image Web Part doesn't seem to have an href attribute that I can set.  Is there something I am missing?

[A]
Does it have to be an Image Web Part? If not I would simply use a
Content Editor Web Part
and paste the required HTML there.
```
```

```
```


q:
This is what I have so far:

myArray.map!{ rand(max) }

Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers?

Edit:

I'd really like to see this done w/o loop - if at all possible.

[A]
You could use a hash to track the random numbers you've used so far:
```
```
seen = {}
max = 100
(1..10).map { |n|
  x = rand(max)
  while (seen[x])
    x = rand(max)
  end
  x
}
```
```


q:
How do you extract an RT_RCDATA section from a Win32 executable (preferably in C#)?

The only way I know how to do this currently is opening up the EXE in Visual Studio.  I'd love to be able to do this entirely in C# if possible.

Thanks!

[A]
P/Invoke LoadResource will be your safest bet.
Otherwise you'll have to write your own
P/E
processor eg.
PE Processor example
.  The processor isn't the end of the world, but as you can see much more involved than a P/Invoke.
Almost forgot,as far as tools go, most P/E browsers will do this for you.  Eg. P/E Explorer, which is available but not really being developed.  I've also used IDA Pro for stuff like this.  A quick IDA plugin would do this easily.


q: Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members?

[A]
This is because of padding added to satisfy alignment constraints.
Data structure alignment
impacts both performance and correctness of programs:
Mis-aligned access might be a hard error (often
```
SIGBUS
```
).
Mis-aligned access might be a soft error.
Either corrected in hardware, for a modest performance-degradation.
Or corrected by emulation in software, for a severe performance-degradation.
In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors.
Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes):
```
```
struct X
{
    short s; /* 2 bytes */
             /* 2 padding bytes */
    int   i; /* 4 bytes */
    char  c; /* 1 byte */
             /* 3 padding bytes */
};

struct Y
{
    int   i; /* 4 bytes */
    char  c; /* 1 byte */
             /* 1 padding byte */
    short s; /* 2 bytes */
};

struct Z
{
    int   i; /* 4 bytes */
    short s; /* 2 bytes */
    char  c; /* 1 byte */
             /* 1 padding byte */
};

const int sizeX = sizeof(struct X); /* = 12 */
const int sizeY = sizeof(struct Y); /* = 8 */
const int sizeZ = sizeof(struct Z); /* = 8 */
```
```
One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure
```
Z
```
in the example above).
IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined.  Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts.  For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data.  Some compilers have command-line settings and/or special
```
#pragma
```
statements to change the structure alignment settings.


q:
What is the difference between this:

this.btnOk.Click += new System.EventHandler(this.btnOK_Click);

and this?

this.btnOk.Click += this.btnOK_Click;

They both work.  The former is what Visual Studio defaults to when you use the snippets.  But it seems like it only ads extra verbiage, or am I missing something?

[A] I believe that C# since 3.0 has implicitly added the delegate handler.  However, it can help to be more explicit, especially when there are multiple possible delegate types.


q:
I'm taking a look at how the model system in django works and I noticed something that I don't understand.

I know that you create an empty __init__.py file to specify that the current directory is a package.  And that you can set some variable in __init__.py so that import * works properly.

But django adds a bunch of from ... import ... statements and defines a bunch of classes in __init__.py.  Why?  Doesn't this just make things look messy?  Is there a reason that requires this code in __init__.py?

[A]
All imports in
```
__init__.py
```
are made available when you import the package (directory) that contains it.
Example:
```
./dir/__init__.py
```
:
```
```
import something
```
```
```
./test.py
```
:
```
```
import dir
# can now use dir.something
```
```
EDIT: forgot to mention, the code in
```
__init__.py
```
runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code.
EDIT2: dgrant pointed out to a possible confusion in my example. In
```
__init__.py
```
```
import something
```
can import any module, not necessary from the package. For example, we can replace it with
```
import datetime
```
, then in our top level
```
test.py
```
both of these snippets will work:
```
```
import dir
print dir.datetime.datetime.now()
```
```
and
```
```
import dir.some_module_in_dir
print dir.datetime.datetime.now()
```
```
The bottom line is: all names assigned in
```
__init__.py
```
, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.


q: I have a large quantity of clearcase data which needs to be migrated into perforce.  The revisions span the better part of a decade and I need to preserve as much branch and tag information as possible.  Additionally we make extensive use of symbolic links, supported in clearcase but not in perforce.  What advice or tools can you suggest which might make this easier?

[A]
The first step is to decide if you need to migrate everything, or just certain key versions.  If you only migrate the important versions (releases and major milestones) you'll end up with a much simpler history in Perforce, without losing anything important.  Then ClearCase can be keep as a historical archive in case it is ever needed.  (Unless IBM has changed things ClearCase licenses do not expire when maintainance runs out, you just lose the right to new upgrades and patches and acces to support)
Keep in mind that Perforce does not version control directories and does not keep a full per-element version tree - this means a 1:1 with exact results is going to be impossible.  Recreating the important snapshots is a much more achievable goal; keeping everything may be impossible, as Perforce lacks features ClearCase relies upon.
To see what Perforce says about the miration, check out
http://perforce.com/perforce/ccaseconv.html
This explains the key differences and covers a few approaches you can take.


q:
I'm new to Ruby, and I'm trying the following:

mySet = numOfCuts.times.map{ rand(seqLength) }

but I get the 'yield called out of block' error. I'm not sure what his means. BTW, this question is part of a more general question I asked here.

[A]
if   "numOfCuts" is an integer,
```
```
5.times.foo
```
```
is invalid
"times" expects a block.
```
```
5.times{   code here   }
```
```


q:
I have a large 2d array that I serialize and base64_encode and throw into a database.  On a different page I pull the array out and when I base64_decode the serialized array I can echo it out and it definitely looks valid.

However, if I try to unserialize(base64_decode($serializedArray)) it just throws the same error to the point of nearly crashing Firefox.

The error is:

Warning: unserialize() [function.unserialize]: Node no longer exists in /var/www/dev/wc_paul/inc/analyzerTester.php on line 24

I would include the entire serialized array that I echo out but last time I tried that on this form it crashed my Firefox.

Does anyone have any idea why this might be happening?

[A]
Are you sure you're just serializing an array, and not an object (e.g. DOMNode?)  Like resources, not all classes are going to be happy with being unserialized.  As an example with the DOM (which your error suggests to me you're working with), every node has a reference to the parentNode, and if the parentNode doesn't exist at the moment a node is being unserialized, it's not able to recreate that reference and problems ensue.
I would suggest saving the dom tree as XML to the database and loading it back later.


q: Since AspectJ LoadTime-Weaving needs to load the JVM with an agent/it's own classloader - is there a way to load/make changes in the user's JVM from my applet? or maybe just before loading the applet (with a parent applet?)

[A]
I'm afraid you'll be completely out of luck there.  According to the
Sun docs on applet classloaders
, a "web browser uses only one class loader, which is established at start-up. Thereafter, the system class loader cannot be extended, overloaded, overridden or replaced.
Applets cannot create or reference their own class loader
" (emphasis mine).
You will probably have more success with compile-time weaving on this problem, unless there's some reason why you can't do that.
If the applet is signed, however, you might be able to work around this.  AspectJ is not really clear on what its requirements are by way of Java Security.  I'd get on the AspectJ mailing list and ask.


q:
Just wondering if someone could help me with some msbuild scripts that I am trying to write.  What I would like to do is copy all the files and sub folders from a folder to another folder using msbuild.

{ProjectName}
      |----->Source
      |----->Tools
              |----->Viewer
                       |-----{about 5 sub dirs}

What I need to be able to do is copy all the files and sub folders from the tools folder into the debug folder for the application.  This is the code that I have so far.

<ItemGroup>
    <Viewer Include="..\$(ApplicationDirectory)\Tools\viewer\**\*.*" />
</ItemGroup>

<Target Name="BeforeBuild">
    <Copy SourceFiles="@(Viewer)" DestinationFolder="@(Viewer->'$(OutputPath)\\Tools')" />
</Target>

The build script runs but doesn't copy any of the files or folders.

Thanks

[A]
Did you try to specify concrete destination directory instead of
```
```
DestinationFolder="@(Viewer->'$(OutputPath)\\Tools')" ?
```
```
I'm not very proficient with advanced MSBuild syntax, but
```
```
@(Viewer->'$(OutputPath)\\Tools')
```
```
looks weird to me. Script looks good, so the problem might be in values of
```
$(ApplicationDirectory)
```
and
```
$(OutputPath)
```
Here is a blog post that might be useful:
How To: Recursively Copy Files Using the <Copy> Task


q:
I would like to be able to override the default behaviour for positioning the caret in a masked textbox.

The default is to place the caret where the mouse was clicked, the masked textbox already contains characters due to the mask.

I know that you can hide the caret as mentioned in this post, is there something similar for positioning the caret at the beginning of the textbox when the control gets focus.

[A]
This should do the trick:
```
```
private void maskedTextBox1_Enter(object sender, EventArgs e)
    {
        this.BeginInvoke((MethodInvoker)delegate()
        {
            maskedTextBox1.Select(0, 0);
        });
    }
```
```


q:
Consider the following ruby code

test.rb:

begin

  puts
  thisFunctionDoesNotExist
  x = 1+1
rescue Exception => e
  p e
end

For debugging purposes, I would like the rescue block to know that the error occurred in line 4 of this file.  Is there a clean way of doing that?

[A]
```
```
p e.backtrace
```
```
I ran it on an IRB session which has no source and it still gave relevant info.
```
```
=> ["(irb):11:in `foo'",
    "(irb):17:in `irb_binding'",
     "/usr/lib64/ruby/1.8/irb/workspace.rb:52:in `irb_binding'",
     "/usr/lib64/ruby/1.8/irb/workspace.rb:52"]
```
```
If you want a nicely parsed backtrace, the following regex might be handy:
```
```
p x.backtrace.map{ |x|
     x.match(/^(.+?):(\d+)(|:in `(.+)')$/);
    [$1,$2,$4]
}

[
  ["(irb)", "11", "foo"],
  ["(irb)", "48", "irb_binding"],
  ["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", "irb_binding"],
  ["/usr/lib64/ruby/1.8/irb/workspace.rb", "52", nil]
]
```
```
( Regex /should/ be safe against weird characters in function names or directories/filenames )
( If you're wondering where foo camefrom, i made a def to grab the exception out :
```
```
>>def foo
>>  thisFunctionDoesNotExist
>> rescue Exception => e
>>   return e
>>end
>>x = foo
>>x.backtrace
```
```


q:
Within our Active Directory domain, we have a MS SQL 2005 server, and a SharePoint (MOSS 3.0 I believe) server.  Both authenticate against our LDAP server.  Would like to allow these authenticated SharePoint visitors to see some of the data from the MS SQL database.  Primary challenge is authentication.

Any tips on getting the pass-through authentication to work?  I have searched (Google) for a proper connection string to use, but keep finding ones that have embedded credentials or other schemes.  I gather that SSPI is what I want to use, but am not sure how to implement.

clarification: we don't have a single-sign-on server (e.g. Shibboleth) setup yet

[A]
If you are using C# the code and connection string is:
```
```
using System.Data.SqlClient;
...
SqlConnection oSQLConn = new SqlConnection();
oSQLConn.ConnectionString =
    "Data Source=(local);" +
    "Initial Catalog=myDatabaseName;" +
    "Integrated Security=SSPI";
 //Or
 // "Server=(local);" +
 // "Database=myDatabaseName;" +
 // "Trusted_Connection=Yes";
oSQLConn.Open();
...
oSQLConn.Close();
```
```
An excellent resource for connection strings can be found at
Carl Prothman's Blog
. Yoy should probably replace
```
(local)
```
with the name of the SQL server.
You will need to either configure SQL server to give the Domain Roles the access privilages you want. In SQL server you will need to go to Security\Logins and make sure you have the Domain\User Role (ie MyCompany\SharpointUsers). In your config you should have