Question:
Let say I run this command:

makecert testcert.cer

Is a private key created? If so, where is it automatically stored in the system even though I did not tell makecert to install this certificate in any certificate store?

Answer:
It looks like the private key is stored in the file itself.  From the documentation at
http://msdn.microsoft.com/en-us/library/bfsktky3(VS.80).aspx
it states...
Caution
You should use a certificate store to securely store your certificates. The .snk files used by this tool store private keys in an unprotected manner. When you create or import a .snk file, you should be careful to secure it during use and remove it when you are done.


Question:
I'm building a webpage that queries a MySQL database and (currently) produces a text-only list of the findings. The queries to complete a single record are similar to:

movie (title, description, etc)

actors in the movie (name, gender)

related movies

Out of curiosity I've used memory_get_peak_usage() and memory_get_usage():

start   110,440 bytes
peak    656,056 bytes
end 637,976 bytes
time    0.008 seconds

The above is with no records found!

With 40 records I'm reaching approximately 2MB, though the time remains the same.

I know that premature optimization is evil and all, but I have to ask:

Do I need to do some reworking? Is this memory usage normal? What is considered excessive?

Answer: Ultimately it's preferable to optimize when convenient of course, but 2MB of memory use sounds fine. PHP4 has a default config of 8mb, and PHP5 16mb. A lot of pre-packaged PHP builds will have different configs, of course, but generally speaking, if you can keep your app under 8mb, you can be sure it'll be highly portable in that regard.


Question: How to invoke the default browser with an URL from C#?

Answer:
```
```
System.Diagnostics.Process.Start("http://mysite.com");
```
```


Question: I need to create reports in a C# .NET Windows app. I've got an SQL Server 2005 .I want to display  two more field to report(not available in data base table. I want to create these field by adding some data from existing field of data base table)

Answer:
If you look at the .NET API exposed by Crystal Reports, you'll find that you can inject a DataSet into a report - this gives your application full control over the data used by the report, leveraging Crystal Reports as a presentation engine.
I've used this technique to generate reports over data soures not natively supported by Crystal Reports - it also helps to ensure that all the data comes from the sames source (as the API for changing the connection used within a normal Crystal report is somewhat flakey).
So, what I'd do in your situation is to load all the required data into a DataSet, add the extra columns, and then pass the dataset into the report. Only complex bit is that you need to save out the XML schema of the dataset and import it into Crystal Reports so that it is aware of the shape of your data.


Question:
Could you tell me, please, if it's possible to preview (or at least retroview, for example, in a kind of a log file) SQL commands which SQL Server Management Studio Express is about to execute (or has just executed)?

In the past I used Embarcadero DBArtisan which shows SQL queries to be executed before actually running them on the server, so I am eager for this feature in Management Studio.

I have found an option "Auto generate change scripts", but it shows only DDL SQL queries
(structure change), not data change.

Answer:
You can use Query Profiler (from SQL) to view the queries and in your SQL Query embed in a transaction and at the end do a rollback.
```
```
BEGIN TRAN

 INSERT INTO Clients
 SELECT 'Bruno', 'Alexandre';

END

ROLLBACK TRAN
```
```
when you rollback a transaction the process will go back to the begining of the BEGIN TRAN and you can be sure that nothing was made, this is the way to commit queries and to safe rollback if the SQL encounter an error...
like:
```
```
IF @@ERROR > 0 GOTO Error

:Error
ROLLBACK TRANSACTION
```
```


Question: Can any body tell me the differences between them?

Answer: Basically, there isn't one.  Embedded refers to the hosting computer / microcontroller, not the language.  The embeddded system might have fewer resources and interfaces for the programmer to play with, and hence C will be used differently, but it is still the same ISO defined language.


Question: Is it OK (or even recommended/good practice) to #include a .c file in another .c file?

Answer:
No.
Depending on your build environment (you don't specify), you may find that it works in exactly the way that you want.
However, there are many environments (both IDEs and a lot of hand crafted Makefiles) that expect to compile *.c - if that happens you will probably end up with linker errors due to duplicate symbols.
As a rule this practice should be avoided.
If you absolutely must #include source (and generally it should be avoided), use a different file suffix for the file.


Question:
When querying ntp servers with the command ntpdate, I can use the -u argument to make the source port an unrestricted port (port 1024 and above).

With ntpd, which is meant to run in the background, I can't seem to find a way to turn this option on. So the source port is always 123.  It's playing around horribly with my firewall configuration.

Is there a configuration option in ntp.conf to make it use a random source port?

Answer:
Doesn't sound look this is possible...see the
ntp troubleshooting page
:
If you're going to run ntpd, you need to fix your network/firewall/NAT so that ntpd can have full unrestricted access to UDP port 123 in both directions.
If this is not possible, you may need to run ntpd on the firewall itself, so that it can have full unrestricted access to UDP port 123 in both directions, and then have it serve time to your internal clients.
If that's not possible, your only other option may be to buy the necessary hardware to connect to one or more of your own computers and run your own Stratum 1 time server or buy a pre-packaged Stratum 1 time server.


Question:
How do I convert a string to DateTime format? For example, if I had a string like:

"24/10/2008"

How do I get that into DateTime format ?

Answer:
Use
DateTime.ParseExact
:
```
```
string str = "24/10/2008";
DateTime dt = DateTime.ParseExact(str, "dd/MM/yyyy",
                                  Thread.CurrentThread.CurrentCulture);
```
```
(You should consider what culture you actually want to parse it in, admittedly.)
EDIT: Other answers have specified "null" as the third parameter - this is equivalent to using
```
Thread.CurrentThread.CurrentCulture
```
.
For other formats, see
"Custom Date and Time Format Strings"
in MSDN.


Question: Sometimes gdb prints "incomplete type" for some type of variables. What does this mean and how can we see that value?

Answer:
It means that the type of that variable has been incompletely specified. For example:
```
```
struct hatstand;
struct hatstand *foo;
```
```
GDB knows that
```
foo
```
is a pointer to a
```
hatstand
```
structure, but the members of that structure haven't been defined. Hence, "incomplete type".
To print the value, you can cast it to a compatible type.
For example, if you know that
```
foo
```
is really a pointer to a
```
lampshade
```
structure:
```
```
print (struct lampshade *)foo
```
```
Or, you could print it as a generic pointer, or treat it as if it were an integer:
```
```
print (void *)foo
print (int)foo
```
```
See also these pages from the GDB manual:
http://sourceware.org/gdb/current/onlinedocs/gdb/Data.html#Data
http://sourceware.org/gdb/current/onlinedocs/gdb/Symbols.html#Symbols


Question:
User A logs into a ticket management system to edit content on "SomePage.aspx"

User B logs in 30 seconds later to edit the same ticket on "SomePage.aspx"

What are some of the best known practices(in a 3-tier architecture) for notifying each of the users that someone else is modifying the same content?

Answer:
In a request/response system like HTTP, there isn't much of a concept of what a user is currently doing. You could notify them that someone else opened the ticket for edit "within the last two minutes" (or even prevent them from opening it in such a case) but user A could edit for half an hour - unless you prohibit that as well. You could keep a note of the fact that you believe user A has effectively "got" the item for edit, but with a web app there's nothing to stop the user from just walking away from the computer and never either saving/canceling.
Before thinking about the technological solutions, I suggest thinking about the technological
restrictions
(the asynchronous and request/response nature of the web, basically) and work out the desired behaviour. Some common behaviours are:
First edit wins (tell second editor that their changes have been rejected, basically)
Second edit wins (overwrite first edit - it's too late to tell the first editor)
Merge (can be insanely difficult and/or impossible, depending on the content). This may be automatic or manual (on the part of the second editor).
Prevent a second person from editing while you think a first person may be editing (rarely appropriate for web apps due to the issue mentioned in the first paragraph)


Question:
I recently baselined my machine and installed VS2008 and I am trying to import my settings file: http://naspinski.net/file.axd?file=naspinski.vssettings

I click Tools->Import Settings, select Import selected environment settings and click on Next

Next screen I select No, just import new settings, overwrite my current settings and click Next

I browse to my file and click Open -or- double-click on the file and it just dumps out... I don't get the option to click Finished, it just dumps out?

Any ideas what is wrong?

Answer:
try only importing by section - you should then see which bits seem to be wrong...
Imports fine on my machine. = VS2008 sp1 - there are warnings on
Command Window Alises
External Tools
Might want to check them out.
Would also suggest changing to Monaco font - easier reading...
have a look at
http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx


Question:
This is one of those ajax "alternate flow" questions. Normally I expect my ajax request to return a part of the page. But sometimes it may return a full page with html, head and body tag.

At the time I return from my ajax-request I can detect if this is a full page, but is it possible to trigger a full page reload (with full event cycle) based on the string content I have ?

(And yes, I have tried replacing the body element, but that does not give me the events and does not allow me to change the content in the head block)

Any framework reference is ok

Answer:
I don't think it's possible to do directly.
You'd be better off saving the HTML somewhere and sending back a URL where it can be retrieved, then using
```
location.href = ...
```
;


Question:
can anybody show me how to build a string using checkbox. what would be the best way to do this.

for example i have 4 checkbox's each with its own value (valueA, valueB, valueC, valueD)
the thing is i want to display each result in different lines.

result if B & C is selected :

valueB

valueC

and how would i display this again if i saved this into a database?

Answer:
```
```
"if I saved this into a database" ?
```
```
You'll need to be a bit more specific with your homework assignments if you're actually going to receive any help here ...
Edit:
ok, it
might
not be homework but it certainly read like it - after all, manipulating a GUI to generate a view of the user's choices is Interfaces 101 - and even it wasn't it was a terrible question without enough detail to have any chance of getting a decent answer.


Question: What are some uses of #pragma in C, with examples?

Answer:
Putting
```
#pragma once
```
at the top of your header file will ensure that it is only included once. Note that
```
#pragma once
```
is not standard C99, but supported by most modern compilers.
An alternative is to use include guards (e.g.
```
#ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */
```
)


Question:
After installing asp.net (and aspnet_regIIS.exe -i) the site doesn't accept my default.aspx page. When trying to access it I get a 404.
When hitting directly to my mvc pages (/search.mvc for example) it works like a charm.

We checked the website configuration and noted that there are no .aspx references in the scriptmaps node.

What am I missing?

Answer:
Probably you are missing the .aspx references in the scriptmaps. SCNR. ;-)
More seriously, are they there at the "Web Sites" properties level in IIS manager? What is the output you get when running
```
aspnet_regIIS.exe -i
```
?
Mine says:
```
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis.exe -i
Start installing ASP.NET (2.0.50727).
..............................
Finished installing ASP.NET (2.0.50727).

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>
```


Question:
I'm writing code like this, doing a little quick and dirty timing:

var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
    b = DoStuff(s);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

Surely there's a way to call this bit of timing code as a fancy-schmancy .NET 3.0 lambda rather than (God forbid) cutting and pasting it a few times and replacing the DoStuff(s) with DoSomethingElse(s)?

I know it can be done as a Delegate but I'm wondering about the lambda way.

Answer:
You could try writing an extension method for whatever class you're using (or any base class).
I would have the call look like:
```
```
Stopwatch sw = MyObject.TimedFor(1000, () => DoStuff(s));
```
```
Then the extension method:
```
```
public static Stopwatch TimedFor(this DependencyObject source, Int32 loops, Action action)
{
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < loops; ++i)
{
    action.Invoke();
}
sw.Stop();

return sw;
}
```
```
Any object deriving from DependencyObject can now call TimedFor(..). The function can easily be adjusted to provide return values via ref params.
--
If you didn't want the functionality to be tied to any class / object you could do something like:
```
```
public class Timing
{
  public static Stopwatch TimedFor(Action action, Int32 loops)
  {
    var sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < loops; ++i)
    {
      action.Invoke();
    }
    sw.Stop();

