q:
I'm using a preformatted text file as a template for emails. The file has line breaks where I want them. I'd like to use this template to send a plain text email, but when I do I'm losing all formatting. Line breaks are stripped.

How do I parse this file and retain line breaks? I don't want to use a <pre> tag because I want to send plain text emails.

I'm using the classic ASP ReadAll method to pull the template into a string:

            Dim TextStream
        Set TextStream = FSO.OpenTextFile(Filepath, ForReading, False, TristateUseDefault)

        ' Read file in one hit
        Dim Contents
        GetTemplate = TextStream.ReadAll ' return file contents

What am I missing?

[A]
this is what I have done...
I take a text, or HTML file, ( I'll show text, since its smaller, but the exact same code applies ), and I put well know values into the text file that I can later replace.
-- Begin Text File
```
```
We've generated a new password for you at your request, you can use this new password with your username to log in to various sections of our site.

Username: ##UserName##
Temporary Password: ##Password##

To use this temporary password, please copy and paste it into the password box.

Please keep this email for your records.
```
```
-- End Text File
Then its a simple matter of creating a list of key/value pairs, with the text to be replaced, and the value your replacing it with. Load the file into memory as a string, and loop through your key/value pair replacing your text values.
```
```
ListDictionary dictionary = new ListDictionary
                                            {
                                                {"##UserName##", user.BaseUser.UserName},
                                                {"##Password##", newPassword}
                                            };

            string fromResources = GetFromResources("forgotpasswordEmail.html");
            string textfromResources = GetFromResources("forgotpasswordEmail.txt");
            foreach (DictionaryEntry entry in dictionary)
            {
                fromResources = fromResources.Replace(entry.Key.ToString(), entry.Value.ToString());
                textfromResources = textfromResources.Replace(entry.Key.ToString(), entry.Value.ToString());
            }
```
```
Then you can email the text, ( in this case the textfromResources variable ), and it will contain all of the necessary line breaks and formatting.
Like I said, you can do this eact same thing with HTML files, or any type of file you want to.
Although my example is in C#, ( I don't have any classic ASP code handy, sorry ), the concept of finding and replacing values will apply to classic ASP.


q:
This is in the context of Automatic Differentiation - what would such a system do with a function like map, or filter - or even one of the SKI Combinators?

Example: I have the following function:

def func(x):
    return sum(map(lambda a: a**x, range(20)))

What would its derivative be? What will an AD system yield as a result? (This function is well-defined on real-number inputs).

[A]
Higher-order functions are discrete. They don't have the Cartesian quality of having arguments that have well-defined mappings to points in some n-dimensional space.
However, with your clarification on the answer, there are several things that can be said. Symbolically differentiating some higher-order functions would be possible, but only for certain calling patterns that resolve to well-known functions.
Probably,
numerical differentiation
would be more fruitful, as it can estimate the derivative by repeatedly evaluating the given function.
Also, functions that are totally general - and your example is heading that way, with use of relatively arbitrary functions - eventually you'll hit Turing completeness, which will mean that no amount of cleverness on the part of a symbolic differentiator will be able to automatically differentiate the function.

s: huggingface

c: devops

d: intermediate


q:
Is there a preferred way to return multiple values from a C++ function?  For example, imagine a function that divides two integers and returns both the quotient and the remainder.  One way I commonly see is to use reference parameters:

void divide(int dividend, int divisor, int& quotient, int& remainder);

A variation is to return one value and pass the other through a reference parameter:

int divide(int dividend, int divisor, int& remainder);

Another way would be to declare a struct to contain all of the results and return that:

struct divide_result {
    int quotient;
    int remainder;
};

divide_result divide(int dividend, int divisor);

Is one of these ways generally preferred, or are there other suggestions?

Edit: In the real-world code, there may be more than two results.  They may also be of different types.

[A]
Alternatives include arrays,
generators
, and
inversion of control
, but none is appropriate here.
Some (e.g. Microsoft in historical Win32) tend to use reference parameters for simplicity, because it's clear who allocates and how it will look on the stack, reduces the proliferation of structures, and allows a separate return value for success.
"Pure" programmers prefer the struct, assuming it
is
the function value (as is the case here), rather than something that's touched incidentally by the function.  If you had a more complicated procedure, or something with state, you'd probably use references (assuming you have a reason for not using a class).


q:
I have an xml file ('videofaq.xml') that defines a DTD using the following DOCTYPE

<!DOCTYPE video-faq SYSTEM "videofaq.dtd">

I am loading the file from the classpath (from a JAR actually) at Servlet initialization time using:

getClass().getResourceAsStream("videofaq.xml")

The XML is found correctly, but for the DTD in the same package, Xerces gives me a FileNotFoundException, and displays the path to the Tomcat startup script with "videofaq.dtd" appended to the end. What hints, if any, can I pass on to Xerces to make it load the DTD properly?

[A]
When you do
```
```
getClass().getResourceAsStream("videofaq.xml")
```
```
It's not xerces you are calling and as such, when you give the stream to xerces, it can't know where the file is loaded from. It loads it from the application root path (which you have described).
A simple solution would be to specify the whole path in your xml file to the dtd.
Also, xerces seems to try multiple places. So you should have a look at the grammar caching mecanism or the entity resolvers (which are used in that order I think).
Xerces grammar doc:
http://xerces.apache.org/xerces2-j/faq-grammars.html
Xerces features use-entity-resolver2:
http://xerces.apache.org/xerces2-j/features.html


q: How would you run the Selenium process (thread) from a Java process so I don't have to start Selenium by hand?

[A]
The server:
```
```
import org.openqa.selenium.server.SeleniumServer;
public class SeleniumServerControl {
  private static final SeleniumServerControl instance = new SeleniumServerControl();
  public static SeleniumServerControl getInstance() {
    return instance;
  }
  private SeleniumServer server = null;
  protected SeleniumServerControl() {
  }
  public void startSeleniumServer() {
    if (server == null) {
      try {
        server = new SeleniumServer(SeleniumServer.DEFAULT_PORT);
        System.out.println(" selenium server " + server.toString());
      } catch (Exception e) {
        System.err.println("Could not create Selenium Server because of: "
            + e.getMessage());
        e.printStackTrace();
      }
    }
    try {
      server.start();
    } catch (Exception e) {
      System.err.println("Could not start Selenium Server because of: "
          + e.getMessage());
      e.printStackTrace();
    }
  }
  public void stopSeleniumServer() {
    if (server != null) {
      try {
        server.stop();
        server = null;
      } catch (Exception e) {
        System.err.println("Could not stop Selenium Server because of: "
            + e.getMessage());
        e.printStackTrace();
      }
    }
  }
}
```
```
The client:
```
```
browser = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com");
browser.start();
```
```


q: What is the shortcut in eclipse to terminate debugging/running? Looking under Preferences -> Keys says Ctrl + F2 but it doesn't work.

[A]
As said
here
, you can add/enable the Debug command group to any perspective using
```
Window / Customize Perspective > Commands
```
.
(Select the 'Debug' group)
Then open the Debug view in the Java perspective (as a Fast view perhaps)  and you should get your Terminate keybinding.
I suppose it was not working because you tried it in a non-debug session.


q:
I have two simple tables in my database. A "card" table that contains Id, Name, and text of a card, and a "rulings" table which contains the Id of the card, and text detailing the rulings for the card.

Often enough in the ruling text, there is a reference to another card in the database. It is easy enough to find this in the text because each card is encapsulated within quotes in the text. It is not uncommon to have multiple cards referenced within the text of the ruling.

What I'd like to do is be able to create a cross reference table (or procedure if it is efficient enough) so that when I submit a query for a card, I can find all the ruling records that directly reference the card through the Id and get all of the ruling records where the card name is referenced in the text.

What would be the best way to approach this? My environment is SQL 2005, but any kind of "DB agnostic" solutions are greatly accepted here.

[A]
I would recommend that you create another table that stores your references.  Then, create an insert and update trigger that maintains this table.  This way, you would have a faster query to return the data you are looking for.
I recognize that initially populating this table might be a little difficult, which is why I am showing some sample data (and query) below, that you can use to get you started.
```
```
Declare @Card Table(Id Int, Name VarChar(20), CardText VarChar(8000))

Declare @Ruling Table(CardId Int, CardRuling VarChar(8000))

Insert Into @Card Values(1, 'Card 1', 'This is the card ID = 1')
Insert Into @Card Values(2, 'Card 2', 'This is the card id = 2.')
Insert Into @Card Values(3, 'Card 3', 'This is the card id = 3.')

Insert Into @Ruling Values(1, 'This is the ruling for 1 which references "2"')
Insert Into @Ruling Values(2, 'This is the ruling for 2 which references nothing')
Insert Into @Ruling Values(3, 'This is the ruling for 3 which references "1" and "2"')

Declare @CardId Int
Set @CardId = 1

Select  *
From    @Card As Card
        Inner Join @Ruling As Ruling
            On Card.Id = Ruling.CardId
        Left Join @Card As CardReferences
            On Ruling.CardRuling Like '%"' + Convert(VarChar(10), CardReferences.Id) + '"%'
```
```
EDIT:
The reason I suggested another table is because you will likely be disappointed with the performance of this query, especially for large tables.


q: I need to open a password protected shared folder on a network to gain access to an Access 97 database. How do I open the folder and pass in the password?

[A]
one solution would be to map the network folder to an available drive letter. You could accomplish that using Windows OS commands:
```
```
System.Diagnostics.Process.Start("net.exe", "use K: \\Server\URI\path\here /USER:<username> <password>" )
```
```
Simply replace the username and password with the credentials you need and make sure the drive letter is available.
To disconnect you can call
```
```
System.Diagnostics.Process.Start("net.exe", "use /delete K:" )
```
```


q: How do I make the computer's internal speaker beep in C# without external speakers?

[A]
The solution would be,
```
```
Console.Beep
```
```


q:
I have used the smtp class to send emails through code.

Can I use the classes in the .net framework to display emails received on a page without having to use something like exchange sdk?

How would I go about using gmail pop and smtp server information in .net web apps (with the .net classes) to send and receive email?

[A]
Yes, it's possible. You'll probably find it easier to use one of the many third-party components which are available and encapsulate much of the logic you would otherwise need to develop.
I like Chilkat's
email component
. They provide
an online example showing how to use their component to access a Gmail inbox via POP3
.
They also have an
IMAP component
which you might find useful.


q:
I have a function that, among other things, takes in an object and a Type, and converts the object into that Type.  However, the input object is often a double, and the type some variation of int (uint, long, etc.).  I want this to work if a round number is passed in as a double (like 4.0), but to throw an exception if a decimal is passed in (4.3).  Is there any more elegant way to check if the Type is some sort of int?

if (inObject is double && (targetType == typeof (int)
                         || targetType == typeof (uint)
                         || targetType == typeof (long)
                         || targetType == typeof (ulong)
                         || targetType == typeof (short)
                         || targetType == typeof (ushort)))
{
    double input = (double) inObject;
    if (Math.Truncate(input) != input)
        throw new ArgumentException("Input was not an integer.");
}

Thanks.

[A]
This seems to do what you ask.  I have only tested it for doubles, floats and ints.
```
```
public int GetInt(IConvertible x)
    {
        int y = Convert.ToInt32(x);
        if (Convert.ToDouble(x) != Convert.ToDouble(y))
            throw new ArgumentException("Input was not an integer");
        return y;
    }
```
```


q:
For example, never define a macro like this:

#define DANGER 60 + 2

This can potentially be dangerous when we do an operation like this:

int wrong_value = DANGER * 2; // Expecting 124

Instead, define like this because you don't know how the user of the macro may use it:

#define HARMLESS (60 + 2)

The example is trivial, but that pretty much explains my question. Are there any set of guidelines or best practices that you would recommend when writing a macro?

Thanks for your time!

[A]
In the expansion, put parenthesis around the arguments, so that if they pass in a expression you will get the intended behavior.
```
```
#define LESS_THAN(X,Y) (((X) < (Y) ? (X) : (Y))
```
```


q:
I am trying to center a form in VB.net. Instead of centering the form, it ends up about halfway between center and 0,0(upper left).

I am using the code

Me.StartPosition = FormStartPosition.CenterScreen

Which is called from the IntializeDisplay Method, which in turn is called from the Form Load method.

I assume I'm setting some propertity along the way that messes up the center calculation, but I'm not sure what it could be.

If anyone has any ideas they would be much appreciated.

Thanks.

[A]
Do you have any form resizing/positioning logic implemented? If so, comment it out and try again.
Try setting the
```
Form.StartPosition
```
in the designer (which will set it in
```
InitializeComponent()
```
) instead of in the Load event.
Try resetting the
```
Form.Location
```
and
```
Form.Size
```
value. If your form is localized, remove the
```
Form.Location
```
AND
```
Form.Size
```
entry in the resource file.


q:
I'm reading all the files in a single directory and I want to filter on JPG,JPEG,GIF and PNG.

Both capital and small letters. Those are the only files to be accepted.

I am currently using this:

$testPics = takeFiles($picsDir, "([^\s]+(?=\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF))\.\2)");

and the function takeFiles looks like this:

function takerFiles($dir, $rex="") {
    $dir .= "/";
    $files = array();
    $dp = opendir($dir);
    while ($file = readdir($dp)) {
      if ($file == '.')  continue;
      if ($file == '..') continue;
      if (is_dir($file)) continue;
      if ($rex!="" && !preg_match($rex, $file)) continue;
      $files[] = $file;
    }
    closedir($dp);
    return $files;
  }

And it always returns nothing. So something must be wrong with my regex code.

[A]
I think something is wrong with your regex. Try testing regexes here first:
https://www.regexpal.com/
I think this one might work for you:
```
/^.*\.(jpg|jpeg|png|gif)$/i
```
Note the /i at the end - this is the "case insensitive" flag, saves you having to type out all permutations :)


