q:
Any python libs for parsing Bind zone files?
Basically something that will aid in adding/removing zones and records.
This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution.

[A]
See answer above about bicop.
As an aside, the Python Package Index at
http://pypi.python.org/pypi
is a great place to look for Python packages.
EDIT
: The below may still be helpful to someone trying to figure out simple parsing, but bicop is apparently an existing solution.
If someone has modified the config by hand, and you don't want to overwrite it, does that imply that you wish to insert/remove lines from an existing config, leaving all comments etc intact?  That does prevent parsing then re-outputting the config, but that's a positive as well -- you don't need to fully parse the file to accomplish your goal.
To add a record, you might try a simple approach like
```
```
# define zone_you_care_about and line_you_wish_to_insert first, then:
for line in bindfile.read():
    out.write(line + '\n')
    if ('zone "%s" in' % zone_you_care_about) in line:
        out.write(line_you_wish_to_insert)
```
```
Similar code works for removing a line:
```
```
# define zone_you_care_about and relevant_text_to_remove, then:
for line in bindfile.read():
    if not relevant_text_to_remove in line:
        out.write(line + '\n')
```
```
You may get as far as you need with simple snippets of code like this.


q:
this is a question that when programming I always wonder: What to use when we are writing code:

var myFiles = Directory.GetFiles(fullPath);

or

string[] myFiles = Directory.GetFiles(fullPath);

var is new and is a Implicitly Typed Local Variables, so we can only use locally and it has rules like can't be null, etc., but I wonder if we get any advantage of using it "normally".

The "normally" part says, not in Anonymous Types, Object and Collection Initializers and Query Expressions where that was the intent to use the var anonymous object, so what I mean is... just like the example above.

what are your thoughts?

[A]
You'll get a huge variety of opinions on this one - from "use var everywhere" to "only use var with anonymous types, where you basically have to." I like
Eric Lippert's take on it
:
All code is an abstraction. Is what
  the code is “really” doing is
  manipulating data? No. Numbers? Bits?
  No. Voltages? No. Electrons? Yes, but
  understanding the code at the level of
  electrons is a bad idea! The art of
  coding is figuring out what the right
  level of abstraction is for the
  audience.
In a high level language there is
  always this tension between WHAT the
  code does (semantically) and HOW the
  code accomplishes it. Maintenance
  programmers need to understand both
  the what and the how if they’re going
  to be successful in making changes.
The whole point of LINQ is that it
  massively de-emphasizes the "how" and
  massively emphasizes the "what". By
  using a query comprehension, the
  programmer is saying to the future
  audience "I believe that you should
  neither know nor care exactly how this
  result set is being computed, but you
  should care very much about what the
  semantics of the resulting set are."
  They make the code closer to the
  business process being implemented and
  farther from the bits and electrons
  that make it go.
Implicitly typed locals are just one
  small way in which you can deemphasize
  the how and thereby emphasize the
  what. Whether that is the right thing
  to do in a particular case is a
  judgment call. So I tell people that
  if knowledge of the type is relevant
  and its choice is crucial to the
  continued operation of the method,
  then do not use implicit typing.
  Explicit typing says "I am telling you
  how this works for a reason, pay
  attention". Implicit typing says "it
  doesn’t matter a bit whether this
  thing is a List or a
  Customer[], what matters is that it is
  a collection of customers."
Personally I don't
tend
to use it if the type isn't reasonably obvious - where I include LINQ queries as being "reasonably obvious". I wouldn't do it for
```
Directory.GetFiles
```
for instance, as it's not really obvious that that returns a
```
string[]
```
instead of (say) a
```
FileInfo[]
```
(or something else entirely) - and that makes a big difference to what you do later.
If there's a constructor call on the right hand side of the assignment operator, I'm much more likely to go with
```
var
```
: it's blatantly obvious what the type will be. This is particularly handy with complex generic types, e.g.
```
Dictionary<string,List<int>>
```
.

s: huggingface

c: devops

d: intermediate


q:
I'm thinking of an application that would try to prove the "Six degrees of separation" theory with a set of users that are part of a social network.

I would have those elements:

A couple of users for which I'd like to prove the six degrees theory

For each user, I know the list of friends in the social network

Which is the best algorithm to see if the two users are connected, with which degree and show the eventual steps in the connection?

[A]
Some additional background material:
To solve this problem generally, you'd want to avoid web scraping and other ad-hoc techniques that are specific to one social network.  Instead, you will probably want to look into
XHTML Friends Network (XFN)
which is a way to use the rel="" attribute of a hyperlink to indicate the relationship between the target of that hyperlink and you. There is also a competing standard called
FOAF
which uses
RDF
.
These
microformats
have been around for a while, but support for them has grown a great deal just recently.  StackOverflow uses "me" in the link on your profile page.  WordPress blogs provide an easy way in the editing interface for the blogroll to add these tags.  Many social sites use these in links between friends to indicate relationships.
Because of this, Google has gotten interested in this, and is starting to mine this data.  They have a
Social Graph API
that can mine both XFN and FOAF data to do exactly some of the things you want to do. I suggest you start there.  The nice thing about Google's API is since they are mining this all over the web, you can widen out your search beyond the specific social network you had in mind.


q:
So, I'm writing a Cocoa application that needs to be able to display web content using Opera's rendering engine. This is for a feature, not because I'm an Opera fanboi (I'm not). All I've been able to find on the subject is this press release about Adobe's use of the Opera engine.

Has anyone done this? What's the API like? Are they going to want royalties, payments, an NDA, etc?

Edited to add: This is for a cross-engine web debugging tool. I'm going to be using this alongside WebKit.

[A]
Adobe has gone to Opera and licensed their software for some (exorbitant?) amount of money. What that probably means is Adobe has access to the library and SDK documentation so they can embed it in their applications. Opera doesn't give its engine away for free as in beer or freedom. It appears there are several B2B opportunities and I'm sure for the right amount of money you can get access to it. More information can be found out at
http://www.opera.com/b2b/
.


q:
Unit testing sounds great to me, but I'm not sure I should spend any time really learning it unless I can convince others that is has significant value.  I have to convince the other programmers and, more importantly, the bean-counters in management, that all the extra time spent learning the testing framework, writing tests, keeping them updated, etc.. will pay for itself, and then some.

What proof is there?  Has anyone actually developed the same software with two separate teams, one using unit testing and the other not, and compared the results?  I doubt it.  Am I just supposed to justify it with, "Look it up on the Internet, everybody's talking about it, so it must be the right thing to do"?

Where is the hard evidence that will convince the laymen that unit testing is worth the effort?

[A]
There are statistics that prove that fixing a bug found in the unit/integration test costs many times less than fixing once it's on the live system (they are based on monitoring thousand of real life projects).
Edit
: for example, as pointed out, the book "
Code Complete
" reports on such studies (paragraph 20.3, "Relative Effectiveness of Quality Techniques"). But there is also private research in the consulting field that proves that as well.


q:
A string will be made up of certain symbols (ax,bx,dx,c,acc for example) and numbers.

ex:
ax 5 5
dx 3 acc
c ax bx

I want to replace one or all of the symbols (randomly) with another symbol of the same set. ie, replace one of {ax,bx,dx,c,acc} with one of {ax,bx,dx,c,acc}.

replacement example:
acc 5 5
dx 3 acc
c ax bx
or
c 5 5
dx 3 acc
c ax ax

Is there a way to do this with regexes? In Java? If so, which methods should I use?

[A]
To answer the first question: no.
Since you are doing a random replace, regex will not help you, nothing about regex is random. * Since your strings are in an array, you don't need to find them with any pattern matching, so again regex isn't necessary.
**Edit: the question has been edited so it no longer says the strings are in an array. In this case, assuming they are all in one big string, you might build a regex to find the parts you want to replace, as shown in other answers.*


q:
I have several strings in the rough form:

[some text] [some number] [some more text]

I want to extract the text in [some number] using the Java Regex classes.

I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].

EDIT: I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].

[A]
Full example:
```
```
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
    // create matcher for pattern p and given string
    Matcher m = p.matcher("Testing123Testing");

    // if an occurrence if a pattern was found in a given string...
    if (m.find()) {
        // ...then you can use group() methods.
        System.out.println(m.group(0)); // whole matched expression
        System.out.println(m.group(1)); // first expression from round brackets (Testing)
        System.out.println(m.group(2)); // second one (123)
        System.out.println(m.group(3)); // third one (Testing)
    }
}
```
```
Since you're looking for the first number, you can use such regexp:
```
```
^\D+(\d+).*
```
```
and
```
m.group(1)
```
will return you the first number. Note that signed numbers can contain a minus sign:
```
```
^\D+(-?\d+).*
```
```


q:
i am trying to compile this very simple piece of code

class myList
{
public:
    std::vector<std::string> vec;
    class Items
    {
    public:
        void Add(std::string str)
        {
            myList::vec.push_back(str);
        };
    }items;
};

int main()
{
    myList newList;
    newList.items.Add("A");
}

what can i do to make this work without creating more objects that needed or overcomplicating stuff...

[A]
Add a couple of constructors and a pointer to the parent class.
```
```
#include <string>
#include <vector>
class myList
{
public:
    std::vector<std::string> vec;
    myList(): items(this) {} // Added
    class Items
    {
    public:
        Items(myList *ml): self(ml) {}  // Added
        void Add(std::string str)
        {
                self->vec.push_back(str); // Changed
        };
        myList *self; //Added
    }items;
};

int main()
{
    myList newList;
    newList.items.Add("A");
}
```
```
You need the myList() constructor, so it registers instances of itself with the instance of the inner class member variable. Then you need the Items constructor to store the pointer to the outer myList class instance. Finally in the Add method, you need to reference vec in the stored myList instance.
As Catskul points out, the Item constructor mustn't actually do anything with the myList pointer it receives. I'd also like to say that though this answer is closer to the original intent, steveth45's answer is closer to what you would want to do in a real program.


q:
It's possible to write Markdown content with invalid syntax. Invalid means that the BlueCloth library fails to parse the content and throws an exception. The markdown helper in Rails doesn't catch any BlueCloth exceptions and because of that the complete page fails to render (500 Server Error page is rendered instead).

In my case, users are allowed to write Markdown content and save it to the database. If someone used invalid syntax, all successive rendering attempts of that content fail (Status Code 500 - Internal Server Error).