    return sw;
  }
}
```
```
Then you could use it like:
```
```
Stopwatch sw = Timing.TimedFor(() => DoStuff(s), 1000);
```
```
Failing that, this answer looks like it has some decent "generic" ability:
Wrapping StopWatch timing with a delegate or lambda?


Question:
Generate the Fibonacci sequence in the fewest amount of characters possible. Any language is OK, except for one that you define with one operator, f, which prints the Fibonacci numbers.

Starting point: <s>25</s> 14 characters in Haskell:

<s>  f=0:1:zipWith(+)f(tail f) </s>

f=0:scanl(+)1f

Answer:
22 characters with dc:
```
```
1[pdd5**v1++2/lxx]dsxx
```
```
Invoke with either:
```
dc -e'1[pdd5**v1++2/lxx]dsxx'
```
Or:
```
echo '1[pdd5**v1++2/lxx]dsxx' | dc
```
Note: not my work, poached from
perlmonks
.


Question:
In VS2005 and up, is it possible to specify which configuration should be selected by default?

I have several configurations in my solution but one of them should be used in most cases. Hence I'd like to make sure that devs who pull it out of Source Control use the right configuration(unless of course they specifically choose another one).

Ideally, this setting should be in the .sln file since that one is under Source Control.

Answer:
I don't know if I understand the complete situation behind your question, but there is a way to "externalize" some of VS.Net's project configuration values such as FxCop settings into a separate file. Then you could have all projects in a solution point to that file. However, I don't think it would allow for your devs to chose their own configuration after doing the "externalization"
If this seems like the right path for you, check out these posts from me in regards to coding standards on how to make similar changes for configuration.
My Seattle Code Camp Presentation on Coding Standards and Code Review
Automating Standards and Best Practices


Question:
I came across an interesting article which shows how we can transparently encrypt jdbc connections using java thin client.

http://javasight.wordpress.com/2008/08/29/network-data-encryption-and-integrity-for-thin-jdbc-clients/

However I want to know how this can be achieved for application servers (like oc4j) datasources.

Answer:
It can be similarly done. I believe on the Oracle AS there is an option at the bottom of the page when you create datasource which says add properties. I believe you can add the following over there and give it a try.
```
```
// Set the Client encryption level
"oracle.net.encryption_client" = Service.getLevelString(level)

// Set the Client encryption selected list
"oracle.net.encryption_types_client"= "(RC4_40)"

// Set the Client integrity level
"oracle.net.crypto_checksum_client"= Service.getLevelString(level)

// Set the client integrity selected list
"oracle.net.crypto_checksum_types_client"="( MD5 )"
```
```
If it works out. Please let us know.
Thanks,
Franklin.


Question:
For instance, winsock libs works great across all versions of the visual studio. But I am having real trouble to provide a consistent binary across all the versions. The dll compiled with VS 2005 won't work when linked to an application written in 2008. I upgraded both 2k5 and 2k8 to SP1, but the results haven't changed much. It works some what ok. But when they include this with a C# app, the C# app gets access violation errors, but with classic C++ application it works fine.

Is there a strategy that I should know when I provide dlls ?

Answer:
First, dont pass anything other than plain old data accross DLL boundries. i.e. structs are fine. classes are not.
Second, make sure that ownership is not transferred - i.e. any structs passed accross the dll boundry are never deallocated outside the dll. So, if you dll exports a X* GetX() function, there is a corresponding FreeX(X*) type function ensuring that the same runtime that allocated is responsible for de-allocation.
Next: Get your DLLs to link to the static runtime. Putting together a project comprimising dls from several 3rd parties, each linked to and expecting different runtimes, potentially different to the runtime expected by the app, is a pain, potentially forcing the installer software to install runtimes for 7.0, 7.1, 8.0 and 9.0 - several of which exist in different service packs which may or may not cause issues. Be kind - statically link your dll projects.
-- Edit:
You cannot export a c++ class directly with this approach. Sharing class definitions between modules means you MUST have a homogeneous runtime environment as different compilers or versions of compilers will generate decorated names differently.
You
can
bypass this restriction by exporting your class instead as a COM style interface... which is to say, while you cannot export a class in a runtime independent way, you CAN export an "interface", which you can easilly make by declaring a class containing only pure virtual functions...
```
```
struct IExportedMethods {
    virtual long __stdcall AMethod(void)=0;
  };
  // with the win32 macros:
  interface IExportedMethods {
    STDMETHOD_(long,AMethod)(THIS)PURE;
  };
