Question:
For loading time considerations I am using a runtime css file in my Flex Application.

I am having a problem with a multi line text control :

<mx:Text id="txtDescription" selectable="false"
styleName="imageRolloverButtonTextDark" width="100%" textAlign="center"
text="{_rolloverText}"/>

When my CSS stylesheet has loaded the text style correctly changes, but the height is not recalculated. It appears to be just a single line field.

FYI: The control is not actually visible, and triggered by a rollover. So I dont really care if the stylesheet hasnt loaded and they get standard system text. I jsut want it to be the correct height when it has been loaded.

Answer: Could you use a fixed pixel width instead of 100%? I've had issues with 100% being wrongly calculated on dynamic text controls before.


Question:
Given a class:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=20)

Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments?  For example:

 # Instead of:
 Person.objects.filter(name__startswith='B')
 # ... and:
 Person.objects.filter(name__endswith='B')

 # ... is there some way, given:
 filter_by = '{0}__{1}'.format('name', 'startswith')
 filter_value = 'B'

 # ... that you can run the equivalent of this?
 Person.objects.filter(filter_by=filter_value)
 # ... which will throw an exception, since `filter_by` is not
 # an attribute of `Person`.

Answer:
A really complex search forms usually indicates that a simpler model is trying to dig it's way out.
How, exactly, do you expect to get the values for the column name and operation?
Where do you get the values of
```
'name'
```
an
```
'startswith'
```
?
```
```
filter_by = '%s__%s' % ('name', 'startswith')
```
```
A "search" form?  You're going to -- what? -- pick the name from a list of names?  Pick the operation from a list of operations?  While open-ended, most people find this confusing and hard-to-use.
How many columns have such filters? 6? 12? 18?
A few?  A complex pick-list doesn't make sense.  A few fields and a few if-statements make sense.
A large number?  Your model doesn't sound right.  It sounds like the "field" is actually  a key to a row in another table, not a column.
Specific filter buttons.  Wait... That's the way the Django admin works.  Specific filters are turned into buttons.  And the same analysis as above applies.  A few filters make sense.  A large number of filters usually means a kind of first normal form violation.
A lot of similar fields often means there should have been more rows and fewer fields.


Question: Mac OS X stores some files with resource forks.  I need to create a file with a resource fork.  The trouble is, I need to create this file on the command line.  Is anyone aware of how you can create a file with a resource fork on the command line in Mac OS X?

Answer:
First, OS X doesn't really use resource forks... it supports named forks and HFS+ supports the resource forks, but that's mostly for backwards compatibility with OS 9 and old-style Carbon stuff... however, there are command line tools installed with the Developer Tools (so you'll have to install these... if you don't have them, you can get them from developer.apple.com).
See the man pages for the following tools:
ResMerger
Rez
RezDet
RezWack
The man pages are installed with the developer tools, so
```
```
man Rez
```
```
in the terminal will work. The man pages are also available online:
Rez(1)


Question: Comparable to cacti or mrtg.

Answer:
http://www.zenoss.com/
This is a lot more than just SNMP but it is based on Python.


Question:
I have an array (arr) of elements, and a function (f) that takes 2 elements and returns a number.

I need a permutation of the array, such that f(arr[i], arr[i+1]) is as little as possible for each i in arr. (and it should loop, ie. it should also minimize f(arr[arr.length - 1], arr[0]))

Also, f works sort of like a distance, so f(a,b) == f(b,a)