How do you get around this issue? Is it possible to validate the Markdown syntax at the Model-level before saving to the database?

[A]
You should write your own validation method in which you would initialize BlueCloth object, and try to call
```
to_html
```
method catching any exception. If you catch an exception, validation fails, otherwise it should be ok.
In your model:
```
```
protected:

def validate
  bc = BlueCloth.new(your_markdown_string_attribute)
  begin
    bc.to_html
  rescue
    errors.add(:your_markdown_string_attribute, 'has invalid markdown syntax')
  end
end
```
```


q:
What is the most concise and efficient way to find out if a JavaScript array contains a value?

This is the only way I know to do it:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

Is there a better and more concise way to accomplish this?

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.

[A]
If you are using JavaScript 1.6 or later (Firefox 1.5 or later) you can use
Array.indexOf
.  Otherwise, I think you are going to end up with something similar to your original code.


q:
I have a legacy DLL written in C that contains a function that returns a string, and I need to access this function from Delphi. The only info I have about the DLL is the VB declare for accessing the function:

Public Declare Function DecryptStr Lib "strlib" (Str As String) As String

I've tried the following without success:

Declaration:

function DecryptStr(s: PChar): PChar; cdecl; external 'strlib.dll';

Usage:

var
  p1, p2 : pchar;
begin
  GetMem( p1, 255 );
  StrPCopy( p2, 'some string to decrypt' );
  p1 := DecryptStr( p2 );
end;

This consistently crashes the DLL with an Access Violation. I'm at a loss.

Any suggestions ?

[A]
I'm guessing here, but are you sure it's cdecl? If the VB declare isn't mentioning it, I'd assume it's in fact a STDCALL function (STDCALL is quite common on Windows, as almost all of its native API uses it). Calling a function of one calling convention as if it were of another calling convention can really mess up the stack, usually leading to a crash.
Also, be sure to check whether the string is ANSI (LPSTR/LPCSTR) or UNICODE (LPWSTR/LPCWSTR). I don't know VB or Delphi, so I don't know what each one uses by default.


q: I know that python has a len() function that is used to determine the size of a string, but I was wondering why it's not a method of the string object?

[A]
```
```
met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.
```
```


q:
I have a radio button on my Windows Form. How can I determine if the CheckChanged event occurred due to a user clicking or selecting the radio button vs programatically setting the event with

this.radioButtonAdd.Checked = true;

I would like some code to take a different action depending on if the user clicked the button or I raised the event myself.

Or maybe the better question is how do I handle the event when a user clicks vs when the state is changed in my code.

[A]
If there is a built-in method, then I am not aware of it.
One way to handle it is by setting a global flag while the code is making changes that tells the event handler.  For example, the code making the changes could look something like the following:
```
```
savedFlag = modifyingProgrammatically;
modifyingProgrammatically = true;
this.radioButtonAdd.Checked = true;
modifingProgrammatically = savedFlag;
```
```
Within your event handler:
```
```
if(modifyingProgramatically) {
    // The event was raised by an assignment within the code.
} else {
    // The event was raised by a user action.
}
```
```


q: I would like to assign a drive letter to a GMail drive so that I could script some output to it.  Are they any hacks to get this to work?

[A]
GMail Drive no longer works (well) -- Google put rate limits into Gmail to prevent this kind of (ab)use of Gmail.  It's like being attached to a hard drive over a bad satellite connection to Rwanda*.
You might look into Amazon's S3, which is a cheap web-hosted data storage service; then ask this question again from an S3 perspective.
* Incidentally, that's what I deal with at work on a weekly basis.


q:
I normally use the following idiom to check if a String can be converted to an integer.

public boolean isInteger( String input ) {
    try {
        Integer.parseInt( input );
        return true;
    }
    catch( Exception e ) {
        return false;
    }
}

Is it just me, or does this seem a bit hackish?  What's a better way?

See my answer (with benchmarks, based on the earlier answer by CodingWithSpike) to see why I've reversed my position and accepted Jonas Klemming's answer to this problem.  I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.

[A]
How about:
```
```
return Pattern.matches("-?\\d+", input);
```
```


q:
I'm experimenting with the NavBar sample project for iPhone.  When I tap on one of the rows in the table in the default view a new view slides in (so far so good).  I want to remove the UINavigationBar bar at the top of the new view that slides in.  How can I do this?

EDIT:  I meant "UINavigationBar".  Thanks to everyone who responded!

[A]
```
```
[[UIApplication sharedApplication]setHidesStatusBar:YES];
```
```


q:
I'm trying to perform a simple LINQ query on the Columns property of a DataTable:

from c in myDataTable.Columns.AsQueryable()
    select c.ColumnName

However, what I get is this:

Could not find an implementation of the query pattern for source type 'System.Linq.IQueryable'. 'Select' not found.  Consider explicitly specifying the type of the range variable 'c'.

How can I get the DataColumnCollection to play nice with LINQ?

[A]
How about:
```
```
var x = from c in dt.Columns.Cast<DataColumn>()
        select c.ColumnName;
```
```


q:
Any python libs for parsing apache config files or if not python anyone aware of such thing in other languages (perl, php, java, c#)?
As i'll be able to rewrite them in python.

[A]
No Python libraries exist that I know of, but here's a perl one:
http://packages.debian.org/sid/libapache-configfile-perl
```
```
Package: libapache-configfile-perl
Priority: optional
Section: interpreters
Installed-Size: 124
Maintainer: Michael Alan Dorman
Version: 1.18-1
Depends: perl (>= 5.6.0-16)
Description: Parse an Apache style httpd.conf configuration file

This module parses the Apache httpd.conf, or any
compatible config file, and provides methods for
you to access the values from the config file.
```
```
If you do rewrite it in Python, please update your post to mention the name of your package on PyPI! :)


q:
I am working on an application that uses several large canvas controls (several thousand pixels across), layered on top of each other.  The canvas controls themselves are completely invisible, but each contains a number of controls, mainly images.

My question is, is there a recommended maximum size for a canvas, or is it purely a memory issue?  And also, are we better off setting the Canvas size to (0, 0) and making use of the fact that we can happily render controls outside of the bounds of the canvas?

Thanks,

G

[A]
From my understanding of the innards of
```
Canvas
```
, it should need no additional memory for being bigger.
The first thing that comes to my mind on having a non-zero sized
```
Canvas
```
is that it allows one to put items on it relatively to any of the four corners, which helps when e.g. resizing the container.


q:
I'm looking for an algorithm that places tick marks on an axis, given a range to display, a width to display it in, and a function to measure a string width for a tick mark.

For example, given that I need to display between 1e-6 and 5e-6 and a width to display in pixels, the algorithm would determine that I should put tickmarks (for example) at 1e-6, 2e-6, 3e-6, 4e-6, and 5e-6.  Given a smaller width, it might decide that the optimal placement is only at the even positions, i.e. 2e-6 and 4e-6 (since putting more tickmarks would cause them to overlap).

A smart algorithm would give preference to tickmarks at multiples of 10, 5, and 2.  Also, a smart algorithm would be symmetric around zero.

[A]
Take the longest of the segments about zero (or the whole graph, if zero is not in the range) - for example, if you have something on the range [-5, 1], take [-5,0].
Figure out approximately how long this segment will be, in ticks. This is just dividing the length by the width of a tick. So suppose the method says that we can put 11 ticks in from -5 to 0. This is our upper bound. For the shorter side, we'll just mirror the result on the longer side.
Now try to put in as many (up to 11) ticks in, such that the marker for each tick in the form i*10*10^n, i*5*10^n, i*2*10^n, where n is an integer, and i is the index of the tick. Now it's an optimization problem - we want to maximize the number of ticks we can put in, while at the same time minimizing the distance between the last tick and the end of the result. So assign a score for getting as many ticks as we can, less than our upper bound, and assign a score to getting the last tick close to n - you'll have to experiment here.
In the above example, try n = 1. We get 1 tick (at i=0). n = 2 gives us 1 tick, and we're further from the lower bound, so we know that we have to go the other way. n = 0 gives us 6 ticks, at each integer point point. n = -1 gives us 12 ticks (0, -0.5, ..., -5.0). n = -2 gives us 24 ticks, and so on. The scoring algorithm will give them each a score - higher means a better method.
Do this again for the i * 5 * 10^n, and i*2*10^n, and take the one with the best score.
(as an example scoring algorithm, say that the score is the distance to the last tick times the maximum number of ticks minus the number needed. This will likely be bad, but it'll serve as a decent starting point).


q:
In my django application I am using a template to construct email body, one of the parameters is url, note there are two parametes separated by ampersand in the url.

t = loader.get_template("sometemplate")
c = Context({
   'foo': 'bar',
   'url': 'http://127.0.0.1/test?a=1&b=2',
})
print t.render(c)

After rendering it produces: http://127.0.0.1/test?a=1&amp;amp;b=2

Note the ampersand is HTML encoded as "&amp;". One way around the problem is to pass each parameter separately to my template and construct the url in the template, however I'd like to avoid doing that.

Is there a way to disable HTML encoding of context parameters or at the very least avoid encoding of ampersands?

[A]
To turn it off for a single variable, use
```
mark_safe
```
:
```
```
from django.utils.safestring import mark_safe

t = loader.get_template("sometemplate")
c = Context({
   'foo': 'bar',
   'url': mark_safe('http://127.0.0.1/test?a=1&b=2'),
})
print t.render(c)
```
```
Alternatively, to totally turn autoescaping off from your Python code,
use the
```
autoescape
```
argument when initialising a
```
Context
```
:
```
```
c = Context({
   'foo': 'bar',
   'url': 'http://127.0.0.1/test?a=1&b=2',
}, autoescape=False)
```
```
The
How to turn [Automatic HTML escaping] off
section of the documentation covers some of the in-template options if you'd rather do it there.


q:
Doing like so:

Shell ("C:\Program Files\Internet Explorer\iexplore.exe -embedding http://www.websiteurl.com")

Doesn't work how I need it as I essentially need it to be able to redirect and prompt a user to download a file.  Any ideas?

[A]
There are a couple of things you could do.
Use an external program like
```
wget
```
to get the file instead of IE.  You can get wget for free at
http://www.cygwin.com
with the cygnus tools.  It's GPL, so just watch out if you have a commercial product.
Write a little .NET program that uses the HttpWebRequest class to get the file and shell out to that program instead of IE.  I don't think you're going to have a lot of luck shelling out to IE itself.  Sounds like a, to paraphrase Steve Jobs, "bag of hurt".


q:
I'm constructing a method to take in an ArrayList(presumably full of objects) and then list all the fields(and their values) for each object in the ArrayList.

Currently my code is as follows:

public static void ListArrayListMembers(ArrayList list)
    {
        foreach (Object obj in list)
        {
            Type type = obj.GetType();
            string field = type.GetFields().ToString();
            Console.WriteLine(field);

        }
    }

Of course, I understand the immediate issue with this code: if it worked it'd only print one field per object in the ArrayList. I'll fix this later - right now I'm just curious how to get all of the public fields associated with an object.

[A]
```
```
foreach (Object obj in list) {
    Type type = obj.GetType();

    foreach (var f in type.GetFields().Where(f => f.IsPublic)) {
        Console.WriteLine(
            String.Format("Name: {0} Value: {1}", f.Name, f.GetValue(obj));
    }
}
```
```
Note that this code requires .NET 3.5 to work ;-)


q:
At my workplace, we tend to use  iostream, string, vector, map, and the odd algorithm or two.  We haven't actually found many situations where template techniques were a best solution to a problem.

What I am looking for here are ideas, and optionally sample code that shows how you used a template technique to create a new solution to a problem that you encountered in real life.

As a bribe, expect an up vote for your answer.

[A]
General info on templates:
Templates are useful anytime you need to use the same code but operating on different data types, where the types are known at compile time.   And also when you have any kind of container object.
A very common usage is for just about every type of data structure.  For example: Singly linked lists, doubly linked lists, trees, tries, hashtables, ...
Another very common usage is for sorting algorithms.
One of the main advantages of using templates is that you can remove code duplication.  Code duplication is one of the biggest things you should avoid when programming.
You could implement a function Max as both a macro or a template, but the template implementation would be type safe and therefore better.
And now onto the cool stuff:
Also see
template metaprogramming
, which is a way of pre-evaluating code at compile-time rather than at run-time.  Template metaprogramming has only immutable variables, and therefore its variables cannot change.  Because of this template metaprogramming can be seen as a type of functional programming.
Check out this example of template metaprogramming from Wikipedia.  It shows how templates can be used to
execute code at compile time
.  Therefore at runtime you have a pre-calculated constant.
```
```
template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}
```
```