```
```
In your class definition, you inherit from this interface:
```
```
class CMyObject: public IExportedMethods { ...
```
```
You can export interfaces like this by making C factory methods:
```
```
extern "C" __declspec(dllexport) IExportedClass* WINAPI CreateMyExportedObject(){
    return new CMyObject;
  }
```
```
This is a very lightweight way of exporting compiler version and runtime independent class versions. Note that you still cannot delete one of these. You Must include a release function as a member of the dll or the interface. As a member of the interface it could look like this:
```
```
interface IExportedMethods {
    STDMETHOD_(void) Release(THIS) PURE; };
  class CMyObject : public IExportedMethods {
    STDMETHODIMP_(void) Release(){
      delete this;
    }
  };
```
```
You can take this idea and run further with it - inherit your interface from IUnknown, implement ref counted AddRef and Release methods as well as the ability to QueryInterface for v2 interfaces or other features. And finally, use DllCreateClassObject as the means to create your object and get the necessary COM registration going. All this is optional however, you can easilly get away with a simple interface definition accessed through a C function.


Question:
How do I multiply the values of a multi-dimensional array with weights and sum up the results into a new array in PHP or in general?

The boring way looks like this:

$weights = array(0.25, 0.4, 0.2, 0.15);
$values  = array
           (
             array(5,10,15),
             array(20,25,30),
             array(35,40,45),
             array(50,55,60)
           );
$result  = array();

for($i = 0; $i < count($values[0]); ++$i) {
  $result[$i] = 0;
  foreach($weights as $index => $thisWeight)
    $result[$i] += $thisWeight * $values[$index][$i];
}

Is there a more elegant solution?

Answer:
Hm...
```
```
foreach($values as $index => $ary )
  $result[$index] = array_sum($ary) * $weights[$index];
```
```


Question:
I want to subclass the built-in DropDownList in ASP.NET so that I can add functionality to it and use it in my pages. I tried doing this with a UserControl but found that it doesn't expose the internal DropDownList (logically, I guess). I've googled for the answer but can't find anything.

I've come as far as writing the actual class, and it's possible to subclass from DropDownList but I'm unable to register the file in my ASP.NET page and use it in the source view. Maybe I'm missing some properties in my class?

Any ideas?

Answer:
You want to extend DropDownList in a Custom Control... not in a usercontrol.
Create a new Class Library Project called MyLibrary.
Add a class called MyDropDownList.cs
```
```
namespace My.Namespace.Controls
{
[ToolboxData("<{0}:MyDropDownList runat=\"server\"></{0}:MyDropDownList>")]
public class MyDropDownList: DropDownList
{
    // your custom code goes here
    // e.g.
    protected override void  RenderContents(HtmlTextWriter writer)
    {
        //Your own render code
    }
}
}
```
```
Once you compile your library, you can add a reference to it in your web application.
And a tagprefix in your web.config
```
```
<add tagPrefix="my" namespace="My.Namespace.Controls" assembly="MyLibrary" />
```
```
That should allow you to add this to your aspx/ascx's
```
```
<my:MyDropDownList ID="myDDl" runat="server">
    ...
</my:MyDropDownList>
```
```


Question:
I have a .rc file which is used to include some text data in my executable, like this:

1234 RCDATA myfile.txt

This works fine: the content of the 'myfile.txt' is included in my executable.
The problem is that no 0-terminator is added to the string, and I cannot add it to the file. Is there any way of adding a 0-terminator from within the .rc file? Something like this:

1234 RCDATA { myfile.txt, "\0" }         // error RC2104

Note that I already found this solution, but I am looking for something more elegant.

1234 RCDATA myfile.txt
1235 RCDATA { "\0" }

Thanks alot,
eli

Answer:
I don't think so, unless you write your own resource compiler.
I have not meet one which allowed to build one resource from several sources.
You may write a small utility to add a trailing '\0' to a file, say makeZ.exe,
and set an additional build step:
```
```
makeZ myfile.txt myfileZ.txt
```
```
In you .rc there will be
```
```
1234 RCDATA myfileZ.txt
```
```


Question:
Where to read up on (the best-practice in) source code formatting, for individual languages i.e. what are the conventions for naming variables etc., for indentation and where to place braces, how and where to include comments, etc.

For example for C Kernighan and Ritchie's book The C Programming Language and Linus Torvalds' Linux kernel coding style guide or Google's C++ Style Guide and for Perl at least perlstyle - Perl style guide.

Edit: Perhaps I should have asked "How to get a good start with coding styles".

Answer:
I wouldn't give too much on such style-guides. They are a good start, but in the end you or your team will develop own coding-styles.
EDIT: Rob Kam made a comment, that he want to find out more about these 'starting-conventions'.
That's a good point. But mostly you will join existing projects, open-source-projects or commercial, and the people working on it already have a code-convention. In a company probably exists already a code convention. If you start a new project, start with the conventions of another project you did before.
If you really start a new project with a new language you didn't used before ... then you might start with conventions of another language that is somehow similar (i.e. for a new oo-language you can use conventions from Java or Smalltalk) and adjust your conventions as you gain experience for the new language. As I started programming in Java I used my Pascal-coding-conventions. Some of the pascal-conventions didn't work very good for Java, but with the time I dropped some old conventions and developed new.
S.Lott had the idea to look into an open-source-project written in the language of your choice. That's a good idea to get some suggestions about good conventions. Srikanth had the good idea to ask for good conventions here at Stackoverflow. A very good idea, because with the time Stackoverflow will become a good reference for coding-conventions this way.


Question: I'm looking to get data such as Size/Capacity, Serial No, Model No, Heads Sectors, Manufacturer and possibly SMART data.

Answer:
You can use
WMI
to get most of the information you want, and there's an introduction to WMI
here
.


Question:
I'm looking to create an Intellij IDEA language support plugin for Erlang.

The first and biggest problem I've had is in making the JFlex Erlang syntax definition.

Does anyone know where can I get the EBNF or BNF for Erlang?

Answer:
Why not go
straight to the source
?  The
Erlang 4.7 specification
lists productions in a grammar.


Question:
Ok: This is some of my table structure that matters here

CaseStudyID int
Title nvarchar(50)
OverrideTitle nvarchar(50)

Part of my procedure

Declare @Temp table(CaseStudyID int,
            Title nvarchar(50))

Insert Into @Temp
SELECT CaseStudyID,Title
FROM CaseStudy
WHERE Visible = 1 AND DisplayOnHomePage = 1
ORDER BY Title

Update @Temp Set Title = TitleOverride
--Here is where im lost if the title occurs more than once
--I need to replace it with the override
--Schoolboy error or leaking brain I cant get it going

Select * From @Temp

Can anyone help?

Answer:
You could achieve it without using tempory table this way:
```
```
SELECT
    MIN(CaseStudyID) AS CaseStudyID,
    CASE WHEN count(*) = 1 THEN
       MIN(Title)
    ELSE
       MIN(OverrideTitle)
    END AS Title
FROM CaseStudy
GROUP BY Title
ORDER BY Title
```
```


Question:
How to set the turbo c path in windows globally so that i can compile and run my C programs (which are in other drives) using command prompt in windows XP?
Can any one tell me how to get commands at every drive in the command prompt just by typing in

c:\tcc

in command prompt in windows and turbo c environment?

Answer:
Go to the Start Menu, then Control Panel.
Choose the "System" applet.
Click on the "Advanced" tab.
Click on "Environment Variables"
Find the "Path" variable, and press "Edit"
Append a semicolon, then the path to Turbo C
For setting the include and library paths, go to the same place, but instead of editing the "Path" variable, create a new variable called "INCLUDE", and set it to the location of your turboc "\include" directory; and create one called "LIB" and one called "CLASSPATH", and set them to your turboc "\lib" directory.


Question:
I was hoping someone could send me in the direction of a regularily updating time zone database.

I have found one, but apologies i cant remember where it was from, however with the current GMT clock change fast approaching, i fear all my data will be incorrect, ie the differences from UK to New Yrok will change from 5 hours behind to 6 hours behind.

Any help on this matter would be much appreciated.

Cameron

Answer:
Do you mean like the
Olson database
?
For instance, the
fleegix.js
javascript library is a timezone-enabled, drop-in replacement for the stock JavaScript Date, giving you full-blown timezone support, independent from the timezone set on the end-user's machine running the browser. It uses the Olson zoneinfo files for its timezone data.
I believe the
time-converter
uses also such a database, as well as
timeanddate.com
, e.g. for
London
or
New-York
.
Any DST information (Daylight Saving times) can be deduced from
timeanddate.com
, but also from
daylight-savings-time.info
Here is a
javascript program
that does exploit DST informations in order to apply the correct time shift.
And also another script for
SimpleTimeZone
.
You can also query DST data from
global-time-zones.com
, as in
wwp.britishsummertime.co.uk
. You have also informations in
webexhibits.org
See
this forum
for a lengthy discussion about how to retrieve DST informations.
Finally, see that
SO question
for a tar.gz Olson database example.


Question:
How to include any assembly code lines into my C program ?

In turbo c is there a possibility to add an assembly code file (.asm) to a project of few .c files?

Answer:
One way to include assembly code is to add a wrapper function and write the assembly code in the asm block, as shown in the example below:
```
```
void wrapper_function()
{
    asm
    {
        /* your assembly code */
    }
}
```
```


Question:
Please could someone help me with writing a regex expression to replace 0044 token which will be at the start of the string with a 0. Please note that I do not want to replace all 0044 tokens with 0, only those that appear at the start of the string.

Thanks a lot

Answer:
In perl:
```
```
s/^0044/0/;
```
```
The
```
^
```
means that the match will only happen at the beginning of the string.


Question: What exactly is the purpose of the 'obj' directory in .NET?

Answer:
The
"obj" folder
is used to store temporary object files and other files used in order to create the final binary during the compilation process.
The
"bin" folder
is the output folder for complete binaries (assemblies).


Question:
Does anyone have any T4 example Templates (or links to same) that can be used to generate a Webservice?

I'm thinking of the fact that I guess the Webservice is not just the Vb or Cs field but also requires an appropriate asmx file.

I'm really not sure how to achieve this

Answer:
Oleg Sych: How to generate multiple outputs from single T4 template
; create another method that generates your asmx - should be pretty simple, as it's one line - and renders it to a file.
T4 Toolbox
also has some methods that are helpful for this.  Oleg Sych's site also has other articles that will guide you through it, particularly these:
T4 Toolbox
Creating a complex code generator


Question: Is there a name meaning "not a singleton"?

Answer:
Multi-Instance ?
http://elegantcode.com/2008/04/17/the-opposite-of-a-singleton/


Question:
How do I get the type of a generic typed class within the class?

An example:

I build a generic typed collection implementing ICollection< T>. Within I have methods like

    public void Add(T item){
        ...
    }

    public void Add(IEnumerable<T> enumItems){
        ...
    }

How can I ask within the method for the given type T?

The reason for my question is: If object is used as T the collection uses Add(object item) instead of Add(IEnumerable<object> enumItems) even if the parameter is IEnumerable. So in the first case it would add the whole enumerable collection as one object instead of multiple objects of the enumerable collection.

So i need something like

if (T is object) {
    // Check for IEnumerable
}

but of course that cannot work in C#. Suggestions?

Thank you very much!

Michael

Answer:
You can use:
```
typeof(T)
```
```
```
if (typeof(T) == typeof(object) ) {
    // Check for IEnumerable
}
```
```


Question:
I have a comma separated list of strings like the one below.

a,b   ,c ,d, ,      , , ,e, f,g,h  .

I want to write a regular expression that will replace the empty values i.e., strings that contain only white spaces to 'NA'. So the result should be

a,b   ,c ,d,NA,NA,NA,NA,e, f,g,h  .

I tried using ",\s+," to search but it skips the alternate empty strings and results in

a,b   ,c ,d,NA,      ,NA, ,e, f,g,h  .

What's the correct regex to use here ?

Answer:
```
(?<=,)\s+(?=,)
```
This is a lookbehind for a comma, then whitespace, then a lookahead for a comma


Question:
I keep reading that, in C, using pointer arithmetic is generally faster than subscripting for array access. Is this true even with modern (supposedly-optimizing) compilers?

If so, is this still the case as I begin to move away from learning C into Objective-C and Cocoa on Macs?

Which is the preferred coding style for array access, in both C and Objective-C? Which is considered (by professionals of their respective languages) more legible, more "correct" (for lack of a better term)?

Answer:
You need to understand the reason behind this claim. Have you ever questioned yourself why it is faster? Let's compare some code:
```
```
int i;
int a[20];

// Init all values to zero
memset(a, 0, sizeof(a));
for (i = 0; i < 20; i++) {
    printf("Value of %d is %d\n", i, a[i]);
}
```
```
They are all zero, what a surprise :-P The question is, what means
```
a[i]
```
actually in low level machine code? It means
Take the address of
```
a
```
in memory.
Add
```
i
```
times the size of a single item of
```
a
```
to that address (int usually is four bytes).
Fetch the value from that address.
So each time you fetch a value from
```
a
```
, the base address of
```
a
```
is added to the result of the multiplication of
```
i
```
by four. If you just dereference a pointer, step 1. and 2. don't need to be performed, only step 3.
Consider the code below.
```
```
int i;
int a[20];
int * b;

memset(a, 0, sizeof(a));
b = a;
for (i = 0; i < 20; i++) {
    printf("Value of %d is %d\n", i, *b);
    b++;
}
```
```
This code
might
be faster... but even if it is, the difference is tiny. Why might it be faster? "*b" is the same as step 3. of above. However, "b++" is not the same as step 1. and step 2. "b++" will increase the pointer by 4.
(
important for newbies
: running
```
++
```
on a pointer will not increase the
pointer one byte in memory! It will
increase the pointer by as many bytes
in memory as the data it points to is
in size. It points to an
```
int
```
and the
```
int
```
is four bytes on my machine, so b++
increases b by four!)
Okay, but why might it be faster? Because adding four to a pointer is faster than multiplying
```
i
```
by four and adding that to a pointer. You have an addition in either case, but in the second one, you have no multiplication (you avoid the CPU time needed for one multiplication). Considering the speed of modern CPUs, even if the array was 1 mio elements, I wonder if you could really benchmark a difference, though.
That a modern compiler can optimize either one to be equally fast is something you can check by looking at the assembly output it produces. You do so by passing the "-S" option (capital S) to GCC.
Here's the code of first C code (optimization level
```
-Os
```
has been used, which means optimize for code size and speed, but don't do speed optimizations that will increase code size noticeably, unlike
```
-O2
```
and much unlike
```
-O3
```
):
```
```
_main:
    pushl   %ebp
    movl    %esp, %ebp
    pushl   %edi
    pushl   %esi
    pushl   %ebx
    subl    $108, %esp
    call    ___i686.get_pc_thunk.bx