I don't need the optimum solution if it's too inefficient, but one that works reasonable well and is fast since I need to calculate them pretty much in realtime (I don't know what to length of arr is, but I think it could be something around 30)

Answer:
What does "such that f(arr[i], arr[i+1]) is as little as possible for each i in arr" mean? Do you want minimize the
sum
? Do you want to minimize the largest of those? Do you want to minimize f(arr[0],arr[1]) first, then among all solutions that minimize this, pick the one that minimizes f(arr[1],arr[2]), etc., and so on?
If you want to minimize the
sum
, this is
exactly
the Traveling Salesman Problem in its full generality (well, "metric TSP", maybe, if your f's indeed form a metric). There are clever optimizations to the naive solution that will give you the exact optimum and run in reasonable time for about n=30; you could use one of those, or one of the heuristics that give you approximations.
If you want to minimize the
maximum
, it is a simpler problem although still NP-hard: you can do binary search on the answer; for a particular value d, draw edges for pairs which have f(x,y)
If you want to minimize it
lexiocographically
, it's trivial: pick the pair with the shortest distance and put it as arr[0],arr[1], then pick arr[2] that is closest to arr[1], and so on.
Depending on where your f(,)s are coming from, this might be a much easier problem than TSP; it would be useful for you to mention that as well.


Question: When using a subdomain and trying to view anything related to current_user. user is sent to a new session page, the page shows the session is created and gives the option to logout. I can use no subdomain and it works fine.

Answer:
Set it in your environment.rb (or environments/*.rb if you'll use different domains for each environment):
```
```
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update( :session_domain => '.domain.com')
```
```


Question:
I want to do this in Actionscript:

typeof(control1) != typeof(control2)

to test if two objects are of the same type. This would work just fine in C#, but in Actionscript it doesnt. In fact it returns 'object' for both typeof() expressions because thats the way Actionscript works.

I couldn't seem to find an alternative by looking in the debugger, or on pages that describe typeof() in Actionscript.

Is there a way to get the actual runtime type?

Answer:
You'll want to use the Object.prototype.constructor.
From the
documentation
:
```
```
dynamic class A {}
  trace(A.prototype.constructor);      // [class A]
  trace(A.prototype.constructor == A); // true
  var myA:A = new A();
  trace(myA.constructor == A);         // true
```
```
(Conveniently, this is also how to check types in javascript, which is what originally led me to this in the docs)
So, to test this out before I posted here, I tried it in an app I have, in a class called Player.  Since the prototype property is static, you can't call it using "this" but you can just skip the scope identifier and it works:
```
```
public function checkType():void {
    trace(prototype.constructor, prototype.constructor == Player);
    // shows [class Player] true
}
```
```


Question:
I am building a small device with its own CPU (AVR Mega8) that is supposed to connect to a PC. Assuming that the physical connection and passing of bytes has been accomplished, what would be the best protocol to use on top of those bytes? The computer needs to be able to set certain voltages on the device, and read back certain other voltages.

At the moment, I am thinking a completely host-driven synchronous protocol: computer send requests, the embedded CPU answers. Any other ideas?

Answer:
There's a lot to be said for client-server architecture and synchronous protocols.  Simplicity and robustness, to start.  If speed isn't an issue, you might consider a compact, human-readable protocol to help with debugging.  I'm thinking along the lines of modem AT commands: a "wakeup" sequence followed by a set/get command, followed by a terminator.
```
```
Host -->  [V02?]      // Request voltage #2
AVR  -->  [V02=2.34]  // Reply with voltage #2
Host -->  [V06=3.12]  // Set voltage #6
AVR  -->  [V06=3.15]  // Reply with voltage #6
```
```
Each side might time out if it doesn't see the closing bracket, and they'd re-synchronize on the next open bracket, which cannot appear within the message itself.
Depending on speed and reliability requirements, you might encode the commands into one or two bytes and add a checksum.
It's always a good idea to reply with the
actual
voltage, rather than simply echoing the command, as it saves a subsequent read operation.
Also helpful to define error messages, in case you need to debug.


Question:
I've been looking around for a good MVC framework for Python using PyGTK. I've looked at Kiwi but found it a bit lacking, especially with using the Gazpacho Glade-replacement.

Are there any other nice desktop Python MVC frameworks?  I'm one of the few (it seems) to not want a webapp.

Answer:
There's
Dabo
, made by some guys moving from FoxPro.  It might work for you if you're writing a data driven business app.
Beyond that, I haven't found anything that you haven't.
GUI stuff is
supposed
to be hard. It builds character.
(
Attributed
to Jim Ahlstrom, at one of the early Python workshops.  Unfortunately, things haven't changed much since then.)


Question:
Today I ran XtUnit at a part of my unit testing framework to to rollback database changes created while running a test case. This is a skeleton of how I have used it. The Test case ran successfully but the database state changed as a result.

using NUnit.Framework;
using TeamAgile.ApplicationBlocks.Interception;
using TeamAgile.ApplicationBlocks.Interception.UnitTestExtensions;

namespace NameSpace.UnitTest
{
  [TestFixture]
  public class Test : InterceptableObject
  {
    [Test]
    [DataRollBack]
    public void CreateTest()
    {

I use Nhibernate with Mysql. Am I missing something?

Answer:
I think your test fixture needs to extend
```
ExtensibleFixture
```
, not
```
InterceptableObject
```
.  In the XtUnit source,
```
ExtensibleFixture
```
itself inherits from
```
InterceptableObject
```
.  The comments in ExtensibleFixture.cs state:
This is the base class for all the test fixtures you will
have in your project. You MUST inherit from this in order
for the custom attributes to work. No other special action is needed.


Question:
Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'?

Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part.

Answer:
I guess that at some point, it checks
```
if (newContent == false)
```
, and doesn't continue with adding any content? I tried looking at the source, but got a bit lost...
I also guess that this would not be counted as a bug, since the function calls for a string, and if "0" is passed (as a string), it works as expected.
A workaround would be to do this:
```
```
var myNum = 0;
$('p').html('' + myNum);
```
```


Question:
I've never liked wrapping the

mysql_real_escape_string

function around input I expect to be integer for inclusion in a MySQL query.
Recently I came across the

filter_var

function. Nice!

I'm currently using the code:

if (isset($idUserIN)
    && filter_var($idUserIN, FILTER_VALIDATE_INT)
    && 0 < filter_var($idUserIN, FILTER_SANITIZE_NUMBER_INT)
    ) {
      $idUser = filter_var($idUserIN, FILTER_SANITIZE_NUMBER_INT);
      $sql = 'SELECT * FROM TABLE_NAME WHERE idUser = '.$idUser;
} else {
  // handle invalid data
}

Does this leave any holes open?

('> 0' chosen rather than '>= 0' as its a table auto_increment field, so 0 would not be a normal value)

Answer:
A much simpler and easier-to-read method that I use is this:
```
```
$sql = 'SELECT * FROM TABLE_NAME WHERE idUser = ' . intval($idUser);
```
```
It attempts to convert $idUser to an integer and on failure returns 0 which none of my tables have as real id's. (So I know the input was invalid if it evaluates to 0.)
To answer your actual question, no that won't leave any holes open. I suggest getting rid of the repetitive code though:
```
```
$idUserIN_filtered = filter_var($idUserIN, FILTER_VALIDATE_INT);

if (isset($idUserIN)
    && $idUserIN_filtered
    && 0 < $idUserIN_filtered
    ) {
      $sql = 'SELECT * FROM TABLE_NAME WHERE idUser = '.$idUser_filtered;
} else {
  // handle invalid data
}
```
```


Question:
I want to send an email from my iPhone application. I have heard that the iOS SDK doesn't have an email API. I don't want to use the following code because it will exit my application:

NSString *url = [NSString stringWithString: @"mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];

So how can I send an email from my app?

Answer:
If you want to send email from your application, the above code is the only way to do it unless you code your own mail client (SMTP) inside your app, or have a server send the mail for you.
For example, you could code your app to invoke a URL on your server which would send the mail for you. Then you simply call the URL from your code.
Note that with the above code you can't attach anything to the email, which the SMTP client method would allow you to do, as well as the server-side method.


Question:
While accessing a webservice which is availbale at http://recpushdata.cyndigo.com/jobs.asmx, I am getting this Exception. "Remote name could not be resolved"

Any Suggesytion..what to do..

Answer:
Try using the URL:
http://216.10.246.91/jobs.asmx
If this works, whereever you are calling the web service from has a problem with DNS. If that does not work report back.


Question:
Very simply, what is tail-call optimization?

More specifically, what are some small code snippets where it could be applied, and where not, with an explanation of why?

Answer:
Look here:
http://tratt.net/laurie/tech_articles/articles/tail_call_optimization
As you probably know, recursive function calls can wreak havoc on a stack; it is easy to quickly run out of stack space. Tail call optimization is way by which you can create a recursive style algorithm that uses constant stack space, therefore it does not grow and grow and you get stack errors.


Question: I am working on lock free structure with g++ compiler. It seems that with -o1 switch, g++ will change the execution order of my code. How can I forbid g++'s optimization on certain part of my code while maintain the optimization to other part? I know I can split it to two files and link them, but it looks ugly.

Answer:
Look here:
http://tratt.net/laurie/tech_articles/articles/tail_call_optimization
As you probably know, recursive function calls can wreak havoc on a stack; it is easy to quickly run out of stack space. Tail call optimization is way by which you can create a recursive style algorithm that uses constant stack space, therefore it does not grow and grow and you get stack errors.


Question:
Possible Duplicate:

  How do I select last 5 rows in a table without sorting?

I want to select the top 10 records from a table in SQL Server without arranging the table in ascending or descending order.

Answer:
if random order is needed, you can try
```
```
select top 10 * from [tablename] order by newid()
```
```


Question:
I have a scrolling div with Three linkbuttons and three differents divs. I need to apply CSS to active linkbutton  as soon as button is clicked.The codes used by me are:

protected void btnNetwork_Click(object sender, EventArgs e)
    {
        this.btnForecast.CssClass = "li_1";
        this.btnBlog.CssClass = "li_2";
        this.btnNetwork.CssClass = "li_3_active";
        this.btnNetwork.ForeColor = System.Drawing.Color.White;
        lblMsg.Visible = false;
        BindGW("-----------------------------------");
        Forecast.Visible = false;
        Blog.Visible = false;
        Network.Visible = true;
    }

Thanks & Regards,

Khushi

Answer:
Instead of using server side event use client side javascript event. Try:
```
```
$get('btnId').setAttribute("class", "some_class_name");
```
```


Question:
I'm looking for a way to change the CSS rules for pseudo-class selectors (such as :link, :hover, etc.) from JavaScript.

So an analogue of the CSS code: a:hover { color: red } in JS.

I couldn't find the answer anywhere else; if anyone knows that this is something browsers do not support, that would be a helpful result as well.

Answer:
You can't style a pseudo-class on a particular element alone, in the same way that you can't have a pseudo-class in an inline style="..." attribute (as there is no selector).
You can do it by altering the stylesheet, for example by adding the rule:
```
```
#elid:hover { background: red; }
```
```
assuming each element you want to affect has a unique ID to allow it to be selected.
In theory the document you want is
http://www.w3.org/TR/DOM-Level-2-Style/Overview.html
which means you can (given a pre-existing embedded or linked stylesheet) using syntax like:
```
```
document.styleSheets[0].insertRule('#elid:hover { background-color: red; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';
```
```
IE, of course, requires its own syntax:
```
```
document.styleSheets[0].addRule('#elid:hover', 'background-color: red', 0);
document.styleSheets[0].rules[0].style.backgroundColor= 'red';
```
```
Older and minor browsers are likely not to support either syntax. Dynamic stylesheet-fiddling is rarely done because it's quite annoying to get right, rarely needed, and historically troublesome.


Question: I want to select the last 5 records from a table in SQL Server without arranging the table in ascending or descending order.

Answer:
Without an order, this is impossible.  What defines the "bottom"?  The following will select 5 rows according to how they are stored in the database.
```
SELECT TOP 5 * FROM [TableName]
```


Question: Which is the best method to make the browser use cached versions of js files (from the serverside)?

Answer:
From PHP:
```
```
function OutputJs($Content)
{
    ob_start();
    echo $Content;
    $expires = DAY_IN_S; // 60 * 60 * 24 ... defined elsewhere
    header("Content-type: x-javascript");
    header('Content-Length: ' . ob_get_length());
    header('Cache-Control: max-age='.$expires.', must-revalidate');
    header('Pragma: public');
    header('Expires: '. gmdate('D, d M Y H:i:s', time()+$expires).'GMT');
    ob_end_flush();
    return;
}
```
```
works for me.
As a developer you'll probably quickly run into the situation that you
don't
want files cached, in which case see
Help with aggressive JavaScript caching


Question:
How to filter my datagridview by the value of my label.text on click event? That value is from my linq query:

dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
     c.Field<int>("ageColumn") < 5).Count();

Let's just say the above query gives me 12 (label.text = 12), now when I click "12", I want my datagridview to ONLY show those 12 rows that meet my above query.

Answer:
Now I do not use LINQ, but logic would suggest that whatever is retured by the expression
```
```
dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
 c.Field<int>("ageColumn") < 5)
```
```
Contains the data you seek? Is there not a property in there to enumerate the data?


Question:
In my application I have a Customer class and an Address class. The Customer class has three instances of the Address class: customerAddress, deliveryAddress, invoiceAddress.

Whats the best way to reflect this structure in a database?

The straightforward way would be a customer table and a separate address table.

A more denormalized way would be just a customer table with columns for every address (Example for "street": customer_street, delivery_street, invoice_street)

What are your experiences with that? Are there any advantages and disadvantages of these approaches?

Answer:
I'd go (as database theory teaches) for two separate tables: Customer and Address.
The idea of putting three fields in the Customer table is bad, as you say, because it would violate normalization rules (and fail when addresses would become more than three).
edit
: also, I'd split the Address table record in several fields, one for the toponomastic prefix, one for the street, etc. and put a unique key on those. Otherwise, you'd end with a database full of duplicates.


Question:
I am working on an app with an NSTextView.  When I paste random bytes into it (say, from a compiled C program) it displays gibberish, as it should.  However, when I -setShowsControlCharacters:YES, the same causes a crash and gives the following error multiple times:

2008-11-22 00:27:22.671 MyAppName[6119:10b] *** -[NSBigMutableString _getBlockStart:end:contentsEnd:forRange:stopAtLineSeparators:]: Range or index out of bounds

I created a new project with just an NSTextView with the same property and it does not have this problem.

My question is, how can I debug my app to find the cause of the error?  I have no idea where the bug originates.  I am not familiar with the debugger built in to Xcode.  If anyone could point me in the right direction in terms of how to track down such a bug I would be very grateful.  Thanks.

Answer:
It's not really clear how much you know so I'm going to try a very basic approach, please don't be offended.
I'm assuming the NSTextView is in a external nib/xib and is not created programatically.
If so open up your nib/xib in Interface builder and click on the offending NSTextView element.
Then hit
Cmd-5
or
Tools->Connections Inspector
From here you can see which
Outlets/Actions
to look for in the actual source code.
Most likely you're problem is manipulation of a "
Reference Outlet
" object, or in a "
Sent Action
" function.
Once you have an idea of which method(s)/variable(s) you need to watch you can open up the source code for those parts in Xcode. You can then set a break point at any line by click on that line number on the left hand side of the editor window.
Click on
Run->Debugger
. A new window should popup, click "
Run and Go
" in the toolbar of that window. Your app should run as normal until it hit's the break point you set in your source code. when the break point is hit you can mouse over variables in your code in the bottom half of the debugger window. The current values of the variables should popup allowing for easy inspection.
Usually you can gain the same information by using the Top Right panel of the Debugger to inspect the variable table.
When your done with that break point click "
Continue
" at the top of the debugger window and your program will execute till completion or the next break point.
This should get you started with debugging under Xcode.
Their are different kinds/uses of break points and all kinds of additional fancy stuff you can do in Xcode.
For more information check out this awesome
CocoaHeads video
.
Good Luck,
Brian G.


Question:
I need a map that has two keys, e.g.

Map2<String /*ssn*/, String /*empId*/, Employee> _employees;

So that I can

_employees.put(e.ssn(), e.empId(), e)

And later

_employees.get1(someSsn);
_employees.get2(someImpId);

Or even

_employees.remove1(someImpId);

I am not sure why I want to stop at two, why not more, probably because that's the case I am I need right now :-) But the type needs to handle fixed number of keys to be type-safe -- type parameters cannot be vararg :-)

Appreciate any pointers, or advice on why this is a bad idea.

Answer:
My first thought was: the easiest way to do this, I think, would be two maps.
```
```
Map< String, Map< String,Employee> > _employees;
```
```
But from what it looks like, you just want to be able to look up an employee by either SSN or ID.  What's to stop you then from making two maps, or at worst a class that contains two maps?
As a clarification, are you looking for a
compound key
being employees are uniquely identified by the combination of their SSN and ID, but not either one by itself, or are you looking for two different ways of referencing an employee?


Question: I have mixed views about commercial class libraries. Am I better off using a commercial  class library or starting  from scratch? If buying a library is the way forward which one for a C# developer?

Answer:
Put a value on your time, say $30 an hour.  Estimate how long it would take you to write the library, then add two times that for debugging and testing.  Subtract the time it's going to take you to learn how to use the commercial library with the given documentation.  Multiply by your hourly rate.  Compare.
Writing a library can be fun and rewarding, but "not invented here" syndrome keeps a lot of companies from creating anything useful, as they're stuck reinventing the wheel for additional cost.  Make sure it is extensible (if you don't get access to the source) and has what you need.  Buy it.
As a personal project, it's probably worth writing it from scratch at least once to see what you can learn, but on company dime you need to be productive and efficient.
Or write it from scratch and release it open source ;)


Question: Anyone have experience with algorithmic trading (like stocks)?  Any good services to use to get quotes and to make trades?

Answer:
I had a freelance project that used
Interactive Brokers
, which provided both a proprietary API as well as a FIX-based one. The proprietary API is somewhat painful to use (and they probably can't change it much, for compatibility), but you can easily code a "translation layer" to make it much more pleasant. I haven't tried the FIX-based API, so no comments there.
And yes, I reopened the question. I happen to think it's a fair question to ask.


Question:
I've written a WPF UserControl, and want to add one or more of it to my Window at runtime when I click a button. How can I do that?

Edit: Further specification
I want to add the usercontrols to a Canvas, and put in a absolute position. The canvas is a drawing of the floors in my house, and each usercontrol has properties to indicate where in the house it is positioned. So I want all the controls to be positioned in the correct position on the canvas.

I'm thinking something like this

var light = new LightUserControl(2);
HouseCanvas.Children.Add(light); // this should be positioned in a specific place

Answer:
Add a StackPanel to the window and on each button click,
```
```
_stackPanel.Children.Add(new YourControl());
```
```
You can do this in many ways.


Question: I have a .fla file with some text that I want to get at. Is there a free app than you can use to open .fla files, or just a tool to dump strings and pics?

Answer:
With such question, I just experiment...
I went to deviantART, went to the
Flash .FLA Files
gallery and downloaded one at random.
I got a .fla file of about 1MB.
I went to Sysinternals's site to get the latest version of
Strings
, a command line tool to extract plain text strings from binary files.
Ran:
```
```
strings -n 10 "D:\Archives\scrolling flash gallery with preloader.fla" > str
```
```
Got at text file with lot of data you have to sort yourself...
There are some other similar freewares utilities, some with GUI, but this command line version is handy. Works with both (or either) Unicode and Ansi strings.
Oh, obviously it is for Windows. You forgot to specify if you target a specific platform.
PS.: for what it is worth, I believe the Flash SDK is free at Adobe's site. You just don't have the Flash IDE, only a compiler, etc. for AS development. Perhaps it includes a tool to look at .fla files (not tried the toolkit yet).


Question: How can you convert a byte array to a hexadecimal string and vice versa?

Answer:
You can use
```
Convert.ToHexString
```
starting with .NET 5.
There's also a method for the reverse operation:
```
Convert.FromHexString
```
.
For older versions of .NET you can either use:
```
```
public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}
```
```
or:
```
```
public static string ByteArrayToString(byte[] ba)
{
  return BitConverter.ToString(ba).Replace("-","");
}
```
```
There are even more variants of doing it, for example
here
.
The reverse conversion would go like this:
```
```
public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  return bytes;
}
```
```
Using
```
Substring
```
is the best option in combination with
```
Convert.ToByte
```
. See
this answer
for more information. If you need better performance, you must avoid
```
Convert.ToByte
```
before you can drop
```
SubString
```
.