q: I'm looking for a way to configure the color used for line numbering (as in: :set nu) in Vim.  The default on most platforms seems to be yellow (which is also used for some highlighted tokens).  I would like to color the line numbers a dim gray; somewhere in the vicinity of #555.  I'm not picky though, any subdued color would be acceptable.

[A]
Try:
```
```
help hl-LineNr
```
```
I found this through:
```
```
help 'number'
```
```
which is the way to get help on the
```
'number'
```
option, instead of the
```
:number
```
command.
To actually change the displayed colour:
```
```
:highlight LineNr ctermfg=grey
```
```
This would change the foreground colour for LineNr on a character terminal to grey. If you are using gVim, you can:
```
```
:highlight LineNr guifg=#050505
```
```


q:
I'm currently displaying a UIViewController like this:

[[self navigationController] presentModalViewController:modalViewController animated:YES];

and hiding it like this:

[self.navigationController dismissModalViewControllerAnimated:YES];

The animation is "slide up from the bottom"... then slide back down.  How can I change the animation style?  Can I made it fade in/out?

Cheers!

[A]
Marcus Zarra posted a great solution to this on the SDK mailing list:
```
```
UIViewController *controller = [[[MyViewController alloc] init] autorelease];
UIViewAnimationTransition trans = UIViewAnimationTransitionCurlUp;
[UIView beginAnimations: nil context: nil];
[UIView setAnimationTransition: trans forView: [self window] cache: YES];
[navController presentModalViewController: controller animated: NO];
[UIView commitAnimations];
```
```
There are transitions for flipping and page-curling. If you are set on fading, can try adjusting your new view's alpha:
```
```
UIViewController *controller = [[[MyViewController alloc] init] autorelease];
controller.view.alpha = 0.0;
[navController presentModalViewController: controller animated: NO];
[UIView beginAnimations: nil context: nil];
controller.view.alpha = 1.0;
[UIView commitAnimations];
```
```
However, what you probably want is a crossfade, or at least a fade-over. When the UINavigationController switches to a new view, it removes the old one. For this effect, you're probably better off just adding a new view to your existing UIViewController and fading its alpha in over time.
Note: If you are not in your app delegate [self window] will not work. Use self.view.window , thanks to user412500's post for pointing this out.


q:
The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data:

if table t has a row exists that has key X:
    update t set mystuff... where mykey=X
else
    insert into t mystuff...

Since Oracle doesn't have a specific UPSERT statement, what's the best way to do this?

[A]
The
MERGE statement
merges data between two tables.  Using DUAL
allows us to use this command.  Note that this is not protected against concurrent access.
```
```
create or replace
procedure ups(xa number)
as
begin
    merge into mergetest m using dual on (a = xa)
         when not matched then insert (a,b) values (xa,1)
             when matched then update set b = b+1;
end ups;
/
drop table mergetest;
create table mergetest(a number, b number);
call ups(10);
call ups(10);
call ups(20);
select * from mergetest;

A                      B
---------------------- ----------------------
10                     2
20                     1
```
```


q:
I am trying to call a setTimeout from within a setInterval callback:

function callback()
{
   //assign myVar
   var myVar = document.getElementById("givenID");
   //...
   //now wait 2 secs then call some code that uses myVAr
   setTimeout("myVar.innerHTML = 'TEST'", 2000);
}

setInterval("callback();", 10000);

setInterval works as expected but setTimeout call is failing. I guess the problem is related to the fact that I am referencing a variable (myVar) that's not in scope.

What's the best way to solve this?

[A]
Run it in Firefox and check Tools | Error Console.  if setTimeout fails it may tell you why there.
Also, try replacing
```
"someFunction();"
```
with
```
"alert('hi')"
```
(no semicolon) and see if that works.  If so, the problem is narrowed down significantly.


q:
When I connect to a MySQL database using PDO, the way I need to connect is:

$pdoConnection = new PDO("mysql:host=hostname;dbname=databasename",user,password);

But, for PostgreSQL, the DSN is more standard (IMO):

$pdoConnection = new PDO("pgsql:host=hostname;dbname=databasename;user=username;password=thepassword");

Is there any reason why MySQL cannot use a single string?  Or is this just because of the versions I am using (PHP 5.2, MySQL 5.0, PostgreSQL 8.1)?

[A]
As the person that implemented both, I can tell you that the reason is that by passing the string through as-is to postgres (and ODBC) the PDO driver code for those databases does not need to be updated as the underlying library adds new features.
Since MySQL does not have its own connection string parsing code, we invented a mechanism for passing data in to the underlying MySQL function calls, which have a very specific API with fixed parameters.
No accident; it's very deliberate.


q:
For the sake of simplicity:

There is a permission based system in place with different kinds of user levels and actions (think: UNIX file system permissions)

What would be the best approach to visualize this in UML?

[A]
I like to think of a file system object has having a number of standard methods, each of which has an associated permission.
There are 9 methods/permissions that of usually of interest: the combinations of (User, Group, Other) * (Read, Write, Execute).  Additionally, there are options like Sticky and SetUID.
A file system object is associated with one user and one group. A user is associated with any number of groups.
The current user is associated with any number of groups.
The above is pretty standard class diagram stuff.  File system objects, users, groups, associations.  And the file system objects have a pile of attributes and the 9 canonical methods.
The constraint on what's allowed doesn't have a tidy diagram.  It's a set of rules expressions.  The first is which permission set to use (user, group or other) and then which permission in the set (read, write or execute).
You could, I suppose, define a class of users with some set of concrete objects (Unix has user, group, other), and a class of operations with some set of concrete objects (Unix has read, write, execute).  You can then define permissions with two associations: one to user class and one to operation class.
I think it's easier to just list the complete set methods that to fussily diagram the combinations user class instances and operation class instances.


q:
Is there a better way to do this?

string[] s = {"zero", "one", "two", "three", "four", "five"};

var x =
s
.Select((a,i) => new {Value = a, Index = i})
.Where(b => b.Value.StartsWith("t"))
.Select(c => c.Index);

i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria.

[A]
Seems fine to me. You might save a couple characters by changing the select to:
```
```
.Select((Value, Index) => new {Value, Index})
```
```


q:
Is possible to insert a line break where the cursor is in Vim without entering into insert mode? Here's an example ([x] means cursor is on x):

if (some_condition) {[ ]return; }

Occasionally, I might want to enter some more code. So I'd press i to get into insert mode, press Enter to insert the line break and then delete the extra space. Next, I'd enter normal mode and position the cursor before the closing brace and then do the same thing to get it on its own line.

I've been doing this a while, but there's surely a better way to do it?

[A]
For the example you've given, you could use
r
Enter
to replace a single character (the space) with Enter. Then,
f
space
.
to move forward to the next space and repeat the last command.
Depending on your autoindent settings, the above may or may not indent the return statement properly. If not, then use
s
Enter
Tab
Esc
instead to replace the space with a newline, indent the line, and exit insert mode. You would have to replace the second space with a different command so you couldn't use '.' in this case.


q:
Can someone explain this in a practical way?  Sample represents usage for one, low-traffic Rails site using Nginx and 3 Mongrel clusters.  I ask because I am aiming to learn about page caching, wondering if these figures have significant meaning to that process.  Thank you.  Great site!

me@vps:~$ free -m
                   total       used       free     shared    buffers     cached
Mem:           512        506            6             0          15           103
-/+ buffers/cache:       387        124
Swap:         1023        113        910