"L00000000001$pb":
    leal    -104(%ebp), %eax
    movl    $80, 8(%esp)
    movl    $0, 4(%esp)
    movl    %eax, (%esp)
    call    L_memset$stub
    xorl    %esi, %esi
    leal    LC0-"L00000000001$pb"(%ebx), %edi
L2:
    movl    -104(%ebp,%esi,4), %eax
    movl    %eax, 8(%esp)
    movl    %esi, 4(%esp)
    movl    %edi, (%esp)
    call    L_printf$stub
    addl    $1, %esi
    cmpl    $20, %esi
    jne L2
    addl    $108, %esp
    popl    %ebx
    popl    %esi
    popl    %edi
    popl    %ebp
    ret
```
```
Same with the second code:
```
```
_main:
    pushl   %ebp
    movl    %esp, %ebp
    pushl   %edi
    pushl   %esi
    pushl   %ebx
    subl    $124, %esp
    call    ___i686.get_pc_thunk.bx
"L00000000001$pb":
    leal    -104(%ebp), %eax
    movl    %eax, -108(%ebp)
    movl    $80, 8(%esp)
    movl    $0, 4(%esp)
    movl    %eax, (%esp)
    call    L_memset$stub
    xorl    %esi, %esi
    leal    LC0-"L00000000001$pb"(%ebx), %edi
L2:
    movl    -108(%ebp), %edx
    movl    (%edx,%esi,4), %eax
    movl    %eax, 8(%esp)
    movl    %esi, 4(%esp)
    movl    %edi, (%esp)
    call    L_printf$stub
    addl    $1, %esi
    cmpl    $20, %esi
    jne L2
    addl    $124, %esp
    popl    %ebx
    popl    %esi
    popl    %edi
    popl    %ebp
    ret
```
```
Well, it's different, that's for sure. The 104 and 108 number difference comes of the variable
```
b
```
(in the first code there was one variable less on stack, now we have one more, changing stack addresses). The real code difference in the
```
for
```
loop is
```
```
movl    -104(%ebp,%esi,4), %eax
```
```
compared to
```
```
movl    -108(%ebp), %edx
movl    (%edx,%esi,4), %eax
```
```
Actually to me it rather looks like the first approach is faster(!), since it issues one CPU machine code to perform all the work (the CPU does it all for us), instead of having two machine codes. On the other hand, the two assembly commands below might have a lower runtime altogether than the one above.
As a closing word, I'd say depending on your compiler and the CPU capabilities (what commands CPUs offer to access memory in what way), the result might be either way. Either one might be faster/slower. You cannot say for sure unless you limit yourself exactly to one compiler (meaning also one version) and one specific CPU. As CPUs can do more and more in a single assembly command (ages ago, a compiler really had to manually fetch the address, multiply
```
i
```
by four and add both together before fetching the value), statements that used to be an absolute truth ages ago are nowadays more and more questionable. Also who knows how CPUs work internally? Above I compare one assembly instructions to two other ones.
I can see that the number of instructions is different and the time such an instruction needs can be different as well. Also how much memory these instructions needs in their machine presentation (they need to be transferred from memory to CPU cache after all) is different. However modern CPUs don't execute instructions the way you feed them. They split big instructions (often referred to as CISC) into small sub-instructions (often referred to as RISC), which also allows them to better optimize program flow for speed internally. In fact, the first, single instruction and the two other instructions below might result in the
same set of sub-instructions
, in which case there is no measurable speed difference whatsoever.
Regarding Objective-C, it is just C with extensions. So everything that holds true for C will hold true for Objective-C as well in terms of pointers and arrays. If you use Objects on the other hand (for example, an
```
NSArray
```
or
```
NSMutableArray
```
), this is a completely different beast. However in that case you must access these arrays with methods anyway, there is no pointer/array access to choose from.


Question:
What is the best way to do GUIs in Clojure?

Is there an example of some functional Swing or SWT wrapper?
Or some integration with JavaFX declarative GUI description which could be easily wrapped to s-expressions using some macrology?

Any tutorials?