q:
I have the following code:

var address;
getAddress(0,0);
function getAddress(latlng)
{
  if (latlng != null)
  {
    geocoder.getLocations(latlng,
    function(addresses)
    {
      if(addresses.Status.code == 200)
      {
        address = addresses.Placemark[0].address.toString();
        alert(address);  // Outputs something :)
      }
    });
   }
   return address;   //returns nothing :(
}

address always returns undefined but the alert does output something. Why is this?

(Geocoder is an instance of Google Maps APIs)

[A]
I think that your problems are all related to scope. Generally speaking, you don't want to rely on a global declaration of a variable to be used within the scope of a function.
This should correct any scope issues with your function:
```
```
var address = getAddress(0,0);

function getAddress(latlng) {
    if (latlng != null) {
        var address = geocoder.getLocations(latlng, function(addresses) {
            if(addresses.Status.code == 200) {
                return addresses.Placemark[0].address.toString();
            }
        });
    }
return address;
}
```
```


q:
My team works on a project in cvs containing about 20,000 Java files.  Because of the number of files, it takes a while to do a cvs update.  I typically keep about 5 copies of the entire tree checked out, to make it easy to check in different requests without worrying about which files were modified for each.  It's a real pain to keep all 5 trees up to date and in sync with each other.

I've read that it's fairly easy to use git locally with a remote cvs server, and that git is fast.  Will git significantly speed up the updating of my local trees?

I realize the lower bound is the time to do one cvs update.  But I'm thinking that once the first tree is up to date, it might possible to quickly sync the other 4 with the first, rather than to do 4 more cvs update commands.  Do I understand git correctly?

[A]
We do something similar at work.  We basically use the
```
master
```
branch in git as a single, updated CVS version of the code; we don't do any development there, just CVS updates.  Then, all of our development projects happen on feature branches that we rebase.  When we do CVS updates on the
```
master
```
branch we commit those changes to
```
master
```
and then rebase our other development branches against
```
master
```
.
It's not ideal -- it makes sharing branches with other people difficult.  But, we can manage several development projects at once and do branches, merges, and diffs against them easily.  And, we only interact with CVS on the one
```
master
```
branch, as needed.


q: Is there a way to send an email from an iSeries terminal, adding an attachment from the IFS? I know how to send a normal email using the SNDDST utility.

[A]
There is two main methods of doing this.
The Do-It-Yourselfer will use QtmmSendMail API
Otherwise there are several other free and purchased products that you could use. The ones I would recommend are:
MAILTOOL
- Currently $399. Depending on what you are trying to do, I would recommend
SplTool Suite
if you want to email out spool files.
RPGMail
- Free API making use of JavaMail


q:
I am trying to generate some code at runtime using the DynamicMethod class in the Reflection.Emit namespace but for some reason its throwing a "VerificationException". Here is the IL code I am trying to use...

ldarg.1
ldarg.0
ldfld, System.String FirstName
callvirt, Void Write(System.String)
ldarg.1
ldarg.0
ldfld, System.String LastName
callvirt, Void Write(System.String)
ldarg.1
ldarg.0
ldfld, Int32 Age
callvirt, Void Write(Int32)
ret

I need a way to debug the generated IL code. What options do I have? I am using VS2008 professional.

[A]
Try using the
peverify
tool to check the IL. From MSDN:
peverify.exe performs comprehensive
  MSIL verification checks based on
  dataflow analysis plus a list of
  several hundred rules on valid
  metadata. For detailed information on
  the checks Peverify.exe performs, see
  the "Metadata Validation
  Specification" and the "MSIL
  Instruction Set Specification" in the
  Tools Developers Guide folder in the
  .NET Framework SDK.
You'll need to save the generated code to disk as an assembly for this to be useful though.


q:
I am looking for a Visual Studio add-in that would analyze the text around the cursor position and navigate to the corresponding class definition.

For example I have this XML file that is currently open:

<object id="abc" type="MyProject.Foo.Bar, MyProject"/>

If I put the cursor somewhere between the double quotes on the type attribute the add-in should obtain the string "MyProject.Foo.Bar, MyProject" and search for all projects and project references in the current solution for the given type and if it finds one, it should navigate to the class definition (or metadata if the source code is not available in the current solution).

If such add-in doesn't exist I would greatly appreciate some pointers that could help me writing one.

[A]
Well you could use the '
Code Definition Window
' that comes with the VS2008 IDE. When you place your cursor, the Code Def window dynamically updates with the source code for that type.
Works with regular source files.. don't have the IDE at hand to verify with XAML/XML
Also you could 'Jump to Symbol' key combo but you would need CodeRush Express add in for that. Shift+Ctrl+Q. More details
here
.


q: I would like to be able to fusion an IEnumerable<IEnumerable<T>> into IEnumerable<T> (i.e. merge all individual collections into one). The Union operators only applies to two collections. Any idea?

[A]
Try
```
```
var it = GetTheNestedCase();
return it.SelectMany(x => x);
```
```
SelectMany is a LINQ transformation which essentially says "For Each Item in a collection return the elements of a collection".  It will turn one element into many (hence SelectMany).  It's great for breaking down collections of collections into a flat list.


q: I'd like to hide a div when user click anywhere on the page outside of that div. How can I do that using raw javascript or jQuery?