Question: I'm looking for a open source .Net HTTP proxy library. Basically I want to develop something like Fiddler (so much lighter with less features).

Answer:
There is
URLRewriter.NET
, a free open-source component for IIS/ASP.NET.
As the name suggests, it's an URL rewriting component, but it has
also proxying capabilities
. With a simple line like this in the configuration file
```
```
RewriteRule ^(.*) http://www.testsiteXY.com$1 [P]
```
```
you could easily use it as proxy.


Question:
I'm using Oracle 10g and I'm trying to "stack" the conditions in a CASE statement, like I would do in C++ :

case 1:
case 2:
    // instructions
    break;

i.e. having the same code block executed for two different successful conditions.

I've tried :

WHEN 1, 2 THEN
WHEN 1 OR 2 THEN

... without luck.
Is it even possible ?

EDIT - Full snippet

CASE v_n
  WHEN (1 OR 2) THEN
    dbms_output.put_line('Case 1 or 2');
  WHEN 3 THEN
    dbms_output.put_line('Case 3');
END CASE;

Generates an expression is of wrong type error

Answer:
You need to use this format:
```
```
CASE
  WHEN v_n = 1 OR v_n = 2 THEN
    dbms_output.put_line('Case 1 or 2');
  WHEN v_n = 3 THEN
    dbms_output.put_line('Case 3');
END CASE;
```
```


Question:
I am using django 1.0 and I have created my models using the example in the Django book.  I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete!

Please show me an example of the code I need to write on my view.py and urls.py for perform this task.

Answer:
Say you have a model Employee. To edit an entry with primary key emp_id you do:
```
```
emp = Employee.objects.get(pk = emp_id)
emp.name = 'Somename'
emp.save()
```
```
to delete it just do:
```
```
emp.delete()
```
```
so a full view would be:
```
```
def update(request, id):
   emp = Employee.objects.get(pk = id)
   #you can do this for as many fields as you like
   #here I asume you had a form with input like <input type="text" name="name"/>
   #so it's basically like that for all form fields
   emp.name = request.POST.get('name')
   emp.save()
   return HttpResponse('updated')

def delete(request, id):
   emp = Employee.objects.get(pk = id)
   emp.delete()
   return HttpResponse('deleted')
```
```
In urls.py you'd need two entries like this:
```
```
(r'^delete/(\d+)/$','myproject.myapp.views.delete'),
(r'^update/(\d+)/$','myproject.myapp.views.update'),
```
```
I suggest you take a look at the
docs


Question: I am migrating an application from .NET 1.1 to .NET 2.0. Should I remove all uses of CollectionBase? If so, what is the best strategy for migration?

Answer:
Yes, the best classes to look at are in System.Collections.Generic.
I usually use List.
There are two approaches you can use either:
A
```
```
public class MyClass
{
  public List<MyItem> Items;
}
```
```
B
```
```
public class MyItemCollection : List<MyItem>
{
}

public class MyClass
{
  public MyItemCollection Items;
}
```
```
The two approaches only differ very slightly and you only need to use method (B) if you plan on extending the functionality of List.
Here's a link with more info:
http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx
With regards to the classes that you've already implemented, you can remove all of the functions which are specified in the IList interface. e.g.
```
```
public int Add(InstrumentTradeDataRow instTrade) { return List.Add(instTrade); }
```
```
This can be removed because List already implements a type safe Add function for you.
See this link for more information:
http://msdn.microsoft.com/en-us/library/3wcytfd1(VS.80).aspx


Question:
I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate).

Pybloom is one option but it seems to be showing its age as it throws DeprecationWarning errors  on Python 2.5 on a regular basis. Joe Gregorio also has an implementation.

Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation.

Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?

