q:
I am battling regular expressions now as I type.

I would like to determine a pattern for the following example file: b410cv11_test.ext. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance.

Further clarification of question:

I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'

[A]
To avoid confusion, read the following, in order.
First, you have the
glob
module, which handles file name regular expressions just like the Windows and unix shells.
Second, you have the
fnmatch
module, which just does pattern matching using the unix shell rules.
Third, you have the
re
module, which is the complete set of regular expressions.
Then ask another, more specific question.


q:
I'm an end-user of one of my company's products. It is not very suitable for integration into Spring, however I am able to get a handle on the context and retrieve the required bean by name.  However, I would still like to know if it was possible to inject a bean into this class, even though the class is not managed by Spring itself.

Clarification: The same application which is managing the lifecycle of some class MyClass, is also managing the lifecycle of the Spring context. Spring does not have any knowledge of the instance of MyClass, and I would like to some how provide the instance to the context, but cannot create the instance in the context itself.

[A]
suppose that u have the following dependency chain:
A --> B --> C --> x --> y -- > Z
A, B, C are spring managed beans (constructed and manged  by spring framework)
x, y are really simple POJOs that constructed by your application, without spring assistance
now if you want that y will get a reference to Z using spring that you need to have a 'handle' to the spring ApplicationContext
one way to do it is to implement
ApplicationContextAware
interface . In this case I would suggest that either A, B or C will implement this interface and will store the applicationContext reference in a static member.
so lets take Class C for example:
```
```
class C implmenets ApplicationContextAware{
    public static ApplicationContex ac;
     void setApplicationContext(ApplicationContext applicationContext)  {
               ac = applicationContext;
     }
 .............
}
```
```
now, in class y you should have:
```
```
(Z)(C.ac.getBean("classZ")).doSomething()
```
```
HTH -- Yonatan

s: huggingface

c: devops

d: intermediate


q:
The default behavior of NHibernate is the write all changes to objects to the database when Session.Flush() is called. It does this whether you want it to or not.

How do we prevent writing bad data to the database when we need to do things like validate business rules or input?

For instance ..

Customer Name is not null.

User opens a web browser (without javascript) and deletes the customer name.

Hits update.

Customer.Name property is updated and ..

Customer.IsValid() is called.

Even if IsValid() is false and we show error messages NHibernate still updates the database.

[A]
Use the ISession.Evict(objectToEvict) method to evict invalid objects.
See:
http://www.tobinharris.com/2007/2/3/nhibernate-faq
and
http://www.surcombe.com/nhibernate-1.2/api/html/M_NHibernate_ISession_Evict.htm


q: A quick search gave me this announcement of Parrot DBDI from January 2004 and a dbdi-dev mailing list which appears to be long dead. Is Parrot DBDI still being developed? Is anyone working on a different database API or interface for Parrot?

[A]
The lookup is done at a time when the constness of
```
this
```
is not known.  You just have to give it a hint via casting.  Try this:
```
```
typedef void (abc::*fptr)(int) const; // or remove const
std::tr1::bind((fptr)&abc::hello, x , _1)(a);
```
```
You may also notice here that removing the
```
const
```
still works.  This is because you should be passing x by pointer (because the first argument to a C++ member function, the implicit
```
this
```
parameter, is always a pointer).  Try this instead:
```
```
typedef void (abc::*fptr)(int) const; // won't compile without const (good!)
std::tr1::bind((fptr)&abc::hello, &x , _1)(a);
```
```
As discovered during within my comments below, if you omit the
```
&
```
as you originally did, you'll be passing x
by value
, which is usually not what you want (though it makes little practical difference in your particular example).  This actually seems like an unfortunate pitfall for
```
bind
```
.


q:
Currently I have a table that I search upon 4 fields, FirstName, LastName, MiddleName, And AKA's. I currently have a CONTAINSTABLE search for the rows and it works. Not well but it works. Now I want to make the First Name weighted higher and middle name lower.