[A]
by my reading of this, you have used almost all your memory, have 6 M free, and are going into about 10% of your swap. A more useful tools is to use top or perhaps ps to see how much each of your individual mongrels are using in RAM. Because you're going into swap, you're probably getting more slowdowns. you might find having only 2 mongrels rather than 3 might actually respond faster because it likely wouldn't go into swap memory.
Page caching will for sure help a tonne on response time, so if your pages are cachable (eg, they don't have content that is unique to the individual user) I would say for sure check it out


q:
I have a local Git repository I've been developing under for a few days: it has eighteen commits so far. Tonight, I created a private Github repository I was hoping to push it to; however, when I did so, it only ended up pushing eight of the eighteen commits to Github. I deleted the Github repo and retried, with the same result.

Any thoughts on why this might be happening? I've done this procedure before without a few times successfully, so I'm a bit stumped.

Update: There is, and has always been, only the master branch in this repo. Just to address a few of the posted answers...

[A]
I suppose the first thing I would do would be to run
```
git fsck
```
on your local repository to make sure that it is all in good order.
I've never seen this problem before, and I can't think of what might be wrong.


q:
I have written this generator code but it returns 'can't convert nil into String' when I call m.directory inside the manifest. Anyone know what had happened?

class AuthGenerator < Rails::Generator::NamedBase
  attr_reader :user_class_name
  def initialize(runtime_args, runtime_options={})
    @user_class_name="User"
    @controller_class_name="AccountController"
    @user_class_file_name="#{@user_class_name}.rb"
    @controller_class_file_name="#{@controller_class_name}.rb"
  end

  def manifest
    record do |m|
      m.class_collisions @controller_class_name, @user_class

      puts @user_class_name
      m.directory File.join('app/models', @user_class_name)

    end
  end

end

[A]
Where is it choking?  Please post the full error.  You can see the source of the
```
directory
```
method
here
.
Plus, you probably just want
```
```
m.directory File.join('app/models')
```
```
Having an app/models/user directory for your generated code is not standard -- unless you're intending namespacing, which it doesn't look like.


q:
Many languages have a facility to check to see if an Object is of a certain type (including parent subclasses), implemented with 'is' and used like this:

if(obj is MyType)

Or slightly more tediously you can in other languages check by using the 'as' keyword to do a soft typecast and seeing if the result null.

I haven't used Java in years and I'm getting back up to speed on it but surely Java has a way to easily do this without delving deep into the Reflection APIs?

Thanks in advance for answers.  I have searched both here and other places but the keywords involved are so generic that even though I'm sure this has a simple answer, googling for it is hard.

[A]
```
```
if (objectReference instanceof type){
    //Your code goes here
}
```
```
More info
here
.


q: I am working with a peripheral device that needs to be communicated through serial.  I can send it commands using HyperTerminal, but now I need to write programs that will let me do it without HyperTerminal.  Can somebody point me to a website and/or show me a sample hello world program to get me started?  I have searched through many sites which give me uncompilable/ancient VC6 code.

[A]
In order to interface with the serial port, you open a file with one of the special filenames "COM1" through "COM9".  For serial ports with higher numbers, the special filename begins with \\?\, which in C/C++ code must be escaped as "\\\\?\\COM10", etc.
http://msdn.microsoft.com/en-us/library/ms810467.aspx
has a really good tutorial on using the serial port.  Note that you should use the Windows file I/O functions such as
```
CreateFile()
```
,
```
ReadFile()
```
, and
```
WriteFile()
```
.  I'm not sure if it will work to use standard I/O functions such as
```
fopen()
```
,
```
fread()
```
, and
```
fwrite()
```
.


q: What solutions do you have in place for handling bandwidth billing for your vhosts on a shared environment in apache?  If you are using log parsing, does your solution scale well when the logs become very very large?  Anyone using any sort of module out there for this?

[A]
Although we use IIS rather than apache we do use log file analysis for bandwidth billing (and bandwidth profiling / analysis). We use a custom application to load data collected in the log files in one hour increments, and act upon any required notifications or bandwidth overuse.
The log file loader runs as a low priority process, so as not to interupt operation of the server. Even on high usage servers with a large number of sites, processing takes less than 15 minutes, so we don't see scalability as a problem with this methodology.
There may be better ways of doing this, but this is perfectly adequate for what we need. I look forward to viewing the other responses.


q:
Google chrome doesn't behave the same as other browsers when encountering this nugget:

<?php
while (true) {
    echo "<script type='text/javascript'>\n";
    echo "alert('hello');\n";
    echo "</script>";
    flush();

    sleep(5);
}
?>

It seems that it's waiting for the connection to terminate before doing anything.

Other than polling how can I do a similar thing in Google Chrome?

[A]
I wish I had access to Chrome at the moment to test out some ideas. Have you tried adding some HTML after
```
</script>
```
and seeing if it renders incrementally?  I imagine it would, and if so that'd be proof that Chrome doesn't want to run javascript in
```
<script>
```
elements while the page is loading.  Of course, rendering the markup might trigger your scripts to run.  If not, you could try including the javascript as external files and see if that affects execution time.
I think browsers generally have some leeway according to the spec in when they begin executing javascript, especially as the page loads.  It might not be possible to do this in a fully cross-browser way without polling.


q: At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)

[A]
I think you need to ask yourself a slighly different question "What advantage does creating a new exception give me or developers who use my code?"  Really the only advantage it gives you or other people is the ability to handle the exception.  That seems like an obvious answer but really it's not.  You should only be handling exceptions that you can reasonably recover from.  If the exception you throw is a truly fatal error why give developers a chance to mis-handle it?
More in depth discussion:
Custom exceptions: When should you create them?


q:
I'm new with Objective-C, so there probably is a simple solution to this.

I want a number to increment, but each iteration to be show on a label. (for example, it shows 1, 2, 3, 4, 5... displayed apart by an amount of time).

I tried:

#import "testNums.h"

@implementation testNums
- (IBAction)start:(id)sender {
    int i;
    for(i = 0; i < 10; ++i)
    {
        [outputNum setIntValue:i];
        sleep(1);
    }
}
@end

and all it did was wait for 9 seconds (apparently frozen) and then displayed 9 in the text box.

[A]
Yes, because that is what you told it to do. The graphics will not actually update until the main run loop is free to display them. You'll need to use
```
NSTimer
```
or some such method to do what you want.
A better question might be why you want to do this?


q: I have two PHP files that I need to link. How can I link the files together using PHP? The effect I want is to have the user click a button, some information is proccessed on the page, and then the result is displayed in a different page, depending on the button the user clicked.Thanks

[A]
It sounds like you might want an HTML form:
```
```
<form method="post" action="other_file.php">
    <input name="foo" type="..."... /> ...
</form>
```
```
Then
```
$_POST["foo"]
```
will contain the value of that input in other_file.php.


q:
Here's what I am trying to do:

Select text from a webpage I pulled up using my web browser control.After clicking a button while this text is still selected I would like a message box to pop-up displaying the text that was highlighted by the user. How do I get this functionality to work in my wpf application?

I think I'm on the right track using mshtml but I get an error that says:

Error HRESULT E_FAIL has been returned from a call to a COM component.

This error will happen even when I try something small on the document like changing the title.

The code is below:

IHTMLDocument2 doc = (IHTMLDocument2)this.webBookText.Document;
doc.title = "l";

[A]
Well, for starters it would be a lot simpler to use
```
WebBrowser
```
than mshtml (note that you can still host
```
WebBrowser
```
in WPF) - this will certainly let you do simple things a lot easier:
```
```
webBook.Document.Title = "foo";
```
```
However, I can't see anything there that would let you work with selections very easily...
You can get the selected
element
with
```
.Document.ActiveElement
```
, but this is the entire element - not the selected portion.


q: So lets say I'm using Python's ftplib to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.

[A]
I believe it should work for you.
```
```
file_name_list = [' '.join(each_file.split()).split()[-1] for each_file_detail in file_list_from_log]
```
```
NOTES -
Here I am making a assumption that you want the data in the program (as list), not on console.
each_file_detail is each line that is being produced by the program.
' '.join(each_file.split())
To replace multiple spaces by 1 space.


q:
In cmd.exe, I can execute the command "copy c:\hello.txt c:\hello2.txt" and it worked fine.
But in my C program, I ran this piece of code and got the following error:

#include <iostream>

using namespace std;

int main()
{
    system("copy c:\hello.txt c:\hello2.txt");
    system("pause");

    return 0;
}

Output:
The system cannot find the file specified.

Anybody know what is going on here?

[A]
Inside C strings (and quite a few other languages that use the same escaping rules),
```
\
```
should be
```
\\
```
since it's the escape character. It allows you to enter, in normal text, non-printable characters such as:
the tab character
```
\t
```
.
the carriage-return character
```
\r
```
.
the newline character
```
\n
```
.
others which I won't cover in detail.
Since
```
\
```
is used as the escape character, we need a way to put an
actual
```
'\'
```
into a string. This is done with the sequence
```
\\
```
.
Your line should therefore be:
```
```
system("copy c:\\hello.txt c:\\hello2.txt");
```
```
This can sometimes lead to obscure errors with commands like:
```
```
FILE *fh = fopen ("c:\text.dat", "w");
```
```
where the
```
\t
```
is actually the
```
tab
```
character and the file that you're trying to open is:
c
:
TAB
e
x
t
.
d
a
t
.


q:
I've been a Delphi (D7) developer for many sometime already, I've always been wondering about the .NET + C# stuffs. What I mean are about not the "Delphi for .NET" or "Oxygene" tech/plugin, but clean .NET/C#.

How much different is it from Delphi? And some other questions...

Is Mono/SharpDevelop (any others that I should know of?) as capable as the Non-Free Visual Studio?

In terms of deployment, how does it work? The Assembly + Framework + Executable?

The Framework (3.5 latest?) works something like the JVM for the Java world, correct? Does it take care of the supporting/making use of techs like Multi-Cores or Windows specific optimizations?

C# has some similarities to Object Pascal, shouldn't be too tough to adapt, right?

Thanks.

