q:
I'm going to try to ask my question in the context of a simple example...

Let's say I have an abstract base class Car.  Car has-a basic Engine object.  I have a method StartEngine() in the abstract Car class that delegates the starting of the engine to the Engine object.

How do I allow subclasses of Car (like Ferrari) to declare the Engine object as a specific type of engine (e.g., TurboEngine)?  Do I need another Car class (TurboCar)?

I'm inheriting a plain old Engine object and I cannot re-declare (or override) it as a TurboEngine in my Car subclasses.

EDIT:  I understand that I can plug any subclass of Engine into myEngine reference within my Ferrari class...but how can I call methods that only the TurboEngine exposes?  Because myEngine is inherited as a base Engine, none of the turbo stuff is included.

Thanks!

[A]
There are lots of ways it could be done.
I would favour having a
```
setEngine()
```
method on
```
Car
```
, then having the
```
Ferrari
```
constructor call
```
setEngine()
```
and pass in an instance of a
```
TurboEngine
```
.


q:
I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1.

Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL, and PHP to do this — is there some standard checklist I can follow, or perhaps troubleshoot where the mismatches occur?

This is for a new Linux server, running MySQL 5, PHP, 5 and Apache 2.

[A]
In PHP, you'll need to either use the
multibyte functions
, or turn on
mbstring.func_overload
. That way things like strlen will work if you have characters that take more than one byte.
You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)

s: huggingface

c: devops

d: intermediate


q:
I am trying my hardest to define a list of CodeAnalysisRules that should be omitted from the Code Analysis tools when MSBuild executes my TFSBuild.proj file.

But each time I test it, my list of Code Analysis Rules to exclude are ignored and Team Build just simply honors the Code Analysis Rules settings for each project.

Anyone have an example of a TFSBuild.proj file that shares one list of Code Analysis Rules exceptions for all projects that are build in Team?  I am using Team System 2008.

Thanks for any assistance?

[A]
Well, it took me a while to find this but here is the best answer I could find
http://bloggingabout.net/blogs/rick/archive/2007/09/04/howto-disable-specific-code-analysis-rules-for-a-team-build.aspx
It works, and it does let me enforce a consistent set of rules across all of my solutions without having to visit each project's file and that is huge for me as we tweak our rulesets and don't wish to manually update each project each time
Anyone else know of anything that works?
- this was a VS2005 solution/workaround so I was hoping that it would be easier in VS2008 Team System but so far haven't found anything else


q:
I have a VB6 picture box that gets an image from a video capture device.

I'm trying to figure out how to then convert the picture box to a byte array.

[A]
It's been a long time since I've worked with VB6 but as far as I remember, you can just serialize the image into a
```
PropertyBag
```
and get the contents as a byte array.
The only alternative I know requires heavy use of WinAPI to accomplish the same.


q:
I'm attempting to resize pngs with transparent backgrounds in PHP and the code samples I've found online don't work for me. Here's the code I'm using, advice will be much appreciated!

$this->image = imagecreatefrompng($filename);

imagesavealpha($this->image, true);
$newImage = imagecreatetruecolor($width, $height);

// Make a new transparent image and turn off alpha blending to keep the alpha channel
$background = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagecolortransparent($newImage, $background);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);

imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height,  $this->getWidth(), $this->getHeight());
$this->image = $newImage;
imagepng($this->image,$filename);

Update
By 'not working' I meant to say the background color changes to black when I resize pngs.

[A]
From what I can tell, you need to set the blending mode to
```
false
```
, and the save alpha channel flag to
```
true
```
before
you do the imagecolorallocatealpha()
```
```
<?php
/**
 * https://stackoverflow.com/a/279310/470749
 *
 * @param resource $image
 * @param int $newWidth
 * @param int $newHeight
 * @return resource
 */
public function getImageResized($image, int $newWidth, int $newHeight) {
    $newImg = imagecreatetruecolor($newWidth, $newHeight);
    imagealphablending($newImg, false);
    imagesavealpha($newImg, true);
    $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
    imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent);
    $src_w = imagesx($image);
    $src_h = imagesy($image);
    imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h);
    return $newImg;
}
?>
```
```
UPDATE
: This code is working only on background transparent with opacity = 0. If your image have 0 < opacity < 100 it'll be black background.


q:
How do I import a Python module given its relative path?

For example, if dirFoo contains Foo.py and dirBar, and dirBar contains Bar.py, how do I import Bar.py into Foo.py?

Here's a visual representation:

dirFoo\
    Foo.py
    dirBar\
        Bar.py

Foo wishes to include Bar, but restructuring the folder hierarchy is not an option.

[A]
Be sure that dirBar has the
```
__init__.py
```
file -- this makes a directory into a Python package.


q: I've got a wxGrid that I populate dynamically. I'd like to store some information with each row that shouldn't be displayed to the user. What is the best way to associate data with a row? Should I just create a hidden column or is there a better way?

[A]
Creating a hidden column is the fastest, but indeed a very ugly method. If you can justify the effort, then you should better create your own grid table base class. Your own
wxGridTableBase
-derived class can hold any information you need it to, without the need to show it in the grid. Unfortunately the documentation for that class is sparse or nearly non-existent.
For an example see the grid demo in the wxWidgets samples directory, specifically the
BugsGridTable
class. What you will notice is that you do not necessarily store the strings that the grid will display, but you can format your data in the
GetValue()
method. This can be a lot better, both in terms of memory consumption, and because you can change the format of displayed data on-the-fly.
The switch to a custom grid table base class has had a big impact on speed, memory consumption and functionality for the result set data grid of
FlameRobin
, an administration tool for the Firebird relational database. You can always check out its source code for how we use wxGrid.


q:
If I have data in the following format

 id    subid      text
 1     1          Hello
 1     2          World
 1     3          !
 2     1          B
 2     2          B
 2     3          Q

And would like it in this format:

 id  fold
 1   HelloWorld!
 2   BBQ

How could I accomplish it in T-SQL?

[A]
a temp table and a cursor leap to mind...
Dear Downvoters: a temp table and a cursor have got to be at least as efficient as the recursive-query and custom-function solutions accepted above. Get over your fear of cursors, sometimes they are the most efficient solution. Sometimes they are the only solution. Deal with it.
EDIT: cursor-based solution below. Note that it has none of the limitations of the non-cursor (and more complicated) solutions proposed elsewhere, and performance is probably about the same (hard to tell from a six-row table of course).
and please, don't abandon the main for-each construct of sql just because some blogger says "it's bad"; use your own judgement and some common sense. I avoid cursors whenever possible, but not to the point where the solution is not robust.
```
```
--initial data table
create table #tmp (
    id int,
    subid int,
    txt varchar(256)
)

--populate with sample data from original question
insert into #tmp (id,subid,txt) values (1, 1, 'Hello')
insert into #tmp (id,subid,txt) values (1, 2, 'World')
insert into #tmp (id,subid,txt) values (1, 3, '!')
insert into #tmp (id,subid,txt) values (2, 1, 'B')
insert into #tmp (id,subid,txt) values (2, 2, 'B')
insert into #tmp (id,subid,txt) values (2, 3, 'Q')

--temp table for grouping results
create table #tmpgrp (
    id int,
    txt varchar(4000)
)

--cursor for looping through data
declare cur cursor local for
    select id, subid, txt from #tmp order by id, subid

declare @id int
declare @subid int
declare @txt varchar(256)

declare @curid int
declare @curtxt varchar(4000)

open cur

fetch next from cur into @id, @subid, @txt

set @curid = @id
set @curtxt = ''

while @@FETCH_STATUS = 0 begin
    if @curid <> @id begin
        insert into #tmpgrp (id,txt) values (@curid,@curtxt)
        set @curid = @id
        set @curtxt = ''
    end
    set @curtxt = @curtxt + isnull(@txt,'')
    fetch next from cur into @id, @subid, @txt
end

insert into #tmpgrp (id,txt) values (@curid,@curtxt)

close cur

deallocate cur

--show output
select * from #tmpgrp

--drop temp tables
drop table #tmp
drop table #tmpgrp
```
```


q:
Let's say I do something in Java like:

RemoteResponse response = null;
try {
   FutureTask task new FutureTask(....);
   executor.execute(task);
   response = task.get(1000, TimeUnits.MILLISECONDS);
}
catch( TimeoutException te ) {

   .. should I do something special here? ...
   .. what happens to the return value of the task if task.get() throws an exception? ...
   .. is it ever garbage collected? ..

}

My question is does something hold onto RemoteResponse in the case where TimeoutException is thrown?  Will it get garbage collected?  Do I have to call the cancel() method on the task for that to happen?

[A]
Edit after the question was revised:
```
response
```
is a reference to a
```
RemoteResponse
```
that
```
task
```
is responsible for allocating.  The assignment of the return value from a method won't happen if the method threw an exception, so there is no need for special handling of
```
response
```
.
```
task
```
will be unreferenced when it goes out of scope, either through normal execution or if an exception is thrown.
If the resources allocated by
```
task
```
are well encapsulated, ie there are no externally held references, and are released (
```
close
```
,
```
release
```
, whatever), then there should be no resource leakage.
There's no need to call cancel unless there is some shared resource the
```
task
```
has exclusively or some other consumable resource that the rest of the application needs.
I'd at least log the fact that the task didn't complete in the time allotted.  What else you do depends on the requirements of your application.
Note that
```
task
```
will continue executing until completion, regardless of the
```
get
```
call.


q:
We are repurposing an application server running WebSphere 6.0.2.23.  I would like to rename the various application server to better reflect its new role.

How can you rename an application server?

It seems like wsadmin can do it, but I'm struggling with the object hierarchy.

[A]
IBM Sample Scripts
download:
ConfigScripts.zip
from command line execute:
```
```
/usr/IBM/WebSphere/AppServer/profiles/AppSrv01/bin/ws_ant.sh \
-profileName AppSrv01 \
-buildfile exportImport.xml \
-logfile rename.log \
-DoldServerName=server1 \
-DnewServerName=server2 \
-DnodeName=yourNode01 changeServerName
```
```
source


q:
Given a date how can I add a number of days to it, but exclude weekends. For example, given 11/12/2008 (Wednesday) and adding five will result in 11/19/2008 (Wednesday) rather than 11/17/2008 (Monday).