I found the command ISABOUT but that seems pretty worthless if I have to do it by word not column (hopefully I understood this wrong). This is not an option if its by word because I do not know how many words the user will enter.

I found the thread here that talks about this same solution however I was unable to get the accepted solution to work. Maybe I have done something wrong but regardless I cannot get it to work, and its logic seems really... odd. There has to be an easier way.

[A]
The key to manipulating the rankings is to use a union.  For each column you use a separate select statement.  In that statement, add an identifier that shows from which column each row was pulled then.  Insert the results into a table variable, then you can manipulate the ranking by sorting on the identifier or multiplying the rank by some value based on the identifier.
The key is to give the appearance of modifying the ranking, not to actually change sql server's ranking.
Example using a table variable:
```
```
DECLARE @Results TABLE (PersonId Int, Rank Int, Source Int)
```
```
For table People with Columns
```
PersonId Int PK Identity, FirstName VarChar(100), MiddleName VarChar(100), LastName VarChar(100), AlsoKnown VarChar(100)
```
with each column added to a full text catalog, you could use the query:
```
```
INSERT INTO @Results (PersonId, Rank, Source)

SELECT PersonId, Rank, 1
FROM ContainsTable(People, FirstName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId

UNION
SELECT PersonId, Rank, 2
FROM ContainsTable(People, MiddleName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId

UNION
SELECT PersonId, Rank, 3
FROM ContainsTable(People, LastName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId

UNION
SELECT PersonId, Rank, 4
FROM ContainsTable(People, AlsoKnown, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId

/*
Now that the results from above are in the @Results table, you can manipulate the
rankings in one of several ways, the simplest is to pull the results ordered first by Source then by Rank.  Of course you would probably join to the People table to pull the name fields.
*/

SELECT PersonId
FROM @Results
ORDER BY Source, Rank DESC

/*
A more complex manipulation would use a statement to multiply the ranking
by a value above 1 (to increase rank) or less than 1 (to lower rank), then
return results based on the new rank.  This provides more fine tuning,
since I could make first name 10% higher and middle name 15% lower and
leave last name and also known the original value.
*/

SELECT PersonId, CASE Source WHEN 1 THEN Rank * 1.1 WHEN 2 THEN Rank * .9 ELSE Rank END AS NewRank FROM @Results
ORDER BY NewRank DESC
```
```
The one downside is you'll notice I didn't use
```
UNION ALL
```
, so if a word appears in more than one column, the rank won't reflect that.  If that's an issue you could use
```
UNION ALL
```
and then remove duplicate person id's by adding all or part of the duplicate record's rank to the rank of another record with the same person id.


q:
To do the equivalent of Python list comprehensions, I'm doing the following:

some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3}

Is there a better way to do this...perhaps with one method call?

[A]
If you really want to, you can create an Array#comprehend method like this:
```
```
class Array
  def comprehend(&block)
    return self if block.nil?
    self.collect(&block).compact
  end
end

some_array = [1, 2, 3, 4, 5, 6]
new_array = some_array.comprehend {|x| x * 3 if x % 2 == 0}
puts new_array
```
```
Prints:
```
```
6
12
18
```
```
I would probably just do it the way you did though.


q: Both static_cast and reinterpret_cast seem to work fine for casting void* to another pointer type. Is there a good reason to favor one over the other?

[A]
Use
```
static_cast
```
: it is the narrowest cast that exactly describes what conversion is made here.
There’s a misconception that using
```
reinterpret_cast
```
would be a better match because it means “completely ignore type safety and just cast from A to B”.
However, this doesn’t actually describe the effect of a
```
reinterpret_cast
```
. Rather,
```
reinterpret_cast
```
has a number of meanings, for all of which holds that “the mapping performed by
```
reinterpret_cast
```
is implementation-defined.” [5.2.10.3]
But in the particular case of casting from
```
void*
```
to
```
T*
```
the mapping is completely well-defined by the standard; namely, to assign a type to a typeless pointer without changing its address.
This is a reason to prefer
```
static_cast
```
.
Additionally, and arguably more important, is the fact that every use of
```
reinterpret_cast
```
is downright dangerous because it converts anything to anything else really (for pointers), while
```
static_cast
```
is much more restrictive, thus providing a better level of protection. This has already saved me from bugs where I accidentally tried to coerce one pointer type into another.


q:
I'm trying to find a way to get the open tasks in C#.  I've been searching on google and can only find how to get a list of the processes.  I want the only the tasks that would show up on the taskbar.

Also, along with that, it would be cool if I could get the process the task is associated with.  And if possible get the thumbnail images that Vista uses for the ALT-TAB menu, like in this image:

I assume that I will have to use pinvokes because it really doesn't look like there are any libraries to do this already.  Any ideas?

[A]
From an API (Win32) perspective there is no such thing as Tasks (at least not the one that Windows Task Manager/Alt-Tab shows).
Those "Tasks" are actually top level windows.
So in order to get a list of those, you need to
enumerate the windows
(here is the
PInvoke
for it).
Then look at the style of the windows to determine if they are actually top level windows.


q:
In ASP.NET (not MVC), what is the best approach to programmatically setting styles on an unordered list used for navigation so the appropriate menu item is styled as the active item if that page is being viewed?

This would most likely be used in conjunction with a MasterPage.

[A]
The answer to your question depends a lot on how you have your list implemented {User control or not, etc}.  How I would do it, is implement the list to be generated by a user control.
I'd have the UserControl tag each element with something like:
```
```
<{...} class="GeneratedMenuItem"> {...}
```
```
And I'd have the appropriate styles in the Style Sheet; of course if it was in a user control then you might be able to use Themes (but that depends on which version of ASP.net you are using.


q: I want a workflow that, when an entry is created in List A, will generate one entry in List B for each entry in List C. Is this possible? If so, how?

[A]
I propose:
```
```
numpy.resize(my_ar, (3,3)).transpose()
```
```
You can of course adapt the shape
```
(my_ar.shape[0],)*2
```
or whatever


q:
I have a server behind a firewall. It runs a web application (Java servlets under Apache Tomcat) and responds only to port 443 (HTTPS). There is no scripting code in the pages served - the forms use HTTP POST to receive the form, process the data (with appropriate input filtering) and then output an HTTP result page.

I am currently using an appliance firewall, but it is 'hardware-flakey'. I have been looking at upgrading to a more 'industrial strength' solution, but the vendor is quite insistant that I purchase a subscription to their "deep packet inspection" software. He claims that even web servers need this kind of protection.

I am not convinced, but do not have the security background to be certain. The firewall would sit between the "world" and my server, and use "port forwarding" to allow only ports 443 and 22 (for maintenance) to reach the server.

So - do I really need this deep packet inspection, or not?

[A]
Given that the only protocols that you're interested in (ssh and https) are "negotiate encryption on connect" there's little that a standard firewall will be able to inspect after that point. Once the SSL/SSH session is established the firewall will only see encrypted packets. Ask your vendor what their product examines in this context.
Alternatively, it is possible that the device acts more like a proxy -- that it acts as the server-side end-point for the connection before relaying on to your real server -- in which case it is possible that the product does something deeper, although this isn't the case if the firewall really is "port forwarding" as you say. Again, your vendor should be able to explain how their device operates.
Also you may want to ask what vulnerabilities/risks the inspection system is intended to protect against. For example: Does it look out for SQL injection? Is it targetted to a particular platform? (If your web server runs on a SPARC CPU, for example, then there's little point inspecting URLs for x86 shellcode).


q: I've always been using the cookie-based session store, and never even knew about Cookies until now. So is there any situation where I'd need the cookies hash?

[A]
You shouldn't store anything you don't want the user to see or change in cookie. If you store a member ID then the user could easily change the value and pretend to be someone else. Cookies are also sent with every single request to your web server including image, JS and CSS requests. If you are storing lots of information in cookies, this could have an impact on speed.
Cookie-based sessions (in a general context, I can't say I know what Rails does) means your session variables are associated with a session ID which is randomly generated. This ID, and only the ID, is returned to the the user as a cookie. This allows you to associate the users request (because you have session ID cookies)  with the user's sessions. This is safer because it would be very difficult for someone to guess the ID of another user's session.


q:
I'm looking for a good Java obfuscator.

I've done initial research into the following Java obfuscators: proguard, yguard, retroguard, dasho, allatori, jshrink, smokescreen, jobfuscate, marvin, jbco, jode, javaguard, jarg, joga, cafebabe, donquixote, mwobfu, bbmug, zelix klassmaster, sandmark, jcloak, thicket, blufuscator, and java code protector.

I tried proguard and it has a really nice GUI, seems really stable, and seems to be the most popular, but it seemed to not like some enumeration on a referenced jar file (not within the code I was trying to obfuscate) which was weird.  Yguard seems to require some interaction with ant, which I didn't know too much about.

What is a good java obfuscator?  It doesn't need to be free, it just needs to work well and be easy to use.

[A]
What is the issue with ProGuard ? (which is recommended both by
this question
and
this one
).
There is a section of
troubleshooting
about enumerator, but they seem to be taken into account
just fine
.
However, Obfuscation breaks some attempts at reflection, even though modern obfuscators can detect and to some extend adjust usages of reflection in the code they're obfuscating.


q:
Are there any good references for best practices for storing postal addresses in an RDBMS?  It seems there are lots of tradeoffs that can be made and lots of pros and cons to each to be evaluated -- surely this has been done time and time again?  Maybe someone has at least written done some lessons learned somewhere?

Examples of the tradeoffs I am talking about are storing the zipcode as an integer vs a char field, should house number be stored as a separate field or part of address line 1, should suite/apartment/etc numbers be normalized or just stored as a chunk of text in address line 2, how do you handle zip +4 (separate fields or one big field, integer vs text)? etc.

I'm primarily concerned with U.S. addresses at this point but I imagine there are some best practices in regards to preparing yourself for the eventuality of going global as well (e.g. naming fields appropriately like region instead of state or postal code instead of zip code, etc.

[A]
You should certainly consult "
Is this a good way to model address information in a relational database
", but your question is not a direct duplicate of that.
There are surely a lot of pre-existing answers (check out the example data models at
DatabaseAnswers
, for example).  Many of the pre-existing answers are defective under some circumstances (not picking on DB Answers at all).
One major issue to consider is the scope of the addresses.  If your database must deal with international addresses, you have to be more flexible than if you only have to deal with addresses in one country.
In my view, it is
often
(which does not mean
always
) sensible to both record the 'address label image' of the address and separately analyze the content.  This allows you to deal with differences between the placement of postal codes, for example, between different countries.  Sure, you can write an analyzer and a formatter that handle the eccentricities of different countries (for instance, US addresses have 2 or 3 lines; by contrast, British addresses can have considerably more; one address I write to periodically has 9 lines).  But it can be easier to have the humans do the analysis and formatting and let the DBMS just store the data.


q:
Here's the goal: to replace all standalone ampersands with &amp; but NOT replace those that are already part of an HTML entity such as &nbsp;.

I think I need a regular expression for PHP (preferably for preg_ functions) that will match only standalone ampersands. I just don't know how to do that with preg_replace.

[A]
You could always run
```
html_entity_decode
```
before you run
```
htmlentities
```
? Works unless you only want to do ampersands (and even then you can play with the charset parameters).
Much easier and faster than a regex.


q: What win32 calls can be used to detect key press events globally (not just for 1 window, I'd like to get a message EVERY time a key is pressed), from a windows service?

[A]
You want to use Win32 Hooks.  In particular a keyboard hook.
You can read more about it here
The type of hook you want is WH_KEYBOARD and you can set it via the Win32 API SetWindowsHookEx.
Basically windows will call a function in a dll that you create everytime a key is pressed in any application system wide.
The hook will call your function which will have this interface:
```
```
LRESULT CALLBACK KeyboardProc(
    int code,
    WPARAM wParam,
    LPARAM lParam
);
```
```
More information about this callback here
.
With windows hooks you can not only track system wide events across all processes, but you can also filter them and stop them altogether.


q:
Is it possible to create a final route that catches all .. and bounces the user to a 404 view in ASP.NET MVC?

NOTE: I don't want to set this up in my IIS settings.

[A]
Found the answer myself.
Richard Dingwall
has an excellent post going through various strategies. I particularly like the FilterAttribute solution. I'm not a fan of throwing exceptions around willy nilly, so i'll see if i can improve on that :)
For the global.asax, just add this code as your last route to register:
```
```
routes.MapRoute(
    "404-PageNotFound",
    "{*url}",
    new { controller = "StaticContent", action = "PageNotFound" }
    );
```
```


q: I'm sure there are different approaches to this problem, and I can think of some. But I'd like to hear other people's opinion on this. To be more specific I've built a widget that allows users to choose their location from a google maps map. This widget is displayed on demand and will probably be used every 1 out of 10 uses of the page where it's placed. The simplest way to load the dependency for this widget (google maps js api) is to place a script tag in the page. But this would make the browser request that script on every page load. I'm looking for a way to make the browser request that script only when the user requires for the widget to be displayed.

[A]
you can load script dynamically by adding
```
<script src="...">
```
tag to DOM tree.


q:
Are there any known methods of finding peers without using a dedicated central server?

ie: If I have peers which are disconnecting and reconnecting to the internet but getting a new IP address each time, and I want to connect to them without setting up a dedicated server to register with.

I was thinking about using peers email address to send a manifest of connected peers periodically, with some sort of timecode, negating the need for a dedicated server.  This would be a fallback if none of the peers could be connected to after trying all the previously known peer addresses.  But existing models of finding peers would be preferable.

[A]
Three ways, off the top of my head, though you're always going to need some central server to start the connection unless you went with option 3.
Central server that maintains known list of peers, with keep-alive.
One or more central servers that maintain some common resource peers can use to discover one another, but once connected no longer need the central server as long as the peer remains connected (something like BitTorrent); can chain peered connections as well.
Port/IP scanning (
strongly not recommended
).
In your example, you'd still have some kind of central server where the peers would be registered; the protocol is the only difference.


q:
I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.

In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, the console, whatever.

Does python have a similar input/output class which can be made to represent almost any form of i/o, or at least files and memory?

[A]
The Python way to do this is to accept an object that implements read() or write().  If you have a string, you can make this happen with
StringIO
:
```
```
from cStringIO import StringIO

s = "My very long string I want to read like a file"
file_like_string = StringIO(s)
data = file_like_string.read(10)
```
```
Remember that Python uses duck-typing: you don't have to involve a common base class. So long as your object implements read(), it can be read like a file.


q:
I'm creating a list of the Slices in my Merb app, like this:

Merb::Slices.each_slice do |slice|

I'd like to get the list of dependencies for each of this slice, any idea how to access it?

I'm still reading merb code, solution might come soon ;)

[A]
I haven't used slices yet, but from my understanding they are like a mini merb app in themself, therefore wouldn't each slice have a
```
/config/dependencies.rb
```
? Maybe this gets parsed into the program and is available somewhere.
There may be something
here in the docs
.
Also, here are the methods available on the Merb constant (which you get things like the environment from). There's one called dependencies which returns an array (which is empty when I'm running with
```
merb -i
```
in an app).
```
```
>> Merb.methods.sort
=> ["<", "<=", "<=>", "==", "===", "=~", ">", ">=", "JSON", "__caller_info__", "__caller_lines__", "__id__", "__profile__", "__send__", "abstract_method", "adapter", "adapter=", "add_generators", "add_mime_type", "add_rakefiles", "ancestors", "args_and_options", "assigns", "at_exit", "at_exit_procs", "autoload", "autoload?", "available_accepts", "available_mime_types", "b64encode", "blank?", "bundled?", "class", "class_eval", "class_variable_defined?", "class_variables", "clone", "config", "const_defined?", "const_get", "const_missing", "const_set", "constants", "context", "debugger", "decode64", "decode_b", "deep_clone", "deferred_actions", "dependencies", "dependency", "describe", "dir_for", "disable", "disabled?", "disabled_components", "disabled_components=", "display", "dup", "encode64", "encoded_hash", "enforce!", "enum_for", "env", "env?", "environment", "environment=", "environment_info", "environment_info=", "eql?", "equal?", "exception", "exiting", "exiting=", "extend", "extract_options_from_args!", "fatal!", "find_const", "forking_environment?", "framework_root", "freeze", "frozen?", "full_const_get", "full_const_set", "generators", "given", "glob_for", "hash", "id", "in?", "include?", "included_modules", "inline", "inspect", "instance_eval", "instance_method", "instance_methods", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "is_haml?", "j", "jj", "kind_of?", "klass_hashes", "klass_hashes=", "load_config", "load_dependencies", "load_dependency", "load_paths", "load_paths=", "log_path", "log_stream", "logger", "make_module", "merb", "merge_env", "meta_class", "method", "method_defined?", "methods", "mime_transform_method", "module_eval", "modules", "name", "nil?", "object_id", "on_jruby?", "on_windows?", "options", "orm", "orm=", "orm_generator_scope", "present?", "print_colorized_backtrace", "private_class_method", "private_instance_methods", "private_method_defined?", "private_methods", "protected_instance_methods", "protected_method_defined?", "protected_methods", "public_class_method", "public_instance_methods", "public_method_defined?", "public_methods", "push_path", "quacks_like?", "rakefiles", "reload", "remove_mime_type", "remove_paths", "rescue_require", "reset_logger!", "respond_to?", "restart_environment", "root", "root=", "root_path", "send", "share_as", "share_examples_for", "shared_examples_for", "should", "should_not", "singleton_methods", "start", "start_environment", "started", "started=", "started?", "taguri", "taguri=", "taint", "tainted?", "template_engine", "template_engine=", "test_framework", "test_framework=", "test_framework_generator_scope", "testing?", "to_a", "to_enum", "to_json", "to_s", "to_yaml", "to_yaml_properties", "to_yaml_style", "track_dependency", "trap", "try_dup", "type", "untaint", "use_orm", "use_template_engine", "use_test", "use_testing_framework", "yaml_as", "yaml_tag_class_name", "yaml_tag_read_class"]
```
```


q:
I am working on a very large legacy code base. We are looking to introduce FindBugs into the development practice.

I intend to have FindBugs run whenever the code is built by eclipse.

I would like to be able to make the findbugs warnings appear as errors in the code much in this way you can change the severity level in eclipse

Is it possible for eclipse to report the warnings it produces as errors?

Thanks

[A]
No, it isn't possible to have the FindBugs Eclipse plugin mark potential bugs as errors in the code.
I did some checking and the
FindBugs Maven plugin
doesn't provide an option to do this either (so no luck there too).
I would suggest logging an RFE (request for enhancement) to the FindBugs Eclipse plugin developers.  Their bug tracking database is available
here
.


q:
I'm retrieving a gzipped web page via curl, but when I output the retrieved content to the browser I just get the raw gzipped data. How can I decode the data in PHP?

One method I found was to write the content to a tmp file and then ...

$f = gzopen($filename,"r");
$content = gzread($filename,250000);
gzclose($f);

.... but man, there's got to be a better way.

Edit: This isn't a file, but a gzipped html page returned by a web server.

[A]
I use curl and:
```
```
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
```
```


q: I am using the functions strpos(string, string) in javascript. In Firefox, Opera and IE the page loads fine, but in Chrome I get the error: Uncaught ReferenceError: strpos is not defined. The page I am working on is http://seniorproject.korykirk.com/0xpi2.php

[A]
Use
```
haystack.indexOf(needle)
```
.


q:
Does anyone have any idea why the following code sample fails with an XmlException "Data at the root level is invalid. Line 1, position 1."

var body = "<?xml version="1.0" encoding="utf-16"?><Report> ......"
XmlDocument bodyDoc = new XmlDocument();
bodyDoc.LoadXml(body);

[A]
I figured it out.  Read the MSDN documentation and it says to use .Load instead of LoadXml when reading from strings.  Found out this works 100% of time.  Oddly enough using StringReader causes problems.  I think the main reason is that this is a Unicode encoded string and that could cause problems because StringReader is UTF-8 only.
```
```
MemoryStream stream = new MemoryStream();
            byte[] data = body.PayloadEncoding.GetBytes(body.Payload);
            stream.Write(data, 0, data.Length);
            stream.Seek(0, SeekOrigin.Begin);

            XmlTextReader reader = new XmlTextReader(stream);

            // MSDN reccomends we use Load instead of LoadXml when using in memory XML payloads
            bodyDoc.Load(reader);
```
```


q: I have a situation where I have a bunch of SQL Update commands that all need to be executed.  I know that DataSets can do batch updates, but the only way I've been able to accomplish it is to load the whole table into a dataset first.  What if I want to only update a subset of the records in a table?

[A]
EDITED: Based on your comment, I'd recommend using the Bulk Copy method to go to a staging table first. Then you can do a single update on your real table based on the staging table.
=========
One way is to build the SQL Command yourself; however, I'd recommend reading about the SQL Injection possibilities to protect yourself. Depending on your situation and your platform there are other options.
For example if you are dealing with a lot of data, then you could do a bulk import into a holding table, which you would then issue a single update command off of. I've also had good success passing records in as XML (I found in my environment that I needed at least 50 rows to offset the cost of loading the DOM, and I knew that the scalability issues were not a factor in my case).
Some other things I've seen was people package the updates into a binary field, for example one binary field for each column, then they have a function which unpacks the binary field. Again you will want to test with your environment.
With that said, have you verified that simply calling a single update command or stored procedure for each update you need is not sufficent? You might not even need to batch the commands up.
Josh
Watch out for Premature Optimization it can be killer!


q:
Can someone explain the main benefits of different types of references in C#?

Weak references

Soft references

Phantom references

Strong references.

We have an application that is consuming a lot of memory and we are trying to determine if this is an area to focus on.

[A]
Soft and phantom references come from Java, I believe.  A long weak reference (pass true to C#'s WeakReference constructor) might be considered similar to Java's PhantomReference.  If there is an analog to SoftReference in C#, I don't know what it is.
Weak references do not extend the lifespan of an object, thus allowing it to be garbage collected once all strong references have gone out of scope.  They can be useful for holding on to large objects that are expensive to initialize, but should be available for garbage collection if they are not actively in use.
Whether or not this will be useful in reducing the memory consumption of your application will depend completely on the specifics of the application.  For example, if you have a moderate number of cached objects hanging around that may or may not be reused in the future, weak references could help improve the memory consumption of the caches.  However, if the app is working with a very large number of small objects, weak references will make the problem worse since the reference objects will take up as much or more memory.


q: can anyone provide/refer a proper OO type helper class for managing a singleton of the SessionFactory and then also for managing Sessions?

[A]
Sure, this is what I used when I was getting started with NHibernate:
Session Factory
```
```
public class BaseDataAccess
{

  protected ISession m_session;

  public BaseDataAccess()
  {
    m_session = NHibernateHttpModule.CurrentSession;
  }

  public static ISession OpenSession()
  {
    Configuration config;
    ISessionFactory factory;
    ISession session;
    config = new Configuration();

    if (config == null)
    {
      throw new ArgumentNullException(nameof(config));
    }
    if (factory == null)
    {
      throw new ArgumentNullException(nameof(factory);
    }
    if (session == null)
    {
      throw new ArgumentNullException(nameof(session));
    }

    config.AddAssembly("My.Assembly.Here");
    factory = config.BuildSessionFactory();
    session = factory.OpenSession();

    return session;
  }
}
```
```
Let me know if that helps.


q: I'm using Emma in my ant build to perform coverage reporting.  For those that have used Emma, is there a way to get the build to fail if the line coverage (or any type of coverage stat) does not meet a particular threshold?  e.g. if the line coverage is not 100%

[A]
Not out of the box.
However, the
```
report.metrics
```
property or attribute of
```
<report></report>
```
can be set for
```
name, class, method, block
```
, and
```
line
```
.  See
Coverage Metrics
in the Emma reference.
Use a plain-text report then a regexp filter to set up a fail condition.


q:
Does anyone know what this means. Getting this in C# winforms applications:

Not a legal OleAut date

[A] It means you provided an invalid date somewhere, attempting to convert to or from an OLE Automation date outside the valid range 1-January-4713 BC to 31-December-9999 AD.  A possible cause is that it might have slipped through because OLE Automation Dates are represented as a double.


q:
I am using Maven (and the Maven Eclipse Integration) to manage the dependencies for my Java projects in Eclipse. The automatic download feature for JAR files from the Maven repositories is a real time saver. Unfortunately, it does not include API documentation and source code.

How can I set up Maven to automatically also get the source and javadoc attachments and register them properly with Eclipse?

[A]
```
```
mvn eclipse:eclipse -DdownloadSources=true
```
```
or
```
```
mvn eclipse:eclipse -DdownloadJavadocs=true
```
```
or you can add both flags, as Spencer K points out.
Additionally, the
```
=true
```
portion is not required, so you can use
```
```
mvn eclipse:eclipse -DdownloadSources -DdownloadJavadocs
```
```


q:
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.

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


q:
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`.

[A]
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.


q: 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?

[A]
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)


q: Comparable to cacti or mrtg.

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


q:
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)

[A]
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.


q: 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.

[A]
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')
```
```


q:
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?

[A]
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
}
```
```


q:
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?

[A]
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.


q:
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.

[A]
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.)


q:
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?

[A]
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.


q:
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.

[A]
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);
```
```


q:
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)

[A]
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
}
```
```


q:
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?

[A]
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.


q:
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..

[A]
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.


q:
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?

[A]
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.


q: 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.


q:
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.

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


q:
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

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


q:
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.

[A]
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.


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

[A]
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]
```


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

[A]
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


q:
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.

[A]
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?


q:
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?

[A]
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.


q:
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.

[A]
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.


q:
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.

[A]
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?


q: 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?

[A]
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 ;)


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

[A]
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.


q:
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

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


q: 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?

[A]
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).


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

[A]
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
```
.


q: 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).

[A]
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.


q:
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

[A]
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;
```
```


q:
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.

[A]
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


q: 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?

[A]
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


q:
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?

[A]
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.]


q:
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.

[A]
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.


q: What are the hidden features of Maven2?

[A]
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


q:
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.

[A]
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.


q: 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.

[A] 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.


q:
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?

[A]
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.


q:
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.

[A]
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]);
    }
}
```
```


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

[A]
You can use
```
history.back()
```
.


q:
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

[A]
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).


q: 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?

[A]
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.


q:
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!

[A]
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
```
```


q: 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.

[A]
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.


q:
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; }
    }
}

[A]
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).


q:
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.

[A]
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.


q:
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?

[A]
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.


q:
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

[A]
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
```
```


q:
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.

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
```
```
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);
```
```


q:
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]

[A]
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)
```


q:
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?

[A]
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.


q:
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?

[A]
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.


q:
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.

[A]
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


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

[A]
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.


q:
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?


q:
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.


q:
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.

[A]
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.


q:
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.

[A]
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.


q:
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).

[A]
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
```
```


q:
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?

[A]
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.


q:
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?

[A]
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
    }
}
?>
```
```