[A]
First idea, in raw javascript (from
this post
):
```
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">

    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">

my div

```
```
Tested with IE6 and FireFox3.1, it does work as advertised.


q:
I have a large legacy C++ project compiled under Visual Studio 2008.  I know there is a reasonably amount of 'dead' code that is not accessed anywhere -- methods that are not called, whole classes that are not used.

I'm looking for a tool that will identify this by static analysis.

This question: Dead code detection in legacy C/C++ project suggests using code coverage tools.  This isn't an option as the test coverage just isn't high enough.

It also mentions a  -Wunreachable-code. option to gcc. I'd like something similar for Visual Studio.  We already use the linker's /OPT:REF option to remove redundant code, but this doesn't report the dead code at a useful level (when used with /VERBOSE there are over 100,000 lines, including a lot from libraries).

Are there any better options that work well with a Visual Studio project?

[A]
You'll want something along the lines of QA-C++ (
http://www.programmingresearch.com/QACPP_MAIN.html
), also see
http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
for similar products.
You're looking for a static code analysis tool that detects unreachable code; many coding guidelines (such as MISRA-C++, if I'm not mistaken) require that no unreachable code exists. An analysis tool geared specifically to enforce such a guideline would be your best bet.
And you'll like be able to find other uses for the tool as well.


q:
I want to add the current month, and the previous two months to a prompt, for a user to select.

e.g. if this month is 2008 Nov, ddlbox should show the following:

112008
102008
092008

How can I do this?

[A]
```
```
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>

for (int i = 0; i < 3; i++)
{
    ListItem item = new ListItem(string.Format("{0: MM/yyyy}", DateTime.Now.AddMonths(-i)));
    DropDownList1.Items.Add(item);
}
```
```
Try this :)


q: My program receives large CSV files and transforms them to XML files. In order to have better performance I would like to split this files in smaller segments of (for example) 500 lines. What are the available Java libraries for splitting text files?

[A]
What do you intend to do with those data ?
If it is just record by record processing then event oriented (SAX or StaX) parsing will be the way to go. For record by record processing, an existing "pipeline" toolkit may be applicable.
You can pre-process your file with a splitter function like
this one
or
this Splitter.java
.


q:
I have a structure which I create a custom constructor to initialize the members to 0's.  I've seen in older compilers that when in release mode, without doing a memset to 0, the values are not initialized.

I now want to use this structure in a union, but get errors because it has a non-trivial constructor.

So, question 1.  Does the default compiler implemented constructor guarantee that all members of a structure will be null initialized?  The non-trivial constructor just does a memset of all the members to '0' to ensure a clean structure.

Question 2:  If a constructor must be specified on the base structure, how can a union be implemented to contain that element and ensure a 0 initialized base element?

[A]
Can you do something like this?
```
```
class Outer
{
public:
    Outer()
    {
        memset(&inner_, 0, sizeof(inner_));
    }
private:
    union Inner
    {
        int qty_;
        double price_;
    } inner_;
};
```
```
...or maybe something like this?
```
```
union MyUnion
{
    int qty_;
    double price_;
};

void someFunction()
{
    MyUnion u = {0};
}
```
```


q:
I'm looking for a very specific USB device for debugging systems that may use USB but not with a regular computer (proprietary hardware). I want a device that has a USB host controller and two USB device connections. The device to be debugged is connected to the USB host controller and one of the device connections is connected to another device with it's own host controller on it. The the other device connection is connected to a pc. The point being that all USB data travelling through the device (from the device connected to the host controller to the device connected to the first device connection) is reported to the pc.

I'll happily write software to do the logging (in fact I want to) but I can't seem to find a board like this anywhere. Can anyone help?

[A]
Sniffing the USB shouldn't be too hard if you have the right hardware.  And that is the tricky question.  I haven't seen anything that describes the USB breakout box that you want.  However I can say that this is in the realm of the following two magazines:
Nuts and Volts
Circuit Cellar
If they don't have a USB breakout box project in their archives, then at least they will have advertisements for small cheap single board computers that would have multiple USB ports that you can use for buffering the signals and reporting it back to your PC.
Alternatively is it possible to just wire your PC up to the middle of your two devices and write a custom drive that echos data back and forth while sniffing off a stream for you?


q: Can we convert a hex string to a byte array using a built-in function in C# or do I have to make a custom method for this?

[A]
Here's a nice fun LINQ example.
```
```
public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}
```
```


q:
This only happens with IE (all versions), on line 1120 in
jquery-1.2.6.js I get the following error:

Line 1120:
Invalid Property Value

The line in the js file is the following:

elem[name] = value;

It is inside attr: function( elem, name, value )

Does anybody have a problem similar to this?

[A]
If
this
is also you, it sounds like you're trying to change the CSS of the element rather than give it an attribute.
If that is the case then try this instead;
```
```
jQuery.css('color', 'inherit');
```
```


q:
I am using cocos2d-iphone to place Sprites onto a Layer to setup a game playfield.  At certain points in the game, certain Sprites need to be removed based upon game conditions.  What I would like to do is setup an array of Sprite pointers, but I have two questions:

What's the best way to place Sprite pointers in an array?

How does one remove the Sprite in cocos2d with only a pointer to the Sprite?  I know how to do it from its parent layer, but that is too runtime intensive for the main game loop.

Thanks in advance!

[A]
The
```
Sprite
```
class inherits from
```
CocosNode
```
, so you should be able to call
```
spritePointer.parent.remove(spritePointer)
```


q: How would I go about adding the "Spent Time" as a column to be displayed in the issues list?

[A]
Since no one answered, I just poked the source until it yielded results.  Then I started a blog to explain how I did it.
Add spent time column to default issues list in Redmine


q:
What the difference between LPCSTR, LPCTSTR and LPTSTR?

Why do we need to do this to convert a string into a LV / _ITEM structure variable pszText:

LV_DISPINFO dispinfo;
dispinfo.item.pszText = LPTSTR((LPCTSTR)string);

[A]
Quick and dirty:
```
LP
```
==
L
ong
P
ointer.  Just think pointer or char*
```
C
```
=
C
onst, in this case, I think they mean the character string is a const, not the pointer being const.
```
STR
```
is
string
the
```
T
```
is for a wide character or char (TCHAR) depending on compiler options.
Bonus Reading
From
What does the letter "T" in LPTSTR stand for?
:
archive
What does the letter "T" in LPTSTR stand for?
October 17th, 2006
The “T” in LPTSTR comes from the “T” in TCHAR. I don’t know for certain, but it seems pretty likely that it stands for “text”. By comparison, the “W” in WCHAR probably comes from the C language standard, where it stands for “wide”.


q: I'm trying to set the initial display order of the column headers in a silverlight datagrid by changing the column header DisplayIndex values. If I try to set the column order at page load time, I get an out of range exception. If I set the column order (same routine) at a later time like, in a button click handler, it works. Is this just a bug in the silverlight datagrid control? Suggestions for a possible work around?

[A]
I'm guessing that you've got a problem modifying the DisplayIndex of the columns in the DataGrid from the Page Loaded event as they haven't yet been created at this point. You don't say but I assume you're getting the DataGrid to AutoGenerate your columns as otherwise you could just set the DisplayIndex in your XAML when defining the DataGrid columns.
When the DataGrid generates Columns it fires a AutoGeneratingColumn event for each Column allowing you to modify its properties. It's a little crude but one solution could be to set the DisplayIndex in a handler for this event using the PropertyName it is creating a column for.
```
```
private void grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    switch (e.PropertyName)
    {
        case "Name":
            e.Column.DisplayIndex = 1;
            break;

        case "Age":
            e.Column.DisplayIndex = 0;
            break;
    }
}
```
```


q:
Are there any libraries or guides for how to read and parse binary data in C?

I am looking at some functionality that will receive TCP packets on a network socket and then parse that binary data according to a specification, turning the information into a more useable form by the code.

Are there any libraries out there that do this, or even a primer on performing this type of thing?

[A]
You don't really need to parse binary data in C, just cast some pointer to whatever you think it should be.
```
```
struct SomeDataFormat
{
    ....
}

SomeDataFormat* pParsedData = (SomeDataFormat*) pBuffer;
```
```
Just be wary of endian issues, type sizes, reading off the end of buffers, etc etc


q: In my WPF app, I call a WCF service to retrieve my business object.  I take that business object and bind it to a grid.  I want to now apply the INotifyPropertyChanged attribute, but am unsure if it would work from WCF.  My ultimate goal is to be able to edit items in a grid, click update and push those back through a WCF service.

[A]
I think there is an option for the generated classes to implement that automatically.
```
svcutil /enableDataBinding
```
- Implement the System.ComponentModel.INotifyPropertyChanged
  interface on all Data Contract types
  to enable data binding.
                                       (Short Form: /edb)


q:
So I have this app that checks for updates on the server getting a JSON response, each new update is put at the top of my list on a new div that is added via insertBefore using javascript.

All works just fine, but i'd like to add an animation effect when the div is added, i.e. "slowly" move the existing divs down, and add the new one at the top, Any pointers on how to do that ?

The application actually runs in facebook not using the iframe, I tried to use jquery but it does not seem to work on facebook, and looking at the code modifications that FB do, I assume other frameworks will have a similar problem.

[A]
It depends on the JavaScript framework you're using; but look at
MooTools
,
Scriptaculous
,
jQuery
and
YUI Animation
. If you're just hammering out JavaScript on your own, you'll find that working with interval timers that modify the style of some element over time and then trigger an animation complete event to stop the timer and finally update the page is a fairly involved error prone process.
You're probably looking for something generally called
slide
down
(try the demos).


q: Does anyone know of any documentation by MS or someone else that lays out the best practices for developing a 3 tier architecture in ASP.NET.  I am in the process of trying to convince my boss that the current architecture needs rethought and reworked to provide a flexible and reusable system.  I have found a lot of generic documentation that tells you at a high level the best practices as far as how to do this but little showing how you actually implement them.  I need to show him documentation as far as the advantages to using business objects versus data sets and things to that level of detail.  Any help would be appreciated.

[A]
Microsoft's
Patterns & Practices group
has published various whitepapers and documents in the form of "architectural guidance" that can be helpful. They recently published a number of
"pocket guides"
as well. Even if you don't follow them to the letter, they're likely to be a great starting point for discussing your particular needs.
That they come from Microsoft may also help add credibility in the discussion with your boss. There's one on
Web Application Architecture
, in particular, that sounds like it may be relevant.


q:
Is there any way to configure SQL Server 2000 Standard Edition (32 bit) to use more than 2Gb of memory on a server running Windows 2003 (64 bit)?

Thanks for any help.

[A]
It appears that this Microsoft article is of relevance:
How to configure SQL Server to use more than 2 GB of physical memory


q: Looking for tips, tutorials, books and other resources to get started with Constraint Programming.

[A]
I recommend getting started with
mozart
.  It is an open-source constraint programming language and the site has plenty of documentation that will get you started.


q:
What is the best way to convert a double to a long without casting?

For example:

double d = 394.000;
long l = (new Double(d)).longValue();
System.out.println("double=" + d + ", long=" + l);

[A]
Assuming you're happy with truncating towards zero, just cast:
```
```
double d = 1234.56;
long x = (long) d; // x = 1234
```
```
This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.


q:
I would like to return all rows from TableA table that does not exists in another table.

e.g.

select bench_id from TableA where bench_id not in (select bench_id from TableB )

can you please help me write equivalent LINQ query. Here TableA is from Excel and TableB is from a Database

I am loading Excel sheet data into DataTable, TableA. TableB I am loading from Database. In short, TableA and TableB is type of DataTable

[A]
So if table A is from Excel, are you loading the data into memory first? If so (i.e. you're using LINQ to Objects) then I suggest you load the IDs in table B into a set and then use:
```
```
var query = tableA.Where(entry => !tableBIdSet.Contains(entry.Id));
```
```
If this isn't appropriate, please give more details.
Converting into a set is probably best done just by using
the HashSet constructor which takes an
```
IEnumerable<T>
```
. For example:
```
```
var tableBIdSet = new HashSet<string>(db.TableB.Select(entry => entry.Id));
```
```
(If the IDs aren't actually distinct, you could add a call to Distinct() at the end.)


q:
I have Enitity Type, Name of Primary Key and Guid of Primary Id. I want to get element of such Id in LinqToSql.

model.GetTable<T>().Where(t => here equality  );

I think I need to generate that Expression myself, but I dont know how :(

[A]
I look forward, and after searching through generated by compiler code, in Reflector I found this creation of lambda.
```
```
public static T GetById(Guid id)
    {
        Type entType = typeof(T);

        if (!CheckTable(entType)) {
            throw new TypeLoadException(string.Format(
                "{0} is not Table Entity, has no attribute Table", entType.FullName));
        }

        string property = GetPrimaryKeyName(entType).Name;

        ParameterExpression cs;
        var lambda = Expression.Lambda<Func<Personal, bool>>(
                Expression.Equal(
                        Expression.Property(
                                cs = Expression.Parameter(typeof(T), "p"),
                                entType.GetProperty(property).GetGetMethod()
                        ),
                        Expression.Constant(id),
                        false,
                        typeof(Guid).GetMethod("Equals")
                ), new ParameterExpression[] { cs }
        );

        return Connection.Model.GetTable<T>().Single(lambda);
    }
```
```
The thing what I need, but I have compiler exception:
Error 5   The type arguments for method
  'System.Linq.Enumerable.Single(System.Collections.Generic.IEnumerable,
  System.Func)' cannot be
  inferred from the usage. Try
  specifying the type arguments
  explicitly.   D:\Projects\Own\Yabeda\Source\trunk\med\Yabeda.Med.Mvc\Data\Oper.cs 48  20  Yabeda.Med.Mvc
Can't find what this Error means!


q: Anyone know of a free xls to text converter that can be run from the unix command line?

[A]
A quick search of
```
apt-cache
```
turned up the
Ubuntu package python-excelerator
for
excelerator
, which includes
```
py_xls2html
```
,
```
py_xls2csv
```
and
```
py_xls2txt
```
utlities. Will this work for you?


q:
How does one read a data file in an iPhone project?  For example, lets say I have a static file called "level.dat" that is structured as follows:
obstacles: 10
time: 100
obstacle1: 10,20
...

I would like to read the contents of the file into a NSString then do the parsing.  How do I read the contents of a file into a string?  Also, where in the project should the "level.dat" file reside?  Should it be under "Resources" or just in the main directory?

Thanks in advance!

[A]
See this answer:
How to fopen() on the iPhone?
which shows how to get access to resources in your bundle. Once you have the path, just use [NSString stringWithContentsOfFile:encoding:error:].
```
```
NSString   *path = [[NSBundle mainBundle] pathForResource: @"level" ofType: @"dat"]
NSError    *error = nil;
NSString   *data = [NSString stringWithContentsOfFile: path
                                             encoding: NSUTF8StringEncoding
                                                error: &error];
```
```


q:
Given:

FieldInfo field = <some valid string field on type T>;
ParameterExpression targetExp = Expression.Parameter(typeof(T), "target");
ParameterExpression valueExp = Expression.Parameter(typeof(string), "value");

How do I compile a lambda expression to set the field on the "target" parameter to "value"?

[A]
.Net 4.0
: now that there's
```
Expression.Assign
```
, this is easy to do:
```
```
FieldInfo field = typeof(T).GetField("fieldName");
ParameterExpression targetExp = Expression.Parameter(typeof(T), "target");
ParameterExpression valueExp = Expression.Parameter(typeof(string), "value");

// Expression.Property can be used here as well
MemberExpression fieldExp = Expression.Field(targetExp, field);
BinaryExpression assignExp = Expression.Assign(fieldExp, valueExp);

var setter = Expression.Lambda<Action<T, string>>
    (assignExp, targetExp, valueExp).Compile();

setter(subject, "new value");
```
```
.Net 3.5
: you can't,  you'll have to use System.Reflection.Emit instead:
```
```
class Program
{
    class MyObject
    {
        public int MyField;
    }

    static Action<T,TValue> MakeSetter<T,TValue>(FieldInfo field)
    {
        DynamicMethod m = new DynamicMethod(
            "setter", typeof(void), new Type[] { typeof(T), typeof(TValue) }, typeof(Program));
        ILGenerator cg = m.GetILGenerator();

        // arg0.<field> = arg1
        cg.Emit(OpCodes.Ldarg_0);
        cg.Emit(OpCodes.Ldarg_1);
        cg.Emit(OpCodes.Stfld, field);
        cg.Emit(OpCodes.Ret);

        return (Action<T,TValue>) m.CreateDelegate(typeof(Action<T,TValue>));
    }

    static void Main()
    {
        FieldInfo f = typeof(MyObject).GetField("MyField");

        Action<MyObject,int> setter = MakeSetter<MyObject,int>(f);

        var obj = new MyObject();
        obj.MyField = 10;

        setter(obj, 42);

        Console.WriteLine(obj.MyField);
        Console.ReadLine();
    }
}
```
```


q: In Qt, when a widget receives focus, how can get a notification about it, so I can execute some custom code? Is there a signal or an event for that?

[A]
There is a "focusChanged" signal sent when the focus changes, introduced in Qt 4.1.
It has two arguments, he widget losing focus and the one gaining focus:
```
```
void QApplication::focusChanged(QWidget * old, QWidget * now)
```
```


q: I change the FontSize of Text in a Style trigger, this causes the Control containing the text to resize as well. How can I change the Fontsize without affecting the parent's size?

[A]
What kind of control are you using? If this is a HeaderedControl like a GroupBox or TabItem then you need to specifically set the HeaderTemplate like this:
```
```
<DataTemplate x:Key="MyHeaderTemplate">
  <TextBlock Text="{Binding}" Fontsize="14" FontWeight="Bold" />
</DataTemplate>
```
```


q: Say I'm extending a TextBox called CustomTextBox in .net. In certain situations I would like to force a tab to the next TabIndex on the form. Is there a way to do this beyond getting all the controls contained in CustomTextBox's parent, sorting them by their TabIndex, and then focusing the next ordinal one?

[A]
I think you are looking for something like the following method:
```
```
form1.SelectNextControl(textBox1, true, true, true, true);
```
```
(All the trues are just different options, read the intellisense!)
You did say it is WinForms and not WebForms right?


q:
I have an application that I want to export high-resolution (or rather, high pixel density?) images for printing - for example, I want images that print at 250 dots per inch (DPI), instead of the default, which I understand to be 72 DPI.

I'm using a BufferedImage with a Graphics2D object to draw the image, then ImageIO.write() to save the image.

Any idea how I can set the DPI?

[A]
Kurt's answer showed the way, still it took me quite some time to get it run, so here is the code that sets DPI when saving a PNG. There is a lot to do to get the proper writers and such...
```
```
private BufferedImage gridImage;
 ...

 private void saveGridImage(File output) throws IOException {
    output.delete();

    final String formatName = "png";

    for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
       ImageWriter writer = iw.next();
       ImageWriteParam writeParam = writer.getDefaultWriteParam();
       ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
       IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
       if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
          continue;
       }

       setDPI(metadata);

       final ImageOutputStream stream = ImageIO.createImageOutputStream(output);
       try {
          writer.setOutput(stream);
          writer.write(metadata, new IIOImage(gridImage, null, metadata), writeParam);
       } finally {
          stream.close();
       }
       break;
    }
 }

 private void setDPI(IIOMetadata metadata) throws IIOInvalidTreeException {

    // for PMG, it's dots per millimeter
    double dotsPerMilli = 1.0 * DPI / 10 / INCH_2_CM;

    IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
    horiz.setAttribute("value", Double.toString(dotsPerMilli));

    IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
    vert.setAttribute("value", Double.toString(dotsPerMilli));

    IIOMetadataNode dim = new IIOMetadataNode("Dimension");
    dim.appendChild(horiz);
    dim.appendChild(vert);

    IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
    root.appendChild(dim);

    metadata.mergeTree("javax_imageio_1.0", root);
 }
```
```


q:
Are the threadlocals variables global to all the requests made to the servlet that owns the variables?

I am using resin for the server.

Thanks for awnser.

I think I can make my self more clear.

The specific Case:

I want to:

initialize a static variable when the request starts the execution.

be able to query the value of the variable in the further executions of methods called from the servlet in a thread safety way until the request ends the execution

[A]
I think they are global to all requests made with that specific thread only. Other threads get other copies of the
thread-local
data. This is the key point of thread-local storage:
http://en.wikipedia.org/wiki/Thread-local_storage#Java
.
Unless you check the appropriate option in the servlets config, the servlet container will use your servlet with multiple threads to handle requests in parallel. So effectively you would have separate data for each thread that's up serving clients.
If your WebApplication isn't distributed (runs on multiple Java Virtual Machines), you can use the
```
ServletContext
```
object to store shared data across requests and threads (be sure to do proper locking then).


q:
I've seen a number of examples that have a thread procedure that looks like this.

    private void ThreadProc()
    {
        while (serviceStarted)
        {
            // do some work

            Thread.Sleep(new TimeSpan(0, 0, 5));
        }

        Thread.CurrentThread.Abort();
    }

Is the Abort() really necessary at the end?

There are number of arguments against calling Abort()

Once the procedure exited - it is expected it has already cleaned up after itself.

Calling Abort() throws an exception, which is generally more resource intensive than just exiting a procedure.

I'd like to read an explanation for why this is or isn't a good practice.

[A]
Calling
```
Thread.Abort()
```
does raise an exception, and if you're writing code that will be re-used (or part of a base library) it's difficult for other developers to handle
```
ThreadAbortExcpetion
```
s.
It's explained in this article about
Reliability Best Practices
.
I've always heard that calling
```
Thread.Join()
```
is a better way to do it, if you can wait until the thread is completed processing.
I don't know if anyone thinks it's a good practice.  It can cause deadlocks (because unmanaged resources aren't properly cleaned up when you throw an exception)
Here's
another article about it
, and other methods to deal with the issue.


q:
I'm trying to encrypt some integers in java using java.security and javax.crypto.

The problem seems to be that the Cipher class only encrypts byte arrays.  I can't directly convert an integer to a byte string (or can I?).  What is the best way to do this?

Should I convert the integer to a string and the string to byte[]?  This seems too inefficient.

Does anyone know a quick/easy or efficient way to do it?

Please let me know.

Thanks in advance.

jbu

[A]
You can turn ints into a byte[] using a DataOutputStream, like this:
```
```
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
DataOutputStream dos = new DataOutputStream (baos);
dos.writeInt (i);
byte[] data = baos.toByteArray();
// do encryption
```
```
Then to decrypt it later:
```
```
byte[] decrypted = decrypt (data);
ByteArrayInputStream bais = new ByteArrayInputStream (data);
DataInputStream dis = new DataInputStream (bais);
int j = dis.readInt();
```
```


q: How do I convert a date string, formatted as "MM-DD-YY HH:MM:SS", to a time_t value in either C or C++?

[A]
I'm afraid there isn't any in Standard C / C++ . There is the POSIX function
```
strptime
```
which can convert to
```
struct tm
```
, which can then be converted to
```
time_t
```
using
```
mktime
```
.
If you are aiming for cross platform compatibility, better use
```
boost::date_time
```
, which has sophisticated functions for this.


q:
I was wondering in C++ if I have an enum can I access the value at the second index?  For example I have

enum Test{hi, bye};

if I want 'hi', can I do something like Test[0], thanks.

[A]
Enumerations map names to values.  In your case, (int)hi would have a value of 0, and (int)bye a value of 1.  You can use a cast to get the value of hi:
```
```
int myInteger = 0;
Test myValue = (Test)myInteger;
```
```
Note, though, that myValue could be an invalid enum value if myInteger is out of range.


q:
Is there a good equivalent implementation of strptime() available for Windows?  Unfortunately, this POSIX function does not appear to be available.

Open Group description of strptime - summary: it converts a text string such as "MM-DD-YYYY HH:MM:SS" into a tm struct, the opposite of strftime().

[A]
An open-source version (BSD license) of
```
strptime()
```
can be found here:
http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD
You'll need to add the following declaration to use it:
```
```
char *strptime(const char * __restrict, const char * __restrict, struct tm * __restrict);
```
```


q:
I have a ‘page a’ using ‘css a’. This page has margins set in css.
I also have a ‘page b’ using ‘css b’. This page also has margins set in css, of the same size as in ‘css a’ (10px).

Is there any way I can make it so that when I am viewing ‘page a’ on its own it has margins, but when viewed in an iframe on ‘page b’ the margins don’t apply to ‘page a’. I know that’s kind of a long way of asking but the basic problem is that I am getting ‘double margins’ for the content in the iframe: the margin from ‘page a’ and then the margin from ‘page b’!

I guess one way of doing it would be to set the iframe not to be affected by ‘page a’s’ margins. Is there some way I can set ‘css a’ to exclude the iframe from the margins, that way only the margins from css b would apply and the page would still be in alignment. is that possible?

Thanks for any help

Matt

[A]
Using one of the most fundamental XSLT design patterns: "Overriding the
identity transformation
" one will just write the following:
```
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="Element[@fruit='apple' and @animal='cat']"/>
</xsl:stylesheet>
```
Do note
how the second template overrides the identity (1st) template only for elements named "Element" that have an attribute "fruit" with value "apple" and attribute "animal" with value "cat". This template has empty body, which means that the matched element is simply ignored (nothing is produced when it is matched).
When this transformation is applied on the following source XML document:
```
<doc>...
    <Element name="same">foo</Element>...
    <Element fruit="apple" animal="cat" />
    <Element fruit="pear" animal="cat" />
    <Element name="same">baz</Element>...
    <Element name="same">foobar</Element>...
