q:
Is there a way to reuse a 3rd party control reference?

For example, I have this referenced in my App.xaml

xmlns:cust="clr-namespace:ThirdParty.Controls;assembly=ThirdParty.Controls"

I don't want to repeat this 3rd party control xml namespace on each page/control that needs a control from the library.

Is there anyway to centralize these references and use the prefix defined here? The possibility of each control having a different prefix is also worrisome.  In asp.net you would put a reference in the web.config and it was available globally, I'm just looking to see if there is a similar method in WPF.

[A]
Two options I am thinking
1) Wrap that control into a UserControl and then use your UserControl in all the places.
2) Declare the third party control as a Resource somewhere and then use DynamicResource reference to that on your other places.
The second option can be implemented as bellow.
Where ever you want the third party control put a ContentControl like bellow
```
```
<ContentControl Template="{DynamicResource thirdPartyControlTemplate}" />
```
```
The ControlTemplate will be in the Resource file or at App.Xaml as bellow.
```
```
xmlns:thridParty="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"                >
<Application.Resources>
    <ControlTemplate x:Key="thirdPartyControlTemplate" TargetType="{x:Type ContentControl}">
        <thridParty:ThirdPartyControl />
    </ControlTemplate>
</Application.Resources>
```
```
You can see that the namespace declaration will be always on this resource file and you will be able to use that Control control from any place


q:
A table exists that someone else loaded.  I need to query against the table, but the lack of indexes makes the query plan abysmal.  What I would like to do is detect if there is an index for a particular column, so that I can created it if it does not exist, and not create it if it is already there.

Thanks.

Evil

[A]
Become familiar with querying the SYS schema:
```
```
Select * from sys.all_ind_columns where table_name=:TabName and table_owner=:TabOwner;
```
```

s: huggingface

c: devops

d: intermediate


q:
I wanted to deserialize an XML message containing an element that can be marked nil="true" into a class with a property of type int?. The only way I could get it to work was to write my own NullableInt type which implements IXmlSerializable. Is there a better way to do it?

I wrote up the full problem and the way I solved it on my blog.

[A]
I think you need to prefix the nil="true" with a namespace in order for XmlSerializer to deserialise to null.
MSDN on xsi:nil
```
```
<?xml version="1.0" encoding="UTF-8"?>
<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="array">
  <entity>
    <id xsi:type="integer">1</id>
    <name>Foo</name>
    <parent-id xsi:type="integer" xsi:nil="true"/>
```
```


q: Is it possible to use EventListener to Listen to a variable and detect when the value of that variable changes? Thanks.

[A]
You used to be able to do something similar in AS2 using Object.watch.  I don't see a direct equivalent, but it looks like
mx.binding.utils.ChangeWatcher
will give you similar functionality for any variables that are bindable.
I don't know of a way to do it in AS3 for non-bindable variables, but if the variable you want to watch is bindable (or if you can modify it to be binadable) then ChangeWatcher might give you what you want.


q:
When I run a wxPython application, it prints the string “Redirecting output to win32trace remote collector”and I must open PythonWin's trace collector tool to view that trace output.

Since I'm not interested in collecting this output, how should I disable this feature?

[A]
This message deceived me into thinking win32trace was preventing me from seeing uncaught exceptions in the regular console (of my IDE). The real issue was that wxPython by default redirects stdout/stderr to a popup window that quickly disappeared after an uncaught exception. To solve
that
problem, I simply had to pass
```
redirect=0
```
to the superclass constructor of my application.
```
```
class MyApp(wx.App):
    def __init__(self):
        # Prevent wxPython from redirecting stdout/stderr:
        super(MyApp, self).__init__(redirect=0)
```
```
That fix notwithstanding, I am still curious about how to control win32trace.


q:
I would like to find all the rows in a table and match on an exact case sensitive string. Unfortunately, my table has the case insensitive collation.

What is the most efficient way to perform this.

Eg.

I would like the following to return no rows:

select * from sysobject where name = 'Sysbinobjs'

For the answer assume @match is in a variable:

declare @match varchar(4000)
set @match = 'sysbinobjs'

EDIT

Clarification, make sure trailing spaces are treated properly, I want an exact match that takes account of trailing spaces so 'Hello' will only be matched with 'Hello' and not with 'Hello     '

[A]
Here is a snippet of code that works, its really tricky to do this in a safe and efficient way. The double match is to avoid a table scan (look at the execution plan). The varbinary casting forces a length and case match. So trailing spaces are treated properly and casing is treated properly.
Note
the type being compared needs to be identical to the type in the table for the varbinary casting to work (eg. name in sysobject is an nvarchar so the @match will need to be an nvarchar).
```
```
declare @match nvarchar(4000)
set @match = 'sysbinobjs'

select * from sysobjects
where name = @match and
cast(name as varbinary(4000)) = cast(@match as varbinary(4000))
```
```


q:
Is it possible to set the size of a checkbox using CSS or HTML across browsers?

width and size work in IE6+, but not with Firefox, where the checkbox stays 16x16 even if I set a smaller size.

[A] My understanding is that this isn't easy at all to do cross-browser. Instead of trying to manipulate the checkbox control, you could always build your own implementation using images, javascript, and hidden input fields. I'm assuming this is similar to what niceforms is (from Staicu lonut's answer above), but wouldn't be particularly difficult to implement. I believe jQuery has a plugin to allow for this custom behavior as well (will look for the link and post here if I can find it).


q: Why are the code-behind pages for an ASP.NET web application locked at run time? I have older projects (probably defined as "web sites" instead of "web apps") where I can edit the code behind, refresh the browser, and see my changes. With the web app, I have to continually close and reopen the browser if I want to see my changes live. Is there a setting or something I'm missing to allow me to edit at run time, and without restarting the debugging session?

[A]
When using IIS as your development server, Edit and continue is not currently available for Visual Studio for ASP.NET.
See this
blog entry
, however, that shows it is possible for the
Visual Studio 2005 Web Application Project
Project type. It requires using the Visual Studio Development Server (Cassini) during development instead of your local IIS (see the properties box on the project).


q: I have a very long-running stored procedure in SQL Server 2005 that I'm trying to debug, and I'm using the 'print' command to do it. The problem is, I'm only getting the messages back from SQL Server at the very end of my sproc - I'd like to be able to flush the message buffer and see these messages immediately during the sproc's runtime, rather than at the very end.

[A]
Use the
```
RAISERROR
```
function:
```
```
RAISERROR( 'This message will show up right away...',0,1) WITH NOWAIT
```
```
You shouldn't completely replace all your prints with raiserror.  If you have a loop or large cursor somewhere just do it once or twice per iteration or even just every several iterations.
Also: I first learned about RAISERROR at this link, which I now consider the definitive source on SQL Server Error handling and definitely worth a read:
http://www.sommarskog.se/error-handling-I.html


q:
need ask you about some help.

I have web app running in Net 2.0.

I wanna ask what storage (cache, session, file) I should use for my objects as they have different scope of using. Can be divide into several groups:

1) objects related directly to visitor (e.g. details about visitor that are received after authentication)

2) objects that are used for every visitor, so its scope of application (some init data, common data)

Most of these objects get data from web service, which is expensive.

So what's my best choices considering speed, memory, accessibility and what else I should look out.

Any help most welcome. Thanks, X.

[A]
Item 1 - Session would most likely be the best as it is per user, however, be sure to limit the number of items there as there are scaling issues, and considerations if in a web farm.
Item 2 - Depending on what you need, this would be a cache or application level item that you want to add, depending on need for expiration, etc.  The key difference is cache has expiration and usage items that can remove it, application is for things that always stay there.
Overall, in a web application I strongly recommend AGAINST files as then you have to worry about thread saftey.


q:
When I open a page(.aspx,xslt,css..etc) from the solution explorer in VS 2008 , it opens to the left of my current active tab. I am used to VS2003/VS2005 where the new page opens up to the right of current active page. How do i set all the pages to open to the right?

Thanks

[A]
It seems this can't be done in VS 2005/VS 2008
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=360962
http://www.codeverge.net/ng.asp-net-forum.visual_studio_2005/order-of-document-tabs-in-vs-2005
Pretty sad...its very tough getting used to this behavior


q:
I have found an example for encrypting a web.config during installation here, but my app is a windows service.  The aspnetreg_iis method works only for web.config files.

I know how to programatically encrypt the config file, but I don't think I can do that using WiX.  Am I wrong?  Any ideas?

[A]
You should be able to do it within a custom action.  The catch that I've found is that loading an assembly for an ExeConfigurationFileMap will throw an exception, but you can handle that by adding an AssemblyResolve handler to the AppDomain.  This is kind of a hack-up from a rich-client app I wrote to encrypt/decrypt protected configuration sections using a machine encryption key.  It's probably not the prettiest code, but I'm hoping you can get the picture from it.  This code assumes that you have the ProtectionProvider you want to use defined in the config file.
```
```
//class global
static System.Reflection.Assembly DefiningAssembly;

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

static System.Reflection.Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
     return DefiningAssembly;
}
```
```
Then, you can load your configuration like this:
```
```
DefiningAssembly = System.Reflection.Assembly.LoadFrom("path to defining assembly for config");

//Set the Configuration using an ExeConfigurationFileMap - This works for any .config file.
ExeConfigurationFileMap CfgMap = new ExeConfigurationFileMap();
CfgMap.ExeConfigFilename = "path to config file";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(CfgMap, ConfigurationUserLevel.None);

List<string> DefiningAssemblyTypes = new List<string>();
foreach (System.Type type in DefiningAssembly.GetExportedTypes())
{
     DefiningAssemblyTypes.Add(type.Name);
}

foreach (ConfigurationSection tempSection in config.Sections)
{
     if (DefiningAssemblyTypes.Contains(tempSection.ElementInformation.Type.Name))
     {
          section = tempSection;
          break;
     }
}
ProtectionProviderName = section.SectionInformation.ProtectionProvider.Name;
section.SectionInformation.ProtectSection(ProtectionProviderName);
config.Save(ConfigurationSaveMode.Minimal, true);
```
```
I hope this helps you, best of luck.


q:
On several of my usercontrols, I change the cursor by using

this.Cursor = Cursors.Wait;

when I click on something.

Now I want to do the same thing on a WPF page on a button click.  When I hover over my button, the cursor changes to a hand, but when I click it, it doesn't change to the wait cursor.  I wonder if this has something to do with the fact that it's a button, or because this is a page and not a usercontrol?  This seems like weird behavior.