[A]
Re the first point: have you tried the (free)
VIsual Studio Express Edition
? For a lot of things, this is perfectly capable. You just don't get as many helpers / designers, and no plug-in support (for IDE extensions).
Re the second: excluding some
nasty tricks
, you can't create a pure native executable from .NET; it relies
heavily
on the framework being available on the local machine. An assembly is just a package of IL, and can be contained (typically) in either a dll, or bootstrapped into an exe that loads the assemblies entry-point; but in this scenario the exe is just a simple loader plus a regular assembly.
Actually, the CLR is more like the JVM; the "framework" is really just the equiavalent of a BCL. The main MS framework+CLR certainly has some Windows specific optimizations, but other runtimes/frameworks (
compact
,
micro
,
Silverlight
,
Mono
) will have different optimizations.
Re multi-core - you have full threading support (for doing it yourself) - but the main
automated
multi-core support will (hopefully) be in .NET 4.0 with the "
parallel extensions
" work.
Re the last point: should be very familiar indeed. Actually, if you want to do some comparisons, "
reflector
" (free) can take a compiled assembly and show you the code in either C# or delphi (or a few others).
[update re questions]
IL = Intermediate Language; .NET doesn't compile to native CPU instructions, but to something in-between that becomes CPU instruction at runtime (compiled "Just In Time" (JIT) on a method-by-method basis). This means that the JIT compiler can optimize the same IL for the local machine. You can do this in advance using
NGen
.
CLR = Common Language Runtime; essentially the VM
BCL = Base Class Library; the set of classes shared my many apps
Re deployment: first, install the .NET framework on the client ;-p
After that - various options. At the simplest level, you can just copy the exe/etc onto the local machine and run. For example, I use "robocopy" to push code to web-servers.
For full local installs of a complex client app, msi is an option (and the full VS IDE will help you with this).
For simple clients, you can use
ClickOnce
- which packages the app into a signed bundle that provides self-updating etc capabilities and allows you to make statements about what security you need (full trust, etc). Express Edition allows you to author  ClickOnce packages. ClickOnce can even be used on locked down clients where the user can't install apps, since the app is isolated and sand-boxed.
Finally, you can run a .NET app off a network share, but there are some security implications: the "Code Access Security" layer won't give a network share "full trust" (although there were some recent changes to this so that mapped (F: etc) shares are trusted). So you'd need to use CASPOL at each client to trust the code. ClickOnce would be easier ;-p


q:
Does any one know of some kind of Comparator factory in Java, with a

public Comparator getComparatorForClass(Class clazz) {}

It would return Comparators for stuff like String, Double, Integer but would have a

public void addComparatorForClass(Class clazz, Comparator comparator) {}

For arbitrary types.

[A]
Instead of:
```
```
factory.getComparatorForClass(x.getClass()).compare(x, y)
```
```
you could simply implement
```
Comparable
```
and write:
```
```
x.compareTo(y)
```
```
String, the primitive wrappers, and standard collections already implement
```
Comparable
```
.


q:
Has anybody succeeded in customizing the Places Bar for VS 2008? My customizations from VS 2005 did not transfer to 2008 (obviously), and no matter what I do with the registry, I cannot make my custom places appear on the Open dialogs. I have read and applied the relevant MS KB article, to no avail.

This used to work fine with VS 2005, so it may well be a VS 2008 bug, but I may be wrong trying the same approach.

[A]
some observations:
VS2008 uses now Common File Dialog. With Powertoys TweakUK i was able to set all places to 'none' and the VS2008 'Open File' dialog becomes empty.
Unfortunately VS2008 ignores user defined places or directories, and shows instead the default places: 'Desktop', 'standard_project_folder', 'My Computer'.
With Sysinternals RegMon i see that Registry Key [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\comdlg32\PlacesBar] gets read on ctrl+o...altough the places defined in here are still being ignored.


q:
I have a php script that is executing an executable that writes to a serial port.
However, everytime it runs
system("c:\Untitled1.exe")

it just opens up a cmd window and freezes.

Anybody know how to fix this? Or if there is an easier way to get PHP to write to the serial port directly? (I've already tried these two: http://blogs.vinuthomas.com/2007/04/09/php-and-serial-ports/ and they don't work for me)

P.S. I am on Windows XP

[A]
AFAIK
```
system()
```
call blocks the execution until the program finishes. Maybe using
```
popen()
```
,
```
fread()
```
and
```
pclose()
```
could solve this.
See
http://php.net/manual/en/function.popen.php
for more info.


q:
We have an R Server
 (R is a programming language used in statistical analysis) that basically takes a script and a csv file, processes some data and returns results as text.

I need to write a service on the R server so that .net clients (could be .Net Windows Forms, or ASP.Net) can connect to the R server, submit the script and CSV file, and get the results back.

I'm confused by the many different bindings available to me and information on the web seems to be sparse/scattered about what one to choose.

Also, is it best to run the service in IIS, or as a separate "command line" type listener service (the latter seems ugly compared to IIS and I have no idea why anyone would choose to do this if they could run it in IIS)?