Answer:
From this
page
:
```
```
(import '(javax.swing JFrame JButton JOptionPane)) ;'
(import '(java.awt.event ActionListener))          ;'

(let [frame (JFrame. "Hello Swing")
     button (JButton. "Click Me")]
 (.addActionListener button
   (proxy [ActionListener] []
     (actionPerformed [evt]
       (JOptionPane/showMessageDialog  nil,
          (str "<html>Hello from <b>Clojure</b>. Button "
               (.getActionCommand evt) " clicked.")))))

 (.. frame getContentPane (add button))

 (doto frame
   (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
   .pack
   (.setVisible true)))

print("code sample");
```
```
And, of course, it would be worth looking at the
interoperability
section of clojure's website.


Question:
I am trying to get data from my server, used RemoteObject to accomplish it.
When I run the application on my localhost it works great but when iam using it on my server i get a Channel.Security.Error(Security Error accessing URL).

On the server side logs there is a mention about cross domain .
77.127.194.4 - - [23/Oct/2008 21:15:11] "GET /crossdomain.xml HTTP/1.1" 501

Any one encountered the same problem ? any idea ?

Answer:
One thing you didn't list, that are used commonly to detect bad crawlers.
Hit speed, good web crawlers will break their hits up so they don't deluge a site with requests.  Bad ones will do one of three things:
hit sequential links one after the other
hit sequential links in some paralell sequence (2 or more at a time.)
hit sequential links at a fixed interval
Also, some offline browsing programs will slurp up a number of pages, I'm not sure what kind of threshold you'd want to use, to start blocking by IP address.
This method will also catch mirroring programs like fmirror or wget.
If the bot randomizes the time interval, you could check to see if the links are traversed in a sequential or depth-first manner, or you can see if the bot is traversing a huge amount of text (as in words to read) in a too-short period of time.  Some sites limit the number of requests per hour, also.
Actually, I heard an idea somewhere, I don't remember where, that if a user gets too much data, in terms of kilobytes, they can be presented with a captcha asking them to prove they aren't a bot.  I've never seen that implemented though.
Update on Hiding Links
As far as hiding links goes, you can put a div under another, with CSS (placing it first in the draw order) and possibly setting the z-order.  A bot could not ignore that, without parsing all your javascript to see if it is a menu.  To some extent, links inside invisible DIV elements also can't be ignored without the bot parsing all the javascript.
Taking that idea to completion, uncalled javascript which could potentially show the hidden elements would possilby fool a subset of javascript parsing bots.  And, it is not a lot of work to implement.


Question:
I have an abstract generic class BLL<T> where T : BusinessObject. I need to open an assembly that contains a set of concrete BLL classes, and return the tuples (businessObjectType, concreteBLLType) inside a Dictionary. There is the part of the method I could do until now, but I'm having problems to discover T.

protected override Dictionary<Type, Type> DefineBLLs()
{
   string bllsAssembly = ConfigurationManager.AppSettings["BLLsAssembly"];

   Type[] types = LoadAssembly(bllsAssembly);

   Dictionary<Type, Type> bllsTypes = new Dictionary<Type, Type>();

   foreach (Type type in types)
   {
     if (type.IsSubclassOf(typeof(BLL<>)))
        /* how to know T in the situation below? */
        bllsTypes.Add(??businessObjectType (T)??, type);
   }

   return bllsTypes;
}

Answer:
So the concrete classes will be closed rather than generic? Here's a short program which demonstrates what I
think
you're after...
```
```
using System;
using System.Reflection;

public abstract class Base<T>
{
}

public class Concrete : Base<string>
{
}

class Test
{
    static void Main()
    {
        Type type = typeof(Concrete);
        Type baseType = type.BaseType;
        Type typeOfT = baseType.GetGenericArguments()[0]; // Only one arg
        Console.WriteLine(typeOfT.Name); // Prints String
    }
}
```
```
Note that here I'm
assuming
that we only need to go up one level to get to the appropriate base type, and that the concrete class
will
be closed. You'd want to put more checks into your real code, of course, but I suspect it was the call to
GetGenericArguments
that you were missing.


Question:
I'm writing a C Shell program that will be doing su or sudo or ssh. They all want their passwords in console input (the TTY) rather than stdin or the command line.

Does anybody know a solution?

Setting up password-less sudo is not an option.

expect could be an option, but it's not present on my stripped-down system.

Answer:
Take a look at
```
expect
```
linux utility.
It allows you to send output to stdio based on simple pattern matching on stdin.


Question:
I have 3 divs where only one is visible by default, they each contain information about a product. Below this divs is a list of 3 images which are images of the products. By default of course the 1st list item is selected and has class="selected". When a different product image is clicks then class="selected" moves to that list item and the div above it changes to hidden and the div containing the other product information needs to appear.

I have searched all over the place for a plugin which can do what I want, they are all limited in some way which stops me doing from doing it.

Answer:
Consider the following code:
```
```

description 1

description 2

description 3

```
```
This should get you pretty close.  You need to define the relationship between your images and divs...  so I added a 'desc' attribute to the images.  The extra 'prodImg' class on the images allows you to ensure that only those images are being wired up for this type of swap in and out behavior.


Question:
In all honesty, I think the answer is "no;" however, I want to get a second opinion. Basically, I need one micro-controller device to send a steady signal to another one, but the communicate between them is using RS232. So I think that I have to create/update the communication messages to get it to do what I want.

What do you think?

Answer:
You should be able to set something like DTR (Data Terminal Ready), pin 20, or DSR (Data Set Ready), pin 6, high and keep it there as your steady-state signal. This is how modems/terminals detect that there is a device on the other end that is ready to communicate.  It all depends on what level of access you have to the hardware through your driver.
[EDIT] This doesn't involve sending data, although you could still do that using TX/RX, pins 2 & 3.
RS-232 Reference
on wikipedia


Question: Since many years a GUI-standard are the menu-bars of applications with menus popping up, if you click or hover an entry in the menu-bar. Some websites implement this feature too, but they are using Javascript, as far as  I can see. For different reasons Javascript can be a problem, so the question: Is this possible to implement without Javascript, only using HTML and CSS?

Answer:
You can use the pseudoclass :hover to get an hover effect.
```
```
a:link {
 color: blue;
}

a:hover {
  color: red;
}
```
```
I can give a more extensive example but not right now (need to get the kids to the dentist).


Question:
I have created a .NET DLL which makes some methods COM visible.

One method is problematic. It looks like this:

bool Foo(byte[] a, ref byte[] b, string c, ref string d)

VB6 gives a compile error when I attempt to call the method:

Function or interface marked as
  restricted, or the function uses an
  Automation type not supported in
  Visual Basic.

I read that array parameters must be passed by reference, so I altered the first parameter in the signature:

bool Foo(ref byte[] a, ref byte[] b, string c, ref string d)

VB6 still gives the same compile error.

How might I alter the signature to be compatible with VB6?

Answer:
Try
```
```
[ComVisible(true)]
bool Foo([In] ref byte[] a, [In] ref byte[] b, string c, ref string d)
```
```


Question:
I'm running Python 2.6 on Unix and when I run the interactive prompt (SQLite is supposed to be preinstalled) I get:

[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>

How do I resolve this?

Answer:
```
```
import sqlite3
```
```
sqlite3
- DB-API 2.0 interface for SQLite databases.
You are missing the
```
.so
```
(shared object) - probably an installation step. In my Linux python installation,
```
_sqlite3
```
is at:
```
```
${somewhere}/lib/python2.6/lib-dynload/_sqlite3.so
```
```


Question: I want to print the full length of a C-string in GDB.  By default it's being abbreviated, how do I force GDB to print the whole string?

Answer:
```
```
set print elements 0
```
```
From the GDB manual
:
```
set print elements
```
```
number-of-elements
```
Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the
```
set print elements
```
command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200.
Setting
number-of-elements
to zero means that the printing is unlimited
.


Question: So what is the easiest way to accomplish this?

Answer:
Path of least resistance is to download
Tortoise
, which supports this out of the box.
From their features page:
Can create a graph of
  all revisions/commits. You can then
  easily see where you created a
  tag/branch or modified a file/folder
  Graphs of commit statistics of the
  project Easy comparing of two branches
  or tags


Question: I have to override Add method of "Controls" property of myControl that is extended from a Panel control of windows. For that i extended ControlCollection class into MyControlCollection where i overriden its Add method. Now i declared a Controls property of MyControlCollection type to hide panel's Controls property. When i am accessing this.Controls.Add(control), it refers to overriden Add method. But if i drags and drops a control on myControl the behaviour is of base type's Add method. Can any body suggest the cause and remedy for this problem? Thanks in advance.

Answer:
The cause is that the designer is calling Control.Controls rather than accessing your separate collection. To be honest, your solution sounds like it's destined to cause trouble - hiding members usually does.
What are you trying to achieve, exactly? It doesn't look like there's a nice event to hook into in
```
ControlCollection
```
but there may be a different way of tackling the problem.
EDIT: I've just seen that
```
Control
```
has a
```
ControlAdded
```
event - would subscribing to that be enough for you?


Question: Is it possible to enable a second monitor programatically and extend the Windows Desktop onto it in C#? It needs to do the equivalent of turning on the checkbox in the image below.

Answer:
I don't have the full answer here but I am almost sure that you will have to call out of .Net to do this.  You will have to use Pinvoke to call an unmanaged dll.  A great resource for this is pinvoke.net.
I did a quick search and found
http://www.pinvoke.net/default.aspx/user32/ChangeDisplaySettings.html
which probably isn't exactly what you want but you will probably find it somewhere on pinvoke.net


Question:
I am trying to make our SQL Server Integration Services packages as portable as possible and the one thing that is preventing that is that the path to the config is always an absolute path, which makes testing and deployment a headache. Are there any suggestions for making this more manageble?

Another issue is when another developer gets the package out of source control the path is specific to the developers machine.

Answer:
If you are trying to execute your packages using Visual Studio then the configuration file path will be hardcoded in there. So if you move your project around you'll need to change the path in the package settings. To avoid this you could use the Environment variable option to store the configuration file path. Then you'll only need to change that.
For testing and deployment however you should probably use the dtexec utility to execute your packages. Make some batch files for that. Preferably one for each different environment. Here the configuration file path can be relative.
```
```
dtexec /File Package.dtsx /Conf configuration.dtsConfig
```
```
This is if you're packages are on file system. You can also store them in SQL Server. You can also store your configuration in SQL Server which may provide flexibility.


Question: I need to display a small (15x15 pixel) animation in a Flex app.  I have it FLV format, but it could be converted to somthing else.  I'd prefer to have the file embedded in the app (it's only 8k in size).  I've seen posts about displaying animated GIFs using third-party code which would be OK, but is there a way to do this with the native Flex libs.  I also realize that FLVs can be displayed in Video objects but only if they are external files.

Answer:
It is a lot easier converting it into a SWF and displaying it in an
```
Image
```
control.
SWFTools
can convert animated GIF into SWF file, small enough to be embedded in your app.


Question: I'm trying to write a small app that monitors how much power is left in a notebook battery and I'd like to know which Win32 function I could use to accomplish that.

Answer:
For Vista and up you can use
RegisterPowerSettingNotification
For earlier functions see the
Power Management Functions
in this section of the MSDN page "Power Management Functions: Windows Server 2003 and Earlier"
You can see example code of the Vista method on
codeproject
.


Question:
I have a number of custom controls that I am trying to enable designer support for. The signature looks something like the following:

[ToolboxData("<{0}:MyDropDownList runat=\"server\" CustomProp="123"></{0}:MyDropDownList>")]
public class MyDropDownList: DropDownList
{
   ... code here
}

This works fine, but when I drag a control onto the page from the toolbox, the TagPrefix that gets added is "cc1":

<%@ Register Assembly="DBMClientPortal.Controls" Namespace="DBMClientPortal.Controls"
    TagPrefix="cc1" %>

Obviously it is somewhat irrelevant what that TagPrefix is... it works as it stands, but I figured I must be able to change it somehow and curiosity got the better of me...

Anyone know how to define what the TagPrefix will be set to when dragging a custom control onto a page in visual studio?

Thanks,
Max

Answer:
It looks something like this:
```
```
[assembly:TagPrefix("MyControls","RequiredTextBox")]
```
```
and
here's
some more info about it.


Question:
I'm writing tests for a business method that invokes some DAO classes to perform operations over a database.

This method, firstly retrieves a JDBC connection from a DataSource object, The same connection is passed to all DAO instances, so I can use it to control the transaction. So, if everything works properly, I must invoke commit() over the connection object.

I would like to test if the commit() is invoked, so I've thought to create an expectation (I'm using JMock) that checks that. But since the Connection class isn't a direct neighbour from my Business class, I don't know how to do this.

Someone knows how to overcome this? There is some JMock facility for this, or some alternative design that allows to overcome this?

Thanks

Answer:
You need to mock
```
DataSource
```
and
```
Connection
```
so that your mock
```
DataSource
```
returns your mock
```
Connection
```
. And yes, this kind of thing ends up becoming a real pain...


Question:
I need to access a network resource on which only a given Domain Account has access.
I am using the LogonUser call, but get a "User does not have required priviliege" exception, as the web application is running with the asp.net account and it does not have adequate permissions to make this call.

Is there a way to get around it?
Changing the identity or permissions of the ASP.Net account is not an option as this is a production machine with many projects running.
Is there a better way to achieve this?

Using Asp.Net 2.0, Forms Authentication.

Kind Regards.

Answer:
You could add an
```
```
<identity impersonate="true" userName=""/>
```
```
tag to your web.config but that might not be ideal as you probably don't want to run the entire site as that user...
Can you map the network share as a local drive with the DomainName & Password... and then pull files to the website via the mapped drive ?
```
```
NET USE Z: \\SERVER\Share password /USER:DOMAIN\Username /PERSISTENT:YES
```
```


Question:
I have a very simple jQuery Datepicker calendar:

$(document).ready(function(){
    $("#date_pretty").datepicker({
    });
});

and of course in the HTML...

<input type="text" size="10" value="" id="date_pretty"/>

Today's date is nicely highlighted for the user when they bring up the calendar, but how do I get jQuery to pre-populate the textbox itself with today's date on page load, without the user doing anything?  99% of the time, the today's date default will be what they want.

Answer:
```
```
var myDate = new Date();
var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +
        myDate.getFullYear();
$("#date_pretty").val(prettyDate);
```
```
seemed to work, but there might be a better way out there..


Question:
What is the best practice for writing a rather large wcf service, containing a lot of OperationContracts and DataContracts?

How would I separate functional areas into several contracts, would it be best to create an endpoint for each functional area?

Is there any way to keep the source for the different parts apart, but still use only one service for all of them?

Where do I get good information how to plan the contracts, what to include, how to split...?

Answer:
That's been a big question surrounding services since their inception. SOA done successfully is SOA planned to the extent you're talking about. Having said that, I've always leaned more toward splitting services out, but using them in a composite manner. That is, several endpoints when you have several contracts, but most of them are only consumed by a few endpoints that are consumed by non-service callers. (wow, that was a mouthful, did it even make sense?)
Also, I would advise to have as few contracts as possible. Too many contracts can lead to poor manageability. Good contract design will help limit the number of endpoints and service calls. Removing OO concepts from contract design is one way of doing so. Contract design is a massive topic in itself, but suffice it to say that through good contract planning (up front), comes good service design.
Maarten Mullender
writes a great blog
on WCF design, and is a must read. There are also some great SOA/WCF books emerging as well.
Some good books:
Pro WCF: Practical Microsoft SOA Implementation
Programming WCF


Question:
I have heard that closures could be introduced in the next Java standard that is scheduled to be released somewhere around next summer.

What would this syntax look like?

I read somewhere that introducing closures in java is a bigger change than generic was in java 5. Is this true? pros and cons?

(By now we definitely know that closures not will be included in the next Java release)

OR

edit: http://puredanger.com/tech/2009/11/18/closures-after-all/ :D

edit2: Re-thinking JDK7: http://blogs.oracle.com/mr/entry/rethinking_jdk7

edit3: There’s not a moment to lose!: http://blogs.oracle.com/mr/entry/quartet

Answer:
Have a look at
http://www.javac.info/
.
It seems like this is how it would look:
```
```
boolean even = { int x => x % 2 == 0 }.invoke(15);
```
```
where the
```
{ int x => x % 2 == 0 }
```
bit is the closure.


Question: Does Eclipse have a feature that lets you search a project to find all calls to deprecated methods?

Answer:
You can set the compiler to generate errors or warnings (your choice) for any usage of deprecated API.
Preferences -> Java -> Compiler -> Errors/Warnings ->
Deprecated and restricted API
section.
Then, each use of a deprecated method or API will show up as an error/warning in the Problems view.


Question: In my experience it seems that most people will tell you that it is unwise to force a garbage collection but in some cases where you are working with large objects that don't always get collected in the 0 generation but where memory is an issue, is it ok to force the collect?  Is there a best practice out there for doing so?

Answer:
I've learned to not try to outsmart the garbage collection.  With that said, I just stick to using
```
using
```
keyword when dealing with unmanaged resources like file I/O or database connections.


Question:
All the PHP files in my workspace are encoded in Unicode (UTF-8, no BOM). I often duplicate an existing source file to use as a base for a new script. Invariably (with Path Finder or the original Finder), OS X will convert the encoding of the duplicate file to Western (Mac OS Roman).

Is there any way to make OS X behave and not convert the text encoding when duplicating a text file? Or make it use a specific text encoding (other than Western!) by default for all files with .php extension?

Answer:
I highly doubt that the "conversion" you're seeing is an actual difference in the two copies of the file.  OS X doesn't store any sort of encoding value for a file's content, so it's much more likely that it's whatever tool you're using to view/edit your files that's interpreting the content differently, whether it be Xcode, TextWrangler, or whatever other editor you're using.  Doing a straight copy of the file, whether it be from the Finder, Path Finder, or the command line, won't ever change the actual data in the file in the process of copying.
UTF-8 and Mac OS Roman are actually the same if you don't have any characters above 0x7f, so it's very possible that a valid UTF-8 file with no BOM could be interpreted as a Mac OS Roman file.  In any case, I would look into whatever program it is that's showing you that encoding to find the solution, not the file copying procedure of OS X itself.


Question:
Ok

I'm working on a little project at the moment, the Report expects an int but the ReportParameter class only lets me have a value that's a string or a string[]

How can I pass an int?

thanks

dan

Answer:
You can call the method
```
GetReportParameters()
```
which will return a
```
ReportParameter[]
```
array. If you iterate through each parameter and look at its Type property it will indicate if it is an
```
int
```
. The Type property is an
```
enum
```
of type
```
ParameterTypeEnum
```
and would be
```
ParameterTypeEnum.Integer
```
for an
```
int
```
.


Question:
I had a VBA project in outlook with a few email macros - but after a PC crash they are all gone and all I see is a fresh 'Project1' when I hit Alt+F11

I'm not a VBA programmer, but had a collection of handy macros for email sorting etc. I would not like to have to code them again. Anyone know where the code files should be on the filesystem so that I might rescue the code?

Answer:
This page
has some really good insight on where Outlook keeps all its stuff. It suggests the following:
All Outlook macros are stored in a single file named VbaProject.otm in the user's %appdata%\Microsoft\Outlook folder, which will be a hidden folder on most systems.
Now, the problem is that if you do not see them now, then you probably won't be able to restore them from that location: there is probably either an "empty" project there or no project at all, but if that folder is being backed up, you might be able to restore it.
Moving forward, you might consider exporting your macros periodically in case this happens again, either through the VBA IDE (right-click and select Export File...) or using one of the tools mentioned in the linked article (like the
Office Profile Wizard
).


Question:
i have a data access layer which returns data from stored procedures. If i bind this to a gridview control in asp.net 2.0, the users then have an option of filtering on that data select list where in they can choose the conditional clause of

like

=

or

and

Once the result is returned, I do not want to hit the Db again with the filters applied.

I have an option to use .net 3.5 if the need be. i looked at this:
http://weblogs.asp.net/jgaylord/archive/2006/05/31/Filter-A-GridView-After-The-Initial-Bind.aspx

and not sure of its efficiency.

Answer:
This page
has some really good insight on where Outlook keeps all its stuff. It suggests the following:
All Outlook macros are stored in a single file named VbaProject.otm in the user's %appdata%\Microsoft\Outlook folder, which will be a hidden folder on most systems.
Now, the problem is that if you do not see them now, then you probably won't be able to restore them from that location: there is probably either an "empty" project there or no project at all, but if that folder is being backed up, you might be able to restore it.
Moving forward, you might consider exporting your macros periodically in case this happens again, either through the VBA IDE (right-click and select Export File...) or using one of the tools mentioned in the linked article (like the
Office Profile Wizard
).


Question:
I use an anonymous object to pass my Html Attributes to some helper methods.
If the consumer didn't add an ID attribute, I want to add it in my helper method.

How can I add an attribute to this anonymous object?

Answer:
I assume you mean anonymous types here, e.g.
```
new { Name1=value1, Name2=value2}
```
etc. If so, you're out of luck - anonymous types are normal types in that they're fixed, compiled code. They just happen to be autogenerated.
What you
could
do is write
```
new { old.Name1, old.Name2, ID=myId }
```
but I don't know if that's really what you want. Some more details on the situation (including code samples) would be ideal.
Alternatively, you could create a container object which
always
had an ID and whatever other object contained the rest of the properties.


Question:
This question is about App domains and Sessions. Is it possible to have IIS run each User Session in a seperate App Domain. If Yes, Could you please let me settings in the config file that affect this.

Regards,
Anil.

Answer:
I assume you mean anonymous types here, e.g.
```
new { Name1=value1, Name2=value2}
```
etc. If so, you're out of luck - anonymous types are normal types in that they're fixed, compiled code. They just happen to be autogenerated.
What you
could
do is write
```
new { old.Name1, old.Name2, ID=myId }
```
but I don't know if that's really what you want. Some more details on the situation (including code samples) would be ideal.
Alternatively, you could create a container object which
always
had an ID and whatever other object contained the rest of the properties.


Question: I was wondering if the C# project setting "Allow unsafe code" applies only to unsafe C# code in  the project itself, or is it necessary to set this option when linking in a native C++ DLL? What about linking in a managed DLL that itself links to a native DLL? What does this option really do, under the hood?

Answer:
It allows you to use the "unsafe" block.
```
```
unsafe(...)
{
}
```
```


Question:
I am trying to detect Blackberry user agents in my app, which works fine in my development version. But nothing happens when I redeploy the app in production.

application_helper.rb

  def blackberry_user_agent?
    request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(Blackberry)/]
  end

application.html.erb

<% if blackberry_user_agent? -%>
<div class="message">
<p>Using a Blackberry? <a href="http://mobile.site.ca/">Use the mobile optimized version</a>.</p>
</div>

I've tried clearing the cache using rake tmp:cache:clear and restarted mongrel a few times. Apparently the HTTP_USER_AGENT is coming back nil in production. I am using Nginx with a mongrel cluster.

Answer:
Are you using Apache or nginx in front of your mongrel(s)?
Are you logging the user_agent? This is from my nginx.conf:
```
```
log_format main '$remote_addr - $remote_user [$time_local] $request '
                  '"$status" $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "http_x_forwarded_for"';
```
```


Question:
I would like to create a link between a winMo device and a server, so that they can pass information back and forth to each other. I actually don't really know where to start, I've had SOAP, RPC and creating a TCP link suggested to me. If someone could provide a link to an example that would be great.

Thanks!

Thanks for the responses. Updates:

It's not critical that the server initiate the communications, I could have the mobile device poll the server

timing is not ultra critical

I would prefer that it uses some open standard, if I wanted to also communicate with a palm device as well for example.

I had the idea that webservices were one way, unless the mobile device runs a server also?!

Answer:
Your best bet is to set up an ASP.NET web service on the server, and then have your PDA application talk to it.
You can also use the web service to talk back to the PDA.  Essentially, the PDA has to initially call the web service and pass in a delegate method that the server then calls when it needs to talk to the PDA.  I do not recommend this latter method, especially in an environment where the PDA is not continuously connected to the network.  It's usually better to have the PDA initiate each contact with the server.


Question:
Let's say you have a aspx page that does not rely on session, but does rely on viewstate for persistance between postbacks.

If a user is accessing this page, and leaves for a long lunch, will viewstate still be valid when he returns?

Answer:
No ViewState is kept as part of the PostBack process.  You can, however,
override
the Page class's  SavePageStateToPersistenceMedium() and LoadPageStateFromPersistenceMedium(), to implement that behavior if desired.  For more information read
Understanding the ASP.NET ViewState
.
Note that
Page
ViewState is stored in the Session so if your Session expires, the ViewState will be lost.  I wouldn't say this is ViewState expiring, but yes, it will be destroyed after Session timeout.


Question:
What are the best algorithms (and explanations) for representing and rotating the pieces of a tetris game?  I always find the piece rotation and representation schemes confusing.

Most tetris games seem to use a naive "remake the array of blocks" at each rotation:

http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris

However, some use pre-built encoded numbers and bit shifting to represent each piece:

http://www.codeplex.com/wintris

Is there a method to do this using mathematics (not sure that would work on a cell based board)?

Answer:
There is a limited amount of shapes, so I would use a fixed table and no calculation. That saves time.
But there are rotation algorithms.
Chose a centerpoint and rotate pi/2.
If a block of a piece starts at (1,2) it moves clockwise to (2,-1) and (-1,-2) and (-1, 2).
Apply this for each block and the piece is rotated.
Each x is the previous y and each y - the previous x. Which gives the following matrix:
```
```
[  0   1 ]
[ -1   0 ]
```
```
For counterclockwise rotation, use:
```
```
[  0  -1 ]
[  1   0 ]
```
```


Question:
I know the statement:

create table xyz_new as select * from xyz;

Which copies the structure and the data, but what if I just want the structure?

Answer:
Using sql developer select the table and click on the DDL tab
You can use that code to create a new table with no data when you run it in a sql worksheet
sqldeveloper is a free to use app from oracle.
If the table has sequences or triggers the ddl will sometimes generate those for you too. You just have to be careful what order you make them in and know when to turn the triggers on or off.


Question:
The Microsoft unit testing framework has suddenly gone on strike.

When I try to run tests in VS2008, I get a dialog with the message "VSTestHost.exe has stopped working".

I have Visual Studio Team System 2008 (version 9.0.30729.1 SP) running on Vista with all updates applied.

The "Problem reports and solutions" suggests that I "Upgrade to the latest retail version of Visual Studio Team Edition for Software Testers" which is not right.

I have tried rebooting.

I have tried "devenv /resetuserdata"

These made no difference.

I'd like to go back to MbUnit based on this nonsense, but that's not my choice.

Any suggestions on how to fix this?

Answer:
I have found the issue that I was asking about, and it was my fault. I had coded a stack overflow: I refactored some code into an extension method, renamed it to match the Linq extension method that it called, and so  it just called it self recursively.
The lessons to learn from this:
1:
"select" isn't broken
.
I was too quick to blame the framework, due to its bad reputation.
2:
But it did have a pathologically general and entirely misleading error message.
In cases where the error message is that bad, a good debugging technique is to try to pin down what does and what doesn't cause the error. In my case, the breakthrough came as soon as I noticed that it wasn't "the test run" that was failing, it was only runs containing Sql database tests - domain object and mock repository test could run just fine, so there had to be something about the code that it was running. And that the debugger would step into the tests. I had assumed from the calamitous errors that it wasn't even getting that far.


Question: Is there a way to create a blank solution, or some type of file-based project solution within Visual Studio so that I can point to a root folder, and have all of the sub-folders and files in that root, show up in my solution explorer? I realize I can create a blank solution and then add the individual items manually by add > existing item, however, this does not keep the folder structure intact, and, well, it would take forever if I have a lot of folders/files.

Answer:
You can also create the blank solution and then click the second-from-the-right icon at the top of the solution explorer (it looks like three files with one "cut out").  Once you click that button to show the files in the solution directory that are not in a project, you can select all the files (with shift-click) and then right-click on your selection and select "Include In Project."
Also note you can select multiple files in the "Add Existing..." file window with shift- or control-click.


Question:
Im currently using ie as an active x com thing on wxWidgets and was wanting to know if there is any easy way to change the user agent that will always work.

Atm im changing the header but this only works when i manually load the link (i.e. call setUrl)

Answer:
The only way that will "always work," so far as I've been able to find, is
changing the user-agent string in the registry
. That will, of course, affect
every
web browser instance running on that machine.
You might also try a Google search on
```
DISPID_AMBIENT_USERAGENT
```
. From
this Microsoft page
:
MSHTML will also ask for a new user
  agent via
```
DISPID_AMBIENT_USERAGENT
```
when navigating to clicked hyperlinks.
  This ambient property can be
  overridden, but it is not used when
  programmatically calling the Navigate
  method; it will also not cause the
  userAgent property of the DOM's
  navigator object or clientInformation
  behavior to be altered - this property
  will always reflect Internet
  Explorer's own UserAgent string.
I'm not familiar with the MSHTML component, so I'm not certain that's helpful.
I hope that at least gives you a place to start. :-)


