Question:
My compact framework application creates a smooth-scrolling list by rendering all the items to a large bitmap surface, then copying that bitmap to an offset position on the screen so that only the appropriate items show.  Older versions only rendered the items that should appear on screen at the time, but this approach was too slow for a smooth scrolling interface.

It occasionally generates an OutOfMemoryException when initially creating the large bitmap.  If the user performs a soft-reset of the device and runs the application again, it is able to perform the creation without issue.

It doesn't look like this bitmap is being generated in program memory, since the application uses approximately the same amount of program memory as it did before the new smooth-scrolling methods.

Is there some way I can prevent this exception?  Is there any way I can free up the memory I need (wherever it is) before the exception is thrown?

Answer:
Your bitmap definitely
is
being created in program memory.  How much memory the bitmap needs depends on how big it is, and whether or not this required size will generate the OutOfMemoryException depends on how much is available to the PDA (which makes this a randomly-occuring error).
Sorry, but this is generally an inadvisable control rendering technique (especially on the Compact Framework) for which there is no fix short of increasing the physical memory on the PDA, which isn't usually possible (and often won't fix the problem anyway, since a CF process is limited to 32MB no matter how much the device has available).
Your best bet is to go back to the old version and improve its rendering speed.  There is also a simple technique available on CF for making a control double-buffered to eliminate flicker.


Question:
Every time that I create a new form in my application, it uses the "Microsoft Sans Serif, 8.25pt" font by default. I'm not changing it because I know that in this case my form should pick up whatever the default font is for the system. However, when I run my application, the font that is used is still anything but Segoe UI (my default system font in my Windows Vista OS).

Why does this happen? How do I make sure that my application looks like a normal Windows application?

Answer:
Yes, it uses the font returned by
```
GetStockObject(DEFAULT_GUI_FONT)
```
.  Which is MS Sans Serif.  An old font, long gone from most machines.  The font mapper translate it to, no surprise, Microsoft Sans Serif.
There is no documented procedure I know of to change that default font, the SDK docs mention MS Sans Serif explicitly.  If you want Segoe, you'll have to ask for it.  Which isn't that safe to do, there are still a lot of XP machines out there without Office 2007.  The font mapper will translate it on a machine that doesn't have Segoe available.  Not sure what pops out, I don't have such a machine left anymore.


Question: I would like to convert an array if IDs, into a string of comma separated values, to use in a MySQL UPDATE query. How would I do this?

Answer:
```
```
implode(',', $array);
```
```


Question:
Given:

CR = %0d = \r
LF = %0a = \n

What does

%3E,
%3C

Mean?

Answer:
They are URL encoded characters.  %3C is <, %3E is >
More info on
URL Encoding
, and
a chart
of some of the lower ASCII values.


Question:
I am trying to import an existing PDF as a template with FPDI.  The template is in landscape format.  If I import the template into a new document the template page is inserted in portrait form with the content rotated 90 degrees.  If my new document is in portrait the full content appears, but if the new document is also landscape, the content is cropped.

Is it possible to use a landscape template with FPDI?

Answer:
sure, it is no problem. Just add "L" as parameter when calling "addPage()". Here is a sample which works fine for me (the template is in landscape)
```
```
<?php
require_once('fpdf.php');
require_once('fpdi.php');

$pdf =& new FPDI();
$pdf->addPage('L');
$pagecount = $pdf->setSourceFile('template.pdf');
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx);
$pdf->SetFont('Arial');
$pdf->SetTextColor(255,0,0);
$pdf->SetXY(25, 25);
$pdf->Write(0, "This is just a test");
$pdf->Output('newpdf.pdf', 'F');

?>
```
```


Question:
I have a question about variable initialization in MASM's assembly.

How can I initialize 2^32 to a variable and to what kind of variable should I initialize? DWORD or REAL4?

I try to do it like:

val DWORD 2.0E+32

When I assign var to a register(e.g. mov eax,val) and try to write the value, I see something that is not 2^32. I also tried it with REAL4 type. Result is still same.

So What I am doing wrong here?

Thanks in advance...

Answer:
2^32 = 4294967296 = 0x100000000 (that's 8 zeroes).
```
2.0E+32
```
is 2 * 10^32 = 200000000000000000000000000000000, a
completely
different number. It's also a floating-point number, whereas
```
0x100000000
```
is an integer.


Question: In Java, is there a way to have a window that is "Always on top" regardless if the user switches focus to another application?  I've searched the web, and all of the solutions lean to some sort of JNI interface with native bindings.  Truly this can't be the only way to do it?.. or is it?

Answer:
Try this method of the
```
Window
```
class:
Window.setAlwaysOnTop(boolean)
It works the same way as the default in the Windows TaskManager: switch to another app but it shows always on top.
This was added in Java 1.5
Sample code:
```
```
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Annoying {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Hello!!");

        // Set's the window to be "always on top"
        frame.setAlwaysOnTop( true );

        frame.setLocationByPlatform( true );
        frame.add( new JLabel("  Isn't this annoying?") );
        frame.pack();
        frame.setVisible( true );
    }
}
```
```
Window remains on top even when is not active


Question:
I am developing a .NET CF based Graphics Application, my project involves a lot of drawing images, We have decided to go for porting the application on different handset resolution.(240 X 240 , 480 X 640) etc.

How would i go onto achieve this within single solution/project?

Is there a need to create different projects based on resolutions?
How would i handle common files? and i need the changes in one of the common classes to occur across all devices.

Thank you,
Cronos

Answer:
This code has worked for me in determining the resolution of the screen dynamically:
```
```
[DllImport("coredll.dll", EntryPoint = ("GetSystemMetrics"))]
public static extern int GetSystemMetrics(int nIndex);

private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;

private int width = GetSystemMetrics(SM_CXSCREEN);
private int height = GetSystemMetrics(SM_CYSCREEN);
```
```
I don't remember it out of the top of my head, but there is also a way to get the Screen Orientation. These would help merge some code in a single Class.
I would strongly recommend to create a single solution for all resolutions. You could have as many projects as you want under these solution. These projects could be Windows Forms Applications, Dll Library projects or Set Up Projects.
I would aim to create a single Windows Forms Application Project. I would use the above technique and read the static images from the File System. If this doesn't work for you and/or you prefer to read your images as resources, then create an 'engine' dll project, containing all the code that is common to all resolutions. Add then the output of this project as reference to as many Windows Forms Applications projects as you need.


Question:
I have some code on my PHP powered site that creates a random hash (using sha1()) and I use it to match records in the database.

What are the chances of a collision? Should I generate the hash, then check first if it's in the database (I'd rather avoid an extra query) or automatically insert it, based on the probability that it probably won't collide with another.

Answer:
If you assume that SHA-1 does a good job, you can conclude that there's a 1 in 2^160 chance that two given messages have the same hash (since SHA-1 produces a 160-bit hash).
2^160 is a ridiculously large number. It's roughly 10^48. Even if you have a million entries in your database, that's still a 1 in 10^42 chance that a new entry will share the same hash.
SHA-1 has proved to be fairly good, so I don't think you need to worry about collisions at all.
As a side note, use PHP's
raw_output
feature when you use SHA-1 as this will lead to a shorter string and hence will make your database operations a bit faster.
EDIT: To address the birthday paradox, a database with 10^18 (a million million million) entries has a chance of about 1 in 0.0000000000003 of a collision.
Really
not worth worrying about.


Question: What are profound advantages that one get when using COM for developing components over the WCF? Is there anything that can be done with COM and not with WCF?

Answer:
No it's not dead yet, but it's on its death-bed, that's for sure. You see there's still to many legacy systems that use/require COM, that assures us it'll be with us for a few more years, but not in the long-run.
As for WCF, there might be some edge cases of stuff COM can do, and WCF can't, but more importantly, and related to legacy stuff, is that there are COM bindings for almost every language you can put on a windows stack, but the WCF bindings are not ready yet for everyone (languages)


Question: What are all the problem that you foresee in doing that.

Answer:
How big of a code base are you talking about?
Porting a little program (that is mostly non-templated C++ code) should be fairly trivial.
However I once had to convert 100.000 lines of template-using code from VC6 to VC2005, and it was a nightmare week(5 days of work), the main problem was that I had to fix by hand about 30% of the problems (70% were fairly trivial and could fix them with search & replaces). But more of an issue was the fact that the old code had no test cases and no test framework, so even after I got the application to compile and not segfault, and look ok(?), I had no assurance everything it was actually working as it was supposed to be.
So actually my advice is to consider the size of the code, and the availability of tests, and also consider if the code really needs to be ported (in my case that was a Yes, but its not always the case, especially if the software will be faded out soon)


Question:
Boost is a great set of libraries and it really boosts productivity. But debugging code that uses it is a total nightmare. Sure, stepping through twenty thousand header files can be a valuable intellectual exercise, but what if you need to do it over and over again?

Is there a developer-friendly way of just skipping the boost portion and having the debugger go straight to my code?

Visual Studio has a DebuggerStepThroughAttribute for .NET framework. Is there anything similar for native C++?

Answer:
You can skip the boost namespace entirely by using the techniques described
here
. Just use something like:
```
boost\:\:.*=NoStepInto
```
... in the relevant registry entry.
However if your code gets called from within boost (e.g. through a
```
boost::function
```
or similar) then your code will be skipped as well! I'll be interested if someone can come up with a good solution for
that
problem...


Question:
If it does, then how do you justify the overheads incurred (journaling etc.)?
If it does not, then how come the pagefile gets fragmented?
Additionally, would increasing the cluster size improve pagefile performance (cluster slack space is a non-issue)?

Answer:
You can skip the boost namespace entirely by using the techniques described
here
. Just use something like:
```
boost\:\:.*=NoStepInto
```
... in the relevant registry entry.
However if your code gets called from within boost (e.g. through a
```
boost::function
```
or similar) then your code will be skipped as well! I'll be interested if someone can come up with a good solution for
that
problem...


Question:
I have a custom control that I need to use in another custom control. I have written all code at server side (no HTML). Can anyone tell me how to write below line of code in code behind using htmlTextWriter and how to register this control or how to write custom control within another where html is written from code behind?

<cc2:test id="test1" runat="server" marqueedirection="left" marqueeheight="25"
            marqueewidth="725" ShowImage="False" ShowTitle="False" ShowUrlUnderLine="True"></cc2:test