[A]
Personally, I'd recommend the simplest binding that gives what you need. I've done quite a lot of WCF (some quite complex), and I've never had to use anything other than BasicHttpBinding; this also allows that greatest possible compatibility with non-.NET clients, and lets you use things like MTOM for efficient binary transfer.
Re hosting; IIS is indeed the simplest for a client/server setup; two particular strengths:
easy to configure SSL (i.e. you just configure IIS, and WCF will use it)
easy to load balance (just load balance your web farm)
(I
believe
WCF running over BasicHttpProfile can also leverage your IIS compression [GZip/Deflate] setup, but don't quote me...)
You might choose to use a standalone host (usually via a windows service) if (for example) you want a long-running stateful server. IIS has this habit (by design) of recycling the app-pools, which isn't good if you were keeping something in memory! Another example is where you want it to be already running for fast "first hit" performance (rather than waiting for IIS/ASP.NET to spin up). An example covering both of these might be hosting a WF (workflow) server.
Again; if you don't need this complexity, go for the simplest option: hosting in IIS.


q:
Ive recently been asked to recommend a .NET framework version to use in a (GUI based) project for an XP machine.

Can anyone explain the differences between all the .NET versions?

OR,

Does anyone have a good reference to a site that details (briefly) the differences?

[A]
The short answer is that it depends.
.NET 2.0 is the oldest version you should be considering.
.NET 3.0 is an easy upgrade path from 2.0, not the same amount of breaking changes as from 1.1 to 2.0.  However it is more of an extension, horizontally of functionality, and you would not see a huge shift in graphical options.
.NET 3.5 should be looked at if you are interested in much more sophisticated gui such as sliverlight.  It has a lot more new technologies and options to offer including WPF, a new IDE in Expression and much more.
http://www.asp.net
would not be a bad start.


q:
I have a tabview controller to which I added a UIViewController to each tab. I want to have multiple UIViews inside the UIViewController.

So in the implementation of the UIViewController class I added [self.view addSubView:uiview1] and [self.view addSubView:uiview2]. The problem is that when I run the app, it crahes on load.

However, if I only used a single UIView and did: self.view = UIView1 that would work fine.

Does anyone know what is causing the problem? Or if I'm doing something fundamentally wrong?

[A]
There's no reason you can't have multiple views within your UIViewController's main view member variable. However, there are quite a few items left unanswered in your question:
How are you obtaining view1 and view2?
Are they outlets in your XIB file (are you using a XIB file, or creating everything in code), or are you creating them in code?
Where in your UIViewController subclass are you adding them to your view member variable?
What's the message printed to the console when it crashes?


q:
I have many small files containing code fragments, pseudo-code algorithms, classes, templates, SQL-samples, etc., and I obviously cannot put all these into libraries. I need a practical method to index all of them, and to be able to make this index available to others.

What must such an index contain to
make searching easiest?

Are there any such repositories
available on the web? (So I can test
the techniques they use.)

Are there any applications already
written that implement this that I
can have a look at?

Possible duplicate: https://stackoverflow.com/q/90300/15161

[A]
If you're working with .NET / Visual Studio, you could look at adding them as
code snippets
Code Keep
is a pretty good online repo for CodeSnippets and has plugins for VS2008
What we've done at work is created a common account for the dev to use, so everyone submits to codekeep under a common login and then can retrieve everyone elses snippets.
Also it might be worth your while creating a developer wiki on your dev network. Somewhere that the old hands can leave documentation on your regularly used patterns & snippets and new team members can check for help. We use
TRAC
in house as an all in one WIKI / Issue Management / SVN Integration and it does the job nicely


q:
An answer to one of my questions included the following line of code:

label = std::safe_string(name); // label is a std::string

The intent seems to be a wrapper around a string literal (so presumably no allocation takes place). I've never heard of safe_string and neither, apparently, has google (nor could I find it in the 98 standard).

Does anyone know what this is about?

[A]
There is no such thing as
```
std::safe_string
```


q:
I'm a recent semi-convert to Eclipse after 20 years of using vi and gvim.  One of the things I miss about gvim is that I could cut a bunch of different snippets of code into named buffers, and paste them at will when doing something like repeating a common idiom.  For instance I'd have it so "ap would paste

DatabaseHandle handle = null;
try
{
  handle = DatabaseConnectionPool.newHandle();

and then "bp would paste

  handle.commit();
}
finally
{
  handle.rollback();
  DatabaseConnectionPool.returnHandle(handle);
}

And I could repeat both of them over and over in the course of a day.  In an answer to another question, somebody mentioned that you could "manage code snippets" in Eclipse, but didn't mention how.  So now I'm asking: how do you manage code snippets in Eclipse?

[A]
You might want to store those two snippets into a
code template
, as explained in
this tutorial
.
And do not forget about the possibility to quickly execute any kind of java code snippets in a
scrapbook
(not exactly what you want, but it can come in handy at times)
Newtopian
adds (in the comments)
In fact templates become much more powerful by adding variables and tabstops within, so your example above would become
```
dbHandle ctrl+space
```
. It would copy snippets from both parts and place your cursor right in the middle.


q: How can I replace Line Breaks within a string in C#?

[A]
Use the .Replace() method
```
```
Line.Replace("\n", "whatever you want to replace with");
```
```


q: For a simple linked list in which random access to list elements is not a requirement, are there any significant advantages (performance or otherwise) to using std::list instead of std::vector?  If backwards traversal is required, would it be more efficient to use std::slist and reverse() the list prior to iterating over its elements?

[A]
As usual the best answer to performance questions is to
profile
both implementations for your use case and see which is faster.
In general if you have insertions into the data-structure (other than at the end) then
```
vector
```
may be slower, otherwise in most cases
```
vector
```
is expected to perform better than
```
list
```
if only for
data locality issues
, this means that if two elements that are adjacent in the data-set are adjacent in memory then the next element will already be in the processor's cache and will not have to page fault the memory into the cache.
Also keep in mind that the space overhead for a
```
vector
```
is constant (3 pointers) while the space overhead for a
```
list
```
is paid for each element, this also reduces the number of full elements (data plus overhead) that can reside in the cache at any one time.


q: How is it done? What steps do I need to take and what pitfalls and gotchas are there to consider?

[A]
I write quite a bit of ARM Cortex-A8 assembly-code. The CPU on the iPhone is an ARM11 (afaik) so the core instruction set is the same.
What exactly are you looking for? I could give you some examples if you want.
EDIT:
I just found out that on the iPhone you have to use the llvm-gcc compiler. As far as I know it should understand the inline assembler syntax from GCC. If so all the ARM inline assembler tutorials will work on the iPhone as well.
Here is a very minimal inline assembler function (in C). Could you please tell me if it compiles and works on the iphone? If it works I can rant a bit how to do usefull stuff in ARM inline assembler, especially for the ARMv6 architecture and the DSP extensions.
```
```
inline int saturate_to_255 (int a)
{
  int y;
  asm ("usat %0, #8, %1\n\t" : "=r"(y) : "r"(a));
  return y;
}
```
```
should be equivalent to:
```
```
inline int saturate_to_255 (int a)
{
  if (a < 0) a =0;
  if (a > 255) a = 255;
  return a;
}
```
```


q:
So, when playing with the development I can just set settings.DEBUG to True and if an error occures I can see it nicely formatted, with good stack trace and request information.

But on kind of production site I'd rather use DEBUG=False and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)

At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.

What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as fcgi server and I'm using apache web server as frontend (although thinking of going to lighttpd).

[A]
Well, when
```
DEBUG = False
```
, Django will automatically mail a full traceback of any error to each person listed in the
```
ADMINS
```
setting, which gets you notifications pretty much for free. If you'd like more fine-grained control, you can write and add to your settings a middleware class which defines a method named
```
process_exception()
```
, which will have access to the exception that was raised:
http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception
Your
```
process_exception()
```
method can then perform whatever type of logging you'd like: writing to console, writing to a file, etc., etc.
Edit: though it's a bit less useful, you can also listen for the
```
got_request_exception
```
signal, which will be sent whenever an exception is encountered during request processing:
http://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception
This does
not
give you access to the exception object, however, so the middleware method is much easier to work with.


q:
I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:

fun (head : rest) = ...

So when I pass in a list, head will be the first element, and rest will be the trailing elements.

Likewise, in Python, I can automatically unpack tuples:

(var1, var2) = func_that_returns_a_tuple()

I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:

ls = my_func()
(head, rest) = (ls[0], ls[1:])

I wondered if I could somehow do that in one line in Python, instead of two.

[A]
That's a very much a 'pure functional' approach and as such is a sensible idiom in Haskell but it's probably not so appropriate to Python.  Python only has a very limited concept of
patterns
in this way - and I suspect you might need a somewhat more rigid type system to implement that sort of construct (
erlang
buffs invited to disagree here).
What you have is probably as close as you would get to that idiom, but you are probably better off using a list comprehension or imperative approach rather than recursively calling a function with the tail of the list.
As has been
stated
on a few occasions
before
, Python is not actually a functional language.  It just borrows ideas from the FP world.  It is not inherently
Tail Recursive
in the way you would expect to see embedded in the architecture of a functional language, so you would have some difficulty doing this sort of recursive operation on a large data set without using a lot of stack space.


q:
I am trying to get the signature on the method below to work. As this is an Anonymous Type I have some trouble, any help would be great.

When I looked at sortedGameList.ToList() in a QuickWatch window I get the signature

System.Collections.Generic.List<<>f__AnonymousType0<System.DateTime,System.Linq.IGrouping<System.DateTime,DC.FootballLeague.Web.Models.Game>>>

Many Thanks

Donald

   public List<IGrouping<DateTime, Game>> getGamesList(int leagueID)
{
    var sortedGameList =
        from g in Games
        group g by g.Date into s
        select new { Date = s.Key, Games = s };

    return sortedGameList.ToList();

}

[A]
The simple answer is: don't use an anonymous type.
The closest you're going get with that anonymous type is IEnumerable<object>. The problem is, anybody who uses your stuff is not going to know what to do with that object whose type was "unpredictable".
Instead, make a class like:
```
```
public class GamesWithDate {
    public DateTime Date { get; set; }
    public List<Game> Games { get; set; }
}
```
```
And change your LINQ to:
```
```
var sortedGameList =
    from g in Games
    group g by g.Date into s
    select new GamesWithDate { Date = s.Key, Games = s };
```
```
Now you're returning List<GamesWithDate>.


q:
When the SharePoint application you are working on has unsatisfactory response times how do you pinpoint the causes and in which sequence? So far I have not yet found any open source or commercial profiling tools specific for the SharePoint segment, so any pointer to tools or best practices will be appreciated.

PS. I am aware of the profiling options for the web parts but I am looking for something that covers the entire application.

[A]
My advice is to look at the following:
Data Layer
Check and see if your database is chugging along, and what requests are taking a lot of time.  90% of everything you see in SharePoint is stored in the database somewhere.  Run SQL Profiler for a few hours and examine your logs.
Site Collections
I have found in SharePoint that the deeper you arrange your sites and site collections, the further that performance degrades.  This is purely anecdotal, so take it with a grain of salt.
Other than that, I don't know of many SharePoint profiling tools.  My experience with SharePoint has pushed my away from heavy customization jobs, and towards using more functionality OOTB.  I rarely recommend using SharePoint as an application platform.
Good Luck!


q:
Because windows is case-insensitive and because SVN is case-sensitive and because VS2005 tends to rename files giving them the lower-case form which messes my repositories' history, I've tried to add the pre-commit hook script from http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/case-insensitive.py.
Sure enough, the script uses classes from python's libsvn ("from svn import repos, fs") which I fail to find compiled for Windows.
Is there an alternative? To libsvn or to the hook script?

[A]
There are two alternative Python bindings for libsvn:
pysvn
.
subvertpy
.
Subvertpy is quite new and is written by the author of
bzr-svn
: the transparent
svn
inter-operation bridge for
bzr
.
For a while, bzr-svn used the upstream
SWIG
Python bindings, and the author contributed a lot of bug fixes. It helped move the upstream python support for "horribly broken" to "painfully aggravating and unpythonic". So after wasting too many hours of his life to SWIG, the author decided to make his own bindings.


q:
Every time I do an hg diff file.ext I end up using a console diff application. I would like to use Kdiff3 or WinMerge (I'm using Windows).

Is there a way to change that? I can't find a reference in Mercurial documentation (I'm not talking about merge!).

[A]
I've solved this using a Mercurial built-in extension... I just have to add the following lines to Mercurial.ini (on Mercurial folder):
```
```
[extensions]
hgext.extdiff=

[extdiff]
cmd.vdiff = kdiff3
```
```
When I want to use kdiff3 instead of diff I only have to use:
```
```
hg vdiff file.ext
```
```


q:
I use jsmin to compress my javascript files before uploading them to production.

Since I tend to have one "code-behind" javascript file per page, I wind up doing this a lot.

I installed a Windows Powertoy that adds a context menu item in Windows Explorer, so I can "Open Command Window Here".  When I click that, the command prompt opens up in the right directory.  That saves a little bit of typing.

However, I still have to type something like:

jsmin <script.js> script.min.js

To get it to work. This is a hassle.

I'd like to create a context menu item that will allow me to right-click on a *.js file and select "jsmin-compress this file." Then jsmin would be invoked, and the original file would be compressed into "original_filename.min.js"

How can I do this?

[A]
you could drop a link to a batch script into the user sendto directory.  Something like
```
```
jsmin %1 script.min.js
```
```
which is what I usually do


q:
I have given a location defined by latitude and longitude.
Now i want to calculate a bounding box within e.g. 10 kilometers of that point.

The bounding box should be defined as latmin, lngmin and latmax, lngmax.

I need this stuff in order to use the panoramio API.

Does someone know the formula of how to get thos points?

Edit: Guys i am looking for a formula/function which takes lat & lng as input and returns a bounding box as latmin & lngmin and latmax & latmin.
Mysql, php, c#, javascript is fine but also pseudocode should be okay.

Edit: I am not looking for a solution which shows me the distance of 2 points

[A]
You're looking for an ellipsoid formula.
The best place I've found to start coding is based on the Geo::Ellipsoid library from CPAN.  It gives you a baseline to create your tests off of and to compare your results with its results.  I used it as the basis for a similar library for PHP at my previous employer.
Geo::Ellipsoid
Take a look at the
```
location
```
method.  Call it twice and you've got your bbox.
You didn't post what language you were using.  There may already be a geocoding library available for you.
Oh, and if you haven't figured it out by now, Google maps uses the WGS84 ellipsoid.


q: I'm building an Android app and I want to copy the text value of an EditText widget. It's possible for the user to press Menu+A then Menu+C to copy the value, but how would I do this programmatically?

[A]
Use
```
ClipboardManager#setPrimaryClip
```
method:
```
```
import android.content.ClipboardManager;

// ...

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
```
```
```
ClipboardManager
```
API reference


q:
I have a route

// Sample URL: /Fixtures/Team/id
routes.MapRoute(
     "Fixtures-by-TeamID",
     "Fixtures/Team/{teamId}",
     new { controller = "Fixtures", action = "GetByTeamID", },
     new { teamId = @"\d{1,3}" }
);

and I am trying to use ActionLink in ASP.net MVC p5.

<%= Html.ActionLink(g.HomeTeam.TeamName, "Team", new { teamId = g.HomeTeam.TeamID })%>

However it is not working and giving me

<a href="/Fixtures/Team?teamId=118">Team A</a>

If I use Url.RouteUrl i get the correct link.

<a href="<%=Url.RouteUrl("Fixtures-by-TeamID", new { teamId = g.HomeTeam.TeamID })%>"><%=g.HomeTeam.TeamName%></a>

<a href="/Fixtures/Team/118">Team A</a>

Any help would be great? Will this change in ASP.net MVC beta?

Thanks

Donald

[A]
In my experience, the only time action routes really work properly is when you only have the single default route. As soon as you start adding custom routes like yours above, action routes become... I guess "finicky" is the right word. The matching system doesn't work exactly how you'd expect it to.
In this case, you said the action was "Team", but this route doesn't match an action of "Team", it only matches "GetTeamByID". So the routing system keeps going and ends up giving you a route based on the default route. The teamId isn't explicitly part of your default route, so it ends up as a query parameter tacked on the end.
MVC Beta has already shipped, and this behavior is unchanged.
Also, don't you find the named route to be clearer anyway? Personally, I do.
I even go one step further and actually create route helpers for all my custom routes, which might look like this in your current example:
```
```
<a href="<%= Url.FixturesByTeam(g.HomeTeam.TeamID) %>"><%= g.HomeTeam.TeamName %>
```
```
Or even:
```
```
<%= Html.LinkToFixturesByTeam(g.HomeTeam) %>
```
```
where you can pull the values for name and ID directly from the model.


q:
I'm hosting my first WCF service in IIS. I have two methods, 1 to set a string variable on the WCF Service, and the other to retrieve it. The interface used is:

[OperationContract]
string ReturnText();

[OperationContract]
void SetText(string s);

BasicHttpBinding is used. Stepping through the service with the debugger from the client reveals that the value of the string is set correctly using SetText, but when I immediately do a return text, the string is back to null.

Probably a simple one I know, but I thought that all values on the WCF service were retained between opening the service connection and closing it.

Why is the value lost between the Set and Gets?

[A]
By default things are session-less and instances are per-call.  See
http://msdn.microsoft.com/en-us/library/ms731193.aspx
for some starter information, but in order to have state across the calls, you'll either need a PerSession or Single instancing mode on the server, and in the former case, configure the binding to support sessions (so that the two calls can be correlated as a result of being a part of the same session connection).


q:
Here are my current options.

.Net : Using WPF, Visual C#, SQLServer

Java : Using Spring, Hibernate, Enterprise DB, web-based

Can you suggest which one is better?, especially with regards to building complex forms.

[A]
Wow, .NET vs. Java, can't wait to see how this turns out  ;-)
.NET might have the edge here with WPF and click-once deployment.  WPF is in its second version and is showing itself to be quite powerful and easy to use.  It provides excellent separation between logic and presentation (in XAML).  Personally, I would much prefer a Windows application to web deployment because the programming model is so much more powerful and versatile (and better suited for complex forms).
I won't try to represent the Java viewpoint here, but Windows forms development in Java does not have a great reputation.  Perhaps its unwarranted, I'd be interested to hear what Java programmers have to say. (UPDATE -- Swing is the technology I'm referring to here)
To some extent, this is a false choice, because those other technologies you list (Spring, Hibernate) are also available on the .NET stack (Spring.Net and NHibernate) and are quite mature.  Most popular Java open source technologies have been ported to the .NET stack.


q:
I think I know the answer, but I would like to bounce around some ideas.

I would like to pass several (in this instance 2) somewhat different pieces of data to a View.  My initial thought is simply to wrap-up the various objects into a containing object and pass them along that way. Then from the View, I'd have something like

var objContainer = ViewData.Model;
var thisObject = objContainer.ThisObject;
var thatObject = objContainer.ThatObject;

and these could be used independently in the Master Page and View Page.

Is that the "best" way?

[A]
I've got the same dealie going on.  Here's my solution (may not be the best practice, but it works for me).
I created a number of "Grouping" classes:
```
```
public class Duo<TFirst,TSecond> { /*...*/ }
public class Trio<TFirst,TSecond, TThird> { /*...*/ }
```
```
and a factory object to create them (to take advantage of type inference... some of the TFirsts and TSeconds and TThirds can be LONG)
```
```
public static class Group{

public static Duo<TFirst, TSecond> Duo(TFirst first, TSecond second) {
  return new Duo<TFirst, TSecond>(first, second);
 }
/*...*/
}
```
```
It gives me type safety and intellisense with a minimum of fuss.  It just smells because you're grouping together classes that essentially have no real relation between them into a single object.  I suppose it might be better to extend the ViewPage class to add a second and third ViewModel, but the way I did it takes lots less work.


q: I'm trying to set up Eclipse for php web development.  What I would like to do is preview a php web page from within Eclipse, but I cannot figure out how to do this.  Is there an integrated web server of some sort that allows this, or do I have to set up IIS/Apache to do it?  If so, do I have to have my php files in the web servers path, or does Eclipse auto deploy the files to the local web server?  Any information or links would be very much appreciated.

[A]
There is a plugin for Eclipse called PDT which makes PHP development a breeze.
For an overview on how to install it, you can refer to the Eclipse website:
http://wiki.eclipse.org/PDT/Installation#Eclipse_3.4_.2F_Ganymede_.2F_PDT_2.0
To actually view the PHP scripts running, I would imagine that you'd have to have some sort of server already installed and running. You could probably set the workspace location to be in the server path, and then view the files through localhost. But maybe the PDT package takes care of some of that for you.


q:
I want to make a really simple iphone app:  one screen with a single button... when the button is tapped a new screen appears.  That's it.  No animations, nothing,

I've tried endlessly to make the NavBar sample project do this... and it works but only if I use a UINavigationController with a table that I can tap etc.  I've tried all the skeleton projects in XCode too.

I thought I was done when I did this:

[[self navigationController] presentModalViewController:myViewController animated:YES];

But I couldn't do it without the UINavigationController.  I just want a simple example.

Thanks so much!

[A]
One way you could do this is to create a new UIView and then when the button is pressed add that new UIVIew as a subview, therefore making it what you see.
If you make the new view its own subclass of UIView you would do something like this.
```
```
LoginView *login = [[LoginView alloc] initWithFrame: rect];
[mainView addSubview: login];
```
```


q:
I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API.  It'd be much easier to debug the issue if I could observe every function being called leading up to the crash.  Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program?

Thanks in advance!

[A]
Use a Tracer object.  Something like this:
```
```
class Tracer
{
public:
  Tracer(const char *functionName) : functionName_(functionName)
  {
    cout << "Entering function " << functionName_ << endl;
  }

  ~Tracer()
  {
    cout << "Exiting function " << functionName_ << endl;
  }

  const char *functionName_;
};
```
```
Now you can simply instantiate a Tracer object at the top the function, and it will automatically print "exiting... " when the function exits and the destructor is called:
```
```
void foo()
{
  Tracer t("foo");
   ...
}
```
```


q:
I've been running the built-in Ant from the command line on a Macintosh (10.5.5) and have run into some trouble with the Mail task. Running the Mail task produces the following message:

[mail] Failed to initialise MIME mail: org.apache.tools.ant.taskdefs.email.MimeMailer

This is most likely due to a missing ant-javamail.jar file in the /usr/share/ant/lib directory. I see a "ant-javamail-1.7.0.pom" file in this directory but not the appropriate jar file. Anyone know why this jar file might be missing and what the best way to resolve the problem is?

[A]
Download the Java Mail libraries from:
http://java.sun.com/products/javamail/
.
You will also need
http://java.sun.com/products/javabeans/glasgow/jaf.html
A list of all external dependencies required by Ant's optional tasks are outlined here
http://ant.apache.org/manual/index.html
.
Another way to get dependencies for Ant very easily, is to run:
```
```
ant -f fetch all
```
```
from $ANT_HOME. You can also run -projecthelp for a full list of targets:
```
```
all         load all the libraries
 antlr       load antlr libraries
 bcel        load bcel libraries
 beanshell   load beanshell support
 bsf         load bsf libraries
 debugging   internal ant debugging
 get-m2      Download the Maven2 Ant tasks
 jdepend     load jdepend libraries
 jruby       load jruby
 junit       load junit libraries
 jython      load jython
 logging     load logging libraries
 networking  load networking libraries (commons-net; jsch)
 regexp      load regexp libraries
 rhino       load rhino
 script      load script languages
 xerces      load an updated version of Xerces
 xml         load full XML libraries (xalan, resolver)
```
```


q:
I would like to be able to fetch a web page's html and save it to a String, so I can do some processing on it.  Also, how could I handle various types of compression.

How would I go about doing that using Java?

[A]
Well, you could go with the built-in libraries such as
URL
and
URLConnection
, but they don't give very much control.
Personally I'd go with the
Apache HTTPClient
library.
Edit:
HTTPClient has been set to
end of life
by Apache. The replacement is:
HTTP Components


q:
How do I get the value of a MemberInfo object? .Name returns the name of the variable, but I need the value.

I think you can do this with FieldInfo but I don't have a snippet, if you know how to do this can you provide a snippet??

Thanks!

[A]
Here's an example for fields, using
FieldInfo.GetValue
:
```
```
using System;
using System.Reflection;

public class Test
{
    // public just for the sake of a short example.
    public int x;

    static void Main()
    {
        FieldInfo field = typeof(Test).GetField("x");
        Test t = new Test();
        t.x = 10;

        Console.WriteLine(field.GetValue(t));
    }
}
```
```
Similar code will work for properties using
PropertyInfo.GetValue()
- although there you also need to pass the values for any parameters to the properties. (There won't be any for "normal" C# properties, but C# indexers count as properties too as far as the framework is concerned.) For methods, you'll need to call
Invoke
if you want to call the method and use the return value.


q:
How can I find out the size of a file I opened with an application written in C ?
I would like to know the size, because I want to put the content of the loaded file into a string, which I allocate using malloc(). Just writing malloc(10000*sizeof(char)); is IMHO a bad idea.

[A]
You need to seek to the end of the file and then ask for the position:
```
```
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
```
```
You can then seek back, e.g.:
```
```
fseek(fp, 0L, SEEK_SET);
```
```
or (if seeking to go to the beginning)
```
```
rewind(fp);
```
```


q:
I'm using TortoiseHg 0.5 (which includes Mercurial 1.0.2) on Vista64. My understanding from the Mercurial Book is that Mercurial should handle filenames in a case-insensitive manner on a case-insensitive filesystem (such as NTFS, which is what I'm on). However I find that my installation of Mercurial is in fact sensitive to case:

>hg status -A foo
C foo
>hg status -A FOO
? FOO

Could this be a bug in Mercurial, a bug in the TortoiseHg build of Mercurial, or is it something else? How can I achieve case-insensitive filename handling from Mercurial on Windows?

[A]
I think you misread the hgbook.  The intro to section 7.7 is just describing the three different types of case sensitivity that exist in OSs, not saying that mercurial will mirror those semantics.
Later in section 7.7.2 'Detecting case conflicts' it says:
When operating in the working
  directory, Mercurial honours the
  naming policy of the filesystem where
  the working directory is located. If
  the filesystem is case preserving, but
  insensitive, Mercurial will treat
  names that differ only in case as the
  same.
When you do
```
hg status -A FOO
```
the process that's happening within mercurial is:
Check if a file exists on the file system matching the file argument, 'FOO', -- and at this point it's being case insensitive so it finds 'foo' and says "yup, I've got a file"
Check if there's an entry in the file manifest matching the file argument, 'FOO', and there isn't, so status shows a '?' saying it's a file on disk that hg isn't tracking
To better see mercurial not caring about case on NTFS try these steps:
hg init
echo line > Foo
hg add Foo
hg commit -m 'committed Foo'
move Foo not-foo
move not-foo FOO
hg status
and you should see hg saying that nothing has changed because the only thing that has changed is the case which hg is ignoring for you.
When I do the same thing on linux I instead see:
```
```
! Foo
? FOO
```
```


q: I have a subclass "s" of UIView.  I want to put some buttons and labels on s.  How do I associate my UIView subclass with a nib file?

[A]
In Interface Builder, create a new
xib with the View template.
Click on the view in the list of
objects in the xib (you should also
see "File's Owner and "First
Responder").
Push Cmd-4 to open the Identity pane
of the inspector.
Type your class's name into the
"Class Name" field and push return.
You should be able the drag buttons in. To get at the nib from code, use
```
-[NSBundle loadNibNamed:owner:options:]
```
. Your view should be the first object in the returned array.


q:
I want to skin a vb.net app I made ive googled some stuff and I've seen skinned vb.net apps.

However it seems like any time i try to find someone explaining it its a link to  a pay for product.

Does anyone have anything useful on this?

I have seen some free ways to do this programatically I cannot seem to make it translate entirely over to my own unique program.

[A]
Unfortunatly VB.NET does not provide 'skinning' out of the box. It simply uses the standard windows interface. The only changes to the UI are made when you change the display properties.
I'm not aware of an open source project that provides skinning functionality, however I have used a number of commercial products. By far, one of the best I have used is the Application Styling Framework found in
NET Advantage
by Infragistics.


q:
When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps.

uint z = -1; // Will not compile

uint a = 5;
uint b = 6;
uint c = a - b; // Will result in uint.MaxValue

Is there a good reason why unsigned variables wrap in such a situation instead of throwing an exception?

Thanks.

[A]
Declaring an unassigned variable in C# isn't flagged with an error - trying to assign an invalid value to a variable is. For instance, here's a variable which isn't definitely assigned (assuming it's local) after declaration:
```
```
uint z;
```
```
-1 isn't a valid value for a uint any more than 0.5 is, which is why your example wouldn't compile.
Now, as for the rest: integers types just wrap on overflow - just as adding 1 to
```
int.MaxValue
```
returns
```
int.MinValue
```
. This is a significant performance improvement over having the program check each operation for overflow - at the cost of potentially not spotting an error.
That's only if you're in an unchecked context, mind you - if you perform any of these operations in a checked context, you'll get an exception instead. For instance;
```
```
class Test
{
    static void Main()
    {
        checked
        {
            uint a = 5;
            uint b = 6;
            uint c = a - b;
        }
    }
}
```
```
Run that and you'll see an
```
OverflowException
```
get thrown. If that's what you want for your whole project, you can set it in the project properties (or compile with the
```
/checked+
```
command line option to
```
csc
```
.)
EDIT: It's worth noting that the other answers have shown that you could put smaller amounts of code in the checked context - just the declaration and assignment of
```
c
```
or even just the calculation. It's all pretty flexible.


q: Is there a mechanism to inject dependencies into Linq to Sql or entity framework entities? If so would it be a sensible approach?

[A]
What exactly are you after? Note that you can use LINQ-to-SQL without the attributes, if you want to use existing classes... you need to use an
external xml file
to hold the mappings, and an
```
XmlMappingSource
```
.
Note that this won't work with Entity Framework; only LINQ-to-SQL.


q:
I have a Ruby DateTime which gets filled from a form. Additionally I have n hours from the form as well. I'd like to subtract those n hours from the previous DateTime. (To get a time range).

DateTime has two methods "-" and "<<" to subtract day and month, but not hour. (API). Any suggestions how I can do that?

[A]
If you are working in
Rails
, the following super-intutive possibility exists:
```
```
> Time.now - 12.hours
=> 2019-08-19 05:50:43 +0200
```
```
(This also works with
seconds
,
minutes
,
days
, and
years
)
if you're using just Ruby,
```
DateTime
```
can't do this, but
```
Time
```
can:
```
```
t = Time.now
t = t - (hours*60**2)
```
```
Note that
```
Time
```
also stores date information, it's all a little strange.
If you have to work with
```
DateTime
```
```
```
DateTime.commercial(date.year,date.month,date.day,date.hour-x,date.minute,date.second)
```
```
might work, but is ugly. The doc says
```
DateTime
```
is immutable, so I'm not even sure about
```
-
```
and
```
<<
```


q:
I need advice for rendering an undirected graph with 178,000 nodes and 500,000 edges.  I've tried Neato, Tulip, and Cytoscape.  Neato doesn't even come remotely close, and Tulip and Cytoscape claim they can handle it but don't seem to be able to.  (Tulip does nothing and Cytoscape claims to be working, and then just stops.)

I'd just like a vector format file (ps or pdf) with a remotely reasonable layout of the nodes.

[A]
Mathematica could very likely handle it, but I have to admit my first reaction was along the lines of the comment that said "take a piece of paper and color it black." Is there no way to reduce the density of the graph?
A possible issue is that you seem to be looking for layout, not just rendering. I have no knowledge about the Big O characteristics of the layouts implemented by various tools, but intuitively I would guess that it might take a
long
time to lay out that much data.


q:
I want to "remove" a UIView from a superview and add it again at the end... but at the "bottom" of the rest of the UIviews that belong to the superview.

Is this possible?

Any help is very appreciated!

[A]
Hmmm...
```
```
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
```
```
Might be what you're after?  Alternatively -
```
```
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
```
```
Though you could avoid removing the view all together (if you don't need to for any other reason) by calling sendSubviewToBack: -
```
```
- (void)sendSubviewToBack:(UIView *)view;
```
```


q:
My application is logically divided into server, which contain my Grails domain objects and controllers; and client, where I have my Ext GWT classes that build all the UI pages.

For UI requests, I am using an AJAX call to a controller method that returns, for instance, a list of domain objects as a JSON structure.

Following the DRY principle, I wouldn't like to "serialize" the domain data to a JSON string on the server then de-serialize it on the client to another structure - I'd like to take advantage of the Domain object I already have, this I don't have to change multiple places when I add, change or remove a new field.

Question is: is that a good way to go?

If yes, how would be the best way to make .groovy domain objects available on the "client-side" Ext GWT Java classes?

If no, why is it bad and what would you advice instead?

[A]
There isnt a good way - you need a java object that is GWT serializable. The only real solution that I can see is to write a plugin (or add to the GWT plugin) a way to autogenerate the data transfer object, perhaps using annotations in a grails domain object.
A similar method is being used to autogenerate the RPCAsync interfaces in the gwt plugin - see GwtGrailsPlugin.groovy in the gwt plugin directory, line 133 or so is the start.
You could hook into that (or just modify that file directly, probably easier) and insert some code to generate the data transfer files. An added benefit could be that you could granularize the data transfer object so that private data (like passwords!) dont get transferred.


q: We have a 3D application that retrieves keyboard presses via the IDirectInputDevice8. Is there any way, when we retrive keyboard events via the win32 API winproc loop back that we can send these commands to the DirectInputDevice?

[A]
The wndproc will is sent a combination of these messages on keyboard events:
```
```
WM_SYSKEYDOWN
WM_SYSKEYUP
WM_KEYDOWN
WM_KEYUP
WM_CHAR
```
```


q:
I have the requirement of generating UML Diagrams for one of my C++ assignments. I'm using Visio 2007 and I'm having trouble representing C++ vectors. The only way I can see this working is creating a custom C++ datatype or creating a vector class in my project, then for each instance of a vector in the UML, I need to dig into the properties and add <Class> into the suffix field.

Basically I'm trying to get vector<Object> without digging into the properties and adding <Class> to the suffix field every time.

I'm pretty much stuck with Microsoft software for making diagrams and coding so please don't suggest I use different software. However, if Visual Studio 2003 supports making UML Diagrams in a less painful way than Visio, I wouldn't object to using Visual Studio but please tell me where that option is.

[A]
You don't need to stipulate that it's a vector on the UML diagram.
In the example you're giving, there is a one-to-many relationship between one class and another. That's the significant information you need to communicate.
You've chosen to implement this as a vector: this is an implementation detail that doesn't need to go on the diagram - just display a one-to-many association.
If, for some reason, you need to change this to a std::list, or a std::deque, or any other stl container, you won't need to update the diagram, because the one-to-many concept is still the same.
Remember that you are displaying an
abstraction
of the code.  If you want to convey how all the classes conceptually relate to eachother, a UML class diagram is ideal.
If somebody wants to know the details of how it's implemented, he or she can always use the diagram as a starting point before looking at the source code itself.
For an example of one-to-many relationships displayed using UML, click
here


q:
I have a query:

UPDATE choices SET votes = votes + 1 WHERE choice_id = '$user_choice'

But when I execute it in my script, the votes field is updated twice, so the votes will go from 4 to 6 instead to 5. It doesn't seem that it is getting called twice because I echo out stuff to test this and only get one echo. Is there a way to have it so PHP will only execute this query once per page "refresh"?

EDIT: Thanks for the responses, I'm using regular MySQL, no MySQLi or PDO. Another thing I found is that when doing the query, it works when you start out with 0 and update to 1, but then after that it goes 3, 5, 7, ...

[A]
There are several SQL interfaces for many different brands of database in PHP.  You haven't shown the PHP code you use to execute the query, nor have you identified which brand of database you use.
In some SQL interfaces in PHP, creating the statement implicitly executes the SQL.  Then you have the opportunity to fetch results (if it was a SELECT statement).  If your statement was a SELECT or DELETE, it's likely that no harm was done, though it's unnecessary to execute the statement twice.  If your statement was an INSERT or UPDATE, though, you may find it has taken effect twice.
For example, using PDO:
```
```
$pdo = new PDO(...options...);
$stmt = $pdo->query('UPDATE ...'); // executes once
$stmt->execute(); // executes a second time
```
```