</doc>
```
the wanted result is produced:
```
<doc>...
    <Element name="same">foo</Element>...
    <Element fruit="pear" animal="cat"/>
    <Element name="same">baz</Element>...
    <Element name="same">foobar</Element>...
</doc>
```
More code snippets of using and overriding the identity template can be found
here
.


q:
Does anybody know if it is possible to choose the order of the fields in Dynamic Data (of course, without customizing the templates of each table) ?

Thanks !

[A]
You can do this by modifying the order of the public properties in your LINQ to SQL file.
For example, I went into Northwind.designer.cs which was my auto-generated LINQ to SQL file and moved the public property named Products above the public property CategoryName in the public partial class Category. Then I recompiled and the default template displayed the columns in my new order.
Of course, this means your editing auto-generated code and if you regenerate it, your changes are lost, so this technique is not without peril.


q:
I am new to LINQ. I am trying to find the rows that does not exists in the second data table.

report_list and benchmark both type are : DataTable. Both these datatables are being populated using OleDbCommand,OleDbDataAdapter. I am getting an error "Specified cast is not valid."  in foreach ... loop. I would appreciate your help.

            var result = from a in report_list.AsEnumerable()
                         where !(from b in benchmark.AsEnumerable()
                                 select b.Field<int>("bench_id")
                                )
                                .Contains(a.Field<int>("BenchmarkID"))
                         select a;

            foreach (var c  in result)
            {
                Console.WriteLine(c.Field<string>("Name"));
            }

[A]
I don't know if I understood your question. Are you trying to get the items that exists in the first table but not in the second?
```
```
var first = new string[] { "b", "c" };
var second = new string[] { "a", "c" };
//find the itens that exist in "first" but not in "second"
var q = from f in first
        where !second.Contains(f)
        select f;
foreach (var s in q) {
    Console.WriteLine(s);
}

//Prints:
//b
```
```
I suggest you to make the inner query first, once it does not depend on the outer record.


q:
I currently working on an issue tracker for my company to help them keep track of problems that arise with the network. I am using C# and SQL.

Each issue has about twenty things we need to keep track of(status, work loss, who created it, who's working on it, etc). I need to attach a list of teams affected by the issue to each entry in my main issue table. The list of teams affected ideally contains some sort of link to a unique table instance, just for that issue, that shows the list of teams affected and what percentage of each teams labs are affected.

So my question is what is the best way to impliment this "link" between an entry into the issue table and a unique table for that issue? Or am I thinking about this problem wrong.

[A]
If I understand the question correctly I would create....
ISSUE table containing the 20 so so items
TEAM table containing a list of teams.
TEAM_ISSUES table containing the link beteen the two
The TEAM_ISSUES table needs to contain a foriegn key to the ISSUE and TEAM tables (ie it should contain an ISSUE_ID and a TEAM_ID... it therefore acts as an intersection between the two "master" tables.  It sounds like this is also the place to put the percentage.
Does that make sense?


q:
I'm serializing to XML my class where one of properties has type List<string>.

public class MyClass {
    ...
    public List<string> Properties { get; set; }
    ...
}

XML created by serializing this class looks like this:

<MyClass>
    ...
    <Properties>
        <string>somethinghere</string>
        <string>somethinghere</string>
    </Properties>
    ...
</MyClass>

and now my question. How can I change my class to achieve XML like this:

<MyClass>
    ...
    <Properties>
        <Property>somethinghere</Property>
        <Property>somethinghere</Property>
    </Properties>
    ...
</MyClass>

after serializing. Thanks for any help!

[A]
Try
XmlArrayItemAttribute
:
```
```
using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;

public class Program
{
    [XmlArrayItem("Property")]
    public List<string> Properties = new List<string>();

    public static void Main(string[] args)
    {
        Program program = new Program();
        program.Properties.Add("test1");
        program.Properties.Add("test2");
        program.Properties.Add("test3");

        XmlSerializer xser = new XmlSerializer(typeof(Program));
        xser.Serialize(new FileStream("test.xml", FileMode.Create), program);
    }
}
```
```
test.xml:
```
```
<?xml version="1.0"?>
<Program xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Properties>
    <Property>test1</Property>
    <Property>test2</Property>
    <Property>test3</Property>
  </Properties>
</Program>
```
```


q:
I'm working on a college assignment where I must verify if a certain clause (as a fact or as a rule) exists in the current clause database.

The idea is to use a rule whose head  is verify(+name, +arguments). This rule should be true if in the database exists another rule whose head is name(arguments)

Any help would be greatly appreciated...

[A]
Are you familiar with the concept of unification? What you have to do is: just call a predicate that looks like the one you're trying to find.
So, say in your database is:
```
```
father(abraham,isaac).
```
```
Now you want to call something like:
```
```
verify(father,[abraham,isaac]).
```
```
Your predicate body will then have to contain a mechanism of calling
```
father(abraham,isaac).
```
which should then return
```
true.
```
Calling
```
father(abraham,adam)
```
should fail.
You will need two predicates for this:
```
=../2
```
and
```
call/2
```
. If you are using SWI-Prolog, call
```
help(=..).
```
and
```
help(call)
```
from the interpreter's command line to access the documentation.
I hope I didn't spoil the assignment for you. You still have to find out what to do with partially instantiated predicates (so, say something like
```
verify(father,[abraham,X]).
```
on your own, but it shouldn't be hard from here.
Good luck.


q: Exactly as the question states: How can you check if a variable in PHP contains a file pointer? Some like is_string() or is_object().

[A]
You can use
```
stream_get_meta_data()
```
for this.
```
```
<?php
$f = fopen('index.php', 'r');
var_dump(stream_get_meta_data($f));
?>

array
  'wrapper_type' => string 'plainfile' (length=9)
  'stream_type' => string 'STDIO' (length=5)
  'mode' => string 'r' (length=1)
  'unread_bytes' => int 0
  'seekable' => boolean true
  'uri' => string 'index.php' (length=9)
  'timed_out' => boolean false
  'blocked' => boolean true
  'eof' => boolean false
```
```
You can prefix it with @ to supress warnings if the variable is not a resource - then just check if it returned false.


q:
Given an ordered set of 2D pixel locations (adjacent or adjacent-diagonal) that form a complete path with no repeats, how do I determine the Greatest Linear Dimension of the polygon whose perimeter is that set of pixels? (where the GLD is the greatest linear distance of any pair of points in the set)

For my purposes, the obvious O(n^2) solution is probably not fast enough for figures of thousands of points. Are there good heuristics or lookup methods that bring the time complexity nearer to O(n) or O(log(n))?

[A]
On this page:
http://en.wikipedia.org/wiki/Rotating_calipers
http://cgm.cs.mcgill.ca/~orm/diam.html
it shows that you can determine the maximum diameter of a convex polygon in O(n). I just need to turn my point set into a convex polygon first (probably using Graham scan).
http://en.wikipedia.org/wiki/Convex_hull_algorithms
Here is some C# code I came across for computing the convex hull:
http://www.itu.dk/~sestoft/gcsharp/index.html#hull


q:
Is it possible?

I have a listview with several gridviewcolumns. The last column has a dynamic header. I dont know what the column header will be at design time. It's actually a number I want to display as a string.

    <GridViewColumn Header="{Binding Path=SomeValue}"
                    DisplayMemberBinding="{Binding Path=OtherValue}"/>

This doesn't seem to work. The data will bind fine just the header remains blank. Stepping through the code and it doesn't even break on the SomeValue property.

[A] I think your problem is the source of the "SomeValue" property. If you are binding to a list of objects, it wouldn't make sense to have the header determined by a property on that object, because then you could have a different header for every object. Essentially what you are saying is "Bind the header of the column to the 'SomeValue' property which lives on the same object that my 'OtherValue' property does." The "SomeValue" needs to come from a different source other than the list your grid item is bound to. You need to either set the "RelativeSource" or the "ElementName" property in the binding.


q: Our motor pool wants to scan drivers’ licenses and have the data imported into our custom system. We're looking for something that will allow us to programmatically get the data from the scanner (including the picture) and let us insert it into our application. I was wondering if anyone has had experience with this type of system and could recommend one or tell us which ones to avoid. Our application is written in PowerBuilder and uses a DB2 database.

[A]
If your scanner is "twain compliant", You will then be able to manage it from your app through an ActiveX control you can buy on the net like
this one
. You'll be able to manage your basic scan parameters (quality, color, single/multiple pages can, output format, etc), start the scan from your app, save the result as a file and transfer this file wherever needed. We have been using it with VB code for the last 2 years. It works.


q:
Looking to improve my IF statement, and I want to keep my code looking pretty

This is what I am currently doing, is it readable, any room for improvement?

SomeObject o = LoadSomeObject();

if( null == o
    ||
    null == o.ID || null == o.Title
    ||
    0 == o.ID.Length || 0 == o.Title.Length
 )

I don't have anyone to ask around. That's why I came here in first place. Please don't close my question :(

[A]
Your verbosity is leading to a less readable code, I think the following format is best:
```
```
if ( null == o || null == o.ID || null.Title || 0 == o.ID.Length || 0 == o.Title.Length )
{
  // do stuff
}
```
```
We all have high resolution/widescreen displays for a reason, there's no reason to lock your code at some horribly short syntax.  Also, I would simply create a function named  IsIDEmpty so that the code could look like
```
```
if ( IsIDEmpty(o) )
{
  // do stuff
}
```
```
to keep the code simpler & cleaner.  The function would perform the actual checks and return a boolean.  I'm sure this is something you might have re-use for anyways, plus it serves as a simple way for code to be more self documenting/commenting.


q:
I am trying to make IBM jre to use PCF fonts from default X11 installation on my linux box. In particular adobe-helvetica font. I have toyed to modify fontconfig.properties in jre/lib folder but no matter what I do Java seams to use some other fonts. I guess there is some algorithm how java VM tries to link java logical fonts to actual physical fonts in the system even in case when font specified in config could not be used. On Windows it is pretty straight forward, but on Linux I was unable to make it work with anything except TrueType fonts.

Anybody have experience with configuring fonts on IBM jre on Linux?


q:
I have read an example and tried to duplicate it's methods but with weird results. This is a 1 shot deal so I do not want to buy a package to do this. Also, it will be executed on a Multi-Valued database in a Basic that not many programmers write in anymore.
If anyone can post a small example of this It would be most helpful. Specifically, I need a box centered on an 8x11 paper with the left 1/3 filled in Green, the center 1/3 in Yellow and the last 1/3 in Red. Then Draw a line thru 3 points within each color of the box.

Thanks.

[A]
The simplest way is to draw 3 boxes.  You'll have to position each one on your own doing your own math to determine where to start the first one to make it centered etc.
First position your cursor at the top left of the first box, draw it, move to the top left of the next box, draw it, and do the same for the last.  Here is some code:
```
```
<esc>&u300D<esc>*t300R<esc>*p300x300Y<esc>*r3U<esc>*v2S<esc>*c300a300b5P<esc>*p600x300Y<esc>*r3U<esc>*v3S<esc>*c300a300b5P<esc>*p900x300Y<esc>*r3U<esc>*v1S<esc>*c300a300b5P
```
```
Here is the explanation:
```
```
<esc>&u300D<esc>*t300R -- set the Unit of Measure and Resolution (in this case 300 dpi)
<esc>*p300x300Y -- move cursor to 300x 300y (1 inch x 1 inch)
<esc>*r3U<esc>*v2S -- set the color palette to RGB and use color 2 (green)
<esc>*c300a300b5P -- draw a box that is 300 wide and 300 tall, use current fill pattern
<esc>*p600x300Y -- move cursor to 600x 300y
<esc>*r3U<esc>*v3S -- set the color palette to RGB use color 3 (yellow)
<esc>*c300a300b5P -- draw a box that is 300 wide and 300 tall, use current fill pattern
<esc>*p900x300Y -- move cursor to 900x 300y
<esc>*r3U<esc>*v1S -- set the color palette to RGB use color 1 (red)
<esc>*c300a300b5P -- draw a box that is 300 wide and 300 tall, use current fill pattern
```
```
Here are the other colors and palettes, keep in mind this is the simple way, you can specify your own RGB etc.
```
```
RGB Palette
<esc>*r3U<esc>*v1S - Red
<esc>*r3U<esc>*v2S - Green
<esc>*r3U<esc>*v3S - Yellow
<esc>*r3U<esc>*v4S - Blue
<esc>*r3U<esc>*v5S - Magenta
<esc>*r3U<esc>*v6S - Cyan

CMYK Palette
<esc>*r-3U<esc>*v1S - Cyan
<esc>*r-3U<esc>*v2S - Magenta
<esc>*r-3U<esc>*v3S - Blue
<esc>*r-3U<esc>*v4S - Yellow
<esc>*r-3U<esc>*v5S - Green
<esc>*r-3U<esc>*v6S - Red
<esc>*r-3U<esc>*v7S - Black
```
```


q:
I need to query for a list of available Wireless Access points. I only need their SSIDs.

The App is currently .Net CF 2.0, but it's not a problem going with 3.5 if we have to.

[A]
Well the core of this is in the Windows Zero Config .dll otherwise known as WZC. However from a managed app you'll want to go via
OpenNETCF
as they have a managed wrapper that can provide this information for you.
The classes of interest are the Adapter or NetworkAdapter classes.
The obselete api was:
```
```
Networking.GetAdapters()
```
```
although this is now depreciated I think and I apologise but i've forgotten what they've replaced it with but there will be a new equivalent.


q:
I'd like to write a script that (under certain conditions) will execute gdb and automatically run some program X with some set of arguments Y.  Once the program has finished executing the user should remain at gdb's prompt until s/he explicitly exits it.

One way to do this would be to have the script output the run command plus arguments Y to some file F and then have the script invoke gdb like this:

gdb X < F

But is there a way to do this without introducing a temporary file?

[A]
```
cat F | gdb X
```
should be identical. So you can use anything that produces output and pipe that into gdb instead of the cat command here.
I'm assuming you're correct and gdb reads from stdin.


q:
I'm new to ReSharper and am surprised that there isn't a template defined for

public void MethodName(<params>)
{

}

I realize I could create one, but I would have thought this would have been part of the standard product.  Perhaps I'm missing some other shortcut?

[A]
I'm not aware of any such default template, but as you pointed out it's terribly easy to write:
```
```
public void $METHODNAME$($PARAMS$)
{
    $END$
}
```
```
However, I'm more that a tiny bit perplexed that you're interested in making all your methods both public and void
by default.


q: I have recently started exploring Maven, but I feel a bit overwhelmed of all xml configuration in all the pom files. Are there any good tools i can use?

[A]
When I edit any XML files, I use
vim
with the
xmledit
plugin.
Another good tool for XML editing is
XMLmind XML editor
.  It's free for non-commercial use.  It supports validating XML with W3C XML Schema (and other schema formats), so you can be sure to produce
valid POM format
.


q:
The top of my web.xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
    version="2.5">

But I still get the warning from Eclipse (Ganymede) that no XML schema is detected, and schema violations are not being warned about.  Other XML files in my project (Spring Framework configuration files for example) don't have the warning and do give correct warnings about schema violations.

How do I get the schema checking working and hopefully the warning to go away?  The server does run correctly.  It just appears to be an IDE issue.

[A]
Perhaps try:
```
```
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
```
```
Instead of:
```
```
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd
```
```
Also, the
```
<!DOCTYPE ...>
```
is missing:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app
  xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">
  <!-- ... -->
</web-app>
```
```


q:
I'm reviewing some Spring code, and I see a few bean defs that do not have an id or a name.
The person who did it is not around to ask.
The application is working fine.
I am not familiar what this necessarily means.
Anybody know if this means anything in particular?

[A]
One possibility is that you can define a bean in place, and so you don't need an id since you don't need to refer to it from anywhere else.  Say I have a Foo object that takes a Bar property:
```
```
<bean id="foo" class="Foo">
     <property name="bar">
         <bean class="Bar">
     </property>
</bean>
```
```
The Bar bean doesn't need a name because it's only used to set that one property.


q:
Tomcat documentation says:

The locations for Context Descriptors are;

$CATALINA_HOME/conf/[enginename]/[hostname]/context.xml

$CATALINA_HOME/webapps/[webappname]/META-INF/context.xml

On my server, I have at least 3 files floating around:

1 ...tomcat/conf/context.xml
2 ...tomcat/Catalina/localhost/myapp.xml
3 ...tomcat/webapps/myapp/META-INF/context.xml

What is the order of precedence?

[A]
I haven't found any official documentation, but I have observed the load order to be:
```
```
1 tomcat_home/conf/context.xml
2 tomcat_home/webapps/myapp/META-INF/context.xml
```
```
Where #2 is the last one applied (so its settings override all previous ones, where applicable).
I have never used the webapp named context files (your option #2).


q:
I'm currently trying to implement a marble maze game for a WM 5.0 device and have been struggling with developing a working prototype. The prototype would need the user to control the ball using the directional keys and display realistic acceleration and friction.

I was wondering if anyone has experience with this and can give me some advice or point me in the right direction of what is essential and the best way to go around doing such a thing.

Thanks in advance.

Frank.

[A]
I would recommend checking out XNA Studio 3, it has built in support for PC, Xbox 360 and mobile devices, and it's an official & free spin-off of Visual Studio from Microsoft.
http://creators.xna.com/en-US/
http://blogs.msdn.com/xna/
If you search around, people have written tutorials using physics (velocity on this one)
http://www.xnamachine.com/2007/12/fun-with-very-basic-physics.html


q:
Previously our SharePoint server was 32-bit and we used the web capture web part to display a bugzilla search results page. Since we've migrated to a 64-bit server the webpart no longer works. We're running the same versions of everything, the only change was moving from a Windows Server 2003 32-bit box to a Windows Server 2003 64-bit box.

Oddly enough, the logs don't contain anything. The pages where the webparts appear are the only place that error messages appear. Here is what I have:

-Web Part Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. The type could not be found or it is not registered as safe.

Error - An unexpected error has been encountered in this Web Part.

The reason I suspect the 64bit vs 32bit issue is that I saw numerous posts on the subject in various forums. It would appear that I am not the only one with this issue and all the troubleshooting has lead to this conclusion.

[A]
Not strictly an answer to your question, but have you tried it using a sql server based session store? (Search on MSDN for the permanent script rather than the temp script that's provided with asp.net)
I've heard "bad things" about the executable session service, and consequently have not used it. Never had any problems web farming with the sql server based solution though.
Sorry it's not strictly an answer to your problem, but it should either (a) fix it, or (b) narrow it down significantly.


q:
What is the command-line equivalent of "Switch Port Client User" as found in the p4win gui client?

I am already logged under one port but now I am attempting to connect to a different port on the same server in order to access a separate source control file depot. I assume it would involve using:

p4 login

However, reading the 'help' for 'login' does not show an option to specify the port #. Both user name and client name would remain the same but just need to change the port #.

[A]
The P4PORT configuration variable stores the Perforce server name and port number to connect to. You can set this value as an environment variable or, if you're using Windows, in the registry using 'p4 set':
```
```
p4 set P4PORT=perforce:1669
```
```
To see what the current value of P4PORT is:
```
```
> p4 set P4PORT
P4PORT=perforce:1669
```
```


q:
I've been testing out the performance and memory profiler AQTime to see if it's worthwhile spending those big $$$ for it for my Delphi application.

What amazes me is how it can give you source line level performance tracing (which includes the number of times each line was executed and the amount of time that line took) without modifying the application's source code and without adding an inordinate amount of time to the debug run.

The way that they do this so efficiently makes me think there might be some techniques/technologies used here that I don't know about that would be useful to know about.

Do you know what kind of methods they use to capture the execution line-by-line without code changes?

Are there other profiling tools that also do non-invasive line-by-line checking and if so, do they use the same techniques?

[A]
I don't know about Delphi in particular, but a C application debugger can do line-by-line profiling relatively easily - it can load the code and associate every code path with a block of code. Then it can break on all the conditional jump instructions and just watch and see what code path is taken. Debuggers like gdb can operate relatively efficiently because they work through the kernel and don't modify the code, they just get informed when each line is executed. If something causes the block to be exited early (longjmp), the debugger can hook that and figure out how far it got into the blocks when it happened and increment only those lines.
Of course, it would still be tough to code, but when I say easily I mean that you could do it without wasting time breaking on each and every instruction to update a counter.


q:
I have an iterator to a map element, and I would like gdb to show me the values of the "first" and "second" elements of that iterator.
For example:

std::map<int,double> aMap;
...fill map...
std::map<int,double>::const_iterator p = aMap.begin();

I can use p.first and p.second in the code, but can't see them in gdb. For what it's worth, in dbx one could do something like "print p.node.second_", but I can find anything similar in gbd.

I am totally willing to have a function into which I pass the object types, but I've been unable to get that to work either.

Any ideas?
Thanks!

[A]
Here is how i do it:
```
```
This GDB was configured as "i686-pc-linux-gnu"...
(gdb) list
1       #include <iostream>
2       #include <map>
3
4       int main()
5       {
6           std::map<int, int> a;
7           a[10] = 9;
8           std::map<int, int>::iterator it = a.begin();
9           ++it;
10      }
(gdb) b test.cpp:9
Breakpoint 1 at 0x8048942: file test.cpp, line 9.
(gdb) r
Starting program: /home/js/cpp/a.out

Breakpoint 1, main () at test.cpp:9
9           ++it;
(gdb) set print pretty on
(gdb) p it
$1 = {
  _M_node = 0x94fa008
}
(gdb) p *it
$2 = (class std::pair<const int, int> &) @0x94fa018: {
  first = 10,
  second = 9
}
(gdb)
```
```


q:
I want to examine the contents of a std::vector in gdb but I don't have access to _M_impl because I'm using icc, not gcc, how do I do it? Let's say it's a std::vector for the sake of simplicity.

There is a very nice answer here but this doesn't work if I use icc, the error message is "There is no member or method named _M_impl". There appears to be a nice debug toolset here but it also relies on _M_impl.

[A]
The
```
std::vector
```
template
guarantees the data is stored contiguously
.  If you take the address of the front element (say,
```
&v[0]
```
, for instance), you can access any other element in the vector through a C-style array.  That doesn't require you to have the source code of the STL available to your debugger.
After messing with this some, it appears that
```
v.front()
```
and
```
v.begin()
```
are likely inlined and GDB isn't finding them.  I'll keep looking, but personally I would simply add the line
```
int* i = &v[0]
```
to the source file, and then use GDB commands on
```
i
```
while debugging.  Note that the compiler is free to remove that dead code.  You may need to output the value of
```
i
```
to avoid that, or simply not crank up optimizations.


q:
I'm looking for a regular expression that will match all strings EXCEPT those that contain a certain string within.  Can someone help me construct it?

For example, looking for all strings that do not have a, b, and c in them in that order.

So

abasfaf3 would match, whereas

asasdfbasc would not

[A]
in perl:
```
```
if($str !~ /a.*?b.*?.*c/g)
{
    print "match";
}
```
```
should work.


q:
I feel that it should be something very simple and obvious but just stuck on this for the last half an hour and can't move on.

All I need is to split an array of elements into N groups based on element index.

For example we have an array of 30 elements [e1,e2,...e30], that has to be divided into N=3 groups like this:

group1: [e1, ..., e10]
group2: [e11, ..., e20]
group3: [e21, ..., e30]

I came up with nasty mess like this for N=3 (pseudo language, I left multiplication on 0 and 1 just for clarification):

for(i=0;i<array_size;i++) {
   if(i>=0*(array_size/3) && i<1*(array_size/3) {
      print "group1";
   } else if(i>=1*(array_size/3) && i<2*(array_size/3) {
      print "group2";
   } else if(i>=2*(array_size/3) && i<3*(array_size/3)
      print "group3";
   }
}

But what would be the proper general solution?

Thanks.

[A]
```
```
const int g = 3;                      // number of groups
 const int n = (array_size + g - 1)/g; // elements per group

 for (i=0,j=1; i<array_size; ++i) {
    if (i > j*n)
        ++j;
     printf("Group %d\n", j);
 }
```
```


q:
When editing an XML file in IntelliJ IDEA, if the document references a schema, IDEA will fetch the schema and use the information for auto-complete.  It knows which tags are valid in which contexts, so when you hit CTRL-space, it suggests only those tags.  It also highlights any tags that are invalid according to the schema.

Does anybody know of an extension for Vim that provides similar functionality?

[A]
The closest thing that I've seen for Vim is the
XML Completion
script.
It contains XML definition files for DocBook 4.[234], XSL FO 1.0, XSLT 1.0, Relax NG 1.0, XML Schemas 1.0, SVG 1.1, XHTML 1.1, XInclude 1.0 and OpenOffice 1.0 XML format.


q:
I noticed methods marked optional in several protocols defined in the iPhone SDK, such as the UIActionSheetDelegate protocol for example.

How can I define a protocol of my own, and set a few of the methods as optional?

[A]
Use the
```
@optional
```
keyword before your method declaration to make it optional. Simple as that!
```
```
// myProtocol.h
@protocol myProtocol
- (void)myMandatoryMethod:(id)someArgument;
@optional
- (void)myOptionalMethod:(id)someArgument;
@end
```
```
```
```
// myClass.m
@interface myClass : someSuperClass <myProtocol>
    //...
@end
```
```


q:
It is to my understanding that one should use a forward-class declaration in the event ClassA needs to include a ClassB header, and ClassB needs to include a ClassA header to avoid any circular inclusions. I also understand that an #import is a simple ifndef so that an include only happens once.

My inquiry is this: When does one use #import and when does one use @class? Sometimes if I use a @class declaration, I see a common compiler warning such as the following:

warning: receiver 'FooController' is a forward class and corresponding @interface may not exist.

Would really love to understand this, versus just removing the @class forward-declaration and throwing an #import in to silence the warnings the compiler is giving me.

[A]
Use a forward declaration in the header file if needed, and
```
#import
```
the header files for any classes you're using in the implementation. In other words, you always
```
#import
```
the files you're using in your implementation, and if you need to reference a class in your header file use a forward declaration as well.
The
exception
to this is that you should
```
#import
```
a class or formal protocol you're inheriting from in your header file (in which case you wouldn't need to import it in the implementation).


q:
This question intends to provide a list of solutions to common pitfalls, "gotcha's", or design issues when developing WPF applications. This can also include proper design-patterns as long as there is an explanation as to why it works best. Responses should be voted up or down based on how common the type of issue is. Here are the rules:

One response per post. This will clearly give the most common issues the highest ranking.

It would be best to provide the link to the a related post or solution already living somewhere in SO land.

[A]
Problem
: The major issue I have seen so far is that people start coding in WPF with the winform UI model in mind.
Solution
:
WPF is not WinForms/MFC/Win32
So Forget all the UI side assumptions and norms you have used and learned while developing Windows based UI for last 20+ years.
It is very important to understand the core ideas behind this platform, This link-
Major UI Development Breakthroughs in the new WPF platform
will give an in depth view of WPF. Which lists out the following points. The highlighted ones are my favorite features of this platform.
Advanced Graphics
Drawing Object Model
Rich Application Text
Adaptable UI Layout
Flexible Content Model
Lookless Controls
Data-Driven UI
Consistent Styles
Triggers
Declarative Programming


q:
In jQuery, how do you select the <a> which href is pointing to the current URL

For example:

URL = http://server/dir/script.aspx?id=1

I want to select this <a>

<a href="/dir/script.aspx">...</a>

I tried this but it doesn't work:

var url = window.location.href;
$('#ulTopMenu a["'+url+'"*=href]').addClass("selected");

Probably wrong syntax. Anyone know the right way of doing it?

Thanks in advance

[A]
I do not know the answer to your question but is that selector syntax valid?
```
```
'#ulTopMenu a["http://www.foo.com"*=href]'
```
```
I'd imagine if such a thing is possible it'd be written as
```
```
'#ulTopMenu a[href*="http://www.foo.com"]'
```
```


q:
I'm using Parsley IoC in my current Flex project. So I'd like to embed the container configuration XML onto the result SWF.

How could I load embedded XML file into action script XML object?

[A] I think the problem is that sendmail (your process) is talking to the local sendmail daemon.   The local sendmail daemon thinks that because it is website.com, it should know how to deliver the email.  Unfortunately, the actual address in the to field does not exist on the web server and thus it dumps it in the "catchall" mail box.  You should talk to your ISP and have them update their sendmail configuration so that mail addressed to ...@website.com gets forward to the mail exchanger instead of being handled locally.


q:
Given an array of items, each of which has a value and cost, what's the best algorithm determine the items required to reach a minimum value at the minimum cost? eg:

Item: Value -> Cost
-------------------
A     20   -> 11
B     7    -> 5
C     1    -> 2

MinValue = 30
naive solution: A + B + C + C + C. Value: 30, Cost 22
best option: A + B + B.            Value: 34, Cost 21

Note that the overall value:cost ratio at the end is irrelevant (A + A would give you the best value for money, but A + B + B is a cheaper option which hits the minimum value).

[A]
This is the knapsack problem. (That is, the decision version of this problem is the same as the decision version of the knapsack problem, although the optimization version of the knapsack problem is usually stated differently.) It is NP-hard (which means no algorithm is known that is polynomial in the "size" -- number of bits -- in the input). But if your numbers are small (the largest "value" in the input, say; the costs don't matter), then there is a simple dynamic programming solution.
Let best[v] be the minimum cost to get a value of (exactly) v. Then you can calculate the values best[] for all v, by (initializing all best[v] to infinity and):
```
```
best[0] = 0
best[v] = min_(items i){cost[i] + best[v-value[i]]}
```
```
Then look at best[v] for values upto the minimum you want plus the largest value; the smallest of those will give you the cost.
If you want the actual items (and not just the minimum cost), you can either maintain some extra data, or just look through the array of best[]s and infer from it.


q:
I have a database of companies. My application receives data that references a company by name, but the name may not exactly match the value in the database. I need to match the incoming data to the company it refers to.

For instance, my database might contain a company with name "A. B. Widgets & Co Ltd." while my incoming data might reference "AB Widgets Limited", "A.B. Widgets and Co", or "A B Widgets".

Some words in the company name (A B Widgets) are more important for matching than others (Co, Ltd, Inc, etc). It's important to avoid false matches.

The number of companies is small enough that I can maintain a map of their names in memory, ie. I have the option of using Java rather than SQL to find the right name.

How would you do this in Java?

[A]
Your database may suport the use of Regular Expressions (regex) - see below for some tutorials in Java - here's the link to the MySQL documentation (as an example):
http://dev.mysql.com/doc/refman/5.0/en/regexp.html#operator_regexp
You would probably want to store in the database a fairly complex regular express statement for each company that encompassed the variations in spelling that you might anticipate - or the sub-elements of the company name that you would like to weight as being significant.
You can also use the regex library in Java
JDK 1.4.2
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
JDK 1.5.0
http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html
Using Regular Expressions in Java
http://www.regular-expressions.info/java.html
The Java Regex API Explained
http://www.sitepoint.com/article/java-regex-api-explained/
You might also want to see if your database supports Soundex capabilities (for example, see the following link to MySQL)
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_soundex


q:
I've always been one to simply use:

List<String> names = new ArrayList<>();

I use the interface as the type name for portability, so that when I ask questions such as this, I can rework my code.

When should LinkedList be used over ArrayList and vice-versa?

[A]
It's an efficiency question.
```
LinkedList
```
is fast for adding and deleting elements, but slow to access a specific element.
```
ArrayList
```
is fast for accessing a specific element but can be slow to add to either end, and especially slow to delete in the middle.
Array vs ArrayList vs LinkedList vs Vector
goes more in depth, as does
Linked List
.


q: I’ve built a custom Maven2 plug-in using Ant. I would like to call another maven plug-in in particular the Cargo Maven2 plug-in immediately after the custom Ant plug-in successfully completes. However, I do not want to attach the Cargo plug-in to another goal or phase. Is there a way to have them run consecutively without having to write a batch script? Is there away to have the Custom Ant plug-in call out to the Cargo plug-in?

[A]
The Ant script that the maven-ant-plugin executes is not really aware of Maven as such; this plugin is designed for backwards compatibility with custom Ant tasks. I cannot think of a clean way of doing what you want though there may be some kind of hack that allows you to do it.
It should also be possible to execute a second instance of Maven from inside Ant, which runs purely the Cargo goal, but in that case you might encounter problems with locked files and the like. The way to do it would be to just use an  tag in your Ant script and call the "mvn" executable with the appropriate goals as arguments.
The cleanest way is to simply bind the Cargo goal to a phase of the build, and have that run after Ant is finished. I do not see any disadvantage to that approach - you haven't really stated any specific reasons why you want to avoid it.


q:
I have an enumeration of delivery status codes.  And when I save delivery data to the database they are stored with a foreign key to a table containing the same data (i.e. the same delivery codes)

What is the best strategy for keeping an enumeration in synch with data in a database?

Do you just remember to add to the enumeration when a new code is added to the database?

Or load the data into a dictionary when the application starts? And use the dictionary instead of an enumeration? Though this means that I don't have a strongly typed representation of the data - which I definitely want.

Or something else?

The data is not very volatile but new codes do get added once every blue moon

Would appreciate any suggestions.

thanks

[A]
When I use a enumeration in the code, I usually store the formatted name as a varchar in the database rather than keep a table of the enumeration values in the database.  I realize that  this is not as normalized as one might like, but I believe it is better than trying to keep the database and my enumeration synched.  All that is needed is to format on insert/update and parse on select to reconstitute the value back into the enumeration.
I only do this when I believe that the enumeration is going to be fixed -- although, I too have made infrequent updates.  If I believe that it is likely that the data will be regularly updated, I won't use an enumeration and will have a separate table in the database with foreign key references.


q:
I want to do this, but haven't figured it quite out yet...

    $(document).ready(function() {
        $("a.whateverclass").click(function() {
            $("div.whateverclass").show();
            return false;
        });

Basically when a link with a certain class is clicked all divs with that class are shown. The classes can be any class. And I won't know the name(s) of the classes in the application.js file so I need to match equal classes.


q:
How to query to get count of matching words in a field, specifically in MySQL.
simply i need to get how many times a "search terms"appear in the field value.

for example, the value is "one two one onetwo" so when i search for word "one" it should give me 3

is it possible? because currently i just extract the value out of database and do the counting with server side language.

Thank you

[A]
Are you looking to find a query that, given a list of words, returns the number of matching words in a database field?
eg:
Database table has
```
ID    Terms
1     cat, dog, bird, horse
```
then running a check on the words "cat, horse" returns 2?
If so, I suggest you do your checking
outside
of SQL, in whatever language you're doing the rest of your processing in. SQL isn't designed for this level of processing.
You could
possibly
use a stored procedure to cycle through what words you're needing to check, but I doubt it would be efficient or highly effective.
Of course, if I'm misinterpreting your request, I could be all wrong =)


q:
One of the core fields present on several of my app's major database tables needs to be changed from varchar(5) to varchar(8). The list of stored procedures that depend on these tables is extremely long, not to mention the changes that would have to be made in my Data Access Layer (ASP.NET 2.0 DataSet with TableAdapters).

Is there any way to automatically (and safely) change the Type of the all-important field and have the changes propagate to all the stored procedures / Data Access Layer calls that depend on it?

I'm using a SQL Server 2005 database.

[A]
You might be interested in this
essay
by Scott Ambler on Database Refactoring.  I think he also has a book on it.  The basic idea, I believe, will be to introduce a new column with the proper width, copy existing data to the new column, implement a trigger to synchronize any new inserts/updates, migrate your SP/DAL to use the new column, then remove the old column when you are completely done.  All new code uses the new column, obviously.  I don't know of any automated way to do the updates to your SP/DAL, unfortunately.


q:
I'm getting the following error when trying to compile C++ projects using intel compiler version 10.0.025 on vista business edition (sp1) in vs2008:

unable to obtain mapped memory (see pch_diag.txt)

There is no such file as pch_diag, so that's a bit disheartening.

If I try to just use the microsoft compiler, all of my calls to intel's integrated performance primitives (ipp) are met with an access error into the program files directory where the ipp is stored.

Any ideas?

Thanks!

[A]
It sounds like you are running the compiler as a standard user (good for you!), and the errors you get with the Microsoft compiler seem to point towards a permissions problem. You should use Windows Explorer to check the security properties for the directory you mentioned, if you haven't already. If the problem isn't apparent from the security properties page, here are some tools that may be useful for debugging permissions problems:
LUA Buglight
: a tool for finding the causes of "LUA" (Limited User Access) bugs
Sysinternals Process Monitor
: a tool for monitoring filesystem and registry access in real-time. You can filter out all processes other than the compiler, then look for "ACCESS DENIED" errors.


q:
Using jQuery, how do you match elements that are prior to the current element in the DOM tree? Using prevAll() only matches previous siblings.

eg:

<table>
    <tr>
        <td class="findme">find this one</td>
    </tr>
    <tr>
        <td><a href="#" class="myLinks">find the previous .findme</a></td>
    </tr>
    <tr>
        <td class="findme">don't find this one</td>
    </tr>
</table>

In my specific case, I'll be searching for the first .findme element prior to the link clicked.

[A]
Presumably you are doing this inside an onclick handler so you have access to the element that was clicked.  What I would do is do a prevAll to see if it is at the same level.  If not, then I would do a parent().prevAll() to get the previous siblings of the parent element, then iterate through those backwards, checking their contents for the desired element.  Continue going up the DOM tree until you find what you want or hit the root of the DOM.  This a general algorithm.
If you know that it is inside a table, then you can simply get the row containing the element clicked and iterate backwards through the rows of the table from that row until you find one that contains the element desired.
I don't think there is a way to do it in one (chained) statement.


q:
How would you get a reference to an executing class several stack frames above the current one?  For example, if you have:

Class a {
    foo() {
        new b().bar();
    }
}

Class b {
    bar() {
        ...
    }
}

Is there a way to get the value that would be retrieved by using 'this' in foo() while the thread is executing bar()?

[A]
```
this
```
is always a reference to the current instance of the object. So any usage of
```
this
```
in
```
foo()
```
will return an instance of Class A.