Question:
I have a WinForms app with an input textbox, button, and a multiline output textbox.
A root path is entered in the textbox.  Button click calls a function to recursively check all subdirectories for some proper directory naming validation check.
The results are output into the multiline textbox.

If the recursive work is done in a separate class, I have two options:

Keep track of improper directories in a class property(e.g. ArrayList),return the ArrayList when done, and update the output textbox with all results.

Pass in ByRef the output textbox and update/refresh it for each improper directory.
Even though 1 & 2 are single-threaded, with 2, I would at least get my results updated per directory.

If the recursive work is done in the presentation layer and the validation is done in a separate class, I can multithread.

Which is a cleaner way?

Answer:
You don't need to pass the TextBox ByRef.  It's already a reference object.  Passing it ByRef would only have an effect if you planned to assign a different or new TextBox to the reference.
If you're going to do the work in a separate class, it seems as simple as passing in the contents of the TextBox as a string, and getting the results back as a string or a set of strings (array or
```
List<string>
```
or the like).  This is better than passing in the TextBox in case someday you decide to use a different kind of control to store this information.


Question:
What are my validation options with .net mvc?

Do any of them have a nice validation summary like webforms did?

Answer:
You can use a MVC html validation summary,see this blog
http://blog.maartenballiauw.be/post/2008/08/29/Form-validation-with-ASPNET-MVC-preview-5.aspx