I can think of a simple solution like looping through each day to add and checking to see if it is a weekend, but I'd like to see if there is something more elegant. I'd also be interested in any F# solution.

[A]
Given the number of the original day in the year D and original day in the week W and the number of workdays to add N, the next weekday number is
```
```
W + N % 5.
```
```
The next day in the year (with no wraparound check) is
```
```
D + ((N / 5) * 7) + N % 5).
```
```
This is assuming that you have integer division.


q:
What's the quickest way to convert a date in one format, say

2008-06-01

to a date in another format, say

Sun 1st June 2008

The important bit is actually the 'Sun' because depending on the dayname, I may need to fiddle other things around - in a non-deterministic fashion. I'm running GNU bash, version 3.2.17(1)-release (i386-apple-darwin9.0).

[Background: The reason that I want to do it from the command line, is that what I really want is to write it into a TextMate command...  It's an annoying task I have to do all the time in textMate.]

[A]
```
```
date -d yyyy-mm-dd
```
```
If you want more control over formatting, you can also add it like this:
```
```
date -d yyyy-mm-dd +%a
```
```
to just get the Sun part that you say you want.


q:
Does the CCK api allow me to create a node type, from a custom module, with a bunch of fields that use CCK to store their state?  If so can these fields be locked so that users may not alter them, but still allow the user to add more fields to the node type?

Thanks

[A]
I
think
the answer to your first question is "yes" (for Drupal 6, at least, which has elements of the CCK integrated into Drupal Core).  I believe the
Amazon module
does this sort of thing, albeit it with just one field.
I don't think the idea in your second request is achievable, though.  This would seem to require field-level permissions' control whilst Drupal only supports module-level permissions' control.


q:
I had the following line snippet of code that searches for a propery of an instance by name:

var prop = Backend.GetType().GetProperty(fieldName);

Now I want to ignore the case of fieldName, so I tried the following:

var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase);

... No dice.  Now prop won't find field names that have the exact case.

Hence.....
How do I use .Net reflection to search for a property by name ignoring case?

[A]
You need to specify
```
BindingFlags.Public | BindingFlags.Instance
```
as well:
```
```
using System;
using System.Reflection;

public class Test
{
    private int foo;

    public int Foo { get { return foo; } }

    static void Main()
    {
        var prop = typeof(Test).GetProperty("foo",
                                            BindingFlags.Public
                                            | BindingFlags.Instance
                                            | BindingFlags.IgnoreCase);
        Console.WriteLine(prop);
    }
}
```
```
(When you don't specify any flags, public, instance and static are provided by default. If you're specifying it explicitly I suggest you only specify one of instance or static, if you know what you need.)


q:
A few guys on our team are of the opinion that every web page in the application should be a web user control. So you'll have all of your html + event handling in the Customer.ascx, for example, and there will be a corresponding Customer.aspx page that contains Customer.ascx control.

These are their arguments:

This practice promotes versatility, portability, and re-usability.

Even if the page is not re-used right now, it might be in a future.

Customer page might need to move to a different location or renamed sometimes in a future and moving user controls is easier.

This is a recommendation by MS for new development.

Is this really a recommendation for new development? Are there any drawbacks to this strategy? I agree that it's nice to have a user control on hand if the need arises, but it seems to be an overkill to do this to the entire application "just in case we need it later".

[A]
Seriously complicates client-side script as the NamingContainer jiggery will prepend _ctl0 etc to everything sometimes.
I don't think MS ever recommended it.  Request links to MSDN documentation.
Typically by the time your are done implementing something, and it is sufficiently complicated, you'll find a lot of "gotchas" when ever you try to "reuse" it.   A good example is relative links
in
the user control that no longer work outside of their path.
Users don't need the ability to add/edit/delete Customers on every page.  Indeed, you start to get into caching issues if you have these types of controls on every page.  For example if on an Invoice page, you add a Customer, will the Invoice control be updated with the new Customer?  All sorts of inter-control operability issues can manifest.  These issues are hard to argue for, because of course, everyone's user control will be
perfect
, so this will never happen.  ha ha right.
See if they can come up with an example where moving/renaming a user control actually saved time, instead of making it more complicated.   Draw up an actual example and show the pros/cons of each.


q:
I have created a reference to an IIS hosted WCF service in my ASP.NET website project on my local workstation through the "Add Service Reference" option in Visual Studio 2008.  I was able to execute the service from my local workstation.

When I move the ASP.NET web site using the "Copy Web Site" feature in Visual Studio 2008 to the development server and browse to the page consuming the service, I get the following error:

Reference.svcmap: Specified argument
  was out of the range of valid values.

Has anyone experienced this same error and know how to resolve it?

EDIT: My development server is Win2k3 with IIS 6

[A]
The problem may be due to a mismatch with the solution/project folder structure and the IIS web site folder structure. I ran into similar problems a good while ago and ended up changing how I deploy web services.
Here
and
here
are some discussions of similar problems to yours, they ended up not using the Add Service generated client and rolled their own client. Also, I can vouch for using the "Publish web site" method for deploying my services.
Here
is a good article on web service deployment models.


q:
I know that in the original C++0x standard there was a feature called export.

But I can't find a description or explanation of this feature. What is it supposed to do? Also: which compiler is supporting it?

[A]
See
this
explanation for its use
Quite a few compilers don't support it either because it's too new or in the case of gcc - because they disaprove.
This post describes standard support for many compilers.
Visual Studio support for new C / C++ standards?


q:
I have a sequential workflow with a number of Activities. One of these activities needs to access my paid S3 account. It works fine, but to be cautious, I would like to make sure it can handle unexpected situations, such as 'Host not found' or some timeout, etc.

So .. i would normally put the code inside a TRY / CATCH. That's fine .. but i'm not sure of what i should do with the workflow .. because if the code fails to complete correctly, the rest of the workflow shouldn't occur (based on the logic of this workflow).

So, i wanted to maybe retry the connect a few times .. and if that finally fails, call an Email Activity and terminate workflow.

Can anyone make any suggestions, links to vid's or screenies that help show what is the best practice for this?

cheers!

[A]
Take a look at the
```
FaultHandlerActivity
```
, which is used to handle an Exception of the type specified by the
```
FaultType
```
property. Some links about error handling in WF:
Fault Handling in Workflows
Using the FaultHandlerActivity Activity
Exception and Error Handling
(partial book chapter)
Another way is to use the
```
Activity.HandleFault
```
method, which is called when an exception is raised within the context of the execution of your activity.


q: Is there an ascii value I can put into a char in C++, that represents nothing?  I tried 0 but it ends up screwing up my file so I can't read it.

[A]
The null character '\0' still takes up a byte.
Does your software recognize the null character as an end-of-file character?
If your software is reading in this file, you can define a place holder character (one that isn't the same as data) but you'll also need to handle that character.  As in, say '*' is your place-holder.  You will read in the character but not add it to the structure that stores your data.  It will still take up space in your file, but it won't take up space in your data structure.
Am I answering your question or missing it?


q:
I'd like to find a way to do a SQL query that will calculate the cidr (bit representation) of a subnet mask stored in the database.  So for example, I've got either 255.255.255.0 or its decimal value (4294967040) stored in the database.  I'd like to do a select and get back /24 representation via the query.

I've done things like the following to determine the last IP of a subnet so I'm hoping to do something similar to determine the cidr representation of a mask.

select concat(inet_ntoa(ip_addr),'-',
    inet_ntoa(ip_addr+(POWER(2,32)-ip_mask-1))) range
from subnets
order by ip_addr

Preferably this would be a SQL statement that would work under mysql, postgres, oracle etc.

[A]
SQL queries don't have a procedural looping construct (notwithstanding procedural language), but you can compare one set of rows to another set of rows, which is kind of like a loop.
You only have 32 possible subnet masks.  In cases like this, it makes sense to create a small table that stores these 32 masks and the associated CIDR number.
```
```
CREATE TABLE cidr (
  bits INT UNSIGNED PRIMARY KEY,
  mask INT UNSIGNED NOT NULL
);

INSERT INTO cidr (bits) VALUES
  ( 1), ( 2), ( 3), ( 4), ( 5), ( 6), ( 7), ( 8), ( 9), (10),
  (11), (12), (13), (14), (15), (16), (17), (18), (19), (20),
  (21), (22), (23), (24), (25), (26), (27), (28), (29), (30),
  (31), (32);

UPDATE cidr SET mask = ((POWER(2,32)-1)<<(32-bits)) & (POWER(2,32)-1);

SELECT CONCAT(s.ip_addr, '/', c.bits)
FROM cidr c JOIN subnets s ON (c.mask = inet_aton(s.ip_mask));
```
```


q:
I'm pulling email address records from a table in SQL Server 2005, and want to build a single string to use as the @recipients list with sp_send_dbmail. The table has a field called EmailAddress and there are 10 records in the table.

I'm doing this:

DECLARE @email VARCHAR(MAX)
SELECT
    @email = ISNULL(@email + '; ', '') + EmailAddress
FROM
    accounts

Now @email has a semi-delimited list of 10 email address from the accounts table.

My questions is why/how does this work? Why doesn't @email only have the last email address in the table?

[A]
Because for each row you concatentate the current value of
```
@email
```
with the next result in
```
EmailAddress
```
.  String concatenation is just like calling a function, in that it must evaluate the result for each row in sequence.


q:
currently I have the following code:

String select = qry.substring("select ".length(),qry2.indexOf(" from "));
String[] attrs = select.split(",");

which works for the most parts but fails if given the following:

qry = "select a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy') from tbl_a";

what I'm looking for is the regex to feed to String.split() which will hande that situation, and for that matter any other special cases you might be able to think of that I'm missing.

[A]
```
```
[^,]+\([^\)]+\)|[^,]+,
```
```
Should do it nicely provided you always add a final ',' to your select string:
```
```
a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff
```
```
would fail to split the last 'fff' attributes, but:
```
```
a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff,
```
```
would captures it. So a little pre-processing would smooth things out.
Caveat
: this does not take into account expression within expression
```
```
EXP(arg1, EXP2(ARG11,ARG22), ARG2)
```
```
Tell me if that can happen in the queries you have to process.
Caveat bis
: since this needs a true regexp and not a simple separator expected by split(), you must use a Matcher, based on the pattern
```
[^,]+\([^\)]+\)|[^,]),
```
, and iterate on Matcher.find() to fill the array of attributes
```
attrs
```
.
In short, with split() function, there is no single simple separator that might do the trick.