[A]
Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using
Mouse.OverrideCursor
:
```
```
Mouse.OverrideCursor = Cursors.Wait;
try
{
    // do stuff
}
finally
{
    Mouse.OverrideCursor = null;
}
```
```
This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.


q:
I'm working on an application controller for a program that is spitting text directly to /dev/tty.

This is a production application controller that must be able to catch all text going to the terminal. Generally, this isn't a problem. We simply redirect stdout and stderr. This particular application is making direct calls to echo and redirecting the result to /dev/tty (echo "some text" > /dev/tty). Redirects via my application controller are failing to catch the text.

I do have the source for this application, but am not in a position to modify it, nor is it being maintained anymore. Any ideas on how to catch and/or throw away the output?

[A]
```
```
screen -D -m yourEvilProgram
```
```
should work. Much time passed sinced I used it, but if you need to read some of its output it could even be possible that you could utilize some sockets to read it.
[
Added
: two links,
Rackaid
and
Pixelbeat
, and the home page at
GNU
]


q:
Everyone is familiar with this functionality.  If you open up the the outlook address book and start typing a name, the list below the searchbox instantly filters to only contain items that match your query.  .NET Reflector has a similar feature when you're browsing types ... you start typing, and regardless of how large the underlying assembly is that you're browsing, it's near instantaneous.

I've always kind of wondered what the secret sauce was here.  How is it so fast?  I imagine there are also different algorithms if the data is present in-memory, or if they need to be fetched from some external source (ie. DB, searching some file, etc.).

I'm not sure if this would be relevant, but if there are resources out there, I'm particularly interested how one might do this with WinForms ... but if you know of general resources, I'm interested in those as well :-)

[A]
What is the most common use of the trie data structure?
A Trie is basically a tree-structure for storing a large list of similar strings, which provides fast lookup of strings (like a hashtable) and allows you to iterate over them in alphabetical order.
Image from:
http://en.wikipedia.org/wiki/Trie
:
In this case, the Trie stores the strings:
i
in
inn
to
tea
ten
For any prefix that you enter (for example, 't', or 'te'), you can easily lookup all of the words that start with that prefix. More importantly, lookups are dependent on the length of the string, not on how many strings are stored in the Trie. Read the wikipedia article I referenced to learn more.


q:
This isn't working.  Can this be done in find?  Or do I need to xargs?

find -name 'file_*' -follow -type f -exec zcat {} \| agrep -dEOE 'grep' \;

[A]
```
```
find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'
```
```


q:
The rails books and web pages I've been following have all stuck to very simple projects for the sake of providing complete examples.  I'm moving away from the small project app and into a realm of non-browser clients and need to decide where to put code that is shared by all involved parties.

The non-browser client is a script that runs on any machine which can connect to the database.  Browser clients write commands into the database, which the script examines and decides what to do.  Upon completion, the script then writes its result back.  The script is not started by the RoR server, but has access to its directory structure.

Where would be the best place for shared code to live, and how would the RoR loader handle it?  The code in question doesn't really belong in a model, otherwise I'd drop it in there and be done with it.

[A]
I'd put the shared code in the Rails project's
```
/lib
```
directory and consider making it a custom Rake task.


q:
What is the shortest chunk of C++ you can come up with to safely clean up a std::vector or std::list of pointers?  (assuming you have to call delete on the pointers?)

list<Foo*> foo_list;

I'd rather not use Boost or wrap my pointers with smart pointers.

[A]
```
```
template< typename T >
struct delete_ptr : public std::unary_function<T,bool>
{
   bool operator()(T*pT) const { delete pT; return true; }
};

std::for_each(foo_list.begin(), foo_list.end(), delete_ptr<Foo>());
```
```


q:
The .net framework 3.5 (or vista) provides me with an English voice (David I think) to use with the Speech.Synthesis api. I need a french voice to use with a french dictation practice app I am building for my kids to use to improve their french spelling. The api allows me to change culture when creating a voice, but the default English voice cannot pronounce the french words correctly.

I have been unable to find any way to download a french voice from Microsoft. Is this possible? I did download a Demo commercial voice from Cepstral, but it is crippled in a way that makes it unusable (even for testing). I did not want to buy anything as this exercise is just for fun.

I had hoped alternative language voices might be easily had without resort to the commercial professional voices. Any free alternatives?


q:
i get a Keyword not supported: '192.168.1.1;initial catalog'. error when trying to do this

Dim cn As New SqlConnection(str)

where str is the connection string starts with '192.168.1.1;initial catalog' ...
I have not specified the provider in the connection string

[A]
you need to provide a properly formatted connectionstring such as:
```
```
Dim str As String
str = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"

Dim cn As New SqlConnection(str)
```
```


q:
I'm having trouble with this code:

NSRect itemFrame;
id item;
// code to assign item goes here.
itemFrame.origin.y -= [item respondsToSelector:@selector(selectedHeight)] ? [item selectedHeight]   : [self defaultSelectedHeight];

This is the problematic bit:

[item selectedHeight]

The compiler is assuming that the return type is id. I though that adding a cast would fix this:

(float)[item selectedHeight]

but it doesn't work.