Question: Does anyone know if there is a debug visualiser for this yet along the same lines and the linq to SQL debug visualiser?

Answer:
There isn't one that I'm aware of at the moment (hope to be shown otherwise by other answers here), but Julie Lerman has a post
"An extension method for visualizing ObjectStateEntries"
where she walks through creating a debug tool that pops up a WinForm for inspecting the state of entities via their EntityKey.
Not quite a visualizer, but seriously handy when you need to tease apart ObjectStateEntries to debug change tracking scenarios.


Question:
I need to create at runtime instances of a class that uses generics, like class<T>, without knowing previously the type T they will have, I would like to do something like that:

public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        lists.Add(type, new List<type>()); /* this new List<type>() doesn't work */
    }

    return lists;
}

...but I can't. I think it is not possible to write in C# inside the generic brackets a type variable. Is there another way to do it?

Answer:
You can't do it like that - the point of generics is mostly
compile-time
type-safety - but you can do it with reflection:
```
```
public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        Type genericList = typeof(List<>).MakeGenericType(type);
        lists.Add(type, Activator.CreateInstance(genericList));
    }

    return lists;
}
```
```


Question: How can I find the index in a string that matches a boost regex?

Answer:
Use the
```
position
```
member function of the
```
match_results
```
:
```
```
int find_match_offset(std::string const& string_to_search,
                      boost::regex const& expression)
{
    boost::smatch results;
    if(boost::regex_match(string_to_search,results,expression))
    {
        return results.position()
    }
    return -1;
}
```
```


Question:
Anyone got a ready made function that will take an XML string and return a correctly indented string?

eg

<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>

and will return nicely formatted String in return after inserting linebreaks and tabs or spaces?

Answer:
Using
OmniXML
:
```
```
program TestIndentXML;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  OmniXML,
  OmniXMLUtils;

function IndentXML(const xml: string): string;
var
  xmlDoc: IXMLDocument;
begin
  Result := '';
  xmlDoc := CreateXMLDoc;
  if not XMLLoadFromAnsiString(xmlDoc, xml) then
    Exit;
  Result := XMLSaveToAnsiString(xmlDoc, ofIndent);
end;

begin
  Writeln(IndentXML('<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>'));
  Readln;
end.
```
```
The code fragment above is released to public domain.


Question:
How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code:

<input name = "deleteGameButton" type = "submit" value = "Delete"
 onclick = "submitToServlet('DeleteGameServlet');">

Here is the corresponding javascript:

 function submitToServlet(newAction)
 {
   document.userGameForm.action = newAction;
 }

I'd like the servlet to have access to userBean

 <jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />

Answer:
You kind of mess things here.
onclick() is Javascript and executed on client side. It has no (direct) way to update session-scoped bean. That bean is left on server-side, and was used when the HTML page was
generated
. To pass parameters back to servlet you need to use good old form fields, and submit the form.
Add more fields to the form, set their values before submit, then submit.
In Servlet call request.getParameter("name");
P.S. To automate this kind of things
USE STRUTS
. :-) Struts does exactly what you want: before passing the parameters to action, it populates the bean with those parameters. Transparently.


Question: I have a string containing a date, and another string containing the date format of the first string. Is there a function that I can call to convert that date into something like a SYSTEMTIME structure? Basically, I'd like the opposite of GetDateFormat().

Answer:
No, but you can write a function that will convert the date format string into a
```
sscanf
```
format string and series of variables.  Then copy the data from the variables to the
```
SYSTEMTIME
```
structure and you're all set.
It's not trivial, but it is probably the most flexible arrangement if you must support many different date formats.


Question:
I am creating a WordML document from an xml file whose elements sometimes contain html-formatted text.

<w:p>
  <w:r>
    <w:t> html formatted content is in here taken from xml file! </w:t>
  </w:r>
</w:p>

This is how my templates are sort of set up.  I have a recursive call-template function that does text replacement against the source xml content.  When it comes across a "<b>" tag, I output a string in CDATA containing "</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>" to close the current run and start up a new run with bold formatting enabled.  when it gets to a "</b>" tag, it replaces it with the following CDATA string "</w:t></w:r><w:r><w:t>".

What I'd like to do is use XSL to close the run tag and start a new run without using CDATA string inserts.  Is this possible?

Answer:
I can most probably help you if only I understood your problem... Is the html in a CDATA section or is it parsed as part of the input doc (and thus well-formed XML)?
Since you talk about 'text replacement' I'll assume that you treat the 'html formatted content' as a single string (CDATA) and therefor need a recursive call-template function to perform string replacement. The only way you're going to be able to use an XSL matching template to do what you're doing now is to make the html part of the parsed document (your input document). In such a case you could just match the
```
b
```
tag and replace it with the appropriate output (again: this assumes that it can always be parsed as valid XML). Your problem now has shifted... since (if I understood your problem correctly) what you're trying to do is close the
```
w:t
```
and
```
w:r
```
elements and then 'reopen' them... this is hard because it's (as you probably suspect) very hard to do this nicely in XSLT (you cannot just create an element in template A and then close it in template B). You'll have to start messing with unescaped output etc. to make this happen. I now I've made a lot of assumptions but here is a small example to help you on your way:
input.xml
```
```
<doc xmlns:w="urn:schemas-microsoft-com:office:word">
<w:p>
  <w:r>
    <w:t>before<b>bold</b>after</w:t>
  </w:r>
</w:p>
</doc>
```
```
convert_html.xsl
```
```
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="/doc/w:p/w:r/w:t//b">
  <xsl:value-of select="'</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>'" disable-output-escaping="yes" />
  <xsl:apply-templates select="@*|node()"/>
  <xsl:value-of select="'</w:t></w:r><w:r><w:t>'" disable-output-escaping="yes" />
</xsl:template>
```
```
Now running
```
```
xalan input.xml convert_html.xsl
```
```
produces
```
```
<?xml version="1.0" encoding="UTF-8"?><doc xmlns:w="urn:schemas-microsoft-com:office:word">
<w:p>
  <w:r>
    <w:t>before</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>bold</w:t></w:r><w:r><w:t>after</w:t>
  </w:r>
</w:p>
</doc>
```
```
which I guess is what you wanted.
Hope this helps you somewhat.


Question:
How do you create an application shortcut (.lnk file) in C# or using the .NET framework?

The result would be a .lnk file to the specified application or URL.

Answer:
It's not as simple as I'd have liked, but there is a great class call
ShellLink.cs
at
vbAccelerator
This code uses interop, but does not rely on WSH.
Using this class, the code to create the shortcut is:
```
```
private static void configStep_addShortcutToStartupGroup()
{
    using (ShellLink shortcut = new ShellLink())
    {
        shortcut.Target = Application.ExecutablePath;
        shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
        shortcut.Description = "My Shorcut Name Here";
        shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
        shortcut.Save(STARTUP_SHORTCUT_FILEPATH);
    }
}
```
```