q:
On a web page that is to be displayed on an iPhone, is there a way to get the number pad to come up when the user taps in the field, instead of the qwerty keypad?

This guy says here's how to do it, but as of 2.0, this "feature" was disabled.

I'm guessing there's some fancy javascript to employ to get around this limitation?

[A] Yes, this used to be possible by including the word "zip" in your text field's name attribute. Unfortunately, Apple seems to have removed this in 2.0 and later. I suggest you file a bug.


q:
Given a model

class BaseModel < ActiveRecord::Base
  validates_presence_of :parent_id
  before_save :frobnicate_widgets
end

and a derived model (the underlying database table has a type field - this is simple rails STI)

class DerivedModel < BaseModel
end

DerivedModel will in good OO fashion inherit all the behaviour from BaseModel, including the validates_presence_of :parent_id. I would like to turn the validation off for DerivedModel, and prevent the callback methods from firing, preferably without modifying or otherwise breaking BaseModel

What's the easiest and most robust way to do this?

[A]
From poking around in the source (I'm currently on rails 1.2.6), the callbacks are relatively straightforward.
It turns out that the
```
before_validation_on_create
```
,
```
before_save
```
etc methods, if not invoked with any arguments, will return the array which holds all the current callbacks assigned to that 'callback site'
To clear the before_save ones, you can simply do
```
```
before_save.clear
```
```
and it seems to work


q:
I have a factory that returns an interface FormatService:

public class FormatServiceFactory {
    public FormatService getService() {
        ...
    }
}

Is it possible to mock out this factory so that it will always return a stub implementation of FormatService - FormatServiceStub in our unit tests?

[A]
Depends.  How is the factory obtained/used by the code under test?
If it's instantiated explicitly in the methods you're testing, or if it's a static factory, you won't be able to mock it.
If it's injected into the object under test, you can create and inject the mocked factory before executing the test.
Mocking the factory should be easy enough with JMock.  From your example code, it looks like it's a class, not an interface, so you'll either need to use the cglib version of JMock and the
MockObjectTestCase
class in the cglib package for JMock 1, or the
ClassImposteriser
for JMock 2.
Once mocked, you can make it return your stubbed implementation (or even a mock FormatService) when you define the expectations for the getService() method.


q:
I have a class that maintans a reference to a Hashtable and serializes/deserializes that Hashtable. After the call to SerializationInfo.GetValue, the Hashtable is not fully deserialized because the deserialization happens during the IDeserialization calback.

Hashtable hashtable = (Hashtable) info.GetValue("hash", typeof(Hashtable));

I also implemented the IDeserialization callback in the parent class, but there too the Hashtable is not fully deserialized yet. I expected it to be if the deserialization is happening from the inside out.

My question is, is it safe to explicitely call Hashtable.OnDeserialization from the OnDeserialization method of my parent class, so that I can enumerate it at that point?

public virtual void OnDeserialization(object sender)
{
    hashtable.OnDeserialization(sender);
}

[A]
I suspect you have already googled, but I happened to across
this
pattern yesterday.
```
```
public BoringClass(SerializationInfo info, StreamingContext context)
{
    Hashtable hashtable = (Hashtable) info.GetValue("hash", typeof(Hashtable));
    hashtable.OnDeserialization(this);

    Console.WriteLine("Value is: " + hashtable["testItem"]);

}
```
```


q: What is the best way to remove an entry from a hashtable that uses linear probing? One way to do this would be to use a flag to indicate deleted elements? Are there any ways better than this?

[A]
The Python hash table implementation (arguable very fast) uses dummy elements to mark deletions.  As you grow or shrink or table (assuming you're not doing a fixed-size table), you can drop the dummies at the same time.
If you have access to a copy, have a look at the article in
Beautiful Code
about the implementation.


q:
I am using the Ajax Control Toolkit Calendar Extender control. In some fields though I want to display the time along with the date. I have tried just setting the Format to "dd/MM/yyyy hh:mm:ss" but the time section gets wiped off. If the user wants to change the time section they can do it manually, the calendar drop down is only used for changing the date part.

Are there any workarounds or alternatives to get this working?

[A]
I have a similar issue and I'm planning to use a Date field and an associated time dropdown (in 1/2 hour increments).  User sets the date in the date field, optionally using the calendar control, and pulls down to a valid time.  I plan to have one selection in the time drop down be a "don't care" in case it an "all day" event.
[EDIT] I found this jquery
plugin
that I may end up using.   I also found a link to
Gaia DateTimePicker
in the answers to
this post
(which now looks to be deleted, probably because the OP was asking for WPF controls, not web controls).


q:
What is the idiomatic Python equivalent of this C/C++ code?

void foo()
{
    static int counter = 0;
    counter++;
    printf("counter is %d\n", counter);
}

specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?

[A]
Use a generator function to generate an iterator.
```
```
def foo_gen():
    n = 0
    while True:
        n+=1
        yield n
```
```
Then use it like
```
```
foo = foo_gen().next
for i in range(0,10):
    print foo()
```
```
If you want an upper limit:
```
```
def foo_gen(limit=100000):
    n = 0
    while n < limit:
       n+=1
       yield n
```
```
If the iterator terminates (like the example above), you can also loop over it directly, like
```
```
for i in foo_gen(20):
    print i
```
```
Of course, in these simple cases it's better to use xrange :)
Here is the documentation on the
yield statement
.


q:
I'm a big fan of simpletest because it's what I know. It has excellent support for mocking and web-testing.

But I'm always scared of stagnating so any compelling arguments to switch would be appreciated.

[A]
I haven't used SimpleTest myself, so I can't say much in a way of comparison. Just by observation though, the PHPUnit syntax seems much more verbose.
The
PHPUnit Manual
is a great source of documentation, and covers most areas of the framework. My only complaint about the manual is that some areas lack detail.
My main reason for using PHPUnit over SimpleTest is that it has great
Phing
integration.


q:
HI All,

I have a piece of javaScript that removes commas from a provided string (in my case currency values)

It is:

    function replaceCommaInCurrency(myField, val)
    {
        var re = /,/g;

        document.net1003Form.myField.value=val.replace(re, '');
    }

'MyField' was my attempt to dynamically have this work on any field that I pass in, but it doesn't work, I get errors saying 'MyField' is not valid. I sort of get my, but I thought this was valid.

I am calling by using: onBlur="replaceCommaInCurrency(this.name, this.value);return false;"

this.name and this.value are passing in the right values...field name and its value.

How do I do this dynamically?

-Jason

[A]
If you code it right into the markup like that, e.g. onblur="replaceCommaInCurrency(this)", the control originating the event gets passed as the parameter.  Then you should be able to do something like:
```
```
myField.value = myField.value.replace(re, '');
```
```
with jQuery:
```
```
var jqField = $(myField);
jqField.val(jqField.val().replace(re, ''));
```
```


q:
I have a vector that I want to insert into a set. This is one of three different calls (the other two are more complex, involving boost::lambda::if_()), but solving this simple case will help me solve the others.

std::vector<std::string> s_vector;
std::set<std::string> s_set;
std::for_each(s_vector.begin(), s_vector.end(), s_set.insert(boost::lambda::_1));

Unfortunately, this fails with a conversion error message (trying to convert boost::lambda::placeholder1_type to std::string).

So... what's wrong with this?

[A]
I think part of the problem is that
```
for_each()
```
is expecting a functor and you're passing it the result of a function call. So your code would call
```
vector<string>::insert()
```
first and then pass the result of that call to
```
for_each()
```
. I'm not sure of the exact syntax, but I think you want to use bind in combination with lambda here. e.g.
```
```
for_each(s_vector.begin(), s_vector.end(),
         boost::bind(set<string>::insert, s_set, boost::lambda::_1));
```
```


q:
How can I return the result of a different action or move the user to a different action if there is an error in my ModelState without losing my ModelState information?

The scenario is; Delete action accepts a POST from a DELETE form rendered by my Index Action/View.  If there is an error in the Delete I want to move the user back to the Index Action/View and show the errors that are stored by the Delete action in the ViewData.ModelState.  How can this be done in ASP.NET MVC?

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Delete)]
public ActionResult Delete([ModelBinder(typeof(RdfUriBinder))] RdfUri graphUri)
{
    if (!ModelState.IsValid)
        return Index(); //this needs to be replaced with something that works :)

    return RedirectToAction("Index");
}

[A]
Maybe try
```
```
return View("Index");
```
```
instead of
```
```
return Index();
```
```


q:
I wonder if it's possible to save all files in a Visual Studio 2008 project into a specific character encoding. I got a solution with mixed encodings and I want to make them all the same (UTF-8 with signature).

I know how to save single files, but how about all files in a project?