Answer:
Look at the
array
module.
```
```
class Bit( object ):
    def __init__( self, size ):
        self.bits= array.array('B',[0 for i in range((size+7)//8)] )
    def set( self, bit ):
        b= self.bits[bit//8]
        self.bits[bit//8] = b | 1 << (bit % 8)
    def get( self, bit ):
        b= self.bits[bit//8]
        return (b >> (bit % 8)) & 1
```
```
FWIW, all of the
```
//8
```
and
```
% 8
```
operations can be replaced with
```
>>3
```
and
```
&0x07
```
.  This
may
lead to slightly better speed at the risk of some obscurity.
Also, changing
```
'B'
```
and
```
8
```
to
```
'L'
```
and
```
32
```
should be faster on most hardware.  [Changing to
```
'H'
```
and 16 might be faster on some hardware, but it's doubtful.]


Question:
I have these 2 vectors:

alpha =
     1    1    1    1    1    1    1    1    1

f_uv =
   193  193  194  192  193  193  190  189  191

And when I do this:

alphaf_uv = alpha * f_uv'

I get the error message:

"??? Error using ==> mtimes
Integers can only be combined with integers of the same class, or scalar doubles."

The interesting part is that this error doesn't appear if I define the same vectors in the console and try the multiplication there.

alpha is defined by me and f_uv is obtained from some pixels in a PNG image.

Answer:
Assuming they're both integer matrices to begin with,
```
f_uv'
```
may not be.
Try:
```
```
alphaf_uv = double(alpha) * double(f_uv')
```
```
and let us know if it still occurs.
You may need to turn
```
alphaf_uv
```
back into an integer type afterwards, depending on your needs.


Question: What are the hidden features of Maven2?

Answer:
With maven-dependency-plugin it's possible to resolve dependency conflicts and cyclic dependency problems.
Add to your pom.xml:
```
```
<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-dependency-plugin</artifactId>
</plugin>
```
```
Then run
mvn dependency:resolve
or
mvn dependency:build-classpath
to test it.
More about the dependency plugin:
http://maven.apache.org/plugins/maven-dependency-plugin/howto.html


Question:
Okay, I have a FormView with a couple of child controls in an InsertItemTemplate. One of them is a DropDownList, called DdlAssigned. I reference it in the Page's OnLoad method like so:

protected void Page_Load(object sender, EventArgs e)
{
    ((DropDownList)FrmAdd.FindControl("DdlAssigned")).SelectedValue =
          ((Guid)Membership.GetUser().ProviderUserKey).ToString();
}

Basically I'm just setting the default value of the DropDownList to the user currently logged in.

Anyway, when the page finishes loading the SelectedValue change isn't reflected on the page. I stepped through OnLoad and I can see the change reflected in my Watch list, but when all is said and done nothing's different on the page.

Answer:
I figured it out. I'm still missing exactly why it doesn't work just on FormLoad, but performing the change in the FormView's DataBound event does the trick.
```
```
protected void FrmAdd_DataBound(object sender, EventArgs e)
{
    // This is the same code as before, but done in the FormView's DataBound event.
    ((DropDownList)FrmAdd.Row.FindControl("DdlAssigned")).SelectedValue =
        ((Guid)Membership.GetUser().ProviderUserKey).ToString();
}
```
```
So, I guess the general rule of thumb is that if you are having problems making changes to controls when working with databinding, try to make them immediately after it has been bound.


Question: I have a .NET dll which needs to read it's config settings from it's config file. Usually, the config file is placed in the same directory as the DLL. But how do i read the config file if the DLL is GAC'ed, because I can put only the DLLs in the GAC, and not it's config files.

Answer: Does the user need to configure the Dll?  If so, then the DLL should be using configuration settings from the app.config file, not it's own config.  The app.config file should be stored in the same directory as the application.  If not, then you could go a couple of different ways.  You could make changes to the machine.config file so that your Dll can find them there.  I would not do this.  Alternatively, you can store the configuration in a settings class.  These can be overridden via configuration, but your defaults will be set in the generated code for the settings class via attributes and so the absence of a configuration file will not affect your Dll when the defaults are all that are required.


Question:
If have a set of classes that all implement an interface.

interface IMyinterface<T>
{
    int foo(T Bar);
}

I want to shove them all in a list and enumerate through them.

 List<IMyinterface> list
 foreach(IMyinterface in list)
 // etc...

but the compiler wants to know what T is. Can I do this? How can I overcome this issue?

Answer:
There is no IMyinterface type there is only a IMyinterface`1 type which will require a type argument.  You could create an IMyinterface type:-
```
```
interface IMyinterface { ... }
```
```
then inherit from it
```
```
interface IMyinterface<T> : IMyinterface { ... }
```
```
You would need to move any members you would like to use in the foreach loop to the IMyinterface definition.


Question:
I need to extract multiple text/dropdown list fields from an asp.net form and format appropriately ready for sending to recipient via email.

What's the best way of reading those fields without having to hard code each item such as:

item1 = InputField1.Text;
item2 = InputField2.Text;

I will have about 10 or 20 items on the same input form.

Answer:
Not sure why you're trying to do this - without more info it seems like you're probably taking an approach that is sub-optimal, but I digress. The form field values are also accessible via the Request.Form collection, which is a NameValueCollection if I recall. You could access that as-is like so:
```
```
foreach (string key in Request.Form.Keys) {
    string value = Request.Form[key];
    // format and use value here
}
```
```
If you need to format specific fields based on the field and type of data, you could do a copy to a dictionary like so:
```
```
Dictionary<string, object> values = new Dictionary<string, object>();

foreach (string key in Request.Form.Keys) {
    if (key.Equals("SpecialFieldName")) {
        // for example, parse an int
        values.Add(key, int.parse(Request.Form[key]));
    } else {
        // no special formatting required
        values.Add(key, Request.Form[key]);
    }
}
```
```


Question: Is there an alternative to history.go(-1) for FireFox and Safari. Any Help would be greatly appreciated.

Answer:
You can use
```
history.back()
```
.


Question:
I have an idea about what it is. My question is :-

1.) If i program my code which is amenable to Tail Call optimization(Last statement in a function[recursive function] being a function call only, no other operation there) then do i need to set any optimization level so that compiler does TCO. In what mode of optimization will compiler perform TCO, optimizer for space or time.

2.) How do i find out which all compilers (MSVC, gcc, ARM-RVCT) does support TCO

3.) Assuming some compiler does TCO, we enable it then, What is the way to find out that the compielr has actually done TCO? Will Code size, tell it or Cycles taken to execute  it will tell that or both?

-AD

Answer:
If you want your compiler to do tail call optimization, just check either
a) the doc of the compiler at which optimization level it will be performed or
b) check the asm, if the function will call itself (you dont even need big asm knowledge to spot the just the symbol of the function again)
If you really really want tail recursion my question would be:
Why dont you perform the tail call removal yourself? It means nothing else than removing the recursion, and if its removable  then its not only possible by the compiler on low level but also on algorithmic level by you, that you can programm it direct into your code (it means nothing else than go for a loop instead of a call to yourself).


Question: NDoc has an XML element inheritdoc which allows you to inherit documentation of a member from the parent class (or an implemented interface). However, Visual Studio (i.e. the C# compiler) does not understand this tag and complains about the documentation not being present or complete. So does StyleCop and some other tools. Is there an alternative approach? How do you go about keeping the docs complete, yet without duplicating the XML descriptions?

Answer:
One alternative is to use
GhostDoc
- an add-in for Visual Studio that automatically generates comments for you. This duplicates the XML description of course, which is part of what you're trying to avoid - but at least it does it automatically for you.
What happens if you just leave off the docs entirely for methods which are being inherited, or overriding interface methods? I suspect it depends on how you've got NDoc configured, but certainly in MSDN documentation seems to just naturally inherit the docs - and a quick check
suggests
that VS won't whinge when you don't prodive docs for an inherited method. Worth a try, certainly.


Question:
Does anyone know where I can find an example of how to determine if the Maximize and/or Minimize buttons on a window are available and/or disabled?

The window will not be in the same process as my application.  I have the hWnd and I have tried using GetMenuItemInfo, but I can't find any good samples for how to do this.

Thanks!

Answer:
Use the
GetWindowInfo
function.
Test the
WINDOWINFO
structure's dwStyle field and see if the WS_MAXIMIZEBOX bit is on.
```
```
WINDOWINFO.dwStyle & WS_MAXIMIZEBOX != 0
```
```


Question: If a "WITH NOLOCK" query hint is used on a View in SQL Server, does it propagate that hint to the view definition itself, even if NOLOCK is NOT used for the raw tables in the View definition? The reason to need this is that sometimes the support staff wants to do huge time-consuming queries but would rather not force this lock on all queries using the view within the application itself.

Answer:
Yes, NOLOCK will propagate to the tables used by the view definition (at least in SQL Server 2005).
See
Table Hints
in MSDN:
In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
However,
If a table contains computed columns and the computed columns are computed by expressions or functions accessing columns in other tables, the table hints are not used on those tables. This means the table hints are not propagated. For example, a NOLOCK table hint is specified on a table in the query. This table has computed columns that are computed by a combination of expressions and functions that access columns in another table. The tables referenced by the expressions and functions do not use the NOLOCK table hint when accessed.
If you're using indexed views you might want to read a bit more as there are some special cases there too.
Also see
View Resolution
for more info.


Question:
With generics, is there ever a reason to create specific derived EventArg classes

It seems like now you can simply use them on the fly with a generic implementation.

Should i go thorugh all of my examples and remove my eventArg classes (StringEventArgs, MyFooEventArgs, etc . .)

public class EventArgs<T> : EventArgs
{
    public EventArgs(T value)
    {
        m_value = value;
    }

    private T m_value;

    public T Value
    {
        get { return m_value; }
    }
}

Answer:
As TcKs already said: Use
```
EventArgs<T>
```
if you only need to pass one value, otherwise derive from
```
EventArgs
```
(or
```
EventArgs<T>
```
, whatever you want).


Question:
How would you format/indent this piece of code?

int ID = Blahs.Add( new Blah( -1, -2, -3) );

or

int ID = Blahs.Add( new Blah(
1,2,3,55
)
);

Edit:

My class has lots of parameters actually, so that might effect your response.

Answer:
or
```
```
int ID = Blahs.Add(
            new Blah( 1, 2, 3, 55 )
         );
```
```
I must confess, though, that 76 times out of 77 I do what you did the first time.


Question:
I need to store large amount of data using RMS API through J2ME.

How can I store that multiple-column data, given they must be hardcoded so I need to store those multiple columns and rows data.

How can I do this in this, should I use structs?

Answer:
Well, RMS only allows you to store records that are arrays of bytes. You will have to decide for yourself how a record is stored, and if you want to store your data in a single or in multiple records. If you use the DataInputStream and DataOutputStream classes, you'll be able to read/write Strings, booleans, integers, etc. The
API documentation includes a decent example
of how you can do this.
If you have complex data to store, or a lot of different objects, you may want to create a simple library for RMS I/O, that allows you to pass objects implementing e.g. "Storable" to a library class that writes away your object into RMS.


Question:
Is there a less resource intensive / faster way of performing this query (which is partly based upon: This StackOverflow question ). Currently it takes 0.008 seconds searching through only a dozen or so rows per table.

SELECT DISTINCT *
FROM (
(

SELECT DISTINCT ta.auto_id, li.address, li.title, GROUP_CONCAT( ta.tag ) , li.description, li.keyword, li.rating, li.timestamp
FROM tags AS ta
INNER JOIN links AS li ON ta.auto_id = li.auto_id
WHERE ta.user_id =1
AND (
ta.tag LIKE '%query%'
)
OR (
li.keyword LIKE '%query%'
)
GROUP BY li.auto_id
)
UNION DISTINCT (

SELECT DISTINCT auto_id, address, title, '', description, keyword, rating, `timestamp`
FROM links
WHERE user_id =1
AND (
keyword LIKE '%query%'
)
)
) AS total
GROUP BY total.auto_id

Thank you very much,

Ice

Answer:
I would hope that the query optimizer would do this for you, but you might want to try doing the select on tags by user_id before doing the join just in case in the first subquery.  This would reduce the number of rows that you would have to join across presumably.  You also probably want to have indexes on auto_id AND user_ID.
```
```
SELECT DISTINCT *
FROM (
   (SELECT ta.auto_id, li.address, li.title, GROUP_CONCAT( ta.tag ),
           li.description, li.keyword, li.rating, li.timestamp
    FROM (SELECT auto_id, tag FROM tags WHERE user_id = 1) AS ta
         INNER JOIN links AS li ON ta.auto_id = li.auto_id
         WHERE (ta.tag LIKE '%query%') OR (li.keyword LIKE '%query%')
    GROUP BY li.auto_id
   )
   UNION (
       SELECT auto_id, address, title, '', description, keyword, rating, `timestamp`
       FROM links
       WHERE user_id = 1 AND (keyword LIKE '%query%')
   )
) AS total
GROUP BY total.auto_id
```
```


Question:
In Firefox and Safari, pages that are centered move a few pixels when the page is long enough for the scrollbar to appear.  If you navigate through a site that has long and short pages, the page seems to "jump" around.

IE7 tends to leave the scroll bar visible all of the time but disables it when the page is not long enough.  Since the width of the HTML window never changes the centering of the page doesn't change.

Is there a workaround or a way to style the page so it doesn't jump around in Firefox and Safari?

Thanks.

Answer:
You could simply always enable the scrollbar:
```
```
html{
 overflow: scroll;
}
```
```
but that would give you the horizontal scrollbar too, this is better:
```
```
html{
   overflow-y:scroll;
   overflow-x:auto;
}
```
```
That will give you only the vertical scroll and the horizontal when needed.


Question:
I'm getting pretty tired of my development box dying and then I end up having to reinstall a laundry list of tools that I use in development.

This time I think I'm going to set the development environment up on a Virtual Box VM and save it to an external HDD so that way I can bring the development environment back up quickly after I fix the real computer.

It seems to be like a good way to make a "hardware agnostic backup" and be able to get back up to speed quickly after a disaster.

Has anybody tried this?  How well did it work?  Did it save you time?

Answer:
I've done this with good success, we had this in our QA environment even and we'd also make use of Undo disks, so that if we want to test for example Microsoft patches we could roll the box back to it's previous state.
The only case we had issues was on SQL Server's particullary if you do a lot of disk activity. We had two VM's replicating gigs of data btw each other hosted on the same physical box. The disks just couldn't keep up; however, for all the other tiers it worked like a breeze.


Question:
Given say 11/13/2008 - 12/11/2008 as the value posted back in TextBox, what would be the best way to parse out the start and end date using C#?

I know I could use:

DateTime startDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(0, 10));
DateTime endDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(13, 10));

Is there a better way?

Answer:
```
```
var dates = TextBoxDateRange.Text.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

var startDate = DateTime.Parse(dates[0], CultureInfo.CurrentCulture);
var endDate = DateTime.Parse(dates[1], CultureInfo.CurrentCulture);
```
```


Question:
List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?

allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]

Answer:
How about:
```
```
allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20)
                   if (x.type == "post" and x.deleted is not False)]
```
```
Generally, long lines can be avoided by pre-computing subexpressions into variables, which might add a minuscule performance cost:
```
```
query_ids = self.db.query(schema.allPostsUuid).execute(timeout = 20)
allUuids = [x.id for x in query_ids
                   if (x.type == "post" and x.deleted is not False)]
```
```
By the way, isn't '
```
is not False
```
' kind-of superfluous ? Are you worried about differentiating between None and False ? Because otherwise, it suffices to leave the condition as only: i
```
f (x.type == "post" and x.deleted)
```


Question:
var A = {
    x : function () { }
};

var b = function (method) {
    //want to know method's "parent" here
};

b(A.x);

I want to know that x is defined in A when I call the b(A.x). Is this possible?

Answer:
There's no nice built-in way to do this, because actually there are no methods in Javascript. They are independent Function objects that just happen to be assigned somewhere.
If you create new instance of function every time (e.g. closure)
[thanks Matthew Crumley for pointing that out]
, then you can modify the function object to explicitly associate it with its parent:
```
```
x.parent = A;
```
```
and then you can call it properly as if it was a method:
```
```
x.call(x.parent);
```
```
Otherwise you will have to pass both function and its parent object.


Question:
This is my code:

import datetime
today = datetime.date.today()
print(today)

This prints: 2008-11-22 which is exactly what I want.

But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)

This prints the following:

[datetime.date(2008, 11, 22)]

How can I get just a simple date like 2008-11-22?

Answer:
You need to convert the
```
datetime
```
object to a
```
str
```
.
The following code worked for me:
```
```
import datetime

collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)

print(collection)
```
```
Let me know if you need any more help.


Question:
I'm loading an html snippet using

$("#TemplateDump").load("Themes/default.template", function() { processTemplate() })

The html i am loading contains

<div>
`hello ##name##, your age is ##age##.
your page is <a href="##website##">here</a>
</div>

I need to replace the ## placeholders with "joe","112" and "www.whatever.com". Is there a more jquery way of doing this rather than using straight javascript .replace? Are there any place holder replacement plugins around? using .replace in IE on the url placeholder just doesnt work either. Dont know why. By the way, the templates cant be changed.

Answer:
you could make it static
```
```
public class Foo
{
    List<Bar> Bars = new List<Bar>();

    public void AddBar(Bar bar)
    {
        Bars.Add(bar);
        Bar.AddFoo(bar,this);
    }
}

public class Bar
{
    List<Foo> Foos = new List<Foo>();

    // This shouldn't exist.
    public static void AddFoo(Bar bar, Foo foo)
    {
        bar.Foos.Add(foo);
        //foo.AddBar(this); inf recurtion
    }
}
```
```
Not really ideal but it does get the function off the object its self


Question: Is there any way to get the time down to the Millisecond in MySQL?

Answer:
MySQL doesn't support milliseconds in any of the time / date columns, or return it in
```
NOW()
```
so unfortunately, no.
If you have a string in a date / time + microseconds format you can use
```
SELECT MICROSECOND('1997-12-31 23:59:59.000010');
```
to extract the microseconds.


Question:
I was just wondering if there are any good work-arounds for Deserializing private fields/properties using XmlSerializer.Deserialize() ?

Currently, I Deserialize my XML to a simple disposable type with all public properties, then I load the complex type that has private properties like this:

ComplexType complex = new ComplexType(SimpleType);

and the constructor of ComplexType looks like this:

public ComplexType(SimpleType simpleType){
    this.Property1 = simpleType.Property1;
    this.Property2 = simpleType.Property2;
    .....

}

Anyone has a better way of doing this?

Answer:
MySQL doesn't support milliseconds in any of the time / date columns, or return it in
```
NOW()
```
so unfortunately, no.
If you have a string in a date / time + microseconds format you can use
```
SELECT MICROSECOND('1997-12-31 23:59:59.000010');
```
to extract the microseconds.


Question:
I am trying to write a unix command line utility that will extract the "application" icon from a Windows Mobile executable.  When I look inside the .exe with wrestool from the icoutils package, I see multiple icon and group_icon resources.  I am trying to figure out which icon the Windows Mobile Programs view would choose to display to the end user.

At first, I figured it would be the icon with name 32512 (IDI_APPLICATION), but then I found several Windows Mobile binaries that lacked this icon resource, but sure enough had visible icons in the Programs view.

Is there a simple but correct algorithm?  like lowest resource id? Is there another resource in the .exe that tells me what is the application icon?  Is there something obvious that I am missing?

Any insight would be appreciated.

Answer:
MySQL doesn't support milliseconds in any of the time / date columns, or return it in
```
NOW()
```
so unfortunately, no.
If you have a string in a date / time + microseconds format you can use
```
SELECT MICROSECOND('1997-12-31 23:59:59.000010');
```
to extract the microseconds.


Question:
I have a table that has, in essence, this structure:

 key        value
 ------     ------
 2          val1
 3          val2
 5          val3

The keys are sequential integers from 1 up to (currently) 1 million, increasing by several thousand each day. Gaps in the keys occur when records have been deleted.

I'm looking for an SQL query that returns this:

 key        value
 ------     ------
 1
 2          val1
 3          val2
 4
 5          val3

I can see how to do this with joining to a second table that has a complete list of keys. However I'd prefer a solution that uses standard SQL (no stored procedures or a second table of keys), and that will work no matter what the upper value of the key is.

Answer:
SQL queries have no looping mechanism.  Procedure languages have loops, but queries themselves can only "loop" over data that they find in a table (or a derived table).
What I do to generate a list of numbers on the fly is to do a cross-join on a small table of digits 0 through 9:
```
```
CREATE TABLE n (d NUMERIC);
INSERT INTO n VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
```
```
Then to generate 00..99:
```
```
SELECT n1.d + n2.d*10 AS d
FROM n AS n1 CROSS JOIN n AS n10;
```
```
If you want only 00..57:
```
```
SELECT n1.d + n2.d*10 AS d
FROM n AS n1 CROSS JOIN n AS n2
WHERE n1.d + n2.d*10 <= 57;
```
```
You can of course join the table for the 100's place, 1000's place, etc.  Note that you can't use column aliases in the WHERE clause, so you have to repeat the full expression.
Now you can use this as a derived table in a
```
FROM
```
clause and join it to your data table.
```
```
SELECT n0.d, mytable.value
FROM
   (SELECT n1.d + n2.d*10 + n2.d*100 + n3.d*1000
      + n4.d*10000 + n5.d*100000 AS d
    FROM n AS n1 CROSS JOIN n AS n2 CROSS JOIN n AS n3
      CROSS JOIN n AS n4 CROSS JOIN n AS n5) AS n0
  LEFT OUTER JOIN mytable ON (n0.d = mytable.key)
WHERE n0.d <= (SELECT MAX(key) FROM mytable);
```
```
You do need to add another
```
CROSS JOIN
```
each time your table exceeds an order of magnitude in size.  E.g. when it grows past 1 million, add a join for
```
n6
```
.
Note also we can now use the column alias in the WHERE clause of the outer query.
Admittedly, it can be a pretty expensive query to do this solely in SQL.  You might find that it's both simpler and speedier to "fill in the gaps" by writing some application code.


Question:
I am creating a custom WPF control that let's say for simplicity sake has a vertical stack panel with a "title" TextBlock, followed by a ContentPresenter. I want the font size for the "title" to be 5 Points LARGER than the size used in the content, which is inherited by whatever container the user places this control in.

How can I specify a font size in the control template for the header element using a relative value without exposing a property like "TitleFontSize" to the user? I want do "add 5".

I tried using a ScaleTransform on the header text block with mixed results (the text block scaled fine but the orientation was modified - I had the text right-justified and it moved "off the control" area when scaled). Also, I am not sure if scale transform would be approprite here.

Answer:
I did it with an IValueConverter as follows:
Created a class FontSizeConverter that derives from IValueConverter. The Convert method adds 10 to the value, and the ConvertBack method subtracts 10.
```
```
public class FontSizeConverter : IValueConverter
{

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (double)value + 12.0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (double)value - 12.0;
    }

    #endregion
}
```
```
Next, I declaried an instance of this class in the XAML template for the control:
```
```
<Style.Resources>
        <local:FontSizeConverter x:Key="fontSizeConverter"/>
</Style.Resources>
```
```
And Finnaly, the FontSize binding uses this converter applied to the inherited FontSize property:
```
```
<TextBlock FontSize="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=FontSize, Converter={StaticResource fontSizeConverter}}"
                                   Grid.Row="0" Text="{Binding RelativeSource={RelativeSource TemplatedParent},
                                   Path=Date.Day}" HorizontalAlignment="Right" VerticalAlignment="Top" Padding="2" Margin="2" >
 </TextBlock>
```
```
This works. But I still do not know if this is the correct answer. Let me know if there is a better way, or if this is appropriate.


Question:
I want to select about 4-5 rows from a table, then form a space separated string.

All of this is to be done in a stored procedure (SQL server 2005).

Is this possible?

I will then use this space-separated string and save it to another table.

Update

SELECT *
FROM Users
WHERE userID < 10

output:

john
jake
blah
sam

So, put this in a space separated string:

'john jake blah sam'

and save that string to another row in a table.

All this has to be done in a stored procedure (if possible).

Answer:
I think something like this will work:
```
```
DECLARE @whatever varchar(max)  -- or varchar(1000) or whatever size
SET @whatever = ''

SELECT @whatever = @whatever + MyColumn + ' ' FROM MyTable
```
```


Question:
Code like this often happens:

l = []
while foo:
    # baz
    l.append(bar)
    # qux

This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.

In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.

I understand that code like this can often be refactored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there an equivalent for us Python programmers?

Answer:
Python lists have no built-in pre-allocation. If you really need to make a list, and need to avoid the overhead of appending (and you should verify that you do), you can do this:
```
```
l = [None] * 1000 # Make a list of 1000 None's
for i in xrange(1000):
    # baz
    l[i] = bar
    # qux
```
```
Perhaps you could avoid the list by using a generator instead:
```
```
def my_things():
    while foo:
        #baz
        yield bar
        #qux

for thing in my_things():
    # do something with thing
```
```
This way, the list isn't every stored all in memory at all, merely generated as needed.


Question:
i’m trying to create a url string that works like this:

/app/process/example.com/index.html

so in other words,

/app/process/$URL

i then retrieve the url with

$this->uri->segment(3);

the forward slashes in the URL will of course be a problem accessing uri segments, so i’ll go ahead and url encode the URL portion:

/app/process/example.com%2Findex.html

.. but now I just get a 404 saying ...

Not Found

The requested URL /app/process/example.com/index.html was not found on this server.

it appears that my url encoding of forward slashes breaks CI’s URI parser.

what can i do to get around this problem?

Answer:
With CodeIgniter, the path of the URL corresponds to a controller, a function in the controller, and the parameters to the function.
Your URL, /app/process/example.com/index.html, would correspond to the app.php controller, the process function inside, and two parameters example.com and index.html:
```
```
<?php
class App extends Controller {
    function process($a, $b) {
       // at this point $a is "example.com" and $b is "index.html"
    }
}
?>
```
```
edit:
In rereading your question, it seems like you want to interpret part of the URL as another URL. To do this, you need to write your function to take a variable number of arguments. To do this, you can use the functions func_num_args and func_get_arg as follows:
```
```
<?php
class App extends Controller {
    function process() {
        $url = "";
        for ($i = 0; $i < func_num_args(); $i++) {
            $url .= func_get_arg($i) . "/";
        }

        // $url is now the url in the address
    }
}
?>
```
```


Question: Hey everyone. I'm trying to make a swing GUI with a button and a label on it.  im using a border layout and the label ( in the north field ) shows up fine, but the button takes up the rest of the frame (it's in the center field).  any idea how to fix this?

Answer:
You have to add the button to another panel, and then add that panel to the frame.
It turns out the BorderLayout expands what ever component is in the middle
Your code should look like this now:
Before
```
```
public static void main( String [] args ) {
    JLabel label = new JLabel("Some info");
    JButton button = new JButton("Ok");

    JFrame frame = ...

    frame.add( label, BorderLayout.NORTH );
    frame.add( button , BorderLayout.CENTER );
    ....

}
```
```
Change it to something like this:
```
```
public static void main( String [] args ) {
    JLabel label = new JLabel("Some info");
    JButton button = new JButton("Ok");
    JPanel panel = new JPanel();
     panel.add( button );

    JFrame frame = ...

    frame.add( label, BorderLayout.NORTH );
    frame.add( panel , BorderLayout.CENTER);
    ....

}
```
```
Before/After
Before http://img372.imageshack.us/img372/2860/beforedl1.png
After http://img508.imageshack.us/img508/341/aftergq7.png


Question:
I've got a method JSNI that calls a Java method that take a Hasmap as input.
I've tried

handler.@com.mypackage::myMethod(Ljava/util/Hashmap;)(myHashMap);
handler.@com.mypackage::myMethod(Ljava/util/Hashmap<Ljava/lang/String,Ljava/lang/String>;)(myHashMap);

I'm can't seem to define the correct type signature to include the Strings or find if this usage is even allowed.

Since I'm doing this in gwt I though it might be the implementation of hashmap and the alternative approach I've though takes a String[][] array as input

I was hoping for somwthing like

handler.@com.mypackage::myMethod([[Ljava/lang/String;)(myArray);

However, I hit another issue of finding the correct JNSI sntax for the 2nd dimension of the array

A single dimension array ie. [Ljava/lang/String; is fine but I need the 2nd dimension.

Any help/ideas or links to good jnsi doc appreciated.

Answer:
Can you post the error that your getting, and also what kind of javascript object your trying to pass as a hashmap. I'm assuming you're getting a compile time error?
Here is a good start for JSNI documentation:
GWT JSNI doc
GWT Blog post on JSNI


Question: I've read a few instances in reading mathematics and computer science that use the equivalence symbol ≡, (basically an '=' with three lines) and it always makes sense to me to read this as if it were equality.  What is the difference between these two concepts?

Answer:
In languages that I have seen that differentiate between equality and equivalence, equality usually means the type
and
value are the same while equivalence means that just the values are the same.  For example:
```
```
int i = 3;
double d = 3.0;
```
```
i and d would be have an equivalence relationship since they represent the same value but not equality since they have different types.  Other languages may have different ideas of equivalence (such as whether two variables represent the same object).


Question:
So the following rewrite rules always seem to fire.  This has the effect of hiding another domain that I am hosting on the server?

I can't seem to figure out what's wrong and it is time to call in the experts:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^danielhonig.com
RewriteRule ^(.*)$ http://www.danielhonig.com/$1 [R=permanent,L]

RedirectMatch ^/$ http://www.danielhonig.com/gravl
Options None

Answer:
Place the rewrite rules inside your
```
<VirtualHost>
```
directive, then it will not affect your other domain.


Question:
How do I make gdb print functions of interest as they are called, indented according to how deep in the stack they are?

I want to be able to say something like (made up):

(gdb) trace Foo* Bar* printf

And have gdb print all functions which begin with Foo or Bar, as they are called. Kind of like gnu cflow, except using the debugging symbols and only printing functions which actually get called, not all possible call flows.

Tools which won't help include cachegrind, callgrind and oprofile, which order the results by which functions were called most often. I need the order of calling preserved.

The wildcarding (or equivalent) is essential, as there are a lot of Foo and Bar funcs. Although I would settle for recording absolutely every function. Or, perhaps telling gdb to record all functions in a particular library.

Some GDB wizard must have a script for this common job!

Answer:
Did you see litb's excellent anwser to a similar post
here
?
He uses readelf to get interesting symbols, gdb commands to get the trace, and awk to glue all that.
Basically what you have to change is to modify his gdb command script to remove the 1 depth from backtrace to see the stack and filter specific functions, and reformat the output with an awk/python/(...) script to present it as a tree. (I admit I'm too lazy to do it now...)


Question:
Is there any good way to unit test destructors?  Like say I have a class like this (contrived) example:

class X
{
private:
    int *x;

public:
    X()
    {
         x = new int;
    }

    ~X()
    {
         delete x;
    }

    int *getX() {return x;}
    const int *getX() const {return x;}
};

Is there any good way to unit test this to make sure x gets deleted without cluttering up my hpp file with #ifdef TESTs or breaking encapsulation?  The main problem that I'm seeing is that it's difficult to tell if x really got deleted, especially because the object is out of scope at the time the destructor is called.

Answer:
Some compilers will overwrite deleted memory with a known pattern in debug mode to help detect access to dangling pointers. I know Visual C++ used to use 0xDD, but I haven't used it in a while.
In your test case, you can store a copy of x, let it go out of scope and make sure that *x == 0xDDDDDDDD:
```
```
void testDestructor()
{
    int *my_x;
    {
        X object;
        my_x = object.getX();
    }
    CPPUNIT_ASSERT( *my_x == 0xDDDDDDDD );
}
```
```


Question:
I've been doing html, css and javascript for quite a long time, mostly for my very own enjoyment. I would say I know fairly much, I've created many simple games and apps and experiments with javascript. However there is only so much that is possible to do in the browser, for any more "complete" websites I am constantly confronted with my ignorance on server side programming.

So, what do I need. I need to get my head around how to use databases and how to use some server side programming language, I guess. What is the right choice? What should I avoid?

Thanks.

Answer:
PHP
and
MySQL
have a pretty low barrier to entry (they're both free and ubiquitous).  I'd start with those, since most hosts provide them for you.  As an added bonus, they work really well together (and PHP isn't very hard to learn coming from a web development background).
Head First SQL
is a great book for learning MySQL.  All of the examples in the book are done on MySQL.  The book even explains where to get it and how to install it.  As for PHP, the
introductory tutorial
at official website is the best place to learn it.
Update:
Head First PHP & MySQL
is now available.  I haven't read this one yet, but other books in the series and by the same author are great for learning new languages from scratch.


Question:
I am trying to create a custom accordion for my page to that display my posts. I have it in list format using HTML and I am trying to create an effect when you click each header to expand to show more information.

But I don't want to have say six blocks of code for six of the <li> elements I have on the page.

Is there a way to run it through .each(); perhaps? Instead of creating each section? Try a more dynamic approach.

Answer:
Did you take a look at
this tutorial
?
Because, as this
example illustrates
, one does not need multiple conditions to achieve this.
```
```
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
  //hide the all of the element with class msg_body
  $(".msg_body").hide();
  //toggle the componenet with class msg_body
  $(".msg_head").click(function()
  {
    $(this).next(".msg_body").slideToggle(600);
  });
});
</script>
```
```
All the element with the class name “msg_body” is collapsed when the page is loaded.
The “slideToggle()” function of jQuery is used to expand and collapse the “div” with class “msg_body”.
When user clicks on the element with the class “.msg_head”, then div with class “msg_body” next to it, gets toggled with sliding effect, making toggle panel using jQuery.


Question: We all know that premature optimization is the root of all evil because it leads to unreadable/unmaintainable code.  Even worse is pessimization, when someone implements an "optimization" because they think it will be faster, but it ends up being slower, as well as being buggy, unmaintainable, etc.  What is the most ridiculous example of this that you've seen?

Answer:
Nothing Earth-shattering, I admit, but I've caught people using StringBuffer to concatenate Strings outside of a loop in Java.  It was something simple like turning
```
```
String msg = "Count = " + count + " of " + total + ".";
```
```
into
```
```
StringBuffer sb = new StringBuffer("Count = ");
sb.append(count);
sb.append(" of ");
sb.append(total);
sb.append(".");
String msg = sb.toString();
```
```
It used to be quite common practice to use the technique in a loop, because it was measurably faster.  The thing is, StringBuffer is synchronized, so there's actually extra overhead if you're only concatenating a few Strings.  (Not to mention that the difference is absolutely trivial on this scale.)  Two other points about this practice:
StringBuilder is unsynchronized, so should be preferred over StringBuffer in cases where your code can't be called from multiple threads.
Modern Java compilers will turn readable String concatenation into optimized bytecode for you when it's appropriate anyway.


Question:
I have a system that creates an order and that order can be billed to a house account, sent Cash on Delivery (COD), or charged to a credit card.  I've created the following tables:

ORDERS

order_id

billingoption_id

BILLINGOPTIONS

billingoption_id

I'm unsure of how the next table should be built for the billing data.  Should I build a separate table for each type of billing option (ie. COD, Credit Cards, and House Account)?  Then would I have another foreign key column on the Orders table that would refer to a record for the billing data?

Answer:
Focus on things.  Actual things.  Try to describe things simply, directly, and in natural language first.
Then, when you ask for design guidance, you can provide definitions.  In some cases, the act of writing definitions will make the design crystalize.
Orders
are things.  What are the attributes of an order?  Customer, Product, Payment/Billing options.
Billing Options
are (almost) things.  You can, apparently, define and identify them.  (I'm not sure I could.  From your question, it appears that you might be able to.  But without a one-sentence summary, I'm not sure what's going on with Billion Options.
What's a "billing data?"  What kind of thing is this?  What attributes (or properties) does it have?
How does a "Billing Data" relate to an Order?  How does it relate to a Billing Option?
Feel free to update the question with definitions for each thing.


Question:
I have two tables in a DataSet in .NET. I want to join them on an ID column. Then I want a DataGridView to display two columns from the first table and one column from the second table.

If it makes it easier, the relation between the two tables is one-to-one.

Can it be done?

Answer:
Well, is it read only? In .NET 3.5 / C# 3.0 you could probably use a LINQ join and an anonymous output type pretty easily:
```
```
DataTable left = new DataTable
        {
            Columns = { {"PK", typeof(int)}, {"Name", typeof(string)}},
            Rows = {{1,"abc"},{2,"def"}}
        }, right = new DataTable
        {
            Columns = { { "FK", typeof(int) }, { "Value", typeof(decimal) } },
            Rows = { { 1, 123.45M }, { 2, 678.9M } }
        };
        var qry = from x in left.Rows.Cast<DataRow>()
                  join y in right.Rows.Cast<DataRow>()
                  on x.Field<int>("PK") equals y.Field<int>("FK")
                  select new
                  {
                      Name = x.Field<string>("Name"),
                      Value = y.Field<decimal>("Value")
                  };
        var data = qry.ToList();
```
```
You can then bind to "Name" and "Value" of data. Note it is easier with typed data-sets, since you can lose the
```
Cast<>
```
and
```
Field<>
```
rubbish.


Question:
I'd like a textbox that allows for certain text within to be "constant" and uneditable while the rest of the text is editable.  For instance, I'd like to define a template like this:

<Name:>[]
<Address:>[] <City>:[]

So that the user could later enter:

<Name:>[Stefan]
<Address:>[Nowhere] <City>:[Alaska]

But not:

<I'm typing here lol:>[Stefan]
<Address:>[Nowhere] <State>:[Alaska]

Ideally, they wouldn't even be able to put their cursor in between the <>, similar to Microsoft Word templates.

Any ideas?  The masked textbox control seems to be along the right path, but isn't multiline and doesn't allow you to enter a variable number of characters in between the braces, for instance.

Thanks in advance.

Answer:
I don't know of any ready-made components. But you could try this simple method.
Create a normal multi-line text box control
Create a regex-based template that has
```
(.*)
```
or
```
([a-z]*)
```
or whatever wherever you want the user to add text.
Whenever the text is changed, checked if it still matches the regex. If it does, accept the chagne. If it doesn't, reject the change.
You can then use the same regex to extract your data from the text box.
You could even use a RichTextBox and use the regex to perform formatting.
Update
Here's what I wrote. It seems to work:
```
```
[DefaultProperty("Regex")]
public partial class MaskedEdit : UserControl
{
    private Regex regex = new Regex("");
    private bool myChange = false;

    private string goodText;
    private Font dataFont;

    public MaskedEdit()
    {
        myChange = true;
        InitializeComponent();
        myChange = false;
        dataFont = new Font(Font, FontStyle.Bold);
        goodText = Text;
    }

    [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design", typeof(UITypeEditor)), Localizable(true)]
    [DefaultValue("")]
    public String Regex
    {
        get { return regex.ToString(); }
        set
        {
            if (value != null)
            {
                regex = new Regex(value);
            }
        }
    }

    [EditorBrowsable(EditorBrowsableState.Always)]
    [Browsable(true)]
    [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design", typeof(UITypeEditor)), Localizable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public override string Text
    {
        get { return rtf.Text; }
        set {
            int selSt = rtf.SelectionStart;
            int selLen = rtf.SelectionLength;

            rtf.Text = value;

            rtf.SelectionStart = selSt;
            rtf.SelectionLength = selLen;
        }
    }

    private void rtf_TextChanged(object sender, EventArgs e)
    {
        if (myChange) return;
        Match m = regex.Match(Text);
        if (m.Success)
        {
            goodText = Text;
            Colorize(m);
        }
        else
        {
            myChange = true;
            Text = goodText;
            myChange = false;
            m = regex.Match(Text);
            if (m.Success)
            {
                Colorize(m);
            }
        }
    }

    public IEnumerable<string> Data
    {
        get
        {
            Match m = regex.Match(Text);
            bool first = true;
            foreach (Group g in m.Groups)
            {
                if (first) { first = false; continue; }
                yield return Text.Substring(g.Index, g.Length);
            }
        }
    }

    private void Colorize(Match m)
    {
        int selSt = rtf.SelectionStart;
        int selLen = rtf.SelectionLength;

        rtf.SelectionStart = 0;
        rtf.SelectionLength = rtf.TextLength;
        rtf.SelectionFont = Font;
        bool first = true;
        foreach (Group g in m.Groups)
        {
            if (first) { first = false; continue; }
            rtf.SelectionStart = g.Index;
            rtf.SelectionLength = g.Length;
            rtf.SelectionFont = dataFont;
        }

        rtf.SelectionStart = selSt;
        rtf.SelectionLength = selLen;
    }

    private void MaskedEdit_FontChanged(object sender, EventArgs e)
    {
        dataFont = new Font(Font, FontStyle.Bold);
    }
}
```
```


Question:
is there any way to make IE6 understand double classes,
say I have a class MenuButton with a color class and possibly a clicked class;
like :

.LeftContent a.MenuButton {..general rules..}
.LeftContent a.MenuButton.Orange {..sets background-image..}
.LeftContent a.MenuButton.Clicked {...hum ta dum...}

Now, IE6 understands <a class="MenuButton Orange">, but when adding
Clicked, like <a class="MenuButton Orange Clicked">, IE just ignores the
Clicked rule.

Of course, I could rewrite my CSS, and have own rules for .MenuButtonOrange

and such (and it'd probably taken a lot shorter time than asking this question ;-),

but golly, it just so unappealing and Web 0.9...

Cheers!

Answer:
IE6 doesn't support multiple class selectors. The reason you see a change with the
```
Orange
```
class is because
```
a.MenuButton.Orange
```
is interpreted by IE6 as
```
a.Orange
```
.
I recommend structuring your markup in such a way that you can work around this:
```
```

One

Two

```
```
By grouping by a more specific ancestor you can create variation with classes scoped by that ancestor (in this example
```
navmenu
```
):
```
```
.leftcontent .navmenu a { /* ... basic styles ... */ }
.leftcontent .navmenu a.orange { /* ... extra orange ... */ }
.leftcontent .navmenu a.clicked { /* ... bold text ... */ }
```
```
It's not as good as multiple classes, but I've used it to work around the lack of support in IE.


Question:
I have a class Agent with a property Id

Given a collection of Agents I need to check if any of them have duplicate Ids.

I am currently doing this with a hash table but am trying to get Linq-ified, what's a good way of doing this?

Answer:
```
```
foreach(var agent in Agents) {
    if(Agents.Count(a => a.ID == agent.ID) > 1)
        Console.WriteLine("Found: {0}", agent.ID);
}
```
```


Question:
i m trying to design a mmo game using python...

I have evaluated stackless and since it is not the general python and it is a fork, i dont want to use it

I am trying to chose between
pysage
candygram
dramatis
and
parley

any one try any of these libraries?

Thanks a lot for your responses

Answer:
I would go for
pysage
.
It has the highest level of abstraction and a lightweight messaging API which will give you lots of flexibility.   I would imagine when designing an MMO you will want as much flexibility as possible.
It also takes a page from Erlang's Actor model which is really solid.
That's great you are trying to build an MMO via python!  It has great OpenGL bindings when you want to add graphics which is great!
Hope that helps.


Question:
I know how to do this using for loops.  Is it possible to do something like this using LINQ or lambdas?

int[] a = { 10, 20, 30 };
int[] b = { 2, 4, 10 };
int[] c = a * b; //resulting array should be { 20, 80, 300 }

Answer:
You can do something like this:
```
```
int[] a = {10, 20, 30};
int[] b = {2, 4, 10};

if (a.Length == b.Length)
{
  int[] result = (from i in Enumerable.Range(0, a.Length)
          let operation = a[i]*b[i]
        select operation).ToArray();
}
```
```
But I recommend you if you will work with matrices and more advanced mathematical topics to get a good Math library, like
NMath
or search for a
Matrix class
implementation, there are many out there...


Question:
I have a simple function in which an array is declared with size
depending on the parameter which is int.

    void f(int n){
        char a[n];
    };

    int main() {
        return 0;
    }

This piece of code compiles fine on GNU C++, but not on MSVC 2005.

I get the following compilation errors:

    .\main.cpp(4) : error C2057: expected constant expression
    .\main.cpp(4) : error C2466: cannot allocate an array of constant size 0
    .\main.cpp(4) : error C2133: 'a' : unknown size

What can I do to correct this?

(I'm interested in making this work with MSVC,without using new/delete)

Answer:
Your method of allocating from the stack is a g++ extension. To do the equivalent under MSVC, you need to use _alloca:
```
```
char *a = (char *)_alloca(n);
```
```


Question:
Getting started with jquery and having trouble getting hello world type example going for asp.net mvc. I get a runtime error "object expected" when trying to load a page with this script.

A. Where should script tags be placed in a master page?
B. What might I be doing wrong? There are definitely "a" elements in my page?

<script src="../Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>

            <script src="../Scripts/jquery.corner.js" type="text/javascript"></script>

            <script type="text/javascript">
                $(document).ready(function() {
                    $("a").click(function(event) {
                        alert("Thanks for visiting!");
                    });
                });
            </script>

Answer:
Hmmm ...
To answer your first question:  They should be put in the
```
<head>
```
element.
Also, usually I use the
'bind' method
when sinking events in the DOM (like it looks like you're trying to do).
So, code would look like:
```
```
$(document).ready(function()
{
    //  Bind each link to a handler:
    $("a").bind('click dblclick', function(event)
    {
         alert('click');
    })
});
```
```
Also, a few design tips (since you're working with something close to my heart (ASP.NET MVC with jQuery):
Add an extra 'ContentPlaceHolder' at the bottom of your master page's
```
<head>
```
element.  This will allow you to have page specific javascript run in it's proper location:  in the 'head' section of the page, and it'll allow you to make page-specific javascript includes.
It'll look something like this:
```
```
<asp:ContentPlaceHolder ID="HeadContent" runat="server" />
</head>
```
```
Why is this useful?
I'll tell you:  That jQuery rounded corners plugin you're using might only be used on a few pages -- why include it on every page?


Question:
How would I go about implementation the queries required for pagination?

Basically, when page 1 is requested, get the first 5 entries. For page 2, get the next 5 and so on.

I plan to use this via the couchdb-python module, but that shouldn't make any difference to the implementation.

Answer:
This is what I have came up with so far - to get the ids of all posts, then retrieve the actual items for the first x number of IDs..
It's not terribly efficient, but more so than retrieving all the posts, then throwing most of the away. That said, to my surprise, it seemed to run quite quickly - I ran the
```
posthelper.page()
```
method 100 times and it took about 0.5 seconds.
I didn't want to post this in the actual question, so it wouldn't influence the answers as much - here's the code:
```
```
allPostsUuid = """
function(doc) {
if(doc.type == 'post'){
    emit(doc._id, null);
}
}
"""

class PostsHelper:
    def __init__(self):
        server = Server(config.dbhost)
        db = server[config.dbname]
        return db

    def _getPostByUuid(self, uuid):
        return self.db.get(uuid)

    def page(self, number = 1):
        number -= 1 # start at zero offset
        start = number * config.perPage
        end = start + config.perPage

        allUuids = [
            x.key for x in self.db.query(allPostsUuid)
        ]
        ret = [
            self._getPostByUuid(x) for x in allUuids[start : end]
        ]

        if len(ret) == 0:
            raise Error404("Invalid page (%s results)" % (len(allUuids)))
        else:
            return ret
```
```


Question:
I am given an integer (lets call it x) and I need to generate an array of arrays, where each subarray is a list of elements which are one of a given set of integers, and the sum of all of the elements of each subarray is x. The array of arrays needs to contain all possible distinct subarrays of this form.

For example, if x is 3 and the list of possible elements is {1, 2}, I'm looking to generate {{1, 2}, {2, 1}}.

What would be the best way to go about doing this (in pseudocode or Java)? Is this 2D array the best way to store this type of data? I couldn't think of anything better, but I'm guessing there is something out there.

Answer:
Since you don't know the size of the "subarrays," I suggest you use one of the collections from Java such as
```
ArrayList<E>
```
.


Question:
I want to use part of the output of a command run from the command line in another xterm, or as part of a different command.  For instance:

> grep error error.log
error: can't find file ~/<some very long path>/thisfile

and I want to do this:

>ls ~/<some very long path>/

I know two ways to do this:

1. copy ~/<some very long path>/ with the mouse.

2. use some combination of head/tail/awk/sed/perl/cut/etc... to extract only what I need from the output and then use that inside backticks.

Is there any way to copy text without using the mouse?  The example that comes to mind is visual mode inside VIM, but I don't know how to do that inside the xterm.

Answer:
You can use GNU screen's copy and paste commands.
Quick tutorial:
Open screen:
```
screen
```
(or
```
screen myprog my args here
```
)
Run your program, producing output you want copied
Enter copy mode:
Control
+
a
+
[
Move your cursor to the start point
Hit
Enter
Move your cursor to the end point
Hit
Enter
Paste:
Control
+
a
+
]
Screen is much more powerful than that (I use it to tab several virtual terminals without the need for a special terminal emulator, and also so that I don't loose my sessions when X crashes or something).  To get out of screen, simply end your shell session, or type
Ctrl
+
a
,
Ctrl
+
\
.


Question:
I already have a deploy.rb that can deploy my app on my production server.

My app contains a custom rake task (a .rake file in the lib/tasks directory).

I'd like to create a cap task that will remotely run that rake task.

Answer:
```
```
run("cd #{deploy_to}/current && /usr/bin/env rake `<task_name>` RAILS_ENV=production")
```
```
Found it with Google --
http://ananelson.com/said/on/2007/12/30/remote-rake-tasks-with-capistrano/
The
```
RAILS_ENV=production
```
was a gotcha -- I didn't think of it at first and couldn't figure out why the task wasn't doing anything.


Question:
When working with PDFs, I've run across the MIME types application/pdf and application/x-pdf among others.

Is there a difference between these two types, and if so what is it? Is one preferred over the other?

I'm working on a web app which must deliver huge amounts of PDFs and I want to do it the correct way, if there is one.

Answer:
The standard Media Type (formerly known as MIME types) is
```
application/pdf
```
. The assignment is defined in
RFC 3778, The application/pdf Media Type
, referenced from the
Media Types registry
.
Media Types are controlled by a standards body, The
Internet Assigned Numbers Authority
(IANA). This is the same organization that manages the root name servers and the IP address space.
The use of
```
x-pdf
```
predates the standardization of the Media Type for PDF. Media Types in the
```
x-
```
namespace are considered experimental, just as those in the
```
vnd.
```
namespace are considered vendor-specific.
```
x-pdf
```
might be used for compatibility with old software.


Question: I want to know what's the difference between string and stream in c++, and what's stringstream?

Answer: Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.


Question: Are there any good and easy to use options for sending secure email?  Why is this not commonplace?

Answer:
SMTP has extensions which support encryption which are supported by most vendors. The receiving server is required to have a certificate (not the sender). So configuring your outbound mail relay to insist upon encrypted connections and verify certificates will usually do it.
If you want to encrypt it as far as the end user, S/MIME or GPG are the two main options. S/MIME support is built into mail clients MS Outlook, Thunderbird and some others.
However, there is still a significant problem of certificate management, which is a royal pain in the arse most of the time.


Question:
How do I draw procedural graphics in a Vista Sidebar gadget?

I have a gadget that collects data over time and I want to draw animating graphs.  My current approach is to draw the graph with VML that I update from JScript on a timer tick.  Is this the best way?  Can I return bitmap bits from a DLL function as the srouce to an <IMG>?  Embed bitmap bits into the HTML itself (and again update it via JScript)?  I'd love to hear some ideas.

Thanks!

Answer:
The way I currently do it is with Javascript and Adobe Flash Player communicating via the ExternalInterface in ActionScript. It seamlessly integrates local Javascript instances with an instance of a Flash Player and you can communicate just about anything between the two. You can use the fantastic drawing API in ActionScript and really get some power into you hands for charting or just embed some tools off the net.
But then, if the sandbox permits it, generating data by targeting DLLs would be great! I don't have anything functional at hand to test it, so I leave it to other contributors.


Question:
I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.

Related:

How can I download all emails with attachments from Gmail?

Answer:
You will have to enable IMAP access to your GMail account (Settings → Forwarding and POP/IMAP), and then use
```
imaplib.IMAP4_SSL
```
to access it.
Use the raw text of every message as an argument to
```
email.message_from_string
```
in order to process any attachments.


Question:
On Vista, I got a problem with the application crash handler. Basically, if something unexpected occurs which cannot be captured by SEH, I get this pop-up window with "The application stopped working", blablabla, "Close program/Debug program" -- that is, after I disable the error reporting using the system control panel. With error reporting enabled, you would get a task dialog with search for solution online, close, debug.

This is not so funny if it happens in automated tools, and I wonder whether there is a way to get rid of it totally, read, if my app crashes, it just crashes to the command line or disappears but does not bring up a dialog.

Answer:
Use
```
```
SetErrorMode(SetErrorMode(0)|SEM_NOGPFAULTERRORBOX);
```
```
But I would suggest to install an exceptions handler which creates a dump so you can verify what happened. For example
crashrpt
(or
here
).
See also
http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx


Question: If we implement a stack using arrays in C++, what is the best way to reduce the chance of an overflow condition?  Also while keeping in mind the time-space trade off?

Answer:
Just resize your array when you get close to the "overflow condition", i.e. when the next element wouldn't fit any longer. Or use a
```
std::vector
```
, which you can resize easily.
Not sure, but you are aware of the
```
std::stack
```
class, which implements a stack which resizes automatically in C++?
[EDIT] If you don't want to resize, but fail properly, throwing an exception is the best thing you can do. For example, you could define a
```
StackOverflowException
```
and throw it if there is no space left, so clients can react.


Question:
I have a variable of type Hashmap<String,Integer>.

In this, the Integer value might have to go some manipulation depending upon the value of a flag variable. I did it like this...

Hashmapvariable.put( somestring,
    if (flag_variable) {
     //manipulation code goes here
     new Integer(manipulated value);
    } else {
     new Integer(non-manipulated value);
    }
);

But I get an error:

Syntax error on token(s), misplaced
  constructs.

at the Hashmapvariable.put call.

I also get another error

Syntax error on token ")", delete this
  token.

at the final ");" line. But I can't delete the ")" - its the closing parentheses for the put method call.

I don't get this. What mistake am I doing?

Answer:
You cannot place a statement in the method call.
However, one option could be to make an method that returns a
```
Integer
```
such as:
```
```
private Integer getIntegerDependingOnFlag(boolean flag)
{
    if (flag)
        return new Integer(MANIPULATED_VALUE);
    else
        return new Integer(NON-MANIPULATED_VALUE);
}
```
```
Then, you can make a call like this:
```
```
hashmap.put(someString, getIntegerDependingOnFlag(flag));
```
```