Question: Are pipes considered dangerous to use in Windows, from a security standpoint?

Answer: If you are concerned about network sniffing, I suppose they could be since I don't think that pipes between systems are encrypted.  I don't know exactly how they are implemented in Windows, but I would expect that pipes between processes/threads on the same machine would be implemented with shared memory and not let traffic leak outside the box.  If you need secure communication between systems, I'd go with secure sockets.


Question:
Possible Duplicate:

  Reference: Comparing PHP's print and echo

Is there any major and fundamental difference between these two functions in PHP?

Answer:
From:
http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40
Speed.  There is a difference between the two, but speed-wise it
should be irrelevant which one you use.  echo is marginally faster
since it doesn't set a return value if you really want to get down to the
nitty gritty.
Expression.
```
print()
```
behaves like a function in that you can do:
```
$ret = print "Hello World"
```
; And
```
$ret
```
will be
```
1
```
.  That means that print
can be used as part of a more complex expression where echo cannot.  An
example from the PHP Manual:
```
```
$b ? print "true" : print "false";
```
```
print is also part of the precedence table which it needs to be if it
is to be used within a complex expression. It is just about at the bottom
of the precedence list though.  Only
```
,
```
```
AND
```
```
OR
```
```
XOR
```
are lower.
Parameter(s).  The grammar is:
```
echo expression [, expression[,
expression] ... ]
```
But
```
echo ( expression, expression )
```
is not valid.
This would be valid:
```
echo ("howdy"),("partner")
```
; the same as:
```
echo
"howdy","partner"
```
; (Putting the brackets in that simple example
serves
no purpose since there is no operator precedence issue with a single
term like that.)
So, echo without parentheses can take multiple parameters, which get
concatenated:
```
```
echo  "and a ", 1, 2, 3;   // comma-separated without parentheses
   echo ("and a 123");        // just one parameter with parentheses
```
```
```
print()
```
can only take one parameter:
```
```
print ("and a 123");
   print  "and a 123";
```
```


Question:
I'm trying to come up with a Java regex that will match a filename only if it has a valid extension. For example it should match "foo.bar" and "foo.b", but neither "foo." nor "foo".

I've written the following test program

public static void main(String[] args) {
  Pattern fileExtensionPattern = Pattern.compile("\\.\\w+\\z");

  boolean one = fileExtensionPattern.matcher("foo.bar").matches();
  boolean two = fileExtensionPattern.matcher("foo.b").matches();
  boolean three = fileExtensionPattern.matcher("foo.").matches();
  boolean four = fileExtensionPattern.matcher("foo").matches();

  System.out.println(one + " " + two + " " + three + " " + four);
}

I expect this to print "true true false false", but instead it prints false for all 4 cases. Where am I going wrong?

Cheers,
Don

Answer:
The
Matcher.matches()
function tries to match the pattern against the entire input.  Thus, you have to add
```
.*
```
to the beginning of your regex (and the
```
\\Z
```
at the end is superfluous, too), or use the
find()
method.


Question:
I'm using Chris Pederick's Firefox addon "Web Developer 1.1.6". I get this warning when hitting a certain web page on my site:

Unknown property 'MozOpacity'. Declaration dropped.

What does this mean and how can I fix this on my site?

Answer:
Are you using
```
mozopacity
```
in your CSS stylesheet? This might be spelled wrong and is thus triggering an error.
You might be looking for
```
-moz-opacity
```
which has been dropped as of Firefox 3.0.


Question:
When overriding the MembershipProvider and calling it directly, is there a way to fill the NameValueCollection config parameter of the Initialize method without manually looking through the config file for the settings?

Obviously this Initialize is being called by asp.net and the config is being filled somewhere. I have implemented my own MembershipProvider and it works fine through the build in controls.
I would like to create a new instance of my provider and make a call to it directly, but I don't really want to parse the .config for the MembershipProvider, it's connection string name and then the connection string if it's already being done somewhere.

Answer:
Not sure why you want to create a new one, but if you create it yourself, you'll need to read the web config and get the values yourself to pass to Initialize() as this is done outside the class.  I'm sure, though, that there is already a section handler for this section so it should be just a matter of doing:
```
```
MembershipSection section  = WebConfigurationManager.GetSection("membership");
```
```
Then find your provider and accessing its properties to construct the NameValueCollection.  I don't think you will have to write any code to parse the configuration section.
Here is the
MembershipSection
documentation at MSDN.  Drill down from there.


Question:
I don´t know why, but my form isn´t calling Form_Load event when it loads.

Any ideas why this might be happening?

Answer:
Do you have the event handler set up?
Ultimately, there is going to be a line of code that looks something like this:
```
```
this.Load += new System.EventHandler(this.Form1_Load);
```
```
That might be something you code yourself, or is generated by double-clicking the Load event for the form from within Visual Studio.


Question:
I'm new to Windows programming and after reading the Petzold book I wonder:

is it still good practice to use the TCHAR type and the _T() function to declare strings or if I should just use the wchar_t and L"" strings in new code?

I will target only Windows 2000 and up and my code will be i18n from the start up.

Answer:
Yes, absolutely; at least for the _T macro.  I'm not so sure about the wide-character stuff, though.
The reason being is to better support WinCE or other non-standard Windows platforms.  If you're 100% certain that your code will remain on NT, then you can probably just use regular C-string declarations.  However, it's best to tend towards the more flexible approach, as it's much easier to #define that macro away on a non-windows platform in comparison to going through thousands of lines of code and adding it everywhere in case you need to port some library to windows mobile.


Question:
Disclaimer: I've solved the problem using Expressions from System.Linq.Expressions, but I'm still looking for a better/easier way.

Consider the following situation :

var query =
    from c in db.Customers
    where (c.ContactFirstName.Contains("BlackListed") ||
           c.ContactLastName.Contains("BlackListed")  ||
           c.Address.Contains("BlackListed"))
    select c;

The columns/attributes that need to be checked against the blacklisted term are only available to me at runtime. How do I generate this dynamic where clause?

An additional complication is that the Queryable collection (db.Customers above) is typed to a Queryable of the base class of 'Customer' (say 'Person'), and therefore writing c.Address as above is not an option.

Answer:
```
```
var query = from C in db.Customers select c;

if (seachFirstName)
         query = query.Where(c=>c.ContactFirstname.Contains("Blacklisted"));

if (seachLastName)
         query = query.Where(c=>c.ContactLastname.Contains("Blacklisted"));

if (seachAddress)
         query = query.Where(c=>c.Address.Contains("Blacklisted"));
```
```
Note that they aren't mutually exclusive.


Question:
I'm exploring the iPhone SDK and want to create and use a UI component like the figure below. A rounded table with cells in which each cell can have some label text, maybe an input text field and an action button that would take it to the next screen. The table should not be screen filling.

But... I can't figure out how to do it or find example code. The 'Table View' always seems to result in a screen filling table and although the 'Table View Cell' looks like what I need I can't find any good examples. I'm sure it's all not that hard, but I just can't find it. Any tips, pointers are appreciated.

(This figure is just an example of the sort of UI component I'm looking for, I'm not build something related to flight tracking...)

Table like component http://gerodt.homeip.net/table_ui_component.png

Gero

Answer:
Try looking at the "5_CustomTableViewCell" project of the
TableViewSuite
code sample from Apple. It should how to create custom subclasses of UITableViewCell.
The short answer is, as alluded to above, you'll want to subclass UITableViewCell and add your custom UI elements to it. For the example you provided, you'd want two different types of cells; one with a label (in light blue) and content (in black) for 4 of your cells, and then a more complex one with additional text on the right.


Question:
I have a string which is like this:

this is [bracket test] "and quotes test "

I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:

['this','is','bracket test','and quotes test ']

Answer:
Here's a simplistic solution that works with your test input:
```
```
import re
re.findall('\[[^\]]*\]|\"[^\"]*\"|\S+',s)
```
```
This will return any code that matches either
a open bracket followed by zero or more non-close-bracket characters followed by a close bracket,
a double-quote followed by zero or more non-quote characters followed by a quote,
any group of non-whitespace characters
This works with your example, but might fail for many real-world strings you may encounter. For example, you didn't say what you expect with unbalanced brackets or quotes,or how you want single quotes or escape characters to work. For simple cases, though, the above might be good enough.


Question: Can I setup a custom MIME type through ASP.NET or some .NET code?  I need to register the Silverlight XAML and XAP MIME types in IIS 6.

Answer:
To add to the master mime type list:
```
```
using (DirectoryEntry mimeMap = new DirectoryEntry("IIS://Localhost/MimeMap"))
{
    PropertyValueCollection propValues = mimeMap.Properties["MimeMap"];

    IISOle.MimeMapClass newMimeType = new IISOle.MimeMapClass();
    newMimeType.Extension = extension; // string - .xap
    newMimeType.MimeType = mimeType;   // string - application/x-silverlight-app

    propValues.Add(newMimeType);
    mimeMap.CommitChanges();
}
```
```
Add a reference to :
'System.DirectoryServices' on the .NET add references tab
'Active DS IIS Namespace Provider' on the COM add references tab.
To configure a mime type for a specific site, change ..
```
'IIS://Localhost/MimeMap'
```
to
```
'IIS://Localhost/W3SVC/[iisnumber]/root'
```
...replacing
```
'[iisnumber]'
```
with the IISNumber of the website.


Question:
How do I make vi-Vim never use tabs (converting spaces to tabs, bad!), makes the tab key == 4 spaces, and automatically indent code after curly brace blocks like Emacs does?

Also, how do I save these settings so I never have to input them again?

I've seen other questions related to this, but it always seems to be a little off from what I want.

Answer:
As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your
```
.vimrc
```
):
```
```
filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab
```
```
In your [.vimrc:][1] file:
```
```
set smartindent
set tabstop=4
set shiftwidth=4
set expandtab
```
```
The help files take a bit of time to get used to, but the more you read, the better Vim gets:
```
```
:help smartindent
```
```
Even better, you can embed these settings in your source for portability:
```
```
:help auto-setting
```
```
To see your current settings:
```
```
:set all
```
```
As
graywh
points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax:
```
```
:help C-indenting
```
```