[A]
I'm only offering this suggestion in case there's no way to automatically do this in Visual Studio (I'm not even sure this would work):
Create a class in your project named
足の不自由なハッキング
(or some other unicode text that will force Visual Studio to encode as UTF-8).
Add "using MyProject.
足の不自由なハッキング
;" to the top of each file.  You should be able to do it on everything by doing a global replace of "using System.Text;" with "using System.Text;using MyProject.
足の不自由なハッキング
;".
Save everything.  You may get a long string of "Do you want to save X.cs using UTF-8?" messages or something.


q:
Does anybody have experience using the open source offering from Terracotta as opposed to their enterprise offering? Specifically, I'm interested if it is worth the effort to use terracotta without the enterprise tools to manage your cluster?

Over-simplified usage summary: we're a small startup with limited budget that needs to process millions of records and scale for hundreds-of-thousands of page views per day.

[A]
Update
What I see in the OP message is "well, I don't really know what we need (thus the lack of detailed requirements), but may be some enterprizey tool will magically solve all our problems, known and unforeseen? That would be
awesome
!"
With an architectural approach like this it's not gonna fly. No success stories from Teracotta would change that.
OSS is beneficial when the community around it can replace the commercial support. Suppose the guy have a problem in production. Community cannot help -- it's too small for the obscure product like this. Servers are down, business is in danger. You see? You need a commercial license up-front. No money? Well, then you're
not a business
, and probably not gonna become one (if nobody's willing to invest into it).
Sorry for interrupting your day-dreaming.
IMHO:
Terracotta is a clustering solution. Clustering is required for large, enterprise-grade applications. Large applications mean big budgets. Big budgets mean you can afford commercial license from Terracotta.
To put it in another way: if you don't have budget to buy it, it's probably not beneficial for your project.


q:
I'm new to cryptography and modular arithmetic. So, I'm sure it's a silly question, but I can't help it.

How do I calculate a from

     pow(a,q) = 1 (mod p),

where p and q are known? I don't get the "1 (mod p)" part, it equals to 1, doesn't it? If so, than what is "mod p" about?

Is this the same as

     pow(a,-q) (mod p) = 1?

[A]
Not silly at all, as
this is the basis for public-key encryption.
You can find an excellent discussion on this at
http://home.scarlet.be/~ping1339/congr.htm#The-equation-a%3Csup%3Ex.
PKI works by choosing
```
p
```
and
```
q
```
that are large and
relatively prime
.  One (say
```
p
```
) becomes your private key and the other (
```
q
```
) is your public key.  The encryption is "broken" if an attacker guesses
```
p
```
, given
```
a
```
```
q
```
(the encrypted message) and
```
q
```
(your public key).
So, to answer your question:
```
a
```
```
q
```
= 1 mod
```
p
```
This means
```
a
```
```
q
```
is a number that leaves a remainder of 1 when divided by
```
p
```
.  We don't care about the integer portion of the quotient, so we can write:
```
a
```
```
q
```
/
```
p
```
=
```
n
```
+ 1/
```
p
```
for
any integer value of
```
n
```
.  If we multiply both sides of the equation by
```
p
```
, we have:
```
a
```
```
q
```
=
```
np
```
+ 1
Solving for
```
a
```
we have:
```
a
```
= (
```
np
```
+1)
1/
```
q
```
The final step is to find a value of
```
n
```
that generates the original value of
```
a
```
.  I don't know of any way to do this other than trial and error -- which equates to a "brute force" attempt to break the encryption.


q:
Still struggling to understand what best practices are with respect to macros.  I'm attempting to write a macro which defines packages on the fly.

(defmacro def-dynamic-package (name)
  `(defpackage ,(intern (string-upcase name) "KEYWORD")
     (:use :common-lisp)))

This works fine only for expressions such as:

(def-dynamic-package "helloworld")

But fails miserably for something like this:

(defun make-package-from-path (path)
  (def-dynamic-package (pathname-name path)))

or

(defun make-package-from-path (path)
  (let ((filename (pathname-path)))
     (def-dynamic-package filename)))

I understand how most basic macros work but how to implement this one escapes me.

[A]
Failure is to be expected here, because a macro is used when its argument should not be evaluated.
In your first make-package-from-path, the def-dynamic-package will receive as argument a list that is EQUAL to the value of the following expression:
```
```
(list 'pathname-name 'path)
```
```
In your case, you only want a function:
```
```
(defun def-dynamic-package (name)
  (defpackage (string-upcase name)
    (:use :common-lisp)))
```
```
BTW, if you check the
CLHS
, you'll see that the first argument of
defpackage
needn't be a symbol, but any
string designator
.


q:
My shared host did not provide git, so I built and installed it into ~/bin.
When I ran it, I got the following error on most commands, although they were successful.

stdin: is not a tty

I can solve that problem by adding:

default_run_options[:pty] = true

to my deploy.rb, but then I get this error, which blocks deployment:

sh: git: command not found

How can I resolve both errors?

I tried adding a ~/.ssh/environment file with "PATH=$PATH:$HOME/bin" (and changing sshd_config to use it) but it did nothing.

It seems whatever shell is being used by capistrano is not using the ~/.bashrc or ~/.bash_profile on the remote server.

Any ideas how to set the path on the remote machine?

other info: I'm using OS X locally, and the shared server is linux on Site5.

[A]
A quick workaround is to set the following in your deploy.rb file:
```
```
set :deploy_via, :copy
```
```
This will cause the checkout to occur on your own machine and then be copied to the deployment server.


q: How do you convert between a DateTime and a Time object in Ruby?

[A]
You'll need two slightly different conversions.
To convert from
```
Time
```
to
```
DateTime
```
you can amend the Time class as follows:
```
```
require 'date'
class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24)
    DateTime.new(year, month, day, hour, min, seconds, offset)
  end
end
```
```
Similar adjustments to Date will let you convert
```
DateTime
```
to
```
Time
```
.
```
```
class Date
  def to_gm_time
    to_time(new_offset, :gm)
  end

  def to_local_time
    to_time(new_offset(DateTime.now.offset-offset), :local)
  end

  private
  def to_time(dest, method)
    #Convert a fraction of a day to a number of microseconds
    usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
    Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
              dest.sec, usec)
  end
end
```
```
Note that you have to choose between local time and GM/UTC time.
Both the above code snippets are taken from O'Reilly's
Ruby Cookbook
. Their code reuse
policy
permits this.


q:
Given:

from django.db import models

class Food(models.Model):
     """Food, by name."""
     name = models.CharField(max_length=25)

class Cat(models.Model):
     """A cat eats one type of food"""
     food = models.ForeignKey(Food)

class Cow(models.Model):
     """A cow eats one type of food"""
     food = models.ForeignKey(Food)

class Human(models.Model):
     """A human may eat lots of types of food"""
     food = models.ManyToManyField(Food)

How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class Food, how can one get the classes Cat, Cow and Human.

I would think it's possible because Food has the three "reverse relations": Food.cat_set, Food.cow_set, and Food.human_set.

Help's appreciated & thank you!

[A]
Some digging in the source code revealed:
django/db/models/options.py:
```
```
def get_all_related_objects(self, local_only=False):

def get_all_related_many_to_many_objects(self, local_only=False)
```
```
And, using these functions on the models from above, you hypothetically get:
```
```
>>> Food._meta.get_all_related_objects()
[<RelatedObject: app_label:cow related to food>,
    <RelatedObject: app_label:cat related to food>,]

>>> Food._meta.get_all_related_many_to_many_objects()
[<RelatedObject: app_label:human related to food>,]

# and, per django/db/models/related.py
# you can retrieve the model with
>>> Food._meta.get_all_related_objects()[0].model
<class 'app_label.models.Cow'>
```
```
Note
: I hear Model._meta is 'unstable', and perhaps ought not to be relied upon in the post Django-1.0 world.
Thanks for reading. :)


q:
It's kind of a C puzzle. You have to tell if the program finish its execution, if so, how much time it takes to run and what it returns to the OS.

static unsigned char buffer[256];

int main(void)
{
  unsigned char *p, *q;
  q = (p = buffer) + sizeof(buffer);
  while (q - p)
  {
      p = buffer;
      while (!++*p++);
  }
  return p - q;
}

[EDIT]
I removed the interview-questions tag since that seems to be the primary thing people are objecting to.  This is a great little puzzle but as everyone has already pointed out, not a great interview question.

[A]
this code is garbage, see comments
```
```
static unsigned char buffer[256];
int main(void)
{
  unsigned char *p, *q;
  q = (p = buffer) + sizeof(buffer);    //p=buffer, q=buffer+256
  while (q - p)    //q-p = 256 on first iteration
  {
      p = buffer;        //p=buffer again
      while (!++*p++);   //increment the value pointed at by p+1 and check for !0
  }
  return p - q;    //will return zero if loop ever terminates
}
```
```
it might terminate, it might not; the while loop is essentially scanning an uninitialized buffer so it might throw an access violation instead; i don't remember the binding precedence of ++*p++, nor do i care enough to look it up
if this is really an interview question, my answer is "if this is the kind of code you expect me to work with, i don't want the job"
EDIT: thanks to Robert Gamble for reminding me that static arrays are automatically initialized to zero, so the code is not complete garbage - but I still would not want to maintain it or work with the nutjob that wrote it ;-)


q:
I just realised that Office 2007 now shows multiple pages per default. I can finally take advantage of that huge monitor I've bought.

Is there a similar feature with Visual Studio?

Something like "View -> Two Pages"

[A]
You can use "Tab Groups". Visual Studio supports both horizontal and vertical panes (since at least Visual Studio .NET 2002 I believe, I haven't used VS 5 or 6 in ages..)
There are several ways to create a tab group. One way is:
Open two files.
Grab the tab of one of the files and pull it down and slightly to the side
You'll get a menu prompting you if you want to put it in a new horizontal or vertical pane.
You can move files between panes by grabbing the tab of the open file and pulling it next to the tabs in the pane you want it in.
Another way is:
Click Window
Click New Vertical Tab Group
Here
is a website demonstrating this with pictures and it even includes showing you how to split pane with the
same
file. Handy when refactoring!


q:
Or better said: When to use array as a field data type in a table?

Which solution provides better search results?

[A] I've considered this problem as well and the conclusion that I came to, is to use arrays when you want to eliminate table joins. The number of elements contained in each array isn't as important as the size of the tables involved. If there are only a few thousand rows in each table, then joining to get the 50 sub rows shouldn't be a big problem. If you get into 10's or 100's of thousands or rows, you're likely to start chewing through a lot of processor time and disk i/o though.


q:
I'm loading data from my database, and exporting to an Excel file via a method I found on this site: http://www.appservnetwork.com/modules.php?name=News&file=article&sid=8

It works, but what I want to do now is format the text before it exports - change the font and text size. Does anybody have any ideas on how to do this?

[A]
I have written Excel spreadsheets from PHP 5 using the
```
PEAR :: Package :: Spreadsheet_Excel_Writer
```
classes.  You can do a lot with this package.


q: I'm using Forms Authentication (and the built in Login controls) and letting users click the "remember me" checkbox when logging in. When they return to the site, they are automatically logged in as expected. Is there an event I can catch when this happens? I've been studying the FormsAuthenticationModule.Authenticate event, but I'm not sure that is the correct approach.

[A]
First of all, look into using the Login control that's available in 2.0+ (as I remember).  There is a Authenticate event you can handle on that control, which is where you can set your session variable.
Additionally, let's assume after authenticating the user is taken to some "home" page.  So you can set your session variable inside the "home" page's Load event handler.


q:
I have an entry in my .vimrc which makes it page down the viewport when I hit the spacebar. It looks like this:

map <Space> <PageDown>

I want to create another key mapping which pages the viewport up when holding shift and hitting the spacebar. I have tried the following entries:

map <Shift><Space> <PageUp>
map <S-Space> <PageUp>

Neither work. Anybody know how to achieve this functionality?

[A]
Use this:
```
```
map <Space> ^D   " Pagedown when press Space
map <S-Space> ^U " Page Up when press Shift Space
```
```
To get the ^D and ^U symbol correctly just press Control-V Control-D, and Control-V Control-U


q:
How can I export a GridView's data to a Microsoft Excel 2007 file?

Also, does Microsoft Excel 2007 support html elements and tags?

[A]
I have used
Aspose.Cells
to do this.  This component has a mechanism to programmatically create an Excel document from a GridView.  I usually have a LinkButton whose click event handler constructs the document and writes the data into the Response.


q:
I am new to C++ and I had a few general questions about code separation. I have currently built a small application, all in one file.  What I want to do now is convert this into separate files such that they contain similar code or whatnot.  My real question right now is, how do I know how to separate things? What is the invisible margin that code should be separated at?

Also, what's the point of header files? Is it to forward declare methods and classes so I can use them in my code before they are included by the linker during compilation?

Any insight into methods or best practises would be great, thanks!

[A]
Header files should contain class and function declarations.
Source files contain class and function definitions.
It is standard practice (i.e. read easier) to have one declaration per header file and one definition per source file, though for small (read simpler helper) objects you sometimes group them with related more substantial objects.
Example:  Class Menu
```
```
Menu.h:     Contains the Menu declaration.
Menu.cpp:   Contains the Menu definition.
```
```
The reason header files contain the declarations is so that you can include them from multiple source files and thus each source file has exactly the same definition of each class and function.
Consider it this way:
If you did not have header files then you would need to have the class and/or function declarations (without) definitions in every source file, this means a copy of the same declaration in every file. Thus if you modify a class you need to make the same modification in every file. By the use of a header file you have the declaration in one place and thus only one object to modify.


q:
The term is getting 'hotter' with Microsoft Azure and Windows 7.

 What are the benefits + how does the status quo of desktop computing now change? Does the machine no longer need an OS installation (or a highly stripped down version of a typical OS)... what is needed to interact with the 'Cloud' ?

Update: Received my first RTFM on SO today.

To elaborate.. I'm interested in knowing how different is the 'new way' w.r.t. the services provided by a typical desktop OS today (read Win XP/Vista, linux flavors galore, etc.)... NOT the benefits of cloud computing.

[A]
So far, it looks like the idea of having software & your data hosted at msft's data centre.
SOA seems to be related to what cloud is offering.
No need to have local software (office will run from internet, your docs will be saved there. so that, you can access it anywhere). I think, the target could be big companies - thereby giving them services (software + hardware (data storage + processing power)) on subscription basis.
An expert can shed light on how this can be useful?
Will people be willing to put everything in the cloud?


q:
I want to know when an image has finished loading. Is there a way to do it with a callback?

If not, is there a way to do it at all?

[A]
Image.onload()
will often work.
To use it, you'll need to be sure to bind the event handler before you set the src attribute.
Related Links:
Mozilla on Image.onload()
Example Usage:
```
```
window.onload = function () {

        var logo = document.getElementById('sologo');

        logo.onload = function () {
            alert ("The image has loaded!");
        };

        setTimeout(function(){
            logo.src = 'https://edmullen.net/test/rc.jpg';
        }, 5000);
    };
```
```
```
```
<html>
    <head>
    <title>Image onload()</title>
    </head>
    <body>

    <img src="#" alt="This image is going to load" id="sologo"/>

    <script type="text/javascript">

    </script>
    </body>
    </html>
```
```


q: What are the best ways (or at least most common ways) in ASP (VBScript) for input handling? My main concerns are HTML/JavaScript injections & SQL injections. Is there some equivalent to PHP's htmlspecialchars or addslashes, et cetera? Or do I have to do it manually with something like string replace functions?

[A]
The bottom line is this:
Always HTML-encode user input before you write it to your page.
```
Server.HTMLEncode()
```
does that for you.
Always use parameterized queries to interface with a database. The
```
ÀDODB.Command
```
and
```
ADODB.CommandParameter
```
objects are the right choice here.
Always use the URLScan utility and IIS lockdown on the IIS server that renders the page, unless they are version 6 and up, which do not require these tools anymore.
If you stick to points 1 and 2
slavishly
, I can't think of much that can go wrong.
Most vulnerabilities come from not properly encoding user input or building SQL strings from it. If you for some reason come to the point where HTML-encoding user input stands in your way, you have found a design flaw in your application.


q:
I'm bored with surrounding code with try catch like this..

try
{
    //some boring stuff
}
catch(Exception ex)
{
    //something even more boring stuff
}

I would like something like

SurroundWithTryCatch(MyMethod)

I know I can accomplish this behaviour by creating a delegate with the exact signature of the function, but creating a delegate for all the methods in my application it's just not an option.

I can also do this by injecting IL code but this is expensive in terms of performance as it creates an wrapper assembly around mine.

Any other valid ideeas?

[A]
You can try to use some null validiation instead. I can take a LINQ to SQL example:
```
```
var user = db.Users.SingleOrDefault(u => u.Username == 3);

if (user == null)
    throw new ArgumentNullException("User", "User cannot be null.");

// "else" continue your code...
```
```


q:
I have some low level serialization code that is templated, and I need to know the system's endianness at compiletime obviously (because the templates specializes based on the system's endianness).

Right now I have a header with some platform defines, but I'd rather have someway to make assertions about endianness with some templated test (like a static_assert or boost_if). Reason being my code will need to be compiled and ran on a wide range of machines, of many specialized vendor, and probably devices that don't exist in 2008, so I can't really guess what might need to go into that header years down the road. And since the code-base has an expected lifetime of about 10 years. So I can't follow the code for-ever.

Hopefully this makes my situation clear.

So does anyone know of a compile-time test that can determine endianness, without relying on vendor specific defines?

[A]
Hmm, that's an interesting Question. My bet is that this is not possible. I think you have to continue using macros, and go with
```
BOOST_STATIC_ASSERT(!BIG_ENDIAN);
```
, or
```
static_assert
```
in c++0x. The reason i think this is because the endian'nes is a property if your execution environment. However, static_assert is considered at compile time.
I suggest you look into the code of the new
GNU gold
ELF linker. Ian Lance Taylor, its author, used templates to select the right endianness at compile time, to ensure optimal performance at run time. He explicitely instantiates all possible endians, so that he still has separate compilation (not all templates in headers) of the template definition and declaration. His code is excellent.


q: Does anyone know a good C++ class to read (and possibly also write) INI files on Windows Mobile? Ideally this class sould work on Windows mobile 2003, 5 and 6 and be public domain but other alternatives may be interesting.

[A]
See this question
How to read config file entries from an INI file
, and this followup
Help improve this INI parsing code
, in which I figured out how to do the parsing myself. I can't say what I came up with is the be-all and end-all but it could be a good start.
Also, this article was mentioned
Cross-platform INI configuration files
.


q: If I use inline functions, does the memory usage increase?

[A] Depends on the function. Simple one-liners could have a memory reduction since no callstack needs to be setup and cleaned and no function call is made. If the function is larger than this overhead needed to call a function, then it will of course bloat the code.


q:
The library should;

Be easy to use and few lines of client code should accomplish much

Be as platform independent as possible. (In case of future ports to other platforms)

Have C++ bindings.

Be mature and stable

I would also like to be notified of most HID events through callbacks.

I have considered the following alternatives:

libhid - (Unfortunately?) this is GPL and cannot be used in my application.

WDK - Seems to be a bit low-level for my use. I don’t need that kind of control.

atusbhid - This has an appropriate level of abstraction, but it is firmly tied to the Windows messaging loop

Are there other alternatives to offer?

[A]
If libhid works for you, then perhaps the thing to do would be to write an application (which you would GPL), which uses libhid to talk to devices, then provides whatever you need via a TCP connection. Your real application would connect via TCP to do what it needs. This would obviously be a massive performance hit.
This application would effectively be a 'shim' between libhid and your application. In this case, the shim would exist for legal, not technical, reasons.
I'm not saying it's a good idea, just that it's an idea.


q:
In a html page we use the head tag to add reference to our external .js files .. we can also include script tags in the body .. But how do we include our external .js file in a web user control?

After little googling I got this. It works but is this the only way?

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "MyUniquekey", @"<script src=""myJsFile.js"" type=""text/javascript""></script>", false);

-- Zuhaib

[A]
You can also use
```
```
Page.ClientScript.RegisterClientScriptInclude("key", "path/to/script.js");
```
```
That's the way I always do it anyway


q:
I have input consisting of a list of nested lists like this:

l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]

I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this:

[39, 6, 13, 50]

Then I want to sort based on these. So the output should be:

[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]

What's a nice pythonic way of doing this?

[A]
```
```
l.sort(key=sum_nested)
```
```
Where
```
sum_nested()
```
is:
```
```
def sum_nested(astruct):
    try: return sum(map(sum_nested, astruct))
    except TypeError:
        return astruct

assert sum_nested([[([8, 9], 10), 11], 12]) == 50
```
```


q: What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by '(1 2 3 4 5). Python's lists, [1, 2, 3, 4, 5], and tuples, (1, 2, 3, 4, 5), are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!

[A]
Immutable lists are best represented through two-tuples, with None representing NIL. To allow simple formulation of such lists, you can use this function:
```
```
def mklist(*args):
    result = None
    for element in reversed(args):
        result = (element, result)
    return result
```
```
To work with such lists, I'd rather provide the whole collection of LISP functions (i.e. first, second, nth, etc), than introducing methods.


q:
I have created a site, which parses XML files and display its content on the appropriate page. Is my site a dynamic web page or static web page?

How do dynamic and static web pages differ?

I feel it's dynamic, because I parse the content from xml files; initially i don't have any content in my main page..

What do you think about this, please explain it..

[A]
Static web pages would be plain HTML content that are delivered. If you are processing any type of XML files at the server side and generating content accordingly, this is a dynamic page. Static pages change content when the page is actually edited & modified.
First result on Google if you had searched for it explains it.
http://websiteowner.info/articles/pages/pagetypes.asp
Also, stating that static websites are not updated regularly is not correct. The web and HTML was around even before we started writing stuff in Perl & PHP. There are/were sites that had heavy traffic and were being modified manually.


q:
The situation is, I have a website where the users get a sub domain. eg: client.mydomain.com. If the client fails to meet certain condition (eg. payment default), I want the above site to be pointing to a different web site. The way we want to do it is by creating a dns record with the appropriate redirection.

I use a win 2003 server, and program in .Net. any inputs on how I can programmatically do this?

I do control the website, however the reason is there are a lot of users (and hence sub domains) and also there is no physical website for (client.mydomain.come), it's like a wordpress/blogger where a user has blog.wordpress.com (and I assume they don't create a new website for each user).

[A]
Well, using .Net and a windows 2003 server, you can do this using WMI scripting.
You can find more information on the
DNS WMI classes here
HOWEVER
I strongly recommend that you do not use a Windows server for a public DNS server - for security and performance reasons you are much better off using a linux server running BIND.  In addition, using BIND-dlz (a add on for BIND), you can make BIND use almost any SQL database as a datasource for your DNS records.  As of BIND 9.4, BIND-dlz is included in the core BIND distribution.  More information can be found at
http://bind-dlz.sourceforge.net


q: A complicated-sounding term with no good explanations from a simple google search... are there any more academically-oriented folk who could explain this one?

[A]
Okay, just going to hazard a COMPLETE guess here, based on this
http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4276578
I'd say it's a mathematical representation of parametric polymorphism (generics).


q:
If the framework is persistence agnostic, can my unit tests construct a file system version of the persistance store underneath my entity model?

I'll be using the model first features of entity framework in the GUI for sure because it's too easy for my devs to make schema changes and keep DAL layer in sync.

Has anyone tried using the model first approach and adding persistence ignorance?

I think this would be my ideal modelling world. I use LINQ2SQL atm and it's a bit tricky to swap out the data store yet have an automatically rich data tier that doesn't hide behind a set of business line IDataContext interfaces.

If I can see some scenarios of this working, I'd like to invest more time in the future to try this out.

[A]
Entity Framework does
not
have true persistence ignorance. That is one of the biggest criticisms (i.e. a forced base class, lots of EF ties, etc). LINQ-to-SQL
can
have persistence ignorance, but in reality people tend to use the lazy loading and attributed approach, which means that it still doesn't have persistence ignoance.
Re being persistence
agnostic
- it (EF) would still need a provider. Sure, if you want to write an EF provider that talks to the file system, go ahead! It would be a
lot
of work though. It would be easier to use a SQL Express database (flat file) etc.


q:
While working on a .Net application (let's say an Asp.Net one), are there any differences in the way you would do things while working on the 64 bit platform, as compared to working on a 32 bit platform.

I would imagine very little since you are working on the framework, and the framework is taking care of most things for you, right?

But, please give your comments.

Thanks.

[A]
There are two cases where considering 64-bit-ness might be interesting:
you need to consider containers that have more than 2^31 elements. The standard array .Length property returns Int32, and is thus not capable of representing large arrays - which you can't create in a 32-bit VM anyway. In a 64-bit VM, you should use LongLength instead (unless you know that you have less than 2^31 elements). Unfortunately, many standard collection classes don't seem to support large numbers of elements at all.
you can use the long type with fewer concerns about performance: in the 64-bit version, a long fits into a register, whereas in the 32-bit version, the JIT code will need multiple machine instructions for a single long operation.


q:
This seems like it should be easy but I'm stumped. In WPF, I'd like a TextBox that stretches to the width of it's parent, but only to a maximum width. The problem is that I want it to be left justified within its parent. To get it to stretch you have to use HorizontalAlignment="Stretch", but then the result is centered. I've experimented with HorizontalContentAlignment, but it doesn't seem to do anything.

How do I get this blue text box to grow with the size of the window, have a maximum width of 200 pixels, and be left justified?

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <StackPanel>
    <TextBox Background="Azure" Text="Hello" HorizontalAlignment="Stretch" MaxWidth="200" />
  </StackPanel>
</Page>

What's the trick?

[A]
```
```
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" MaxWidth="200"/>
    </Grid.ColumnDefinitions>

    <TextBox Background="Azure" Text="Hello" />
</Grid>
```
```


q:
How to convert Unicode string into a utf-8 or utf-16 string?
My VS2005 project is using Unicode char set, while sqlite in cpp provide

int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);
int sqlite3_open16(
  const void *filename,   /* Database filename (UTF-16) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

for opening a folder.
How can I convert string, CString, or wstring into UTF-8 or UTF-16 charset?

Thanks very much!

[A]
Use the
WideCharToMultiByte
function. Specify
```
CP_UTF8
```
for the
```
CodePage
```
parameter.
```
```
CHAR buf[256]; // or whatever
WideCharToMultiByte(
  CP_UTF8,
  0,
  StringToConvert, // the string you have
  -1, // length of the string - set -1 to indicate it is null terminated
  buf, // output
  __countof(buf), // size of the buffer in bytes - if you leave it zero the return value is the length required for the output buffer
  NULL,
  NULL
);
```
```
Also, the default encoding for unicode apps in windows is UTF-16LE, so you might not need to perform any translation and just use the second version
```
sqlite3_open16
```
.


q:
I am developing a .NET CF 3.5 network game. My issue is the app loads all the resources at first instance. However upon subsequent launches, the app gives me memory out of exception while loading resources especially sounds or big images.

Please guide me

[A] How much memory is your application taking after loading all the resources ? On default settings I have been getting this error coming over cca 1.3 GB of private bytes (checking the task manager and the processes memory allocation).


q:
In my webpage, I want the website to greet the user, but the username is surrounded by 'single quotations'. Since this isn't to prevent MySQL injection, i just want to remove quotes around my name on the display page.

Ex: Welcome 'user'!
I'm trying to find the way where i can strip the quotations around the user and have it display on the example below.

Ex: Welcome user!

The only line of code that I can think relating is this:

$login = $_SESSION['login'];

Does anyone know how to strip single lines quotes?

[A]
I think the easiest way would be to use the trim() function. It usually trims whitespace characters, but you may pass it a string containing characters you want to be removed:
```
```
echo 'Welcome ' . trim($login, "'");
```
```
See
http://php.net/trim


q:
Spring IoC container gives you an option of replacing a method of a bean. Can someone provide a real life example of using this feature to solve real life problem?

I can see this used for adapting an old legacy code (w/o sources) to work with your app. But I think I would consider writing an adapter class using the legacy code directly instead of Spring method replacement approach.

[A]
Using spring IoC now I can change my Lucene Analyzers to whatever I want just changing a configuration file.
```
```
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
                <property name="locations">
                        <list>
                                <value>file.properties</value>
                        </list>
                </property>
</bean>

<bean id="DocumentAnalyzer" class="${lucene.document_analyzer}">
</bean>

<bean id="QueryAnalyzer" class="${lucene.query_analyzer}">
</bean>

<bean id="IndexSearcher" class="org.apache.lucene.search.IndexSearcher" scope="prototype">
  <constructor-arg>
    <value>${lucene.repository_path}</value>
  </constructor-arg>

</bean>
```
```
and then in the code:
```
```
Analyzer analyzer  = (Analyzer) BeanLoader.getFactory().getBean("DocumentAnalyzer");
```
```


q: I read a little of the help for my advanced installer 6.5.1 and couldn't find a way to change the version string except by hand.

[A]
The files for creating an MSI are usually in XML format, we've created a little tool that runs as part of our build process that goes and changes the build number manually, try openning the advanced installer file in notepad and look for the "ProductVersion" string.
Cheers,
Rob.


q:
I have a COM dll written in vb6. When I try to create a new object of a class module from this dll I get a Run timer error 430: Class does not support automation or does not support expected interface. The interesting thing is that this happens only from outside the IDE, when I am debugging from within the IDE there is no error thrown and the new object of the class is created successfully. What can be the cause?

In general I occasionally get these kind of errors in COM dlls. What is the best way to debug COM issues? How can I know the path of the dll that is being used when a program is running?

[A]
This is almost certainly a versioning problem, sometimes known as "DLL hell".
The background is that the .NET world is explicitly designed to let interfaces evolve while keeping the same name. But in the COM world, interfaces are considered to be immutable.
When you're working within the IDE, Visual Studio is creating a new COM Interop wrapper for the COM dll every time you run your solution. But unless you release and replace your entire solution every time, including a brand-new COM Interop wrapper, you're going to run into a versioning issue, where the .NET code is expecting one COM interface but seeing a different one.
EDIT
: For some reason, I assumed that you're trying to use the COM component from a .NET component. If the entire solution is actually VB6, then Mr Conley's solution is the recommended approach.
Here's a good link
that discusses the problem.


q:
function main()
{
   Hello();
}

function Hello()
{
  // How do you find out the caller function is 'main'?
}

Is there a way to find out the call stack?

[A]
Note that this solution is deprecated and should no longer be used according to MDN documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
```
```
function Hello()
{
    alert("caller is " + Hello.caller);
}
```
```
Note that this feature is
non-standard
, from
```
Function.caller
```
:
Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The following is the old answer from 2008, which is no longer supported in modern Javascript:
```
```
function Hello()
{
    alert("caller is " + arguments.callee.caller.toString());
}
```
```


q:
I have problems with bringing a windows mobile 6 form to the front.
I tried things like this already

Form1 testForm = new Form1();
testForm.Show();
testForm.BringToFront();
testForm.Focus();

But it's always behind the form that includes that code.
The only things that have worked for me are

testForm.TopMost = true;

or Hide(); the old form and then show the new one, but i want to avoid hiding the other form. TopMost isn't very clean anyway with using multiple other forms.

The other thing that works is

testForm.ShowDialog();

but I don't want to show the form modal.

To cut it short. I just want to show the new form in front of another form, and if I close it, I want to see the old form again.

Maybe someone can help me with this problem. Thank you.

[A]
I haven't tried it in WM6, but you can use some pinvoke to call Win32 functions:
```
```
[DllImport("coredll.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("coredll.dll", EntryPoint="SetForegroundWindow")]
private static extern int SetForegroundWindow(IntPtr hWnd);
```
```
Call FindWindow to get the handle and then call SetForegroundWindow. Other functions you may found useful:
ShowWindow, BringWindowToTop, SetWindowPos


q:
Closed as exact duplicate of "How can I find the method that called the current method?"

Is this possible with c#?

void main()
{
   Hello();
}

void Hello()
{
  // how do you find out the caller is function 'main'?
}

[A]
```
```
Console.WriteLine(new StackFrame(1).GetMethod().Name);
```
```
However, this is not robust, especially as optimisations (such as JIT inlining) can monkey with the perceived stack frames.


q: I have one autocomplete search, in which by typing few characters it will show all the names, which matches the entered character. I am populating this data in the jsp using DIV tag, by using mouse I'm able to select the names. But I want to select the names in the DIV tag to be selected using the keyboard up and down arrow. Can anyone please help me out from this.

[A]
I assume that you have an input which handles the input.
map onkeyup-eventhandler for that input in which you read out event.keyCode, and do stuff when it's the appropriate keycodes for up/down-arrow (38, 40), to keep a reference to which node (item in your div) you move the focus to.
Then call the same handler when you hit enter (keyCode 13) as you do onclick.
It's hard to give a coding-example because it highly depend on context, but a tip on how to navigate through your div is to make us of .nextSibling and .previousSibling, aswell as .firstChild and .childNodes.


q:
I want to use input from a user as a regex pattern for a search over some text.  It works, but how I can handle cases where user puts characters that have meaning in regex?

For example, the user wants to search for Word (s): regex engine will take the (s) as a group.  I want it to treat it like a string "(s)" .  I can run replace on user input and replace the ( with \( and the ) with \) but the problem is I will need to do replace for every possible regex symbol.

Do you know some better way ?

[A]
Use the
```
re.escape()
```
function for this:
4.2.3
```
re
```
Module Contents
escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.
```
```
def simplistic_plural(word, text):
    word_or_plural = re.escape(word) + 's?'
    return re.match(word_or_plural, text)
```
```


q:
I'm looking to convert the following mod_rewrite rule to the Nginx equivalent:

RewriteRule ^foo/(.*)$ /bar/index.php?title=$1 [PT,L,QSA]
RewriteRule ^foo/*$ /bar/index.php [L,QSA]

So far I have:

rewrite ^foo/(.*)$ /bar/index.php?title=$1&$query_string last;
rewrite ^foo/?$ /bar/index.php?$query_string break;

The problem is (I think!) that the query string doesn't get appended. I haven't found a way to port the QSA argument to Nginx.

[A]
These rewrite rules made the scripts work:
```
```
rewrite ^/foo/([^?]*)(?:\?(.*))? /bar/index.php?title=$1&$2;
rewrite ^/foo /bar/index.php;
```
```


q: Hi I want to create form on my site, which is run using Micrsoft Sharepoint.

[A]
there are multiple ways to create/use forms in SharePoint. You can do this by
implementing a web part
designing/implementing an aspx page
using InfoPath
To decide which option is the right one for you depends on the problem you want so solve or the goal you want do archive. Perhaps some more details would be helpful.


q:
I have a group by clause in a sql statement and need to use an aggregate function to minus all the values in each group instead of adding like the Sum() function.

i.e.

SELECT Sum(A)
FROM (
  SELECT 2 AS A
  UNION
  SELECT 1) AS t1

..so will evaluate 2+1 and return 3.

I need some way of doing 2-1 to return 1.

Hope this makes sense.  Only way I can think of doing this would be to use CLR integration to make my own aggregate function.

Any other ideas?

[A]
How will you identify the item to be subtracted from?
Once that's been identified it's a
```
SUM()
```
multiplied by
```
-1
```
and then added to that value.
Edit:
If it's the first value to be taken as the subtracted from then take that value, double it, then take away the sum of all the values. (Doubling it cancels out the effect of including it in the sum of all the values.)
```
```
select top 1 @var = [value]
from myTable
order by [some condition]

select @minused = (2 * @var)  - sum([value])
from myTable
```
```


q:
I need to implement a queue using table.
The business requirement is to have a single queue which will be accessed by 5-10 boxes to get the next job/jobs. There will not be more than 5000 jobs per day. Also, a batch of jobs should be "dequeued" at one time.

Just wondering what are the problem areas and issues I might run into as I havent done it before. If anyone has faced this/done this before, can you please point me to a design/sample implementation or issues that need to be taken care of.

Thanks

[A]
There are a lot of general purpose queuing or messaging services. Even if you want to implement your own system, you could try to have a look at a few others. The first thing that come to mind is JMS (
Java Message Service
) with implementations like
Apache ActiveMQ
,
OpenJMS
or
JBoss Messaging
. Then you have a lot of non-opensource offering as well.
Second thing that comes to mind is
Amazon Simple Queue Service
. There is a couple of products that implement the same kind of interface, like
django-queue-service
.
Good luck !


q:
As far as I understand, if I want to get my database under source control then I need to be checking in change scripts for each change and then running them from some revision to get the correct DB.

I am trying to make a batch file that will be checked in too, that allows other developers on the team to re-build the DB locally without too much trouble. I believe sqlcmd is the way to achieve this. I have it setup to enumerate all files in the dir of .sql files and run sqlcmd for each.

My question is who has done this before and do you have an advice on the best way to achieve this? Is the way I intend to do this the best way or is there a better way?

Hope that's not too vague.

Thanks in advance,

Martin.

[A]
One thing to be aware of is that you need to create objects in the order of dependency. So you cannot simply iterate files.
We ended up having a batch file that would list all the objects in order of dependency
Actually we had 2 batch files one called say createDBObject.bat:
```
```
:: Parameters Required:
:: %1 UserID
:: %2 Password
:: %3 Server
:: %4 Database
:: %5 file with scripted object
::
echo. >> CreateDBObjectsLog.txt
echo  %5 >> CreateDBObjectsLog.txt
osql -U%1 -P%2 -S%3 -i%5 -d%4 -n >> CreateDBObjectsLog.txt
echo * %5
```
```
and then the other with the list of all the db objects:
```
```
:: Parameters Required:
:: %1 UserID
:: %2 Password
:: %3 Server
:: %4 Database
::
echo object  in %4 database on %3 server
echo Please Wait ...

if exist CreateDBObjectsLog.txt del CreateDBObjectsLog.txt

call createDBObject.bat %1, %2, %3, %4, ScriptedTable1
call createDBObject.bat %1, %2, %3, %4, ScriptedTable2
...
call createDBObject.bat %1, %2, %3, %4, ScriptedTableN

call createDBObject.bat %1, %2, %3, %4, ScriptedView1

call createDBObject.bat %1, %2, %3, %4, ScriptedSP1

etc
```
```
Now we use
SQL Compare Pro
that automates all those tasks
You can also check related question:
Is there a “poor man’s” alternative to RedGate for scripting out entire database schema?


q:
I try get the mp3 flash player to work with my javascript on all browsers. All went well for first, but fast realized that my code doesn't work on MSIE.

After trying to find out  I found this in the reference code:

<!--[if IE]>
<script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
eval(args);
</script>
<![endif]-->

How to turn this into a javascript or jquery clause that I could stuff it where it belongs to (in audio.js)?

[A]
That syntax, with the <script> tag with the "event" and "for" attributes is an Internet Explorer-only way of setting up an event handler on an DOM object.  Here, it adds a FSCommand event handler to the myFlash object.  This is needed because code running inside the Flash object may want to run JavaScript in the browser.  To do this, the Flash object will invoke the FSCommand event handler, passing the JavaScript to run as the arguments to the event.
With this player, the name of a JS listener object is passed in the FlashVars param to the player.  It then uses FSCommands from ActionScript to modify that listener object, with an occasional call to a method on that listener when it's other properties have been modified.  I suppose that IE isn't able to run the JS code using this method until the FSCommand handler has been added to the Flash player object, which is why that code exists.  Modify it to use the ID of your Flash object and you should be in good shape.


q:
This is probably easy but I am getting stuck: when I build a solution in Visual Studio - how do extract the exact cmd line for the current build command in order to be able to do the same build from VisualStudio console?

In the output window I can see the single projects in the solution build commands but not the one for the whole solution.

I am on VS2005.

Any help would be appreciated

[A]
You can start msbuild from the command line. msbuild understands .sln (solution) files. You can specify the .sln file and the build configuration (debug, release etc.) from the command line.
http://msdn.microsoft.com/en-us/library/ms164311.aspx
Here is the documentation on what you can do with msbuild. MSBuild.exe is installed with the .net framework, not with visual studio. You can find it in c:\windows\microsoft.net\framework\v3.5 (or v2.0.50727)
I searched a bit and found that you can also do a command line build with visual studio using devenv.exe /build, more info here:
http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx


q:
Has anybody got any real world stories build mobile web sites with NetBiscuits?

Someone told me it was the next big thing in mobile development (http://www.netbiscuits.com/home) and it looks pretty good from their site. Just wondered if anybody (besides them) has actually used it.


q: Is there any clever method out there to make my executeEveryDayMethod() execute once a day, without having to involve the Windows TaskScheduler?

[A]
If the time when it is run is not relevant and can be reset each time the program starts you can just set a timer, which is the easiest thing to do. If that's not acceptable it starts getting more complex, like the solution presented
here
and which still doesn't solve the persistence problem, you need to tackle that separately if you truly wish to do what Scheduled Tasks would. I'd really consider again if it's worth going through all the trouble to replicate a perfectly good existing functionality.
Here's a
related question
(Example taken from there).
```
```
using System;
using System.Timers;

public class Timer1
{
    private static Timer aTimer = new System.Timers.Timer(24*60*60*1000);

    public static void Main()
    {
        aTimer.Elapsed += new ElapsedEventHandler(ExecuteEveryDayMethod);
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();
    }

    // Specify what you want to happen when the Elapsed event is
    // raised.
    private static void ExecuteEveryDayMethod(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}
```
```


q:
I am confused about how popen() redirects stdin, stdout and stderr of the child process in unix. The man page on popen() is not very clear in this regard. The call

FILE *p = popen("/usr/bin/foo", "w");

forks a child process and executes a shell with arguments "-c", "/usr/bin/foo", and redirects stdin of this shell (which is redirected stdin of foo), stdout to p. But what happens with stderr? What is the general principle behind it?

I noticed that, if I open a file in foo (using fopen, socket, accept etc.), and the parent process has no stdout, it gets assigned the next available file number, which is 1 and so on. This delivers unexpected results from calls like fprintf(stderr, ...).

It can be avoided by writing

FILE *p = popen("/usr/bin/foo 2>/dev/null", "w");

in the parent program, but are their better ways?

[A]
The  return  value from popen() is a normal standard I/O stream in all
  respects save that it must be closed with pclose() rather than
  fclose(3).  Writing to such a stream writes to the standard input of
  the command; the command's standard output is the same as  that of the
  process that called popen(), unless this is altered by the command
  itself.  Conversely, reading from a "popened" stream reads the
  command's standard output, and the command's standard input is the
  same as that  of  the  process  that  called popen().
From its manpage, so it allows you to read the commands standard output or write into its standard input. It doesn't say anything about stderr. Thus that is not redirected.
If you provide "w", you will send your stuff to the stdin of the shell that is executed. Thus, doing
```
```
FILE * file = popen("/bin/cat", "w");
fwrite("hello", 5, file);
pclose(file);
```
```
Will make the shell execute /bin/cat, and pass it the string
```
"hello"
```
as its standard input stream. If you want to redirect, for example stderr to the file
```
"foo"
```
do this first, before you execute the code above:
```
```
FILE * error_file = fopen("foo", "w+");
if(error_file) {
    dup2(fileno(error_file), 2);
    fclose(error_file);
}
```
```
It will open the file, and duplicate its file-descriptor to 2, closing the original file descriptor afterwards.
Now, if you have your stdout closed in your parent, then if the child calls
```
open
```
it will get 1, since that's (if stdin is already opened) the next free file-descriptor. Only solution i see is to just use dup2 and duplicate something into that in the parent, like the above code. Note that if the child opens
```
stdout
```
, it will
not
make
```
stdout
```
open in the parent too. It stays closed there.


q:
I have a user that keeps getting this error.  Is there a tool that does window handle counting that i can use to figure out why he keeps getting this error.

System.ComponentModel.Win32Exception: Error creating window handle.
   at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
   at System.Windows.Forms.Control.CreateHandle()
   at System.Windows.Forms.Form.CreateHandle()
   at System.Windows.Forms.Control.get_Handle()
   at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)

[A]
Maybe this could help:
Unhandled exception Win32Exception,Error creating window handle
CLR Debugger (DbgCLR.exe)
on mine machine debugger is located at:
```
"c:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\GuiDebug\DbgCLR.exe"
```


q:
I have got some code to load an assembly and get all types, which implement a certain interface, like this (assume asm is a valid and loaded assembly).

var results = from type in asm.GetTypes()
  where typeof(IServiceJob).IsAssignableFrom(type)
  select type;

Now I'm stuck: I need to create instances of these objects and invoke methods and properties on the object. And I need to store the references to the created objects in an array for later usage.

[A]
Oh wow - I only
blogged about this
a few days ago. Here's my method to return instances of all the types that implement a given interface:
```
```
private static IEnumerable<T> InstancesOf<T>() where T : class
{
    var type = typeof(T);
    return from t in type.Assembly.GetExportedTypes()
           where t.IsClass
               && type.IsAssignableFrom(t)
               && t.GetConstructor(new Type[0]) != null
           select (T)Activator.CreateInstance(t);
}
```
```
If you refactor this to accept an assembly parameter rather than using the interface's assembly, it becomes flexible enough to suit your need.


q:
How do I pass a value from a child back to the parent form? I have a string that I would like to pass back to the parent.

I launched the child using:

FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();

[A]
Create a property (or method) on
```
FormOptions
```
, say
```
GetMyResult
```
:
```
```
using (FormOptions formOptions = new FormOptions())
{
    formOptions.ShowDialog();

    string result = formOptions.GetMyResult;

    // do what ever with result...
}
```
```


q:
I'm writing an image processing program to perform real time processing of video frames. It's in C# using the Emgu.CV library (C#) that wraps the OpenCV library dll (unmanaged C++). Now I have to write my own special algorithm and it needs to be as fast as possible.

Which will be a faster implementation of the algorithm?

Writing an 'unsafe' function in C#

Adding the function to the OpenCV library and calling it through Emgu.CV

I'm guessing C# unsafe is slower because it goes throught the JIT compiler, but would the difference be significant?

Edit:

Compiled for .NET 3.5 under VS2008

[A]
It depends on the algorithm, the implementation, the C++ compiler and the JIT compiler. I guess in most cases the C++ implementation will be faster. But this may change.
The JIT compiler can optimize your code for the platform your code is running on instead of an average for all the platforms your code might run on as the C++ compiler does. This is something newer versions of the JIT compiler are increasingly good at and may in some cases give JITted code an advantage. So the answer is not as clear as you might expect. The new Java hotspot compiler does this very well for example.
Other situations where managed code may do better than C++ is where you need to allocate and deallocate lots of small objects. The .net runtime preallocates large chunks of memory that can be reused so it doesn't need to call into the os every time you need to allocate memory.
I'm not sure unsafe C# runs much faster than normal C#. You'll have to try this too.
If you want to know what's the best solution for your situation you'll have to try both and measure the difference. I dont think there will be more than


q:
Ignoring the IE case, are there any other browsers that can't understand the application/xhtml+xml content type? And what about the search engine spiders?

I could not find any answers on the web that would not be a few years old and thus possibly inaccurate.

Edit:
Somehow related question: What problem does XHTML strict solve?

[A]
If you ignore 80% of the market (yes, IE) then XHTML is very well supported, and search engines have no problem with it whatsoever (after all, XHTML is a lot simpler to process).
Overall, XHTML support isn't really a problem. IE doesn't support it, but as long as it's served as a contenttype it does understand, will render it okay anyway, and everyone else support it properly.
Do you have more specific use cases in mind?


q:
How can I check if a string ends with a particular character in JavaScript?

Example: I have a string

var str = "mystring#";

I want to know if that string is ending with #. How can I check it?

Is there a endsWith() method in JavaScript?

One solution I have is take the length of the string and get the last character and check it.

Is this the best way or there is any other way?

[A]
Unfortunately not.
```
if( "mystring#".substr(-1) === "#" ) {}
```


q: What's the story behind our massive repitition of ./foo and cd ... Where do these two . and .. come from? Where could they be seen as a way of navigating a file system tree for the first time?

[A]
I'm sorry I can't answer properly, but I can recommend these links:
The Evolution of the Unix Time-sharing System
and
A Brief history of the BSD Fast File System
for some interesting historical notes on early file systems and their use.
Other than that, the earliest reference I've found is the 1974 paper "
The UNIX Time-Sharing System
" by Dennis Ritchie and Ken Thompson. The precursor of UNIX, Multics, also had hierarchical file systems and the notion of relative paths, but according to "
Introduction to MULTICS
" it used another notation for that.


q:
I'm currently running into some issues resizing images using GD.

Everything works fine until i want to resize an animated gif, which delivers the first frame on a black background.

I've tried using getimagesize but that only gives me dimensions and nothing to distinguish between just any gif and an animated one.

Actual resizing is not required for animated gifs, just being able to skip them would be enough for our purposes.

Any clues?

PS. I don't have access to imagemagick.

Kind regards,

Kris

[A]
There is a brief snippet of code in the PHP manual page of the
```
imagecreatefromgif()
```
function that should be what you need:
```
imagecreatefromgif
```
comment #59787 by ZeBadger


q:
I have let's say two pc's.PC-a and PC-b which both have the same application installed with java db support.I want from time to time to copy the data from the database on PC-a to database to PC-b and vice-versa so the two PC's to have the same data all the time.
Is there an already implemented API in the database layer for this(i.e 1.export-backup database from PC-a 2.import-merge databases to PC-b) or i have to do this in the sql layer(manually)?

[A]
I guess you are using
Java DB (aka Derby)
- in which case, assuming you just can't use a single instance, you can do a
backup/restore
.


q:
I've been thinking of ways of providing syntactic sugar for a framework I have been working on. I want to deal with Immitable objects exclusively.

Say I have an immutable object and wish to create a modified version of it. Would, in your view, a non-instantiable class with a single static factory method break OO principles ?

As an example using a String:

public final class LOWERCASE {

    private LOWERCASE() {}

    public static String string( final String STRING ) {

      return STRING.toLowerCase();
    }
}

Therefore from this example I could write:

String lowercaseString = LOWERCASE.string( targetString );

Which I find very readable.

Any provisos against such an approach?

[A]
Usually on immutable objects, I would have a method returning a modified version of the object. So if you have some immutable collection, it can have a sort() method, that returns a new collection that is sorted. However, in your String example this is not possible, since you cannot touch the String class.
Your approach is quite readable, and I think for edge cases like this, is perfectly fine. For immutable objects you write yourself, I'd have the method on the object itself.
Eric Lippert's series on immutable objects in C#
is quite good, by the way.


q:
Does the "for…in" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn't do it in order?

The object I wish to use will be declared once and will never be modified.

Suppose I have:

var myObject = { A: "Hello", B: "World" };

And I further use them in:

for (var item in myObject) alert(item + " : " + myObject[item]);

Can I expect 'A : "Hello"' to always come before 'B : "World"' in most decent browsers?

[A]
The elements of an object that for/in enumerates are the properties that don't have the DontEnum flag set. The ECMAScript, aka Javascript, standard explicitly says that "An Object is an unordered collection of properties" (see
http://www.mozilla.org/js/language/E262-3.pdf
section 8.6).
It's not going to be standards conformant (i.e. safe) to assume all Javascript implementations will enumerate in declaration order.


q:
I have a T4 template that generates classes from an xml file.

How can I add a dependency between the xml file and the template file so that when the xml file is modified the template is rerun automatically without choosing "Run custom tool" from the context menu?

[A]
How long does the tool take to execute? One lazy option might be to simply edit the csproj such that it
always
runs the tool during build (presumably via
```
<Exec ... />
```
or a custom
```
targets
```
file) - of course, this depends on it being quick to execute.
Another way would be to write a shim that works as the "Custom Tool" in VS, and simply calls the existing exe (or whatever) with the right args. Not trivial, but doable (
see here
) - I believe this then supposedly plays fairly nicely with change detection. It is actually on my list of things to do for a current project, so I'll find out soon enough...