Answer:
First, build a simple custom web control:
```
```
namespace My.Controls
{
    public class InnerControl : Control
    {
        protected override void Render(HtmlTextWriter writer)
        {
            writer.WriteLine("
Inner Control
");
        }
    }
}
```
```
Then build your second web control that contains and renders the first:
```
```
namespace My.Controls
{
    public class OuterControl : Control
    {
        protected override void Render(HtmlTextWriter writer)
        {
            writer.WriteLine("
Outer Control
");
            InnerControl innerControl = new InnerControl();
            innerControl.RenderControl(writer);
        }
    }
}
```
```
Finally, register the control on your page, and display it:
```
```
<%@ Register TagPrefix="c" Namespace="My.Controls" %>
<c:OuterControl runat="server" />
```
```


Question:
paredit binds M-<up> and M-<down>, but I want windmove to own those keybindings.  I have paredit-mode set to activate in certain modes only, but windmove is set to run globally.  I want windmove to win, but paredit steals those keybindings when it loads.

How can I easily stop paredit from stomping on windmove's keybindings?  I have been going into paredit.el and commenting out the lines which set the keybinding, but this is far from ideal (I have to remember to do this every time I update paredit).

More generally, can I load an elisp file while "protecting" certain keybindings from being changed?

Answer:
You can use
```
eval-after-load
```
to configure paredit's behavior after loading it, as described in its comments:
```
```
;;; Customize paredit using `eval-after-load':
;;;
;;;   (eval-after-load 'paredit
;;;     '(progn ...redefine keys, &c....))
```
```
So, for example:
```
```
(eval-after-load 'paredit
  '(progn
     (define-key paredit-mode-map (kbd "<M-up>") nil)
     (define-key paredit-mode-map (kbd "<M-down>") nil)))
```
```


Question:
I want to, from JavaScript, access as a variable the file that is loaded as an image in an img tag.

I don't want to access its name, but the actual data.

The reason for this is that I want to be able to copy it to and from variables so that I can , among other things, change the image without reloading it.

Can this be done? If so, how?

Note: I'm slightly more interested in reading the data than writing it.

Answer:
Try this:
```
```
img = new Image();
img.src = "imagefile.jpg";
```
```


Question:
I have got a table in MS Access 2007 with 4 fields.

Labour Cost

Labour Hours

Vat

Total

How do I multiply 'Labour Hours' by 'Labour Cost' add the 'VAT' and display the answer in 'Total'

Where would I put any formulas?, in a form or query or table ?

Answer:
You don't need the "Total" column in all probability.
Your queries or reports will probably resemble this:
```
```
SELECT [Total] = [Labour Cost] * [Labour Hours] + [VAT]
```
```
You can use the same sort of formula in controls on your forms or reports.


Question: I would like to add a method to a built-in type (e.g. Double), so that I can use an infix operator. Is that possible?

Answer:
Yes and no.  Yes, you can make it
seem
like you have added a method to
```
double
```
.  For example:
```
```
class MyRichDouble(d: Double) {
  def <>(other: Double) = d != other
}

implicit def doubleToSyntax(d: Double) = new MyRichDouble(d)
```
```
This code adds the previously-unavailable
```
<>
```
operator to any object of type
```
Double
```
.  So long as the
```
doubleToSyntax
```
method is in scope so that it could be invoked without qualification, the following will work:
```
```
3.1415 <> 2.68     // => true
```
```
The "no" part of the answer comes from the fact that you aren't really adding anything to the
```
Double
```
class.  Instead, you are creating a conversion from
```
Double
```
to a new type which does define the method you want.  This can be a much more powerful technique than the open-classes offered by many dynamic languages.  It also happens to be completely type-safe.  :-)
Some limitations you should be aware of:
This technique does not allow you to
remove
or
redefine
existing methods, just add new ones
The implicit conversion method (in this case,
```
doubleToSyntax
```
) absolutely must be in-scope for the desired extension method to be available
Idiomatically, implicit conversions are either placed within singleton objects and imported (e.g.
```
import Predef._
```
) or within traits and inherited (e.g.
```
class MyStuff extends PredefTrait
```
).
Slight aside: "infix operators" in Scala are actually methods.  There is no magic associated with the
```
<>
```
method which allows it to be infix, the parser simply accepts it that way.  You can also use "regular methods" as infix operators if you like.  For example, the
```
Stream
```
class defines a
```
take
```
method which takes a single
```
Int
```
parameter and returns a new
```
Stream
```
.  This can be used in the following way:
```
```
val str: Stream[Int] = ...
val subStream = str take 5
```
```
The
```
str take 5
```
expression is literally identical to
```
str.take(5)
```
.


Question:
What is the best way to dynamically add TableRows and TableCells to an ASP.NET table from Javascript?

Thanks,

Jeff

Answer:
Your question is too vague to answer completely, I'm afraid.  If you actually want to create TableRow or TableCell objects, you would of course need to post back (no need for JavaScript) or make an AJAX call (JavaScript) to server-side code.  Either way, it's not really JavaScript doing the work.  If you just want to dynamically add a row to an HTML table presented in the browser, you could accomplish this without any need for TableRow/TableCell abstractions from ASP.NET.
For a more complete answer you'll have to be more specific about what you are trying to accomplish.


Question:
Instead of writing

((x: Double) => (((y: Double) => y*y))(x+x))(3)

I would like to write something like

((x: Double) => let y=x+x in y*y)(3)

Is there anything like this sort of syntactic sugar in Scala?

Answer:
Indeed there is: it's called "
```
val
```
".  :-)
```
```
({ x: Double =>
  val y = x + x
  y * y
})(3)
```
```
The braces are of course optional here, I just prefer them to parentheses when defining functions (after all, this isn't Lisp).  The
```
val
```
keyword defines a new binding within the current lexical scope.  Scala doesn't force locals to define their own scope, unlike languages such as Lisp and ML.
Actually,
```
var
```
also works within any scope, but it's considered bad style to use it.


Question:
I'm looking to find a way to access the .net query string contained in the standard ASP.NET request object inside a web service. In other words if I set a SOAP web service to this url:

http://localhost/service.asmx?id=2

Can I access the ID Get variable?

Answer:
I just looked for "Request" of the context in asmx file and I saw that. But I'm not sure if it is right.
```
```
this.Context.Request.QueryString["id"];
```
```


Question:
I have following string

String str = "replace :) :) with some other string";

And I want to replace first occurance of :) with some other string

And I used str.replaceFirst(":)","hi");

it gives following exception

"Unmatched closing ')'"

I tried using replace function but it replaced all occurance of :).

Answer:
The
```
replaceFirst
```
method takes a regular expression as its first parameter. Since
```
)
```
is a special character in regular expressions, you must quote it. Try:
```
```
str.replaceFirst(":\\)", "hi");
```
```
The double backslashes are needed because the double-quoted string also uses backslash as a quote character.


Question: Parts of my application are in C++ under windows. I need the process id for the current process. Any thoughts?

Answer:
The
```
GetCurrentProcessId
```
function will do this.


Question:
When C# 4.0 comes out and we have the dynamic keyword as described in this excellent presentation by Anders Hejlsberg, (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)

Would I still need the var keyword ? Is there anything that var can do.. that dynamic can't?

var x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x

dynamic x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x

Answer:
No, they're very different.
```
var
```
means "infer the type of the variable at compile-time" - but it's still entirely statically bound.
```
dynamic
```
means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls
really
mean at execution time.
I expect to use
```
dynamic
```
very rarely - only when I truly want dynamic behaviour:
```
var
```
lets you catch typos etc at compile-time
statically bound code is always going to run faster than dynamically bound code (even if the difference becomes reasonably small)
statically bound code gives more compile-time support beyond just errors: you can find call hierarchies, refactoring will work better, Intellisense is available etc


Question:
Is it possible to create a list that can be access by either an index or a key?

I am looking for a Collection type that already exists but has this facility, I want to avoid redefining the indexers

Answer:
You can add an indexer by adding the following property to your collection:
```
```
public object this[int index]
{
    get { /* return the specified index here */ }
    set { /* set the specified index to value here */ }
}
```
```
This can be quickly added in Visual Studio by typing
indexer
and pressing [tab] [tab].
The return type and indexer type can be changed ofcourse. You can also add multiple indexer types.


Question:
I have the following code that I need to add an additonal object to after the results have been retrieved from the databse. Any Ideas on how I might to this ?

   public IEnumerable<ProdPriceDisplay> GetShopProductsPrices()
{

    //ProdPriceDisplay ProdPrice = new ProdPriceDisplay();
    var Products = from shop in db.SHOPs
                   select new ProdPriceDisplay
                   {
                       ProdPrice = shop.S_NAME + " - £" + shop.S_PRICE
                   };

    // *** Want to add something like this:-

    //  Products.Add new ProdPriceDisplay { ProdPrice = "some additional text"; }

    return Products;
}

Answer:
That could be a solution;
```
```
var productsAsList = Products.ToList();
productsAsList.Add(new ProdPriceDisplay { ProdPrice = "some additional text"; });

return productsAsList; // As your return type is IEnumarable, that won't be a problem;
```
```


Question:
How to do this in Java - passing a collection of subtype to a method requiring a collection of base type?

The example below gives:

The method foo(Map<String,List>) is not applicable for the arguments (Map<String,MyList>)

I can implement by creating a class hierarchy for the typed collections - but is it possible otherwise?

public void testStackOverflow() {

    class MyList extends AbstractList {
        public Object get(int index) {
            return null;
        }
        public int size() {
            return 0;
        }
    };

    Map <String, List>   baseColl = null;
    Map <String, MyList> subColl  = null;

    foo (subColl);
}

private void foo (Map <String, List> in) {
}

EDIT: Turns out from the answers that this requires "bounded wildcard" so adding this text for searchability

Answer:
Change
```
foo
```
to:
```
```
private void foo(Map <String, ? extends List> in) {
}
```
```
That will restrict what you can do within
```
foo
```
, but that's reasonable. You know that any value you fetch from the map will be a list, but you don't know what kind of value is valid to put into the map.


Question:
Staring JBoss server from within Eclipse Ganymede gives me the following problem:
"Server JBoss v4.0 at localhost was unable to start within 120 seconds. If the server requires more time, try increasing the timeout in the server editor."

The console shows JBoss has started in so and so minutes but soon after, there is a pop up if the above message.
I can also start the JBoss externally.

Answer: You may check whether you are running Jboss version 4.0.4 or version 4.2.2.  You might get this error when you have installed Jboss 4.2.2 but configured Jboss 4.0.4 in Eclipse.


Question: I have a list of tables i.e. student, teacher, staff, dept. and so on and each of these tables have comments specific to them. Now one record in a table can have one or many comments that shows it's a one to many relation from any table to comments table. I don't know what the best way is to relate comments table to each of these. If I put foreign key from comments table to each of these tables, it will be like 40-50 fields depending on no. of tables. Secondly if I add foreign key from each of these tables to remarks table, it will be like repeating whole row just for the second remarks foreign key? Similarly if I use just one field in each table as comments, I will be actually storing rows in just one text field. Any suggestions on how to achieve efficient solution?

Answer:
Lets assume that your tables (student, teacher, staff, dept) all have a int primary key named Id.
For your comments table you could create a table.
```
```
Id int
CommentType enum (student, teacher, staff, dept)
LinkId int
Comment
```
```
A row in Comments might look like this
```
```
1,'Student',347,'text'
```
```


Question:
I have a Flash movie embedded in some DIV. The trouble is that when I change any property of the enclosing DIV dynamically, Firefox (not other browsers) restarts/reinitializes Flash movie effectively resetting the whole progress (eg: file selection for upload, etc.).

Is there some sort of a workaround for this?

Answer:
Try hiding it with
```
visibility:hidden
```
or if all else fails,
```
position:absolute;left:-9999px
```
.
I presume Firefox doesn't want to waste memory and CPU on Flash animation that's invisible, so it kills it.


Question:
In previous releases there were 3 ways to pass data from controller to view AFAIK (shown below).

I want to use method (2) with MVC Beta 1, but I can't find the renderView method. So what's the new syntax (if it's still possible)? Thanks in advance.

Ben.

Syntax #1: Old-school dictionary

ViewData["Name"] = "Moo-moo";
ViewData["Age"] = 6;
ViewData["HasFunnyFace"] = true;
RenderView("ShowCat");

Syntax #2: Explicitly-typed ViewData object

RenderView("ShowCat", new ShowCatViewData {
    Name = "Moo-moo",
    Age = 6,
    HasFunnyFace = true
});

Syntax #3: Anonymously-typed object

RenderView("ShowCat", new {
    Name = "Moo-moo",
    Age = 6,
    HasFunnyFace = true
});

Answer:
In beta 1, use the View method:
```
```
return View ("ShowCat", <TYPED_DATA_SET_OR_OTHER_MODEL>);
```
```
The View method has replaced the RenderView method.


Question:
I create new ASP.NET web application that use SMTP to send message. The problem is the smtp was not authenticated from who send the message.

How can I make SMTP authenticated in my program? does C# have a class that have attribute for enter username and password?

Answer:
```
```
using System.Net;
using System.Net.Mail;

using(SmtpClient smtpClient = new SmtpClient())
{
    var basicCredential = new NetworkCredential("username", "password");
    using(MailMessage message = new MailMessage())
    {
        MailAddress fromAddress = new MailAddress("from@yourdomain.com");

        smtpClient.Host = "mail.mydomain.com";
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = basicCredential;

        message.From = fromAddress;
        message.Subject = "your subject";
        // Set IsBodyHtml to true means you can send HTML email.
        message.IsBodyHtml = true;
        message.Body = "
your message body
";
        message.To.Add("to@anydomain.com");

        try
        {
            smtpClient.Send(message);
        }
        catch(Exception ex)
        {
            //Error, could not send the message
            Response.Write(ex.Message);
        }
    }
}
```
```
You may use the above code.


Question: When starting a new ASP.NET application, with the knowledge that at some point in the future it must scale, what are the most important design decisions that will allow future scalability without wholsesale refactoring?

Answer:
My Top three decisions are
Disabling or storing session state
in a database.
Storing as little as possible in session state.
Good N-Tier Architecture. Separating business logic and using Webservices instead of directly accessing DLL's ensures that you can scale out both the business layer as well as the presentation layer. Your database will likely be able to handle anything you throw at it although you can probably cluster that too if needed.
You could also look at partitioning data in the database too.
I have to admit though I do this regardless of whether the site has to scale or not.


Question:
Is it possible to get a list of all instances with a name in a flash movie using actionscript 2. Like an array containing all named text areas, or all movieClip instances etc. I would like to get this so the designer can add or remove text areas etc. and the actionscript can dynamically find these and get the texts from a separate datasource.

I guess what I want is something like a DOM tree or even better something like how getElementByName() works in JavaScript. And allso get the string value of the instance name so I can find it's text value in an xml.

Let's say the designer add a new text area with the name "copyright" and my code should (without having to change the script) find the data with the id "copyright" in an XML file if it is there, and add the value to the text area.

Answer:
It's been a while since I did any AS2 coding but perhaps you could use a combination of MovieClip.getInstanceAtDepth() and this.getNextHighestDepth() to find the highest depth in your movie then trace back through each lower depth until you find a getInstanceAtDepth() that corresponds to the clip you are looking to populate with new data.
I also noticed this example code in the AS2 documentation.
The following code traces the depth of all movie clip instances on the Stage:
```
```
for (var i in this) {
    if (typeof (this[i]) == "movieclip") {
    trace("movie clip '"+this[i]._name+"' is at depth "+this[i].getDepth());
    }
}
```
```
PS: I know you probably don't want to hear this but in AS3 it's a doddle as you can just iterate through this.children!


Question:
I have a really simple ASP.NET web application and a web setup project that deploys the project output and content files to a virtual directory in IIS.

What I want is for the MSI to automatically disable Anonymouse Access for that virtual folder in IIS.

I suspect it can probably be done by writing some code in a custom action DLL, that would be acceptable, but is there any way to do it within the the settings of the web setup project?

Answer:
Taken from technet
The property for anonymous access is
  unfortunately not available through
  Web setup projects. For this reason,
  you must:
Write a custom installer to enable or disable anonymous access.
Pass the necessary parameters from the setup wizard to the installer at
  run time.


Question: I just want to create a C# program which will read a word template and create n number of copies of it with mail merge feature.The data to replace is Name and Address the rest of the things in the template should remains the same. Can any one tell me how to do this ?

Answer:
You can use Aspose.Word for handling the Word Object model without having to have office installed (to use interop) where the program is supposed to run, i'm using Aspose.Word to generate word  documents.
Link to Aspose:
http://www.aspose.com/categories/file-format-components/aspose.words-for-.net-and-java/default.aspx
And it works quite decent :)


Question:
If I put a DateTime value into an Excel cell using Range.set_value through .Net COM Interop, and then retrieve the value of that same cell using Range.get_value, the Millisecond part of the value is not returned, though everything else is correct.

Is this a bug?

What is the workaround? I'm guessing that using the Value2 property instead might help. Has anybody else tried this?

Answer:
If you set a date/time with a millisecond value in Excel manually, does it maintain it? I don't know about the Excel internal object model, but it's conceivable that it just doesn't support milliseconds.
EDIT: Okay, now we know that the set fails (the get may also fail, of course)... you could try setting it as a double after converting it via
DateTime.ToOADate()
. I'm not saying I'm holding out
much
hope, but it's worth a try...


Question: in javascript, when I receive a focus event, how can I work out which element has lost focus? I'm trying to avoid having to put an onblur event handler on all elements within my web page.

Answer:
@pbrodka: the target/srcElement property would refer to the element with focus for onfocus events
offhand I can't see a way to get this short of onblur, or if the set of objects you care about all have focus methods you could store a reference to that object instead. It's also possible event bubbling could get you out of jail
this all feels like a bit of a code smell though - perhaps you need to describe the problem in more detail


Question:
This is the HTML:

<div id="testBlue">
    <span>hello</span>
    <span id="testGreen" class="testGreen">hello2</span>
</div>

If I have set in CSS:

#testBlue span { color:Blue; }
.testGreen, #testGreen { color:Green; }

How can I override the general style in the second SPAN?

I have tried both id and class selectors but it doesnt override it.

Answer:
```
```
#testGreen { color: red !important;}
```
```
or
```
```
.testGreen { color: red !important;}
```
```
Either will override the inherited rule, because
```
!important
```
puts more weight to one side of an an otherwise equal decision.


Question:
I have many jobs that have a step to send 1 specific email out to a list of people.  That list of reciepients is hardcoded in the step command and I need to remove one person from that list, in all jobs.

How do I loop through ALL the jobs in the Sql Server Agent and modify the command text to find+replace a specific piece of text.

I am using sql server 2005 and have already looked at sp_update_jobStep but doesn't appear to be exactly what i want.

Cheers.

Answer:
You could try to update the System tables that hold the information on jobs of the SQL server directly. The relevant ones for you would be:
```
```
msdb.dbo.SysJobs
msdb.dbo.SysJobSteps
```
```
If you have a specific email address to remove, you could update the
Command
field in the
SysJobSteps
table with a single UPDATE statement.
```
```
UPDATE SJS SET
    Command = REPLACE(Command, 'EmailAddress&TestDomain.Com', '')
FROM msdb.dbo.SysJobs SJ
INNER JOIN msdb.dbo.SysJobSteps SJS
    ON SJS.Job_Id = SJ.Job_Id
WHERE SJ.Originating_server = ..... -- Your server here
    AND SJS.Command LIKE '%EmailAddress@TestDomain.Com%'
```
```
It would be advisable to run the above query as a SELECT statement first, to test it returns only the job steps your are expecting to update.


Question:
I have some jQuery/JavaScript code that I want to run only when there is a hash (#) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these:

example.com/page.html#anchor

example.com/page.html#anotheranchor

Basically something along the lines of:

if (thereIsAHashInTheUrl) {
    do this;
} else {
    do this;
}

Answer:
Simple use of
location hash
:
```
```
if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
```
```


Question:
Following the JSONRequest proposal, I've found code for the JSONRequest object. However, this object depends on JSONRequestError, and the code for that is nowhere to be found.

Anyone know where I can find the code?

Thanks in advance!

Answer:
I used the request
```
JSONRequestError site:devpro.it
```
in Google, it is a useful tip... ^_^
Found
JSONRequestError.js
which explain the API, and ... hmm, no source code!
Just poked around the magical number 153, got lucky:
JSONRequestError.js
:-D


Question:
I'm making a C program where I need to get the directory that the program is started from.  This program is written for UNIX computers. I've been looking at opendir() and telldir(), but telldir() returns a off_t (long int), so it really doesn't help me.

How can I get the current path in a string (char array)?

Answer:
Look up the man page for
```
getcwd
```
.


Question:
On windows mobile when there is no internet connection and I try to
browse the web using internet explorer i get cannot connect
information at the top of the screen. It says cannot connect with
current connection settings. To change your connection settings, tap
settings. And I am able to tap Settings and setup network connections.
How can I display cannot connect information programmatically? When I
cannot connect to a webservice using my application I would like to
show the same information and let the user set up network connections.
I use compact framework 2.0 and csharp.

Thanks in advance.

Answer:
Look up the man page for
```
getcwd
```
.


Question:
I'm using Tomcat 5.5 as my servlet container. My web application deploys via .jar and has some resource files (textual files with strings and configuration parameters) located under its WEB-INF directory. Tomcat 5.5 runs on ubuntu linux. The resource file is read with a file reader:

fr = new FileReader("messages.properties");

The problem is that sometimes the servlet can't find the resource file, but if i restart it a couple of times it works, then again after some time it stops working.
Can someone suggest what's the best way of reading resource strings from a servlet? Or a workaround for this problem?
Putting the resource files under WEB-INF/classes doesn't help either.

Answer:
I'm guessing the problem is you're trying to use a relative path to access the file.
Using absolute path should help (i.e. "/home/tomcat5/properties/messages.properties").
However, the usual solution to this problem is to use the getResourceAsStream method of the ClassLoader. Deploying the properties file to "WEB-INF/classes" will make it available to the class loader and you'll be able to access the properties stream.
Untested proto-code:
```
```
Properties props = new Properties();

InputStream is =
getClass().getClassLoader().getResourceAsStream("messages.properties");

props.load(is);
```
```


Question:
IBM Rational Application Developer is very slow and has many problems.

I tried to use ant scripts to build EAR/WAR files for Websphere Application Server
but it did not work.

Answer:
My understanding is that you build the EAR/WAR, then open your browser, login to the admin console, then deploy your application.
If my understanding is correct, just add an instance of the WAS server to your workspace, and then right click on the server, select Add/Remove Projects and add your project. This way, you don't have to build the EAR/WAR file at all... Building your project is enough. If the build is successful, then RAD automatically builds the EAR/WAR and publishes the file to the server.
Atleast that's the way we do it.


Question:
I need to write a little tool for a customer to be run on Windows 98. Since this is a very small project I'd hope that I could avoid having to go native C++ and use C#.

The .net Framework 2.0 download claims to support Windows 98. Are there any caveats or hitches to be aware of when installing or coding?

Answer: .NET 2.0 supports Windows 98, but you won't have access to some of the base library classes such as EventLog.


Question:
I Have a problem with my custom Addin to word because sometimes, MS Word was disabled my addin, and I need to write another AddIn, which Was enabled to turn - on/off my first AddIn. Is it possible?

sorry for my English  :(

Answer:
What kind of add-in technology are you using? VSTO?
What version of Office are you using?
In general it is possible to do what you want. However, the reason that Office disables add-ins is that the add-in threw an unhandled exception. In that case Office will set the
```
LoadBehavior
```
value in the Registry to 2.
Maybe it would be better to analyze and handle the underlying problem causing the exception.


Question:
I'm trying to make a window that closes when you click outside it, and at the moment I'm looking into doing that by handling the WndProc function.

None of the messages I'm getting so far seem useful, but there are a few I don't understand at all.  What do codes 0x0118, 0xC123, 0xC128 and 0xC12E represent?

Answer:
An easy way would be to just capture the mouse.  When you have the mouse captured you get one click event outside your window, then capturing is turned off.
A harder way would be to set a low-level mouse windows hook.  To do a global hook, you'll have to put your hook code in an unmanaged DLL.
A
really
easy way would be to just close your form when it's deactivated.
EDIT
:
Oops.  I just realized I didn't answer your direct question about the message IDs.  Message 0x118 is not defined in winuser.h, so I assume it's an undocumented message ID.  Message IDs in the range 0xC000 to 0xFFFF are application-defined messages.  These IDs are returned by
```
RegisterWindowMessage
```
.


Question: Is it possible to generate a XML Schema of a Database programatically with .Net and C#? I want to look into NDbUnit but for big databases it would not really be feasible to make a Schema manually?

Answer:
Is it possible to generate a XML
  Schema from a Database?
It sure is,
XMLSpy
can generate XML Schema from a database.
There's
another way
, though I've never tested it:
```
```
create table Person
(
Age int not NULL check( Age > 0) ,
Height numeric(10,2) not NULL check( Height > 5),
Gender varchar(5) not null check( Gender in ('M', 'F', 'O')),
BirthDate datetime null,
)

DECLARE @schema xml
SET @schema = (SELECT * FROM Person FOR XML AUTO, ELEMENTS, XMLSCHEMA('PersonSchema'))
select @schema
```
```


Question: How can I find the location of exe that runs as a windows service in run-time?

Answer:
If your executable attaches itself to a particular port you could parse the output from
```
```
netstat -ab
```
```
Probably not the most attractive solution though.


Question:
The code below always return an empty array from GetModifiedMembers(object)
but dx.GetChangeSet().Updates.Contains( foo ) returns true.

DataContext dx = new DataContext( string.Empty );
MockLinqDataObject foo = new MockLinqDataObject();
dx.GetTable( foo.GetType() ).Attach( foo );

foo.PK = Guid.NewGuid();

// always returns empty array
ModifiedMemberInfo[] arr_Result = dx.GetTable( foo.GetType() ).GetModifiedMembers( foo );
bool isOk = ( arr_Result.Length == 1 );
return isOk;

Does anyone know what there is wrong?

Thanks in advance?

Answer:
Why you have difficulty in locating the root? go from parent to parent until parent is not set.
BTW Are you talking about B+ trees? They auto balance using blocks of children that get split when a threshold is exceeded look at this image in wikipedia


Question:
I am creating a mobile web application using asp.net. The application must support iPhone, Blackberry and Windows Mobile Platform. What are the low things which should be taken care of while developing this application. Is there any best practices list available for this?

Summary:

Answer:
Can you add some more info? If you are developing a application for all those platforms, I would guess you are creating either some sort of web-services or just a "standard" web-application?
If it's just a standard web-application, I think it's a bit hard to ensure a good compatibility due to the fact that javascript, which is widely used in webapplications isn't always implemented in browsers for mobile phones.... Yes, if you have Opera, and not Pocket Internet Explorer, it get's a bit better. When it comes to Blackberry I'm not quite sure how well the browser performs.
Iphone on the other hand is probably "easy" to develop for, since it's default browser is probably good at javascript - just as Opera mini.
Also - Other graphical issues due to the fact that many Windows Mobile devices have a reather low resolution should also be taken in consideration, but this is eventually getting better with the new devices beeing released :) (As Touch HD, Omnia, Diamond etc)


Question:
P1 and P2 are processes or nodes in a cluster. f1 and f2 are their flags. Supposing  strong memory model, and that both processes may be restarted at any moment, and that restarting a process clears it's flag, here's an algorithm that I came up with and couldn't yet break, but that bothers me for it's not theoretically proven and looks too simple compared with Peterson's.

P1 start:
set f1
if f2 set then clear f1, wait some, goto start
else enter critical section
do whatever
clear f1

P2 start:
set f2
if f1 set then clear f2, wait some, goto start
else enter critical section
do whatever
clear f2

Can anybody see a flow? Except may be that one of the processes may starve the other by quickly re-entering the section?

Answer:
If the "if X set then clear Y" operation is not atomic, there's a potential race condition that could prevent either from getting inside the critical section. I've tried to outline the flow below:
```
```
P1: set f1
P2: set f2
P1: is f2 set?
P2: is f1 set?
P1: yes, clear f1
P2: yes, clear f2
P1: start wait
P2: start wait
P1: end wait
P2: end wait
P1: goto start
P2: goto start
```
```
This could potentially go on forever, until there's a difference in the allocation done by the task scheduler, or the wait times for the two P are different from one another.


Question:
I have two tables, movies and categories, and I want to get an ordered list by categoryID first and then by Name.

The movie table has three columns ID, Name and CategoryID.
The category table has two columns ID and Name.

I tried something like the following, but it didn't work.

var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name })

Answer:
This should work for you:
```
```
var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)
```
```


Question:
How do I send a cross-domain POST request via JavaScript?

Notes - it shouldn't refresh the page, and I need to grab and parse the response afterwards.

Answer:
Create an iFrame,
put a form in it with Hidden inputs,
set the form's action to the URL,
Add iframe to document
submit the form
Pseudocode
```
```
var ifr = document.createElement('iframe');
 var frm = document.createElement('form');
 frm.setAttribute("action", "yoururl");
 frm.setAttribute("method", "post");

 // create hidden inputs, add them
 // not shown, but similar (create, setAttribute, appendChild)

 ifr.appendChild(frm);
 document.body.appendChild(ifr);
 frm.submit();
```
```
You probably want to style the iframe, to be hidden and absolutely positioned.  Not sure cross site posting will be allowed by the browser, but if so, this is how to do it.


Question: I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?

Answer:
Jauco posted a good solution in a comment, so I'm copying it here:
```
```
$(elem)
  .contents()
  .filter(function() {
    return this.nodeType === 3; //Node.TEXT_NODE
  });
```
```


Question:
can i somehow compare two numbers in regex?
i want regex that is correct for 10-12, but incorrect for 12-10. I mean that 10 must be smaller than 12.
I want to do it in Javascript.

Answer:
I wouldn't use regex for this.  I'd split the string on the operator, then compare the two resulting numbers based on what operator I found (I'm assuming
```
10+12
```
and
```
12+10
```
would both be legal).


Question:
I'm trying to ensure a script remains running on a development server. It collates stats and provides a web service so it's supposed to persist, yet a few times a day, it dies off for unknown reasons. When we notice we just launch it again, but it's a pain in the rear and some users don't have permission (or the knowhow) to launch it up.

The programmer in me wants to spend a few hours getting to the bottom of the problem but the busy person in me thinks there must be an easy way to detect if an app is not running, and launch it again.

I know I could cron-script ps through grep:

ps -A | grep appname

But again, that's another hour of my life wasted on doing something that must already exist... Is there not a pre-made app that I can pass an executable (optionally with arguments) and that will keep a process running indefinitely?

In case it makes any difference, it's Ubuntu.

Answer:
Monit
is perfect for this :)
You can write simple config files which tell monit to watch e.g. a TCP port, a PID file etc
monit will run a command you specify when the process it is monitoring is unavailable/using too much memory/is pegging the CPU for too long/etc. It will also pop out an email alert telling you what happened and whether it could do anything about it.
We use it to keep a load of our websites running while giving us early warning when something's going wrong.
-- Your faithful employee, Monit


Question:
When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}.

Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.

Answer:
The
```
{{variable}}
```
is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.
Having said that, you can put this kind of substitution into your JavaScript.
```
```
<script type="text/javascript">
   var a = "{{someDjangoVariable}}";
</script>
```
```
This gives you "dynamic" javascript.


Question:
Since Terminal appeared I've saved as ~/mySrvr.term a modified stock .term file
which opens to execute an ssh to a remote server and to modify the appearance.
I have NOT been able to save "use option key as meta" for emacs-ery; there's no slot for it
in the term file and I'm reluctant to wrestle with a keyboard dictionary file.
Am I missing something simple?  How do I get option-as-meta to stick between sessions?

Thanks

Answer:
Not sure if this helps, but when I go Shell -> Export Settings and save the file as a .terminal file, there are a few lines that save my option-as-meta preference:
```
```
<key>useOptionAsMetaKey</key>
<true/>
```
```
These lines are for a .terminal preference file, not for a .term (which is pretty hard to Google for) so they may not be what you're looking for.


Question:
I have an IIS located on serverA

I have userA at locationA who has opened a content management system site, hosted on serverA.

One of the features of the system is that it allows the user to move a file to LocationB, all within the same network. Now when this move occurs and due to bandwidth restrictions, would this file move from LocationA to serverA to LocationB or is there a way for me to move the file from LocationA to LocationB without going through serverA, i.e using local memory on serverA

I am not using BITS at the moment.

Answer:
That's entirely going to depend on how the CMS works - if it does an
```
scp
```
in the background, then the answer is yes - it skips the local machine.
If it uses http to transfer it to the user's machine then back out, the answer is "no".


Question:
I have two Tables.

Order - With Columns OrderID, OrderStatusID

OrderStatus - With Columns OrderStatusID, Description

I have an Order Object which calls to the database and fills its properties for use in my code.  Right now I have access to Order.OrderStatusID, but in my application I really need access to the "Description" field.

How do you handle this elegantly with good OO design?

Answer:
You can use a SQL select statement with a Join to the OrderStatus table, and include the columns yo want from each table ...
```
```
Select O.OrderId, O.OrderStatusId, S.Descriptiuon
From Order O
    Join OrderStatus S
        On S.OrderStatusId = O.OrderStatusId
Where OrderId = 23 -- or whatever
```
```


Question:
Is there a way to read the properties inside an MSI file?

For example, given a MSI file named Testpackage.msi, I need to find

productName
PackageCode
version

This I am going to use it with WMI uninstall

string objPath = string.Format("Win32_Product.IdentifyingNumber='{0}', Name='{1}', Version='{2}'", "{AC9C1263-2BA8-4863-BE18-01232375CE42}", "testproduct", "10.0.0.0");

Using Orca is a great option, if this can be achieved programmatically. Then I can use this to generate automatic release notes. And in un-installing program too.

Answer:
You can use
Microsoft's Orca.exe
.  Orca will allow you to open the MSI and edit/view all the tables in it. You will have to download the entire
Windows SDK
in order to get it, but thankfully that is free.
One alternative (which might be faster due to the download size of the SDK) is to use dark.exe from the
WiX project
.  Dark is a MSI decompiler, which will export everything into an XML file and collection of resources. The XML it outputs will have the information you are looking for.


Question:
is there a managed code (without adding COM component or wrapped called to C++ routines) way to add integrated security to a C# Managed code assembly?

i.e. I want to write a client-server system where the server uses Remoting instead of IIS, but I want the client to automatically pass it's credentials to the server just like a browser does when communicating with an IIS server that has Integrated security enabled...

Can this be done? and if so, where is there some examples ?

Answer:
When you say "remoting instead of IIS," what exactly do you mean? A remoting endpoint (the server end) is typically hosted in IIS since this gives you lots of stuff for free, like authentication, scaling through load balancing - especially for singlecall type objects - that is to say, you don't want to keep state for successive calls to the endpoint.
You can host a remoting endpoint using the http stack in a client app also in xp/sp2 and beyond utilising the http.sys driver directly (which is handleded automatically for you btw).
Regardless, for automatic logon with NTLM credentials, I suggest you host remoting in IIS, and use System.Net.CredentialCache.DefaultCredentials for the client's credentials your client app. This will pass the context credentials to the server app, presuming the current security zone (intranet/internet/trusted/etc) allows it.
-Oisin


Question:
I'm wondering what good ways there would be make assertions about synchronization or something so that I could detect synchronization violations (while testing).

That would be used for example for the case that I'd have a class that is not thread-safe and that isn't going to be thread-safe. With some way I would have some assertion that would inform me (log or something) if some method(s) of it was called from multiple threads.

I'm longing for something similar that could be made for AWT dispatch thread with the following:

public static void checkDispatchThread() {
    if(!SwingUtilities.isEventDispatchThread()) {
        throw new RuntimeException("GUI change made outside AWT dispatch thread");
    }
}

I'd only want something more general. The problem description isn't so clear but I hope somebody has some good approaches =)

Answer:
For the specific example you give, SwingLabs has some helper code to detect event thread violations and hangs.
https://swinghelper.dev.java.net/
A while back, I worked with the JProbe java profiling tools.  One of their tools (threadalyzer?) looked for thread sync violations.  Looking at their web page, I don't see a tool by that name or quite what I remember.  But you might want to take a look.
http://www.quest.com/jprobe/performance-home.aspx


Question:
I've been putting together a small web form for our technicians to use from their phones out in the field.  However I'm having a lot of trouble getting things working using ASP.NET Mobile, and there seems to be few resources out there to help learn this stuff.  I'm also having trouble getting help.

So the thing is, do I really need to use the mobile controls?  The phones will all have web browsers, so I'm thinking if I'm careful with the interface I can get as good or better results than using the mobile controls.

The only thing I would like from the mobile controls is the PhoneCall control... so the follow up question would be: Can I get the functionality of the PhoneCall control without using it?

Answer:
Use mobile controls has same adventages that web controls in web. Using Mobile Controls + Controls Adapters + WURFL helps to developing very fast to many devices.
Yes, you can use WTAI primitives of WML:
```
<a ref="wtai://wp/mc;34123456789">Call</a>
```


Question:
I'm wondering why the assert keyword is so underused in Java? I've almost never seen them used, but I think they're a great idea. I certainly much prefer the brevity of:

assert param != null : "Param cannot be null";

to the verbosity of:

if (param == null) {
    throw new IllegalArgumentException("Param cannot be null");
}

My suspicion is that they're underused because

They arrived relatively late (Java 1.4), by which time many people had already established their Java programming style/habit

They are turned off at runtime by default

Answer:
In fact they arrived in Java 1.4.
I think the main problem is that when you code in an environment where you do not manage JVM options directly by yourself like in
Eclipse
or J2EE servers (in both cases it is possible to change JVM options, but you need to deeply search to find where it can be done), it is easier (I mean it requires less effort) to use
```
if
```
and exceptions (or worse not to use anything).


Question: In vb.net / winforms, how can a hashtable be bound to a drop down list or any other datasource-driven control?

Answer:
Just use the dropdown lists's Datasource property
```
```
DropDownList dd = new DropDownList();
   Hashtable mycountries = New Hashtable();
   mycountries.Add("N","Norway");
   mycountries.Add("S","Sweden");
   mycountries.Add("F","France");
   mycountries.Add("I","Italy");
   dd.DataSource=mycountries;
   dd.DataValueField="Key";
   dd.DataTextField="Value";
   dd.DataBind();
```
```


Question:
Question says it all really...

I have tried changing the "Allow non-admin users to run this program" setting on the property pages, and have also given the non-admin user in question what looks like the correct privileges in Component Services -> DCOM Config.

Is there anything else I can do ?

This is on Server2003 BTW.

Thanks

Matt

Answer: I saw your question a few days ago, but didn't answer because all I have is something for you to try. I expected someone else with knowledgeable answer to respond, but since you still have no answers I'll tell you the little bit I know. When our tech support department installs our app onto a computer running XP or Vista they log in with an administrator account the first time they run the app. Apparently that allows what ever needs to happen with the ActiveX DLLs to work. After that the users can log in with their regular account and the app is still happy.


Question:
Clearly separation of concerns is a desirable trait in our code and the first obvious step most people take is to separate data access from presentation. In my situation, LINQ To SQL is being used within data access objects for the data access.

My question is, where should the use of the entity object stop? To clarify, I could pass the entity objects up to the domain layer but I feel as though an entity object is more than just a data object - it's like passing a bit of the DAL up to the next layer too.

Let's say I have a UserDAL class, should it expose an entity User object to the domain when a method GetByID() is called, or should it spit out a plain data object purely for storing the data and nothing more? (seems like wasteful duplication in this case)

What have you guys done in this same situation? Is there an alternative method to this?

Hope that wasn't too vague.

Thanks a lot,

Martin.

Answer:
I return IQueryable of POCOs from my DAL (which uses LINQ2SQL), so no Linq entity object ever leaves the DAL. These POCOs are returned to the service and UI layers, and are also used to pass data back into the DAL for processing. Linq handles this very well:
```
```
IQueryable<MyObjects.Product> products = from p in linqDataContext.Products
                                          select new MyObjects.Product //POCO
                                          {
                                              ProductID = p.ProductID
                                          };
 return products;
```
```


Question:
Seeing as C# can't switch on a Type (which I gather wasn't added as a special case because is relationships mean that more than one distinct case might apply), is there a better way to simulate switching on type other than this?

void Foo(object o)
{
    if (o is A)
    {
        ((A)o).Hop();
    }
    else if (o is B)
    {
        ((B)o).Skip();
    }
    else
    {
        throw new ArgumentException("Unexpected type: " + o.GetType());
    }
}

Answer:
One option is to have a dictionary from
```
Type
```
to
```
Action
```
(or some other delegate). Look up the action based on the type, and then execute it. I've used this for factories before now.


Question:
I'm trying to have an XSLT that copies most of the tags but removes empty "<b/>" tags. That is, it should copy as-is "<b> </b>" or "<b>toto</b>" but completely remove "<b/>".

I think the template would look like :

<xsl:template match="b">
  <xsl:if test=".hasChildren()">
    <xsl:element name="b">
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:if>
</xsl:template>

But of course, the "hasChildren()" part doesn't exist ... Any idea ?

Answer:
I wonder if this will work?
```
```
<xsl:template match="b">
  <xsl:if test="b/text()">
    ...
```
```


Question:
Is there anybody who has successfully accessed a Web service from an Oracle stored procedure?  If so, was it a Java stored procedure?  A PL/SQL stored procedure?

Is there any reason why I should not be trying to access a WS from a stored proc?

Here are a couple refs that I found so far

Database Web Services

Calling external Web Service from a Java Stored Procedure

..Just to clarify, this is for SOAP calls

Answer:
First off, what sort of web service are you calling?  I am assuming either SOAP or REST.
For REST web services, UTL_HTTP is often more than sufficient, combined with a bit of XPath in a simple PL/SQL stored procedure.
For SOAP web services, it depends on how sophisticated you need (or want) to be.  You can certainly use XQuery to create an XML document that meets the spec for the web service, use UTL_HTTP to post the document and get the response, and then use some XPath to parse the response all in PL/SQL.  This is a relatively manual and relatively brute-force solution, but if you are talking about a handful of web services, it involves a minimum of infrastructure and the calls can get knocked together pretty quickly.
If you expect the calls to evolve over time or you expect there to be a number of procedures calling a number of web services, it probably makes sense to invest time in something like UTL_DBWS (this isn't something, though, that you generally get working in a couple hours).


Question: I want to create a trace on a database server from my C# app, like what you do in SQL Server Profiler. I have found stored procedures (sys.sp_trace_create etc...) that dont seem to work for my SQL management studio. I was wondering if anyone could help with the coding, or where i would start to do this?!

Answer:
Are you wanting this to be real-time, just like the Profiler itself? That'd be tough to do. You'd basically be re-creating the profiler.
If that is not a requirement, I would recommend simply calling the sp_trace_create stored procs that you found to start a server-side trace, then use your application to open up the files that this trace produces.
The EASIEST way to learn how this works is to run the SQL Profiler itself, set all the options you want, then click Run, and immediately click Stop. Then go to File, Export, Script Trace Definition, and choose the appropriate version.
This should give you a TSQL script that puts all the correct pieces together, including all the trace events, columns, etc.
More technical history of the profiler:
This old SQLMag article
has some history of the Profiler, which replaced an app called "SQL Trace" when SQL 7.0 was introduced.


Question: I'm working with a WinForm app in C#, after I type something in a textbox I want to hit the Enter key but the textbox still has focus (flashing cursor is still in textbox), how can I achieve this?

Answer:
The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):
```
```
TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });
```
```
If this isn't an option, you can look at the KeyDown event etc, but that is more work...
```
```
TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    tb.KeyDown += (sender,args) => {
        if (args.KeyCode == Keys.Return)
        {
            btn.PerformClick();
        }
    };
    Application.Run(new Form { Controls = { tb, btn } });
```
```


Question:
i want the result of an equation rounded to the nearest integer.
e.g.

137 * (3/4) = 103

Consider the following incorrect code.

int width1 = 4;
int height1 = 3;

int width2 = 137;
int height2 = width2 * (height1 / width1);

What is the proper way to perform "integer" math in C#?

Do i really have to do:

int height2 = (int)Math.Round(
      (float)width2 * ((float)height1 / (float)width1)
   );

Answer:
```
```
int height2 = (width2 * height1) / width1;
```
```


Question:
Is there a way to turn off the automatic selection of the first row in the built-in DataGrid in Silverlight?

We build a lot of functionality based off the user selecting a row in a data grid.  The automatic firing of SelectionChanged when databinding or sorting is really causing us issues.  We have tried to put some guards around the selection, but can't seem get all problems covered.

For example, if you have  DataGrid in a tab of a TabControl that is not shown when loading the screen and the DataGrid has a binding to a property of the DataContext that is a list of objects.  The grid is not databound until the tab is shown.  Is there an event telling us that the grid is databinding?  Shouldn't the default behavior of databinding be not to select a row?

Thanks
Mike

Answer:
Mike,
I have solved this problem by wrapping the windows control, and catching the selection changed event of the wrapped windows grid.
In your control, hook up the Loaded event of your control, and when it is loaded, set a boolean private member variable to true.  Then when you are catching the inner data grid's selection changed event, only raise your own selection changed event if you control is loaded.  When this is done, you can now go back to the OnApplyTemplate sub, and set your inner data grid's selected index to -1 and selected item to nothing.  Since the setting of the index and item will happen before your control is finished loading, the selection changed event will not fire. I have tried this in both a tabbed and non-tabbed environment, and it seems to work without issue.  Now on to a little bit harder problem, you may have noticed that when you sort the windows data grid (while it is data bound to an ItemsSource) it always selects the top item of the displayed data.  This will of course, fire the selection changed event, and move to an item that was not previously selected, and as far as I can see, shouldn't be selected. To handle this, you will have to do a little bit more tricky coding.  If you notice, when you catch the inner grid's selection changed event, and look at its selected item, there are only a few cases where the selected item is not set to anything, those are, when there is no longer an item selected (ie. the selection is cleared), or when (HINT) the columns are sorting.  When you are sorting, there are two events that fire, first is the de-selection of the item (SelectedItem is Nothing), and the second is the selection of the top item in the list (SelectedIndex 0).  Now, if you were to put a flag in the event handler for the inner grids selection changed event, and caught the fact that the item is nothing, you could keep track of the prior selected item, and then set the inner data grid's selected item to the previously selected item.
This solves the problem decently well, and as always there may be undesired results while wrapping a windows control, but as far as I can tell, this seems to be the only way to get around the first row being selected on load problem.  I can only imagine, however, that this is going to be fixed by M$ at some point.
I hope this helps,
Thanks,
Scott


Question:
Everything I can find in linq for aggregation has a "group by" clause.  How would I write this query in LINQ?  I have a list of date-value pairs, and I want to take the average of the values:

SELECT AVG(MySuff.Value) AS AvgValue FROM MyStuff

Answer:
morning Alan:
```
```
int count = (from a in myContext.MyStuff
            select a).Count();
```
```
Assuming myContext is the DataContext.
Note that is gives you immediate execution, which you may not want.
You could instead store the results of the query in a var:
```
```
var allResults = from a in myContext.MyStuff
                 select a;

//sometime later when needed
int count = allResults.Count(); // executes the SQL query now!
```
```


Question:
im trying to kick off a Runnable classes run method however i keep getting a NullPointerException,  Im using WebSpheres commonj.workmanager to get an instance of executorService.this is the code im using.

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Inside run ()method..");
    }
});

ANY IDEAS?

Answer:
Are you checking whether
```
executorService
```
is null before calling
```
execute()
```
? If not, it sounds like you need to check the WebSphere docs.


Question:
Let's say I have a List object and an iterator for that list.

Now I sort the list with java.util.Collections.sort()

What happens to the iterator?

Is its behavior still defined and can it still be used?

If not, can I prevent destroying the iterators for the list?

I know, this problem could be circumvented by changing the program design, cloning the list for example, but I specificly want to know the "official" behavior of Java.

Answer:
Iterators are generally invalid after
any
modification to their underlying collections, except via the iterator itself. (For instance,
```
ListIterator
```
allows for insertion and removal.)
I'd certainly expect any iterators to become invalidated after a sort though - and if they weren't, I'd have no idea what order to expect.


Question:
I'm playing with this ActionScript which generates a random 'squiggle'.

Each time a 'squiggle' is placed, it appears within a sprite with a white background.

If I change the background colour of the flash file to pink for example, it would still show up as white.

Does anybody know how I might make the sprite background transparent? Thanks.

Answer:
That is not an actual Sprite (Sprite is an AS3 datatype) it's just a MovieClip that's called 'sprite'. I see that in the code the squiggles are actually being drawn to a MovieClip called 'paintSurface', then when it's done a Bitmap of 'paintSurface' is captured via this line:
```
```
bitmapData.draw(paintSurface);
```
```
then it is attached to the 'sprite' MovieClip here:
```
```
sprite.attachBitmap(bitmapData, 3);
```
```
That is probably why you are getting the white background.
I assume the bitmap is being captured for the sake of processing speed.
Perhaps you could see what happens if you do not capture a bitmap, but instead just attach 'paintSurface' to 'sprite' instead.


Question:
Currently reading quite a heavy WCF book. I have used it myself in production just the once, using tcp, worked a charm.
Anyway what are your opinions on this technology, is it here to stay, is it worth the time invested learning all the complex features etc etc?

Answer:
I think it is here to stay.  It is easily configurable for moving endpoints, it seems robust and allows you to do (pretty much) everything you could do in web services and remoting without the overhead of separate implementations.
I can see where you are coming from, with MS's recent leaks about ongoing support for, and maintenance of  Linq to SQL, but I see WCF as a different beast altogether.  This is a technology that allows interoperability, as well as de-complixifying (I know this isn't a real word, but it should be) communications between systems.


Question: What does the SQL Action keyword do?  Can I use this keyword in a trigger and determine if the trigger was called by an Insert, Delete or Update?

Answer:
No, you can't use it for that. But you can look at the
Inserted and Deleted
tables to see what happened.
A vary basic example would go something like this:
```
```
If exists (select * from inserted) and exists (select * from deleted)
    --Update happened
If exists (select * from inserted)
    --Insert happened
If exists (select * from deleted)
    --Delete happened
Else
    --Nothing happened
```
```
Realistically, though, it just depends on what you need to do.  In some cases, you might just end up joining on these tables by primary key and do various things.
If you post more details in your question about what you're attempting, though, it'd be easier to give a more specific response.


Question:
Ok, heres my issue: I have a JSF application and some JSP files. Let's say i have main.jsp which has a view and includes sub.jsp. This works fine. sub.jsp contains a subview. As a result all the ID's of the form elements in sub.jsp follow the form of 'subview:component'. Now suppose I'm using some ajax and want to fetch the jsp page sub.jsp and include it in a DIV somewhere. Now the ID's all are of the form 'component'. I don't know a way around this, and having to check for 2 different sets of IDs in my interactive javascript is a pain. Is there any way to get consistent IDs?

I've tried:
Removing the subview - (then the AJAX call will fail because no view is found)

and

h:form prependid=false - this only removes the form id, not the subview ids

Answer:
AJAX is tricky to do with JSF. If the JSF framework you're using doesn't support it, you'll run into many view state problems.
I'm surprised an exception isn't thrown when you address
sub.jsp
directly - there should be no h:view in
sub.jsp
and without a UIViewRoot, I'm not sure how a UI tree would be created. If you have a h:view in
sub.jsp
, then you're putting two UIViewRoots into your UI tree - this is a bug. (The JSF component tree is roughly analogous to that of other Java widget kits like Swing or SWT.)
I suspect the problem you're observing is that you're submitting to a different view to the one that was originally rendered. Since the component tree is completely different, the clientIds will be generated from a different view root. You can read about how they are built in
this answer
.
In short, I do not think the mechanism you're using to update the client is a valid one.


Question:
I am looking for good ideas for implementing a generic way to have a single line (or anonymous delegate) of code execute with a timeout.

TemperamentalClass tc = new TemperamentalClass();
tc.DoSomething();  // normally runs in 30 sec.  Want to error at 1 min

I'm looking for a solution that can elegantly be implemented in many places where my code interacts with temperamental code (that I can't change).

In addition, I would like to have the offending "timed out" code stopped from executing further if possible.

Answer:
Well, you could do things with delegates (BeginInvoke, with a callback setting a flag - and the original code waiting for that flag or timeout) - but the problem is that it is very hard to shut down the running code. For example, killing (or pausing) a thread is dangerous... so I don't think there is an easy way to do this robustly.
I'll post this, but note it is not ideal - it doesn't stop the long-running task, and it doesn't clean up properly on failure.
```
```
static void Main()
    {
        DoWork(OK, 5000);
        DoWork(Nasty, 5000);
    }
    static void OK()
    {
        Thread.Sleep(1000);
    }
    static void Nasty()
    {
        Thread.Sleep(10000);
    }
    static void DoWork(Action action, int timeout)
    {
        ManualResetEvent evt = new ManualResetEvent(false);
        AsyncCallback cb = delegate {evt.Set();};
        IAsyncResult result = action.BeginInvoke(cb, null);
        if (evt.WaitOne(timeout))
        {
            action.EndInvoke(result);
        }
        else
        {
            throw new TimeoutException();
        }
    }
    static T DoWork<T>(Func<T> func, int timeout)
    {
        ManualResetEvent evt = new ManualResetEvent(false);
        AsyncCallback cb = delegate { evt.Set(); };
        IAsyncResult result = func.BeginInvoke(cb, null);
        if (evt.WaitOne(timeout))
        {
            return func.EndInvoke(result);
        }
        else
        {
            throw new TimeoutException();
        }
    }
```
```


Question:
i'm a long-time newbie to c#, and this question may be too obvious, so please forgive if i'm "doing it wrong."

Using Visual Studio 2005 Pro, C#, SQL Server 2000 EE SP3.

I have a stored proc that takes one input param and returns several output params pertaining to that input. I am also calling it successfully, and String.Format-ing the outputs into a RichTextBox. I'd like to call this proc periodically and each time stick the output params into a DataGridView row, so the results accumulate over time.

What's the simplest/most elegant way to do get those parameters into the DataGridView? I'd prefer code instead of some GUI builder solution.

Am i overlooking some better approach, such as a more appropriate control?

Thanks!

Answer:
```
```
//set up the datatable
DataTable dt = new DataTable("parms");
dt.Columns.Add("ParmName",typeof(string));
dt.Columns.Add("ParmValue",typeof(string));
//bind to a gui object
myDataGridView.DataSource = dt;

//do this after each sproc call
foreach (SqlParameter parm in cmd.Parameters)
{
    if (parm.Direction == ParameterDirection.Output)
    {
        //do something with parm.Value
        dt.Rows.Add(new object [] { parm.ParameterName,
            Convert.ToString(parm.Value) } );
    }
}
```
```


Question: I am trying to monitor my outlook inbox so whenever new emails come in with attachments I  save the attachment to some other location. Can anyone help me out?

Answer:
This is not a complete solution, but it describes some of the fundamental tools you'll be using in the Outlook API.
From
Access Outlook Emails with ASP.NET, C#
:
```
```
using Outlook;

 Outlook.Application oOutlook;
 Outlook.NameSpace oNs;
 Outlook.MAPIFolder oFldr;
 long iAttachCnt;

 try
 {
     oOutlook = new Outlook.Application();
     oNs = oOutlook.GetNamespace(”MAPI”);

     //getting mail folder from inbox
     oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
     Response.Write(”Total Mail(s) in Inbox :” + oFldr.Items.Count + “
”);
     Response.Write(”Total Unread items = ” + oFldr.UnReadItemCount);
     foreach (Outlook.MailItem oMessage in oFldr.Items)
     {
         StringBuilder str = new StringBuilder();
         str.Append(”

Sender :	”);
         str.Append(oMessage.SenderEmailAddress.ToString() + “
”);
         //basic info about message
         str.Append(”
Date :	” + oMessage.SentOn.ToShortDateString() + “
”);
         if (oMessage.Subject != null)
         {
             str.Append(”
Subject :	” + oMessage.Subject.ToString() + “
”);
         }
         //reference and save all attachments

         iAttachCnt = oMessage.Attachments.Count;
         if (iAttachCnt > 0)
         {
             for (int i = 1; i <= iAttachCnt; i++)
             {
                 str.Append(”
Attachment(” + i.ToString() + “) :	” + oMessage.Attachments[i].FileName + “
”);
             }
         }
         str.Append(”

”);
         Response.Write(str.ToString());

     }

 }
 catch (System.Exception ex)
 {
     Response.Write(”Execption generated:” + ex.Message);
 }
 finally
 {
     GC.Collect();
     oFldr = null;
     oNs = null;
     oOutlook = null;

 }
```
```


Question: What is the best way to convert word HTML to word XML? I cannot buy a tool so need something preferably XSLT which is free and works suitably with basic formatting like paragraphs, lists, bold and italic.

Answer:
XSLT on its own won't do you any good if you want to retain any formatting from outside the XHTML file (for example, in external style sheets). Besides, Word has the ability to open (X)HTML files, and has for a while. It might not come out looking as good as the original, but it works.
In fact, if you have Word and some skill with VB Script, I believe that it is possible to write a script that opens a (X)HTML file, then saves it as WordML or plain old Word if you're using Word 2003 or older, or as .docx if you have 2007.


Question:
Does anyone know tools like SpyStudio to hook processes?
The features I would like to have are:

log function calls on other processes

GUI

scriptable

opensource

I already looked at some tools like:

SpyStudio

Detours

DynInst

but none really fully satisfies me.

Answer:
It likely uses the debugging API and places debug hooks at key points in the application to to trap events. You may even be able to do what you want using
ollydbg
.
EDIT: I just looked at the site and saw the demonstration videos and I would say that they almost certainly do this through the debugging API. They likely place breakpoints in the target at the desired function entry points. When a trap event fires, it looks like they use an RPC call to notify the user of their API and allow them to look at what happened and potentially modify some things. Sending back what to do next also in an RPC call. A nice design, but just a glorified debugger.


Question:
Assuming I have a tree structure

UL
--LI
---INPUT (checkbox)

And I want to grab the checked inputs, I would select

$('ul li input:checked')

However, I want to select the checked inputs of a specific object $myUL that doesn't have an ID.

$myUL.children('li input:checked')

returns all li's since children filters immediate children - the checked filter has no impact.

Is there another way around this? Another descendant filter?

Answer:
use
```
$myUL.find('li>input:checked')
```


Question:
How can I start writing a plugin for Eclipse?

I've looked for documentation, but unfortunately there is very little or it's poor, so what articles can recommended?

Answer:
There are some pretty good resources and tutorials on the main Eclipse and IBM's site. One of the best ways is to pick an open source plug-in that has some similar features to what you want to do and start to dissect it.
PDE Does Plug-ins
Plug-in development 101, Part 1: The fundamentals
Eclipse Plugins Exposed, Part 1: A First Glimpse
Developing Eclipse plug-ins


Question:
Well, heres my scenario.

Client/Server winforms application with SQL Express as the DB. I need to be able to print invoice, packing slips etc..

i would like the customer to be able to modify the invoices. ie. be able to put their logo or change font sizes etc...basically format the display.

Things i have considered so far are.

1) Use a template engine (similar to codesmith or mygeneration) and use templates that output HTML. Then print the html page.

2) Use ReportViewer in local mode. I've heard that users can download a plugin for web dev express and edit the local report files. can anyone confirm this?

3) Use Reportviewer in remote mode.

I don't have much experience with ReportViewer so I'm not sure if i should use local or remote mode as well.

Those of you that have done this kind of thing before whats your recommendation?

Answer:
After just completing a project with it, I would heartily recommend
iTextSharp
to create your invoices and other forms as PDFs. In addition to creating PDFs from scratch, you can also use it to fill in PDF forms and/or templates created with Acrobat (or even MS Office/OpenOffice). And it's free.
It's pretty easy to use in Windows apps or in ASP.Net applications. Most of the documentation and the books on it (
iText in Action
, for example) are about the original Java version,
iText
. However, there are tutorials and example code on the conversion process and, for the most part, all of the functions and libraries work the same in the .Net version, so adapting the book and reference code has been no problem.
I definitely learned the hard way that HTML and CSS are great for browsers (well, great except for the "every browser interprets it different" problem), but horrible for trying to generate consistent, attractive, and precise printed output and forms.


Question:
Does anyone know if its possible to create a new property on an existing Entity Type which is based on 2 other properties concatenated together?

E.g. My Person Entity Type has these fields "ID", "Forename", "Surname", "DOB"

I want to create a new field called "Fullname" which is

Forenames + " " + Surname

So i end up with "ID", "Forename", "Surname", "DOB", "Fullname".

I know i can do this using Linq programmatically i.e.

var results = from p in db.People
select new {
ID = p.ID,
Forename = p.Forename,
Surname = p.Surname,
DOB = p.DOB,
Fullname = p.Forename+ " " + p.Surname
};

Then calling something like

var resultsAfterConcat = from q in results
where q.Fullname.Contains(value)
select q;

However i'd really like to use Linq to Entities to do this work for me at the Conceptual Model level.

Answer:
Not yet, but maybe soon.  First, note that your suggested query will not work at all in LINQ to Entities, with or without the property, because, at present, it doesn't support Contains.  The new version of the Entity Framework in .NET 4.0, however, is supposed to support custom methods in LINQ to Entities queries.  You can see
a video about this from PDC
.  Essentially, you have to write the custom method twice; once in code, and once on your database (e.g., in a calculated field).  See the video for more information.


Question:
In CFEclipse, I do a lot of double-clicking to select text. The standard behavior is to select all text within the nearest word boundaries. This is problematic when editing code where the original editor didn't use camel-case; for example, they wrote "myObject" as "my_object".

Is there a way to change the double-click selection behavior to include '_' as a valid word character?

Answer:
On eclipse 3.4.1 Ganymede, it seems to select the nearest boundaries
including
the '_' (at least in the java file I am using)
What eclipse version are you using ?
This
blog
even reports that eclipse3.3 does select word as you are expecting it...
vs.


Question:
I'm looking for an implementation of the LOGO programming language that supports 'dynaturtles' - animated turtles that can programmatically change shape, speed and direction as well as detect collisions with each other or other objects in the environment.

Back in the mists of time when the earth was new and 8 bit micros ruled supreme, Atari LOGO did this famously well.  One could create all sorts of small games and simulated environments using this technique very easily as that implementation of the language had a very well thought out, elegant syntax.

I know about LCSI's Microworlds but I'm looking for something I can use to get some friends and their kids involved in programming without breaking my budget.

Answer:
Digging around a bit online, I've found
OpenStarLogo
. Though they don't specifically mention "dynaturtles" the docs do mention collision detection.  The site has code and documentation downloads.
From this
wikipedia article
, under the Implementations section, there is a PDF listing known current and antique implementations.  Some of these, such as
StarLogo TNG
and
Elica
have support for 3D objects.  These are definitely not like the LOGO programs I wrote as a kid...


Question:
Say I have the following Objective-C class:

@interface Foo {
     int someNumber;
     NSString *someString;
}

and for reasons I won't get into here, I want to use KVC to update, in a generic fashion, the values for those variables:

[f setValue:object forKey:@"someNumber"];

or

[f setValue:object forKey:@"someString"];`

If object is a string and I'm updating the someNumber variable, it seems that I need to know to use an NSNumberFormatter to get an NSNumber and then Cocoa automatically converts that to an int inside setValue:forKey:.

Is there any way to avoid this custom code and have Cocoa infer the conversion to an int from a string, or do I need to catch this situation each time and handle it myself?

Answer:
You should do the conversion yourself with a number formatter, it gives you finer control than anything that the framework might consider to be appropriate. It is also, probably, not a good idea to use a single instance of an object to update the values for your ivars.  More appropriately, you could perform your update based on the class of the object (providing you are not storing in an
```
id
```
by querying the runtime as to the class of the object by means of
```
object_getClassName
```
.  More information is available in the Objective-C 2.0 Runtime Reference.  But in general, you will likely find bugs in your code as a result of doing things that way.


Question: I'm looking for a library or source code that provides guard methods such as checking for null arguments. Obviously this is rather simple to build, but I'm wondering if there are any out there for .NET already. A basic Google search didn't reveal much.

Answer:
Given Microsoft's
Code Contracts
coming out with .NET 4.0 I'd try to find one which is mostly compatible, if possible - and if not, write it yourself. That way when you upgrade to .NET 4.0 (eventually) the migration will be easier.


Question:
I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution.

def run():
    owd = os.getcwd()
    #first change dir to build_dir path
    os.chdir(testDir)
    #run jar from test directory
    os.system(cmd)
    #change dir back to original working directory (owd)

note: I think my code formatting is off - not sure why. My apologies in advance

Answer:
You simply need to add the line:
```
```
os.chdir(owd)
```
```
Just a note this was also answered in your other
question
.


Question:
I am working on an app for doing screen scraping of small portions of external web pages (not an entire page, just a small subset of it).

So I have the code working perfectly for scraping the html, but my problem is that I want to scrape not just the raw html, but also the CSS styles used to format the section of the page I am extracting, so I can display on a new page with it's original formatting intact.

If you are familiar with firebug, it is able to display which CSS styles are applicable to the specific subset of the page you have highlighted, so if I could figure out a way to do that, then I could just use those styles when displaying the content on my new page.  But I have no idea how to do this........

Answer:
A good start would be the following: make a pass through the patch of HTML you plan to extract, collecting each element (and its ID/classes/inline styles) to an array. Grab the styles for those element IDs & classes from the page's stylesheets immediately.
Then, from the outermost element(s) in the target patch, work your way up through the rest of the elements in the DOM in a similar fashion, eventually all the way up to the body and HTML elements, comparing against your initial array and collecting any styles that weren't declared within the target patch or its applied styles.
You'll also want to check for any * declarations and grab those as well. Then, make sure when you're reapplying the styles to your eventual output you do so in the right order, as you collected them from low-to-high in the DOM hierarchy and they'll need to be reapplied high-to-low.


Question:
For an ASP.NET application, what is the Best Practice implementation method for a custom swear word remover/replacer?

If this is a data table solution, is there free resource to get the data? (Similar to finding a public dictionary table that you can import to your system for spellchecking)

Answer:
Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?
^_^
Also see
How do you implement a good profanity filter?
.


Question:
I need to query Active Directory for a list of users whose password is about to expire.  The obvious (and easy) way to do this is with:

dsquery user -stalepwd n

The problem is that I need to add additional filters to only look for users who are in certain security groups.  This is hard to do with the "dsquery user" syntax that has the built-in -stalepwd option, so I've been using the "dsquery * -filter" option which allows you to use LDAP query syntax.  Unfortunately, while its relatively easy to do apply the other filters with an LDAP query, I'm having trouble filtering users who have a password age greater than n.

Does anyone know the syntax (or if it is even possible) to filter for old passwords using the "dsquery * -filter" method instead of the "dsquery user -stalepwd" method.

Answer:
There are better tools than dsquery to use.
FindExpAcc
from joeware will do the same as stalepwd and allow a filter through its -f switch.
The filter would then look like:
```
```
&(objectCategory=user)(memberof=CN=User Group,OU=Test,DC=foo,dc=com)
```
```
Also check out adfind and admod tools from
joeware
which are more powerful than the command line query tools from Microsoft, but can be a little harder to learn.


Question: What steps do I take? Any gotchas to be aware of or tips to enhance the IDE experience that are specific to SQL Server when using Emacs?

Answer:
Connecting
To connect to a SQL Server database instance from Emacs:
```
```
M-x sql-ms RET
M-x sql-mode
```
```
You will be prompted for standard connection information specifically the following:
User
Password
Server
Database
For SQL Server Authentication, type in the necessary user and password info. However, if connecting via Windows Authentication, then press RETURN for both user and password leaving them blank.
Viewing Output Results
Note that to see the text of any output results in the *SQL* buffer, the 'go' statement should be called at some point. A couple of ways of doing this.
For example, this sql statement will execute but it will not show any result text in the  *SQL* buffer in its current format:
```
```
select 'foo' as bar
```
```
However, if a 'go' is appended to the end:
```
```
select 'foo' as bar
go
```
```
the following will be displayed in the *SQL* buffer:
```
```
bar
 -----
 foo

(1 row affected)
```
```
Alternatively, if you do not want to have 'go' statements littering the text of your SQL script then call 'go' on the fly to see all output results since the last time that the previous 'go' statement was sent to the sql process:
```
```
C-c C-s go RET
```
```
This is helpful if you need to view any error messages that might not initially show in the *SQL* buffer.


Question:
In C# is there a technique using reflection to determine if a method has been added to a class as an extension method?

Given an extension method such as the one shown below is it possible to determine that Reverse() has been added to the string class?

public static class StringExtensions
{
    public static string Reverse(this string value)
    {
        char[] cArray = value.ToCharArray();
        Array.Reverse(cArray);
        return new string(cArray);
    }
}

We're looking for a mechanism to determine in unit testing that the extension method was appropriately added by the developer.  One reason to attempt this is that it is possible that a similar method would be added to the actual class by the developer and, if it was, the compiler will pick that method up.

Answer:
You have to look in all the assemblies where the extension method may be defined.
Look for classes decorated with
```
ExtensionAttribute
```
, and then methods within that class which are
also
decorated with
```
ExtensionAttribute
```
. Then check the type of the first parameter to see if it matches the type you're interested in.
Here's some complete code. It could be more rigorous (it's not checking that the type isn't nested, or that there is at least one parameter) but it should give you a helping hand.
```
```
using System;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;

public static class FirstExtensions
{
    public static void Foo(this string x) {}
    public static void Bar(string x) {} // Not an ext. method
    public static void Baz(this int x) {} // Not on string
}

public static class SecondExtensions
{
    public static void Quux(this string x) {}
}

public class Test
{
    static void Main()
    {
        Assembly thisAssembly = typeof(Test).Assembly;
        foreach (MethodInfo method in GetExtensionMethods(thisAssembly,
            typeof(string)))
        {
            Console.WriteLine(method);
        }
    }

    static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly,
        Type extendedType)
    {
        var query = from type in assembly.GetTypes()
                    where type.IsSealed && !type.IsGenericType && !type.IsNested
                    from method in type.GetMethods(BindingFlags.Static
                        | BindingFlags.Public | BindingFlags.NonPublic)
                    where method.IsDefined(typeof(ExtensionAttribute), false)
                    where method.GetParameters()[0].ParameterType == extendedType
                    select method;
        return query;
    }
}
```
```