What am I doing wrong? (I suspect the problem is to do with resolving pointers related to id but I can't find any relevant documentation).

[A]
You need to look at the declaration of your
```
selectedHeight
```
method. The problem is either that the method is returning a pointer to an object (id), or you haven't imported the header file for
```
item
```
in the file that contains the code snippet, so Xcode assumes it's a pointer by default.
You can't cast a pointer to a float, since they're fundamentally incompatible types. Once you get your declarations straightened out though you should be okay.


q:
I need to test for general URLs using any protocol (http, https, shttp, ftp, svn, mysql and things I don't know about).

My first pass is this:

\w+://(\w+\.)+[\w+](/[\w]+)(\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?

(PCRE and .NET so nothing to fancy)


q:
Vim is acting slow when I scroll. The cursor skips some lines when I'm pressing j/k continually.

I'm using xterm and urxvt. In both vim acts like this.

This happens locally, with small or big files. I do use Control + F/B they work just fine.

EDIT: ttyfast in small files did the trick but in bigger is the same. When running without customization it goes allright.

[A]
Have you tried the 'ttyfast' option? See:
```
```
:help 'ttyfast'
```
```
for help, and:
```
```
:set ttyfast
```
```
to enable it.
Also, what version are you using? And have you tried this with no customizations to see if something you've set is interfering?
Run it like this to omit any of your vimrc settings and plugins:
```
```
vim -u NONE
```
```
EDIT: If removal of customizations fixes it. Remove things iteratively until the behavior returns. Start by narrowing it down to either a vimrc problem or to plugins.


q: What do I gain by adding a timestamp column called recordversion to a table in ms-sql?

[A]
Nothing that I'm aware of, or that Google seems to find quickly.
You con't get anything inherent by using that name for a column.  Sure, you can create a column and do the record versioning as described in the next response, but there's nothing special about the column name.  You could call the column anything you want and do versioning, and you could call any column RecordVersion and nothing special would happen.


q: Is this defined by the language? Is there a defined maximum? Is it different in different browsers?

[A]
>= ES6:
```
```
Number.MIN_SAFE_INTEGER;
Number.MAX_SAFE_INTEGER;
```
```
<= ES5
From
the reference
:
```
```
Number.MAX_VALUE;
Number.MIN_VALUE;
```
```
```
```
console.log('MIN_VALUE', Number.MIN_VALUE);
console.log('MAX_VALUE', Number.MAX_VALUE);

console.log('MIN_SAFE_INTEGER', Number.MIN_SAFE_INTEGER); //ES6
console.log('MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER); //ES6
```
```


q:
In .NET is there a function that tests if a string is syntactically a correct path? I specifically don't want it to test if the path actually exists.

my current take on this is a regex:

([a-zA-Z]:|\\)?\\?([^/\\:*?"<>|]+[/\\])*[^/\\:*?"<>|]*

matches:

c:\
bbbb
\\bob/john\
..\..\

rejects:

xy:
c:\\bob

[A]
I'd suggest just using a regex for this since you specifically don't want to test if the path exists.
Here's something
google helped me dig up
:
```
```
RegEx="^([a-zA-Z]\:|\\\\[^\/\\:*?"<>|]+\\[^\/\\:*?"<>|]+)(\\[^\/\\:*?"<>|]+)+(\.[^\/\\:*?"<>|]+)$"
```
```
You could combine this with System.IO.Path.GetInvalidPathChars() method and make the regex dynamically exclude all of the invalid characters.


q:
I want to store a URL prefix in an Windows environment variable. The ampersands in the query string makes this troublesome though.

For example: I have a URL prefix of http://example.com?foo=1&bar= and want to create a full URL by providing a value for the bar parameter. I then want to launch that URL using the "start" command.

Adding quotes around the value for the SET operation is easy enough:

set myvar="http://example.com?foo=1&bar="

Windows includes the quotes in the actual value though (thanks Windows!):

echo %myvar%
"http://example.com?foo=1&bar=true"

I know that I can strip quotes away from batch file arguments by using tilde:

echo %~1

However, I can't seem to do it to named variables:

echo %~myvar%
%~myvar%

What's the syntax for accomplishing this?

[A]
I think this should do it:
```
```
for /f "tokens=*" %i in (%myvar%) do set %myvar%=%~i
```
```
But you do not need this,
```
```
set myvar="http://example.com?foo=1&bar="
start "" %myvar%
```
```
Will work too, you just need to supply a title to the start command.


q:
I have a field in my form labeled "Name" that will contain both the First & Last name.

Our existing dynamic server (to which the form is being POSTed to), expects two separate fields (first name, last name).

Can I use Javascript to split the user input into two separate variables before the form is posted to the server?  How would I do this?

[A]
You can do something like this:
```
```
var yourForm = document.getElementById('yourFormId');
yourform.onsubmit = new function()
{
    var nameBox = document.getElementById('nameBox');
    var fname = document.createElement('INPUT');
    var lname = document.createElement('INPUT');
    fname.type = 'HIDDEN';
    lname.type = 'HIDDEN';
    fname.name = 'fname';
    lname.name = 'lname';

    var tokens = nameBox.value.split(' ');

    // Note there are a million ways to break this parser, demonstration only
    fname.value = tokens[0];
    lname.value = tokens[1];

    yourForm.appendChild(fname);
    yourForm.appendChild(lname);
}
```
```


q:
I have the whole MVC-Model set up and use HTML views as templates. But I have german strings in there that I would like to translate to other languages at some point.

What is the best way to do this? I know I have to use Zend_Translate, but do I have to implement a single call to a translate function for every word that I have in my view templates?

[A]
First of all, I'd suggest to use complete phrases as the basis for your translation. With words you always have the problem that languages are not consistent when it comes to  sentence structure.
Then you have to choose one of the available Zend_Transalate adapters: Array, Csv, Gettext, Ini, Tbx, Tmx, Qt, Xliff or XmlTm. Most of them are adapters to industry standards for storing translation information, so it probably would suffice if you chose Array, Csv or Ini for the beginning and for the ease of use. Please see
49.2.1. How to decide which translation adapter to use
in the Zend Framework manual.
```
```
// setup your translation
$translate = new Zend_Translate('csv', '/my/path/source-de.csv', 'de');
$translate->addTranslation('/my/path/source-en.csv', 'en');
// add the translation adapter to the registry
Zend_Registry::set('Zend_Translate', $translate);
```
```
As there is a
```
Zend_View_Helper_Translate
```
that access the standardized
```
Zend_Registry
```
entry
```
Zend_Translate
```
as the default translation source, you can use the following in your views:
```
```
[...]
<title><?php echo this->translate('Title'); ?></title>
[...]

You can also do <?php echo $this->translate('Hello %1$s', $this->userName); ?>

[...]
```
```
Please note that this only is a short introduction into
```
Zend_Translate
```
and by no means a complete presentation of the functionality provided by this component. For example there is a lot to be said about determining the locale the translation adapter will use.
I'd suggest you read the following in the Zend Framework manual, because localization can be a complex issue and
```
Zend_Translate
```
can not be described entirely in here:
53.4.1.13. Translate Helper
Chapter 49. Zend_Translate


q: What's the easiest way to play a sound file (.wav) in Python? By easiest I mean both most platform independent and requiring the least dependencies. pygame is certainly an option, but it seems overkill for just sound.

[A]
pyMedia's sound example does
just that
. This should be all you need.
```
```
import time, wave, pymedia.audio.sound as sound
f= wave.open( 'YOUR FILE NAME', 'rb' )
sampleRate= f.getframerate()
channels= f.getnchannels()
format= sound.AFMT_S16_LE
snd= sound.Output( sampleRate, channels, format )
s= f.readframes( 300000 )
snd.play( s )
```
```


q:
how to create a good plugin engine for standalone executables created with pyInstaller, py2exe or similar tools?

I do not have experience with py2exe, but pyInstaller uses an import hook to import packages from it's compressed repository. Of course I am able to import dynamically another compressed repository created with pyInstaller and execute the code - this may be a simple plugin engine.

Problems appears when the plugin (this what is imported dynamically) uses a library that is not present in original repository (never imported). This is because import hook is for the original application and searches for packages in original repository - not the one imported later (plugin package repository).

Is there an easy way to solve this problem? Maybe there exist such engine?

[A]
When compiling to exe, your going to have this issue.
The only option I can think of to allow users access with thier plugins to use any python library is to include all libraries in the exe package.
It's probably a good idea to limit supported libraries to a subset, and list it in your documentation. Up to you.
I've only used py2exe.
In py2exe you can specify libraries that were not found in the search in the
setup.py
file.
Here's a sample:
```
```
from distutils.core import setup
import py2exe

setup (name = "script2compile",
       console=['script2compile.pyw'],
       version = "1.4",
       author = "me",
       author_email="somemail@me.com",
       url="myurl.com",
       windows = [{
                    "script":"script2compile.pyw",
                    "icon_resources":[(1,"./ICONS/app.ico")]  # Icon file to use for display
                 }],
       # put packages/libraries to include in the "packages" list
       options = {"py2exe":{"packages": [   "pickle",
                                            "csv",
                                            "Tkconstants",
                                            "Tkinter",
                                            "tkFileDialog",
                                            "pyexpat",
                                            "xml.dom.minidom",
                                            "win32pdh",
                                            "win32pdhutil",
                                            "win32api",
                                            "win32con",
                                            "subprocess",
                                        ]}}

       )

import win32pdh
import win32pdhutil
import win32api
```
```


q:
Is it possible to forward declare an standard container in a header file?  For example, take the following code:

#include <vector>

class Foo
{
private:
    std::vector<int> container_;
    ...
};

I want to be able to do something like this:

namespace std
{
    template <typename T> class vector;
}

class Foo
{
private:
    std::vector<int> container_;
    ...
};

Can this be done?

[A]
I don't think so because the compiler would have no way of knowing how much space to allocate for the
```
container_
```
object. At best you could do:
```
```
std::vector<int> *container_;
```
```
and new it in the constructor, since the compiler knows the size of a pointer.


q:
I just ran across the following error (and found the solution online, but it's not present in Stack Overflow):

(.gnu.linkonce.[stuff]): undefined
  reference to [method] [object
  file]:(.gnu.linkonce.[stuff]):
  undefined reference to `typeinfo for
  [classname]'

Why might one get one of these "undefined reference to typeinfo" linker errors?

(Bonus points if you can explain what's going on behind the scenes.)

[A]
This occurs when declared (non-pure) virtual functions are missing bodies. In your class definition, something like:
```
```
virtual void foo();
```
```
Should be defined (inline or in a linked source file):
```
```
virtual void foo() {}
```
```
Or declared pure virtual:
```
```
virtual void foo() = 0;
```
```


q:
I have a gallery I quickly coded up for a small site, and under Firefox 3 and Safari 3 works fine. But when I test on my old best friend IE7, it seems to not fire the imageVar.onload = function() {  // code here }.. which I want to use to stop the load effect and load the image.

Please bear in mind...

I know the thumbnails are just scaled down version of the larger images. When the images are finalised by the client I am going to create proper thumbnails.

This is my first attempt to try and get out of procedural JavaScript for the most part.. so please go easy and kindly let me know where my code sucks!

[A]
Cross browser event support is not so straightforward due to implementation differences. Since you are using jQuery at your site, you are better off using its events methods to normalize browser support:
instead of:
```
```
window.load = function(){
      //actions to be performed on window load
 }

 imageViewer.image.onload = function(){
     //actions to be performed on image load
 }
```
```
Do:
```
```
$(window).load(function(){
    //actions to be performed on window load
});

 $(imageViewer.image).load(function(){
      //actions to be performed on image load
 });
```
```


q:
I have two directories in the same parent directory.  Call the parent directory base and the children directories alpha and bravo.  I want to replace alpha with bravo.  The simplest method is:

rm -rf alpha
mv bravo alpha

The mv command is atomic, but the rm -rf is not.  Is there a simple way in bash to atomically replace alpha with bravo?  If not, is there a complicated way?

ADDENDUM:

By the by, it's not an insurmountable problem if the directory doesn't exist for a short period. There's only one place that tries to access alpha, and it checks if alpha exists before doing anything critical. If not, it gives an error message. But it would be nice if there was a way to do this. :) Maybe there's some way to modify the inodes directly, or something...

[A]
I don't believe there's any atomic way to do this. Your best bet is to do something like this:
```
```
mv alpha delme
mv bravo alpha
rm -rf delme
```
```


q:
What's the general consensus?

If you need to change the database after a given action, do you use an observer pattern and let the framework / application handle the update for you?  Or do you bypass the application and delegate the update to a database trigger?

Obviously the trigger is faster, but is it worth it?

[A]
As we use LINQ2SQL this task is quite easy to be acoomplished overriding the SubmitChanges() method. Our main goal is to do auditing in our tables. The code would like this:
```
```
/// <summary>
    /// Sends changes that were made to retrieved objects to the underlying database,
    /// and specifies the action to be taken if the submission fails.
    /// NOTE: Handling this event to easily perform Audit tasks whenever a table gets updated.
    /// </summary>
    /// <param name="failureMode">The action to be taken if the submission fails.
    /// Valid arguments are as follows:<see cref="F:System.Data.Linq.ConflictMode.FailOnFirstConflict"/>
    /// <see cref="F:System.Data.Linq.ConflictMode.ContinueOnConflict"/></param>
    public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
    {
        //Updates
        for (int changeCounter = 0; changeCounter < this.GetChangeSet().Updates.Count; changeCounter++)
        {
            object modifiedEntity = this.GetChangeSet().Updates[changeCounter];
            SetAuditStamp(this, modifiedEntity, ChangeType.Update);
        }

        //Inserts
        for (int changeCounter = 0; changeCounter < this.GetChangeSet().Inserts.Count; changeCounter++)
        {
            object modifiedEntity = this.GetChangeSet().Inserts[changeCounter];
            SetAuditStamp(this, modifiedEntity, ChangeType.Insert);
        }
        base.SubmitChanges(failureMode);
```
```
We particulary don't like using triggers as they are always hidden into you DB and it makes hard to work out problems that may occur ... with having that into your code you just need to start debugging it to find out why something has failed for instance ...


q:
in Web 2.0 applications many users usually want to stay logged in ('remember me' flag) and on the other hand their cookie can give access to very private data. Is there a way to prevent that somebody who steals the cookie - directly from the computer or via sniffing - can use the cookie to get access to the user's data? Always HTTPS is not an option.

Thanks, Bernd

[Edit] Connect the IP address to the cookie is not an option either.

[A]
Store a cookie that is an obscure ID into your local server database. Do a server-side DB lookup based on the ID provided in the cookie.  Be sure to make the ID sufficiently complex that it cannot be easily guessed.  Map the ID to the IP Address of the user. If their IP changes, then force them to log in again, and create a new ID.
On second read, it sounds like you want a high level of security with your hands tied. The user must have the choice to remain logged in and thus increase his/her risk.  You can implement all the security in the world from the application's and server's point of view, but if the user forgets their laptop on a table in Tim Horton's (Canadian Starbucks), then none of it will do you any good.
Leave the choice up to the user as to whether or not they remain logged in, and give them a warning about their information being at risk.


q:
I've got a few Unix shell scripts where I need to check that certain environment variables are set before I start doing stuff, so I do this sort of thing:

if [ -z "$STATE" ]; then
    echo "Need to set STATE"
    exit 1
fi

if [ -z "$DEST" ]; then
    echo "Need to set DEST"
    exit 1
fi

which is a lot of typing. Is there a more elegant idiom for checking that a set of environment variables is set?

EDIT: I should mention that these variables have no meaningful default value - the script should error out if any are unset.

[A]
```
```
${MyVariable:=SomeDefault}
```
```
If
```
MyVariable
```
is set and not null, it will reset the variable value (= nothing happens).
Else,
```
MyVariable
```
is set to
```
SomeDefault
```
.
The above will attempt to execute
```
${MyVariable}
```
, so if you just want to set the variable do:
```
```
MyVariable=${MyVariable:=SomeDefault}
```
```


q:
public static IQueryable<TResult> ApplySortFilter<T, TResult>(this IQueryable<T> query, string columnName)
  where T : EntityObject
{
  var param = Expression.Parameter(typeof(T), "o");
  var body = Expression.PropertyOrField(param,columnName);

  var sortExpression = Expression.Lambda(body, param);
  return query.OrderBy(sortExpression);
}

Because the type for OrderBy is not inferred from sortExpression I need to specify it something like this at run time:

var sortExpression = Expression.Lambda<T, TSortColumn>(body, param);

Or

return query.OrderBy<T, TSortColumn>(sortExpression);

I don't think this is possible however as TSortColumn can only be determined during runtime.

Is there a way around this?

[A]
It seems that
this
is the way to do it, now to verify that:
```
```
// ***** OrderBy(company => company) *****
// Create an expression tree that represents the expression
// 'whereCallExpression.OrderBy(company => company)'
MethodCallExpression orderByCallExpression = Expression.Call(
    typeof(Queryable),
    "OrderBy",
    new Type[] { queryableData.ElementType, queryableData.ElementType },
    whereCallExpression,
    Expression.Lambda<Func<string, string>>(pe, new ParameterExpression[] { pe }));
// ***** End OrderBy *****
```
```


q:
Can you program/configure Visual Studio to produce custom intellisense for your own server controls.

eg can you get it to do this:

alt text http://www.yart.com.au/test/vs.gif

for a tag of your own like:

<MyCompany:MyTag ...

[A]
Bluevision have a nice plugin for Visual Studio to do this for you. Last time I looked, it was free. (yep, it's still free!)
IntellisenseAttribute class allows you to specify members for which intellisense symbols will be generated.
Ability to generate default intellisense symbols for assemblies when you don't have access to the source code.
NEW Snaps right into the IDE so that intellisense generation can be automated during the build process.
Supports two visual views: Full Mode and Skin Mode.
Full source code.
FREE!
http://www.bluevisionsoftware.com/WebSite/ProductsAndServicesInfo.aspx?ID=9


q:
With code like the following, sometimes the child controls correctly finish their animation and sometimes they stop at random places in the middle.  Why don't they work correctly?

var t:Tween;
t = new Tween(child1,"x",Elastic.easeOut,0,100,2,true);
t = new Tween(child1,"y", Elastic.easeOut,0,100,2,true);
t = new Tween(child2,"x",Strong.easeOut,300,400,1,true);
t = new Tween(child2,"y", Strong.easeOut,300,400,1,true);

[A]
Each tween must be assigned to a separate variable in global scope.  The following code behaves reliably:
```
```
var t1:Tween = new Tween(child1,"x",Elastic.easeOut,0,100,2,true);
var t2:Tween = new Tween(child1,"y", Elastic.easeOut,0,100,2,true);
var t3:Tween = new Tween(child2,"x",Strong.easeOut,300,400,1,true);
var t4:Tween = new Tween(child2,"y", Strong.easeOut,300,400,1,true);
```
```
It would appear that when a variable is re-used, the tween that is no longer referenced may get garbage collected or otherwise halted in the middle of its work.
The same problem can occur if you use separate variables but declare them in the local scope of a function instead of in the global scope of your frame.


q:
Relatively new to rails and trying to model a very simple family "tree" with a single Person model that has a name, gender, father_id and mother_id (2 parents). Below is basically what I want to do, but obviously I can't repeat the :children in a has_many (the first gets overwritten).

class Person < ActiveRecord::Base
  belongs_to :father, :class_name => 'Person'
  belongs_to :mother, :class_name => 'Person'
  has_many :children, :class_name => 'Person', :foreign_key => 'mother_id'
  has_many :children, :class_name => 'Person', :foreign_key => 'father_id'
end

Is there a simple way to use has_many with 2 foreign keys, or maybe change the foreign key based on the object's gender? Or is there another/better way altogether?

Thanks!

[A]
I believe you can achieve the relationships you want using :has_one.
```
```
class Person < ActiveRecord::Base
  has_one :father, :class_name => 'Person', :foreign_key => 'father_id'
  has_one :mother, :class_name => 'Person', :foreign_key => 'mother_id'
  has_many :children, :class_name => 'Person'
end
```
```
I'll confirm and edit this answer after work ; )


q:
I keep seeing people say that exceptions are slow, but I never see any proof. So, instead of asking if they are, I will ask how do exceptions work behind the scenes, so I can make decisions of when to use them and whether they are slow.

From what I know, exceptions are the same as doing a return bunch of times, except that it also checks after each return whether it needs to do another one or to stop. How does it check when to stop returning? I guess there is a second stack that holds the type of the exception and a stack location, it then does returns until it gets there. I am also guessing that the only time this second stack is touched is on a throw and on each try/catch. AFAICT implementing a similar behaviour with return codes would take the same amount of time. But this is all just a guess, so I want to know what really happens.

How do exceptions really work?

[A]
There are a number of ways you could implement exceptions, but typically they will rely on some underlying support from the OS.  On Windows this is the structured exception handling mechanism.
There is decent discussion of the details on Code Project:
How a C++ compiler implements exception handling
The overhead of exceptions occurs because the compiler has to generate code to keep track of which objects must be destructed in each stack frame (or more precisely scope) if an exception propagates out of that scope.  If a function has no local variables on the stack that require destructors to be called then it should not have a performance penalty wrt exception handling.
Using a return code can only unwind a single level of the stack at a time, whereas an exception handling mechanism can jump much further back down the stack in one operation if there is nothing for it to do in the intermediate stack frames.


q:
I was wondering if there's a way I can automate the generation of XML files from XSD schemas given that I have the data and the labels. I'd like to do this in python/java. It seems very possible, yet I can't find any library that allows me to do this. I'm looking for a fairly quick solution..
Any ideas?

See also: how-to-generate-sample-xml-documents-from-their-dtd-or-xsd

[A]
JAXB
works fantastic for generating classes from xsd.
Ibatis
works fantastic for getting data into classes.
You can use Ibatis to feed data and automatically create classes, then use JAXB to marshal the classes into an XML file! Mind you, that's a lot of effort if you're not going to be doing it over and over again.


q:
I'm writing some RSS feeds in PHP and stuggling with character-encoding issues. Should I utf8_encode() before or after htmlentities() encoding? For example, I've got both ampersands and Chinese characters in a description element, and I'm not sure which of these is proper:

$output = utf8_encode(htmlentities($source)); or
$output = htmlentities(utf8_encode($source));

And why?

[A]
You want to do
```
$output = htmlentities(utf8_encode($source));
```
.  This is because you want to convert your international characters into proper UTF8 first, and then have ampersands (and possibly some of the UTF-8 characters as well) turned in to HTML entities.  If you do the entities first, then some of the international characters may not be handled properly.
If none of your international characters are going to be changed by utf8_encode, then it doesn't matter which order you call them in.


q:
I am able to create and execute a DTS package that copies tables from a remote Oracle database to a local SQL server, but want to setup the connection to the Oracle database as a linked server.

The DTS package currently uses the Microsoft OLE DB Provider for Oracle with the following properties:

Data Source: SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.1.3.42)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=acc)));uid=*UserName*;pwd=*UserPassword*;

Password: UserPassword

User ID: UserName

Allow saving password: true

How do I go about setting a linked server to an Oracle database using the data source defined above?

[A]
I was able to setup a linked server to a remote Oracle database, which ended up being a multi-step process:
Install Oracle ODBC drivers on SQL Server.
Create System DSN to Oracle database on SQL Server.
Create linked server on SQL server using System DSN.
Step 1: Install Oracle ODBC drivers on server
a. Download the necessary
Oracle Instant Client
packages: Basic, ODBC, and SQL*Plus (optional)
b. Unzip the packages to a local directory on the SQL server, typically
```
C:\Oracle
```
. This should result in a [directory] like
```
C:\Oracle\instantclient_10_2
```
, which will be the value of [directory] referenced in the rest of this answer.
c. Create a text file named
```
tnsnames.ora
```
within the instant client [directory] that contains the following:
```
```
OracleTnsName =
(
  DESCRIPTION=
  (
    ADDRESS = (PROTOCOL=TCP)(HOST=10.1.3.42)(PORT=1521)
  )
  (
    CONNECT_DATA = (SERVICE_NAME=acc)
  )
)
```
```
Note: Actual
```
HOST
```
,
```
PORT
```
, and
```
SERVICE_NAME
```
will vary based on Oracle server you are establishing a connection to. This information can often be found using the Oracle network client tools under the
listeners
.
The
```
OracleTnsName
```
can be any name you want to assign to the Oracle data source, and will be used when setting up the system DSN. You can also use the syntax above to define multiple TNS names in the same
tnsnames.ora
file if desired.
d. Add the [directory] to the system
```
PATH
```
environment variable.
e. Create a new system environment variable named
```
TNS_Admin
```
that has a value of [directory]
f. Execute the
```
[directory]\odbc_install.exe
```
utility to install the Oracle ODBC drivers.
g. It is recommended that you reboot the SQL server, but may not be necessary. Also, you may want to grant security permissions to this directory for the SQL server and SQL agent user identities.
Step 2: Create a System DNS that uses the Oracle ODBC driver
a. Open the
ODBC Data Source Administrator
tool. [ Administrative Tools --> Data Sources (ODBC) ]
b. Select the System DSN tab and then select the Add button.
c. In the drivers list, select
Oracle in instantclient {version}
. (e.g. 'Oracle in instantclient 10_2') and then select Finish button.
d. Specify the following:
```
Data Source Name
```
: {System DSN Name}
```
Description
```
: {leave blank/empty}
```
TNS Service Name
```
: should have the
```
OracleTnsName
```
you defined in the
```
tnsnames.ora
```
file listed, select it as the value.
User ID
: {Oracle user name}
e. Select Test Connection button. You should be prompted to provide the {Oracle user password}. If all goes well the test will succeed.
Step 3: Create linked server in SQL to the Oracle database
Open a query window in SQL server and execute the following:
```
```
EXEC sp_addlinkedserver
     @server        = '{Linked Server Name}'
    ,@srvproduct    = '{System DSN Name}'
    ,@provider      = 'MSDASQL'
    ,@datasrc       = '{System DSN Name}'

EXEC sp_addlinkedsrvlogin
     @rmtsrvname    = '{Linked Server Name}'
    ,@useself       = 'False'
    ,@locallogin    = NULL
    ,@rmtuser       = '{Oracle User Name}'
    ,@rmtpassword   = '{Oracle User Password}'
```
```
Note: The
```
{Linked Server Name}
```
can be anything you want to use when referencing the Oracle server, but the
```
{System DNS Name}
```
must
match the name of the system DSN you created previously.
The
```
{Oracle User Name}
```
should be the same as the User ID used by the system DSN, and the
```
{Oracle User Password}
```
should be the same as you used to successfully test the ODBC connection. See
KB 280106
for information on troubleshooting Oracle linked server issues.
Querying the Oracle linked server
You may use
OPENQUERY
to execute pass-through queries on the Oracle linked server, but be aware that for very large recordsets you may receive a
```
ORA-01652
```
error message if you specify a
```
ORDER BY
```
clause in the pass-through query. Moving the
```
ORDER BY
```
clause from the pass-through query to the outer select statement solved this issue for me.


q: How can I remove duplicate values from an array in PHP?

[A]
Use
array_unique()
.
Example:
```
```
$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
```
```


q:
I have a C#.net winform program which runs with a SQL Server database.  I am using LINQ-to-SQL.  Is it possible to rollback the call to one or more stored procedures inside a transaction within my program using LINQ-to-SQL?

Initially I thought it would make sense to manage the transaction inside the stored procedure but if I need to rollback more than one stored procedure call as part of a single transaction it would need to be done in my C# program.

Can someone point me to a code snippet on how to do this or provide some insight into an alternative?

[A]
Although I'm not using stored procs, you coudl have something like that:
```
```
public Response<SomeObject> SaveSomething(Object yourObject)
    {
        DbTransaction dbTransaction = null;
        try
        {
            using (DataContext context = new DataContext())
            {
                    //Creates a new DB transaction
                    if (context.Connection.State == System.Data.ConnectionState.Closed)
                    {
                        context.Connection.Open();
                    }
                    dbTransaction = context.Connection.BeginTransaction(System.Data.IsolationLevel.Serializable);
                    context.Transaction = dbTransaction;

         context.SaveYourObject(yourObject);
                    //Commit the transaction
                    dbTransaction.Commit();
                    response.ResponseObject = yourObject;
                    response.Messages.AddSuccessfulSave("Saved!");
                }
            }
        }
        catch (ChangeConflictException cex)
        {
            if (dbTransaction != null) dbTransaction.Rollback();
            response.Errors.AddConcurrencyError();
            response.IsSuccessful = false;
        }
        catch (SqlException sqlEx)
        {
            if (dbTransaction != null) dbTransaction.Rollback();
            if (sqlEx.Class == 14 && (sqlEx.Number == 2601 || sqlEx.Number == 2627)) //Duplicated key
            {
                response.Errors.Add(new Error
                {
                    Name = "Duplicate item",
                    Description = "This object already exists."
                });
                ExceptionPolicy.HandleException(sqlEx, SERVICE_EXCEPTION_POLICY);
                response.IsSuccessful = false;
            }
            else //other SQL errors
            {
                response.Errors.AddSavingError("Your object", yourObjectId);
                ExceptionPolicy.HandleException(sqlEx, SERVICE_EXCEPTION_POLICY);
                response.IsSuccessful = false;
            }
        }
```
```


q:
I find myself running scripts and copy-pasting the output of these runs into emails or into some other documents. Is there a way such that I can make the copy-to-clipboard step a part of the script itself? Most of my scripts are either Perl or bat files and I work on Windows.

Thanks.

[A]
Not sure about the clipboard but you can pipe the output to a text file but doing something like this:
```
```
somescript.bat > output.txt
```
```


q:
Say I have a user control like the one below, how would I bind something to the ActualWidth of the "G1" grid from outside of the control?

<UserControl x:Class="Blah">
  <WrapPanel>
    <Grid x:Name="G1">
      ...
    </Grid>
    <Grid>
      ...
    </Grid>
  </WrapPanel>
</UserControl>

[A]
If you want to bind to an external control where you use this user control, declare a
```
DependencyProperty
```
at your UserControl code behind and then Bind G1 to that property.
And bind the external control's property to the UserControl's
```
DependencyProperty
```
.
It is like a 2 level of indirection.


q:
How can I remove duplicate values from a multi-dimensional array in PHP?

Example array:

Array
(
    [0] => Array
    (
        [0] => abc
        [1] => def
    )

    [1] => Array
    (
        [0] => ghi
        [1] => jkl
    )

    [2] => Array
    (
        [0] => mno
        [1] => pql
    )

    [3] => Array
    (
        [0] => abc
        [1] => def
    )

    [4] => Array
    (
        [0] => ghi
        [1] => jkl
    )

    [5] => Array
    (
        [0] => mno
        [1] => pql
    )

)

[A]
The user comments on the
array_unique()
documentation have many solutions to this. Here is one of them:
kenrbnsn at rbnsn dot com
27-Sep-2005 12:09
Yet another Array_Unique for multi-demensioned arrays. I've only tested this on two-demensioned arrays, but it could probably be generalized for more, or made to use recursion.
This function uses the serialize, array_unique, and unserialize functions to do the work.
```
```
function multi_unique($array) {
    foreach ($array as $k=>$na)
        $new[$k] = serialize($na);
    $uniq = array_unique($new);
    foreach($uniq as $k=>$ser)
        $new1[$k] = unserialize($ser);
    return ($new1);
}
```
```
This is from
http://ca3.php.net/manual/en/function.array-unique.php#57202
.


q:
I'm working on a puzzle game, the game engine holds a complex hierarchy of objects, from game actors to vectors to transition animations. Depending on the game state, they might add up from 10 to 1000 (in extreme cases). I've been delaying the moment until I'd have to work on the saving and loading of all that mess, as I have no experience on this, but now the moment I was fearing is about to arrive.

Is it a good idea to use NSKeyedArchiver for this? Its concept seems powerful. That way I could rebuild the objects states, but does that include the pointers between saved objects? And how does it behave performance-wise? Will the system have time to save all these objects on disk on app termination?

[A]
NSKeyedArchiver is quite powerful, but it will not let you retain linkages between objects (unless you add them yourself post-unarchiving). If you can/need to store your entire data set atomically, then NSKeyedArchiver is probably the way to go, but there will be some 're-hydration' involved on your part if there's anything more complex then parent-child relationships.
We have a complex hierarchy of data objects, we store them out to an SQLite database, and re-hook them up when we extract them.


q:
Just need to use find a simple way to have AD authenticate as the login for a Sharepoint site. This fairly quick and simple to get going ?

Thanks!

[A]
For SharePoint 2007, see this
article
.  You probably want to set it up to do Windows integrated authentication with NTLM.  Getting authentication working is probably not too hard, getting your site setup the way you want with permissions/authorization working probably isn't.  Depends on how complex your site is.  I wasn't directly involved but I know that it took a few months to get our intranet up and bug free.
One recommendation that I would have is to use AD groups or SharePoint groups that contain AD groups rather than individuals to control access.  It's much easier to clean up AD group membership when an individual leaves than to track down all the places where you've given them individual access (including membership in SharePoint groups).


q: What is a simple way of downloading a file from a URL path?

[A]
Use
```
System.Net.WebClient.DownloadFile
```
:
```
```
string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;

// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
    myStringWebResource = remoteUri + fileName;
    // Download the Web resource and save it into the current filesystem folder.
    myWebClient.DownloadFile(myStringWebResource, fileName);
}
```
```


q: I would like to know the simplest and most effective way to open and write data to a socket in the C programming language for network programming.

[A] Reading and writing from basic sockets is not any harder than reading and writing normal files (just use recv instead of read and send instead if write).  Things get a little trickey when you need to open a socket.  The reason for that is because there are many different ways to communicate using sockets (TCP, UDP, etc).


q:
Is there any easy way to add a using statement to every class I create in a project without having to write

using SomeNamespace;

in every file?

[edit]
I could add a template I realise but I'm talking about doing it for every file in an existing project.

[A]
I believe you can do something like:
```
```
<system.web>
        <pages>
              <namespaces>
                    <add namespace="System.IO" />
                    <add namespace="System.Text"/>
                    <add namespace="Westwind.Tools"/>
              </namespaces>
        </pages>
</system.web>
```
```
http://www.west-wind.com/WebLog/posts/2287.aspx


q:
When working with Silverlight, I've noticed that Firefox will cache the XAP file, so if I do an update, a user may be stuck using an outdated version.  Is there a way to force the browser to either re-download the XAP file every time, or maybe only force it to after an update has been published?  Or is there a setting in the Silverlight config that stops the browser from caching the XAP file altogether?

Thanks,
jeff

[A]
You could send HTTP headers to prevent it from caching:
```
```
Cache-control: no-cache
Pragma: no-cache
```
```
How you do this depends on the web server you're using.


q:
class Ball:
  a = []
  def __init__(self):
    pass

  def add(self,thing):
    self.a.append(thing)

  def size(self):
    print len(self.a)

for i in range(3):
  foo = Ball()
  foo.add(1)
  foo.add(2)
  foo.size()

I would expect a return of :

2
2
2

But I get :

2
4
6

Why is this? I've found that by doing a=[] in the init, I can route around this behavior, but I'm less than clear why.

[A]
doh
I just figured out why.
In the above case, the a is a class attribute, not a data attribute - those are shared by all Balls(). Commenting out the a=[] and placing it into the
init
block means that it's a data attribute instead. (And, I couldn't access it then with foo.a, which I shouldn't do anyhow.) It seems like the class attributes act like static attributes of the class, they're shared by all instances.
Whoa.
One question though : CodeCompletion sucks like this. In the foo class, I can't do self.(variable), because it's not being defined automatically - it's being defined by a function. Can I define a class variable and replace it with a data variable?


q:
In asp.net mvc, when do we use:

and

Do we ever need to put a ; (colon) ?

[A]
```
<%= %>
```
renders the output (string) of the contained command to the response.
```
<% %>
```
wraps executable statements (logic) in the view to control what gets executed.  You don't use semicolons in the
```
<%= %>
```
blocks, but may in the
```
<% %>
```
depending on what statements are included.
String rendering:
```
<%= Html.Encode( Model. Property ) %>
```
Code block:
```
<% Html.RenderPartial( "ViewName" ); %>
```
EDIT:
Here's a
link
to the reference.


q: How would make a news feed "friendly" database design, so that it wouldn't be extremely expensive to get all of the items (query) to put in the news feed?  The only way I can think of would involve UNIONing nearly every table (representing groups, notes, friends, etc) and getting the dates and such, that just seems like it'd be a really expensive query to run for each user, and it'd be pretty hard to cache something like that with everyone's being different.

[A]
Firstly, consider doing a performance prototype to check your hunch that the union would be too expensive. You may be prematurely optimisizing something that is not an issue.
If it is a real issue, consider a table designed purely to hold the event feed data, that must be updated in parallel with the other tables.
E.g. when you create a Note record, also create an event record in the Event table with the date, description, and user involved.
Consider an indexing the Event table based on UserId (or UserId and Date). Also consider clearing old data when it is no longer required.
This isn't a normalised schema, but it may be faster if getting an event feed is a frequent operation.


q: In VB6, ActiveX DLL is listed as a project template but in VS 2005+ there is no such thing. Where is my good old ActiveX DLL template? Many thanks in advance.

[A]
Try this:
http://msmvps.com/blogs/pauldomag/archive/2006/08/16/107758.aspx
It outlines how to create an activex control and use it in a web page.  As far as I know there's really no 'ActiveX' project template since .NET does it differently.  However you can make your .Net controls visible to the COM world, which the article above illustrates.


q: I was thinking along the lines of using typeid() but I don't know how to ask if that type is a subclass of another class (which, by the way, is abstract)

[A]
In c# you can simply say:
```
```
if (myObj is Car) {

}
```
```


q: How can I list the contents of a zipped folder in C#? For example how to know how many items are contained within a zipped folder, and what is their name?

[A]
Check into
SharpZipLib
```
```
ZipInputStream inStream = new ZipInputStream(File.OpenRead(fileName));

while (inStream.GetNextEntry())
{

     ZipEntry entry = inStream.GetNextEntry();
     //write out your entry's filename
}
```
```


q:
Hopefully a nice simple one.

I've got a php3 website that I want to run on php 5.2

To start with I'd just like to have every reference to the current "index.php3" _within_each_file_ (recursively) changed to "index.php" and then move on to worrying about globals etc.

K. Go!

:)

Update: Thanks a lot! I realise that my question missed the fact that the references are in each file of a website and I wanted to do it recursively in all files/folders.

[A]
```
sed -i 's/php3/php/g' *
```
Assuming you are using a unix-like operating system.


q:
Is there a good reference, or summary list, of new features in WCF 2.0/VS2010?

I'm trying to do a justification proposal for a project, to migrate from Jabber to WCF.

[A] Not answering your question in particular, but WCF 2.0's not going to come out for quite some time, so I'd base my evaluation against the current WCF version.


q:
I am trying to add a UIButton at runtime however it is not visible. What am I doing wrong?

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        UIButton *btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        btn.frame = CGRectMake(0, 0, 100, 25);
        btn.backgroundColor = [UIColor clearColor];
        [btn setTitle:@"Play" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(buttonClick:)
        forControlEvents:UIControlEventTouchUpInside];
        btn.center = self.center;
        [self addSubview:btn];
    }
    return self;
}

[A]
First, make sure the initWithFrame: method is being called. If your view is in a Nib, initWithCoder: is being called instead.
Second, is the button the only subview (from your code it looks like it is, but you never know). The button could be hidden behind another subview. Call bringSubviewToFront: if you need to.
Finally, is the view itself visible? Is it big enough to show the button? Given your example, if the view is less than 100 pixels wide, the button won't show because it will get clipped by the view's bounds.


q:
Well, I must be brain-damaged, because I can't find the java source for Sun's persistence.jar or JBoss's ejb3-persistence.jar JPA package.  They are open-source aren't they?

I looked all over the java.sun.com site as well as the GlassFish wiki, but came up empty.

I'd like a src.zip or folder like Sun delivers with Java JDKs.

Of course, I really don't have to have it, but I think it's fun to browse the source once in a while.  And it helps me to debug my code sometimes.

[A]
The ejb3-persistence.jar contains the JPA API (javax.persistance.*) implementation which specified as part of the EJB 3.0 JSR 220 specification (the upcoming specification for JPA is JSR 317 which is now separate from EJB 3.1 spec)
The reference implementation is the one included with the Glassfish, I believe the one used in JBoss is the Hibernate implementation so you should be able to find the source code there.  You are free to use the one whose license satisfies your need (if you need to redistribute) although I believe they are all redistributable. For an Apache style license I recommend the one used by the Apache OpenEJB.org project (provided by the Apache Geronimo project).
You can browse the source here:
https://github.com/apache/geronimo-specs/tree/trunk/geronimo-jpa_2.2_spec/src/main/java/javax/persistence


q:
I would like to completely reset the scroll position of a UITableView, so that every time I open it, it is displaying the top-most items. In other words, I would like to scroll the table view to the top every time it is opened.

I tried using the following piece of code, but it looks like I misunderstood the documentation:

- (void)viewWillAppear:(BOOL)animated {
    [tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:NO];
}

Is this the wrong approach here?

[A]
The method you're using scrolls to (as the method name implies) the nearest selected row. In many cases, this won't be the top row. Instead, you want to use either
```
```
scrollToRowAtIndexPath:atScrollPosition:animated:
```
```
or
```
```
selectRowAtIndexPath:animated:scrollPosition:
```
```
where you use the index path of the row you want to scroll to. The second method actually selects a row, the first method simply scrolls to it.


q: I'd like to skip the tests and create a (default) Makefile.

[A]
Of course you can write a makefile by hand. A quick googling shows LOTS of tutorials.
This one
looks promising.
For the cliffs notes version, the example boils down this:
```
```
CC=g++
CFLAGS=-c -Wall
LDFLAGS=
SOURCES=main.cpp hello.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=hello

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

.cpp.o:
    $(CC) $(CFLAGS) $< -o $@
```
```


q:
I'm a PHP developer and I've made something I want to push live.

It requires memcache, and I'm expecting a fair amount of traffic, at least at launch, so I'd like it to be fast.

I'm really awesome at programming, but when it comes to getting hosting stuff set-up (other than run-of-the-mill shared hosting) I lack experience.

[A]
Joyent
might be a good solution for you. Honestly adding memcache to a LAMP stack is ridiculously easy and you should be able to do it with relative ease. Find a good VPS provider (linode and slicehost are so good I'll recommend them without my referral code) and you should be able to just apt-get install memcache.
To get a more specific answer though, you really need to quantify how much a 'fair amount of traffic' will be. For some people a hit a second is a massive, for some people 300 h/s is cake.
If you need a hand, email me, I'd be happy to help


q:
In java, does file.delete() return true or false where File file refers to a non-existent file?

I realize this is kind of a basic question, and easy to very through test, but I'm getting strange results and would appreciate confirmation.

[A]
The official javadoc:
```
```
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

Returns:
    true if and only if the file or directory is successfully deleted; false otherwise
Throws:
    SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file
```
```
so, false.


q:
I've connected to a MySQL database using Perl DBI.  I would like to find out which database I'm connected to.

I don't think I can use:

$dbh->{Name}

because I call USE new_database and $dbh->{Name} only reports the database that I initially connected to.

Is there any trick or do I need to keep track of the database name?

[A]
You can ask mysql:
```
```
($dbname) = (each %{$dbh->selectrow_hashref("show tables")}) =~ /^Tables_in_(.*)/;
```
```
Update: obviously select DATABASE() is a better way to do it :)


q:
OK, so Sybase (12.5.4) will let me do the following to DROP a table if it already exists:

IF EXISTS (
    SELECT 1
    FROM sysobjects
    WHERE name = 'a_table'
    AND type = 'U'
)
DROP TABLE a_table
GO

But if I try to do the same with table creation, I always get warned that the table already exists, because it went ahead and tried to create my table and ignored the conditional statement. Just try running the following statement twice, you'll see what I mean:

IF NOT EXISTS (
    SELECT 1
    FROM sysobjects
    WHERE name = 'a_table'
    AND type = 'U'
)
CREATE TABLE a_table (
    col1 int not null,
    col2 int null
)
GO

Running the above produces the following error:

SQL Server Error on (localhost)
  Error:2714 at Line:7 Message:There is
  already an object named 'a_table' in
  the database.

What's the deal with that?!

[A]
```
```
IF object_id('a_table') IS NULL
BEGIN
    CREATE TABLE a_table (
        col1 int not null,
        col2 int null
    )
END
```
```


q: I lost my installation of Dave Gillespie's calc.el by reinstalling Cygwin.  It is not included with the default Cygwin install of Emacs.  Who is considered the master maintainer these days?  Is version 2.02f still most current?

[A]
In the Emacs CVS tree. See
the calc page
and the
Emacs project page
. The root of the calc subtree is
here
and you can get the latest version by typing
```
```
cvs -d:pserver:anonymous@cvs.sv.gnu.org:/sources/emacs co emacs/lisp/calc
```
```


q:
Is it possible to declare an instance of a generic without knowing the type at design-time?

Example:

Int i = 1;
List<typeof(i)> list = new List<typeof(i)>();

where the type of i could be anything, instead of having to do:

List<int> list = new List<int();

[A]
I think the best you are going to be able to do is something like this:
```
```
static void Main(string[] args)
{
    int i = 1;
    var thelist = CreateList(i);
}

public static List<T> CreateList<T>(T t)
{
    return new List<T>();
}
```
```


q:
I have this line of JavaScript and the behavior I am seeing is that the selectedLi instantly disappears without "sliding up".  This is not the behavior that I expected.

What should I be doing so that the selectedLi slides up before it is removed?

selectedLi.slideUp("normal").remove();

[A]
Might be able to fix it by putting the call to remove in a callback arg to slideUp?
e.g
```
```
selectedLi.slideUp("normal", function() { $(this).remove(); } );
```
```


q:
The first thing I do when I incorporate any third party code into my application is reformat it to my personal coding preference:

// Single line comments only

// I never put spaces inside my parenthesis
-(void)myOCDMethod
{
    // If an if or for statement has only one instruction, I don't use brackets
    if(this)
        [self that];
    else
        [self somethingElse];

    // If I do have to use brackets, they go on their own lines so that they line up
    if(this)
    {
        [self that];
        [self andThat];
    }

    // I always put the pointer asterisk next to the instance name
    NSObject *variable = [[NSObject alloc] init];

    // I always put spaces around operators
    if(i == 0)
        x = 2;

}

What OCD coding format do you use?

[A]
I do a lot of this, with a few differences:
I always insert spaces before and after parens:
```
-(void)myOCDMethod   ->   - (void) myOCDMethod
```
I leave braces on the same line:
```
```
if (this)
{
  //code
}
```
```
becomes
```
```
if (this) {
  //code
}
```
```
If I'm feeling particularly OCD, I'll line up my locals:
```
```
float                l1;
NSArray              *array;
ReallyLongClassName  *object;
```
```
And, finally, TABS, not SPACES.


q: I'm wanting to play around with creating an LR parser generators. Does anyone know of a good (free) resource describing how to create a state machine table from a grammar?

[A]
For a free resource, consider the Python source code for
PLY
- a full implementation of Lex and Yacc in Python.
I would recommend a book, however, and you can hardly do better than get
The Dragon Book
.


q:
I have a DataGridView that I want to query using Linq (C# WinForm). I want to "count" rows where a certain criteria is met. For example,

variable1 = "count rows where ColumnBoxAge > 3 || < 5"

label1.Text = variable1

How to do this in C# WinForm using Linq?

[A]
I don't know if it could work but you can try this;
```
```
dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 ||
     c.Field<int>("ageColumn") < 5).Count();
```
```
Edit : Where instead of Select.


q:
I've noticed that in some lines of rails views, this is used:

<% # Code... -%>

instead of:

<% # Code... %>

What is the difference?

[A]
```
```

    <% @posts.each do |post| -%>

<%=post.title%>

    <% end -%>

```
```
There will be no new lines in between the
```
<ul>
```
and first
```
<li>
```
and the last closing
```
</li>
```
and
```
</ul>
```
. If the - was omitted, there would.


q:
I'm using PHP 5.2. I'd like to find a way to output a unique id for every object, so it's easy when looking over logs to see which objects are the same.

In Ruby, I'd just say object.object_id to get Ruby's internal identifier for the object. There doesn't seem to be an obvious way to do this in PHP.

Is there is a built-in way of doing this? If there isn't, can you offer any other suggestions?

[A]
Use
```
spl_object_hash()
```
for that.
It returns an unique identifier for each object instance, and not the name of the class, so it seems more suitable for you.
Edit:
For PHP < 5.2.x users, see
this answer
.


q:
When reviewing our codebase, I found an inheritance structure that resembles the following pattern:

interface IBase
{
    void Method1();
    void Method2();
}

interface IInterface2 : IBase
{
    void Method3();
}

class Class1 : IInterface2
{
    ...
}

class Class2 : IInterface2
{
    ...
}

class Class3 : IInterface2
{
    ...
}

In Class2, Method1 throws NotImplementedException.

Questions:

What do you think in general about inheriting interfaces?

Does the relationship between IBase and Class2 violate the Liskov Substitution Principle?

[A]
Well, first of all, I'm generally against implementing an interface by throwing NotImplementedException exceptions. It is basically like saying "Well, this class can also function as a calculator, err, almost".
But in some cases it really is the only way to do something "the right way", so I'm not 100% against it.
Just something to be aware of.
An interface is a contract, by implementing the interface you say that you abide by the contract. If you then start negating parts of the contract, it sounds to me as the contract, or the implementation of it, was poorly thought out.
Edit
: After seing
Greg Beech
's answer: If an interface specifically says that implementations should throw these exceptions, then it's part of the contract, then I agree that the class is fully allowed to do it.
As for the substitution principle, it
states
that:
Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T.
In this context, it violates the principle just as much as overriding a method from a base class does, if you change what the method does in the descendant type.
The principle is more detailed on the wikipedia page, like the following points (parenthesis and emphasis on my comments):
Preconditions cannot be strengthened in a subclass.
(A precondition could be that "the class is ready for a call to this method at this point")
Postconditions cannot be weakened in a subclass.
(A postcondition could be that after calling the method, something is true about the state of the class)
Since you have not shown the full contract of your interfaces, only the declarative part that the compiler can check, it is impossible to know wether the principle holds for your implementation of not.
For instance, if your Method2 has the following conditions attached to it:
Can be called at all times
Modifies the state of the object to be ready for the next event in a chain of events
Then throwing a NotImplementedException violates the principles.
However, if the contract also states that:
For classes that doesn't support chains of events, this method should throw NotImplementedException or NotSupportedException
Then it probably does not.


q: I have just moved job and gone from VB 6 to VB.Net and found the learning jump fairly steep, have more a problem with the object / conceptual side of things .. but getting there now ... but as I was a assembler / C++ 10/15 years ago and was considering learning C++/C# .Net (XNA games library calls my name) but not sure if it would hinder my VB.NET learning .... or should I just get myself certified

[A]
To me the biggest obstacle for .NET is learn what is available in the framework. Therefore, if you find it easier to code in C# it will mean you only struggle with one thing instead of two. Once you know the framework it's just syntax really as 95% of the stuff you can do with C# can be done with VB.
Also, C# will force you to write code in a more object orientated manner as you can't fall back to coding in a VB6 style.
'
yield return
' is an example of something that doesn't have an equivalent in VB9 (there are rumours this is being added for VBX though).


q:
I'm trying to figure out how to execute a custom query with Castle ActiveRecord.

I was able to run simple query that returns my entity, but what I really need is the query like that below (with custom field set):

select count(1) as cnt, data from workstationevent where serverdatetime >= :minDate and serverdatetime < :maxDate and userId = 1 group by data having count(1) > :threshold

Thanks!

[A]
In this case what you want is
```
HqlBasedQuery
```
. Your query will be a projection, so what you'll get back will be an
```
ArrayList
```
of tuples containing the results (the content of each element of the ArrayList will depend on the query, but for more than one value will be
```
object[]
```
).
```
```
HqlBasedQuery query = new HqlBasedQuery(typeof(WorkStationEvent),
    "select count(1) as cnt, data from workstationevent where
     serverdatetime >= :minDate and serverdatetime < :maxDate
     and userId = 1 group by data having count(1) > :threshold");

var results =
    (ArrayList)ActiveRecordMediator.ExecuteQuery(query);
foreach(object[] tuple in results)
{
    int count = (int)tuple[0]; // = cnt
    string data = (string)tuple[1]; // = data (assuming this is a string)

    // do something here with these results
}
```
```
You can create an anonymous type to hold the results in a more meaningful fashion. For example:
```
```
var results = from summary in
    (ArrayList)ActiveRecordMediator.ExecuteQuery(query)
    select new {
        Count = (int)summary[0], Data = (string)summary[1]
    };
```
```
Now results will contain a collection of anonymous types with properties
```
Count
```
and
```
Data
```
. Or indeed you could create your own summary type and populate it out this way too.
ActiveRecord also has the
```
ProjectionQuery
```
which does much the same thing but can only return actual mapped properties rather than aggregates or functions as you can with HQL.


q:
Assuming some background in mathematics,  how would you give a general overview of computational complexity theory to the naive?

I am looking for an explanation of the P = NP question.  What is P?  What is NP? What is a NP-Hard?

Sometimes Wikipedia is written as if the reader already understands all concepts involved.

[A]
Unfortunately, the best two books I am aware of (
Garey and Johnson
and
Hopcroft and Ullman
) both start at the level of graduate proof-oriented mathematics.  This is almost certainly necessary, as the whole issue is very easy to misunderstand or mischaracterize.  Jeff
nearly got his ears chewed off
when he attempted to approach the matter in too folksy/jokey a tone.
Perhaps the best way is to simply do a lot of hands-on work with big-O notation
using lots of examples and exercises
.  See also
this answer
.  Note, however, that this is not quite the same thing: individual algorithms can be described by asymptotes, but saying that a
problem
is of a certain complexity is a statement about
every possible algorithm
for it.  This is why the proofs are so complicated!


q:
Two snippets of MySQL:

SELECT * FROM annoyingly_long_left_hand_table
    LEFT JOIN annoyingly_long_right_hand_table
    ON annoyingly_long_left_hand_table.id = annoyingly_long_right_hand_table.id;

vs

SELECT * FROM annoyingly_long_left_hand_table
    LEFT JOIN annoyingly_long_right_hand_table
    USING (id);

Given that both tables have an id field, is there any disadvantage to using the second version. It isn't just laziness - the version with USING seems far clearer to me.

(Please don't mention aliasing - I want to know if there is any reason to favour one conditional structure over the other)

[A]
There is a small functional difference between the two, in that instead of getting 2 ID columns, you only get one.
SELECT * FROM foo JOIN bar ON ( foo.id == bar.id )
id , fooname, id, barname
SELECT * FROM foo JOIN bar USING ( id )
id, fooname, barname
So there are at least some additional knowledge requirements for users utilising this syntax,
http://dev.mysql.com/doc/refman/5.0/en/join.html


q:
How do I tell the Vim editor about my include files path so that it can auto complete the function names when I press CTRL+N?

For example, I have a C program like below:

#include<stdio.h>
int main()
{
    sca // here I press control+N, it does not complete to scanf
}

[A]
In your
```
.vimrc
```
, add the paths to your
```
.vimrc
```
:
```
```
set path+=/usr/include/**
set path+=/my_include_dir/include
set path+=/my_include_dir/srclib/apr/**
set path+=/my_other_include_dir/srclib/apr-util/**

** means all sub-directories.
*  means all contained directories
.  means all files in the directory of the found file
+= means prepend to existing path (iirc)
```
```
You can check the paths as well by opening your file and then entering
```
```
:checkpath
```
```
This will give you a list of all included files that are missing. N.B. It doesn't seem to handle preprocessor directives, so you will get some false positives. Entering
```
```
:checkpath!
```
```
Will give a complete list of found and missing include files.


q:
I have a number of databases on a Windows 2000 Server running the 32 bit version of SQL Server 2000. I need to transfer all the data and settings to a new server running the 64 bit version of SQL 2008 on Windows 2003 64 bit.

Is this as simple as backing up the databases and restoring to the new server. Will this work with the system databases (master, model, msdb) as well? If not, is there a way to automate the process of moving across the user accounts and permissions?

Is anybody aware of any other gotchas?

Many thanks for any help.

[EDIT] I've successfully tested an upgrade to SQL2008 32-bit, I'm mostly concerned with any differences in the 64-bit version as I don't have a 64 bit server I can test on at the moment e.g. I know you can't restore a SQL2000 master database to 2008; can you restore a SQL2008 32bit master to SQL2008 64bit? Downtime during the migration is not a problem.

[A]
To transfer logins, you should be able to use the 'Transfer Logins Task' described in Books Online
here
.
Ross Mistry has published a few
articles
on SQL Server 2008 Installation Strategies and Best Practices. Also this
document
, although directed at specific hardware, contains useful info.
EDIT: Have you looked at the
Microsoft SQL Server 2008 Upgrade Advisor
?


q:
As a C# developer I'm used to running through constructors:

class Test {
    public Test() {
        DoSomething();
    }

    public Test(int count) : this() {
        DoSomethingWithCount(count);
    }

    public Test(int count, string name) : this(count) {
        DoSomethingWithName(name);
    }
}

Is there a way to do this in C++?

I tried calling the Class name and using the 'this' keyword, but both fail.

[A]
If I understand your question correctly, you're asking if you can call multiple constructors in C++?
If that's what you're looking for, then no - that is not possible.
You certainly can have multiple constructors, each with unique argument signatures, and then call the one you want when you instantiate a new object.
You can even have one constructor with defaulted arguments on the end.
But you may not have multiple constructors, and then call each of them separately.


q:
I am working on a C++ project and I noticed that we have a number of warnings about unused parameters.

What effect could it have if these warnings are ignored?

[A]
None. except [EDIT]: as others have pointed out, You could have an unassigned output parameter.
You should clean them up, because on many occasions I have seen developers ignore important warnings that were 'hidden' in amongst a large number of warnings, and they were so used to seeing warnings they never paid any attention to them. I try to have zero warnings at all times, and set compiler warnings to the maximum level.


q:
Been thinking, what's the difference between declaring a variable with [] or * ? The way I see it:

char *str = new char[100];
char str2[] = "Hi world!";

.. should be the main difference, though Im unsure if you can do something like

char *str = "Hi all";

.. since the pointer should the reference to a static member, which I don't know if it can?

Anyways, what's really bugging me is knowing the difference between:

void upperCaseString(char *_str) {};
void upperCaseString(char _str[]) {};

So, would be much appreciated if anyone could tell me the difference? I have a hunch that both might be compiled down the same, except in some special cases?

Ty

[A]
The first option dynamically allocates 100 bytes.
The second option statically allocates 10 bytes (9 for the string + nul character).
Your third example shouldn't work - you're trying to statically-fill a dynamic item.
As to the
```
upperCaseString()
```
question, once the C-string has been allocated and defined, you can iterate through it either by array indexing or by pointer notation, because an array is really just a convenient way to wrap pointer arithmetic in C.
(That's the simple answer - I expect someone else will have the authoritative, complicated answer out of the spec :))


q: Is it necessary to pay $99 before I can watch the video to submit an iPhone application to the App Store, or it is available free of cost anywhere?

[A]
I assume you are referring to the $99 fee to register as an iPhone developer?
Even if you can find a copy of the video, you would still have to pay the fee in order to get your application hosted on the App Store. Apple keeps a fairly tight handle on all of this stuff, so they require all developers to register if they want to sell software in the App Store. Apple will also have the final say on wether or not your software can be sold.
Bottom line: if you intend to sell software through the App Store, you will have to pay Apple the $99 fee.


q:
I'm starting up a personal project to develop some open source software.  I want to use Scrum as the PM process on this (as I like the Product Backlog, prioritisation, and if I can get them, the burndowns) but it seems to me that I won't get the full value because  I can't at the outset guarantee the amount of time myself and my collaborators will be able to commit to work during a given sprint.

I know there are other benefits that I will still get from using Scrum but are there variations or tricks and techniques I am unaware of which will enable me to get the value of things like burndown charts and timeboxed iterations?  Or am I just being too hopeful?

TIA.

Regs, Andrew

[A]
In a by the book setting you won't use real time for calculation of the burndown chart but rather story points. After a few sprint you will see an average velocity and thus be able to generate a burndown chart and use this velocity for commiting to the sprint items.
And I strongly disagree with
warrens post
on the scale-down point. The main problem I see is a strongly varying velocity between two sprints, since it is only a hobby.


q:
Using sc command we can query, start , stop windows services.

For ex:

sc query "windows service name"

The sc config command changes the configuration of the service, but I don't know how to use it.

Could someone tell me how we can set the username and password for any windows service?

[A]
This works:
```
```
sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"
```
```
Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)
Just keep in mind that:
The spacing in the above example matters.
```
obj= "foo"
```
is correct;
```
obj="foo"
```
is not.
'.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
Passwords aren't validated until the service is started
Quote your parameters, as above.  You can sometimes get by without quotes, but good luck.


q:
Can anyone point me in the right direction how to configure Visual Studio 2005 with our C++ console project how we can include a 'File Version' in the details section of the file properties.

I've tried resource files without any luck. This is with a C++ project just for clarification, and big thank you for the guys you responded with C# suggestions.

Thanks in advance.

[A]
Unless you have a good reason for your file version to be different than the version of the assembly inside, I think it is a better idea to provide the
AssemblyVersion
alone. If you do not specify an
AssemblyFileVersion
, it will automatically get the same value, so you can see your assembly's version directly in the file's properties.
The advantage is that you can use a wildcard and allow the version to be automatically incremented, so that every time you compile the library you get a different build and/or revision number. As far as I can tell, this trick does
not
work with
AssemblyFileVersion
, so you have to increment it by hand.
Of course, all this only applies if you're writing .NET code. Are you by any chance talking about a project using unmanaged code?


q:
I want to generate a CSV file for user to use Excel to open it.

If I want to escape the comma in values, I can write it as "640,480".

If I want to keep the leading zeros, I can use ="001234".

But if I want to keep both comma and leading zeros in the value, writing as ="001,002" will be splitted as two columns.  It seems no solution to express the correct data.

Is there any way to express 001, 002 in CSV for Excel?

[A]
Do
```
```
"""001,002"""
```
```
I found this out by typing "001,002" and then doing save-as CSV in Excel. If this isn't exactly what you want (you don't want quotes), this might be a good way for you to find what you want.
Another option might be use tab-delimited text, if this is an option for you.


q:
I have a table with the following columns:

A   B   C
---------
1   10  X
1   11  X
2   15  X
3   20  Y
4   15  Y
4   20  Y

I want to group the data based on the B and C columns and count the distinct values of the A column. But if there are two ore more rows where the value on the A column is the same I want to get the maximum value from the B column.

If I do a simple group by the result would be:

B   C    Count
--------------
10  X    1
11  X    1
15  X    1
20  Y    2
15  Y    1

What I want is this result:

B   C    Count
--------------
11  X    1
15  X    1
20  Y    2

Is there any query that can return this result. Server is SQL Server 2005.

[A]
Check this out. This should work in Oracle, although I haven't tested it;
```
```
select count(a), BB, CC from
(
select a, max(B) BB, Max(C) CC
from yourtable
group by a
)
group by BB,CC
```
```


q:
Is either:

<a href="#"><h1>text here</h1></a>

or

<h1><a href="#">text here</a></h1>

"correct". Is there any benefit of using the first one, it seems more logical to me. Perhaps from an SEO point?

[A]
```
```

text here

```
```
is correct, as HTML does not allow a block element (
```
<h1>
```
) within an inline element (
```
<a>
```
) (
src
). your first example will fail
validation
.
Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.


q:
I'm trying to create a very simple form in an Access database. Whenever I drag a textbox on the form, a label gets created with it. I want to be able to move the label without moving the textbox,but whenever I try to do that, the textbox moves with it. Its like they're linked with each other.
Is there a way to separate them from each other so that they can be moved separately?

[A]
Yes, but you are better off looking for the small square black box that appears on the top left corner of each control when you click the textbox or label. This box will allow you to drag each control independently. Don't forget Format->Align (Left,Right,Top,Bottom) it is probably more useful for tidying up controls than anything else.
You can separate the label from its parent control by deleting the label, clicking the detail section to ensure that no controls are selected, and pasting, but I would advise against it. You can do a number of useful things with labels that are related to controls and one of them is move the two together - this is useful when you have the form tidied. Another is to find the parent of the control, which is useful when using VBA to change controls.


q:
I've just done a test with bitfields, and the results are surprising me.

class test1 {
public:
    bool test_a:1;
    bool test_b:1;
    bool test_c:1;
    bool test_d:1;
    bool test_e:1;
    bool test_f:1;
    bool test_g:1;
    bool test_h:1;
};

class test2 {
public:
    int test_a:1;
    int test_b:1;
    int test_c:1;
    int test_d:1;
    int test_e:1;
    int test_f:1;
    int test_g:1;
    int test_h:1;
};

class test3 {
public:
    int test_a:1;
    bool test_b:1;
    int test_c:1;
    bool test_d:1;
    int test_e:1;
    bool test_f:1;
    int test_g:1;
    bool test_h:1;
};

The results were:-

sizeof(test1) = 1   // This is what I'd expect. 8 bits in a byte
sizeof(test2) = 4   // Reasonable. Maybe padded out to the size of an int.
sizeof(test3) = 16  // What???

Is this what you'd expect, or a compiler bug? (Codegear C++ Builder 2007, btw...)

[A]
your compiler has arranged all of the members of test3 on integer size boundaries. Once a block has been used for a given type (integer bit-field, or boolean bit-field), the compiler does not allocate any further bit fields of a different type until the next boundary.
I doubt it is a bug. It probably has something to do with the underlying architecture of your system.
edit:
c++ compilers will allocate bit-fields in memory as follows: several consecutive bit-field members
of the same type
will be allocated sequentially. As soon as a new type needs to be allocated, it will be aligned with the beginning of the next logical memory block. The next logical block will depend on your processor. Some processors can align to 8-bit boundaries, while others can only align to 16-bit boundaries.
In your test3, each member is of a different type than the one before it, so the memory allocation will be 8 * (the minimum logical block size on your system). In your case, the minimum block size is two bytes (16-bit), so the size of test3 is 8*2 = 16.
On a system that can allocate 8-bit blocks, I would expect the size to be 8.


q: I know this may be simple but being C++ I doubt it will be. How do I convert a string in the form 01/01/2008 to a date so I can manipulate it? I am happy to break the string into the day month year constituents. Also happy if solution is Windows only.

[A]
```
```
#include <time.h>
char *strptime(const char *buf, const char *format, struct tm *tm);
```
```


q:
If I type the command:

mvn dependency:list

The docs suggest that I'll get a list of my project's dependencies. Instead though, I get this:

[INFO] Searching repository for plugin with prefix: 'dependency'.
[INFO] -----------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] -----------------------------------------------------------
[INFO] Required goal not found: dependency:list

Call me a hopeful naive, but I had hoped maven would download any plugins it didn't have. Does anyone know what might be leading to this error? Does anyone know where maven stores information about what plugins it has installed, and where they're stored in the maven repository?

[A]
Have you tried
```
mvn -cpu dependency:list
```
(or:
```
mvn --check-plugin-updates dependency:list
```
)? Probably, you have older version of dependency plugin which does not have goal
```
list
```
If this does not help, try upgrading Maven. Since 2.0.9 default versions are provided by the Super POM for most important plugins (dependency plug-in included), so 2.0 version will be downloaded (which has
```
list
```
goal).
Or you can try removing the cached version of the plug-in from the repository  (
```
~/.m2/repository/org/apache/maven/plugins/maven-dependency-plugin/
```
, where
```
~
```
is the user home directory).