q:
I'm trying to verify that a parameter is an instance of a specific class in Rails:

def schedule(action, *args)
  if arg.is_a? Aircraft
    ...
  end
end

I'm doing this in a library class (the file is in lib/) and I get an uninitialized constant Aircraft error. Aircraft is a model class, with a corresponding aircraft.rb file in app/models.

Can I use model classes and instances in a library? How?

Error context:

The error happens in RSpec tests; the code works in the browser. I tried requiring the model in the _spec.rb file, no success at the moment.

[A]
This will give you access to the Aircraft model:
```
```
require File.dirname(__FILE__) + "/../app/models/aircraft"
```
```
[edit]
Daniel brings up a good point about the context. If you're using a rake task make sure you load the environment:
```
```
task :my_task => :environment do
  # something happens...
end
```
```


q:
I am trying to create an expression tree that represents the following:

myObject.childObjectCollection.Any(i => i.Name == "name");

Shortened for clarity, I have the following:

//'myObject.childObjectCollection' is represented here by 'propertyExp'
//'i => i.Name == "name"' is represented here by 'predicateExp'
//but I am struggling with the Any() method reference - if I make the parent method
//non-generic Expression.Call() fails but, as per below, if i use <T> the
//MethodInfo object is always null - I can't get a reference to it

private static MethodCallExpression GetAnyExpression<T>(MemberExpression propertyExp, Expression predicateExp)
{
    MethodInfo method = typeof(Enumerable).GetMethod("Any", new[]{ typeof(Func<IEnumerable<T>, Boolean>)});
    return Expression.Call(propertyExp, method, predicateExp);
}

What am I doing wrong? Anyone have any suggestions?

[A]
There are several things wrong with how you're going about it.
You're mixing abstraction levels. The T parameter to
```
GetAnyExpression<T>
```
could be different to the type parameter used to instantiate
```
propertyExp.Type
```
. The T type parameter is one step closer in the abstraction stack to compile time - unless you're calling
```
GetAnyExpression<T>
```
via reflection, it will be determined at compile time - but the type embedded in the expression passed as
```
propertyExp
```
is determined at runtime. Your passing of the predicate as an
```
Expression
```
is also an abstraction mixup - which is the next point.
The predicate you are passing to
```
GetAnyExpression
```
should be a delegate value, not an
```
Expression
```
of any kind, since you're trying to call
```
Enumerable.Any<T>
```
. If you were trying to call an expression-tree version of
```
Any
```
, then you ought to pass a
```
LambdaExpression
```
instead, which you would be quoting, and is one of the rare cases where you might be justified in passing a more specific type than Expression, which leads me to my next point.
In general, you should pass around
```
Expression
```
values. When working with expression trees in general - and this applies across all kinds of compilers, not just LINQ and its friends - you should do so in a way that's agnostic as to the immediate composition of the node tree you're working with. You are
presuming
that you're calling
```
Any
```
on a
```
MemberExpression
```
, but you don't actually
need to know
that you're dealing with a
```
MemberExpression
```
, just an
```
Expression
```
of type some instantiation of
```
IEnumerable<>
```
. This is a common mistake for people not familiar with the basics of compiler ASTs.
Frans Bouma
repeatedly made the same mistake when he first started working with expression trees - thinking in special cases. Think generally. You'll save yourself a lot of hassle in the medium and longer term.
And here comes the meat of your problem (though the second and probably first issues would have bit you if you had gotten past it) - you need to find the appropriate generic overload of the Any method, and then instantiate it with the correct type. Reflection doesn't provide you with an easy out here; you need to iterate through and find an appropriate version.
So, breaking it down: you need to find a generic method (
```
Any
```
). Here's a utility function that does that:
```
```
static MethodBase GetGenericMethod(Type type, string name, Type[] typeArgs,
    Type[] argTypes, BindingFlags flags)
{
    int typeArity = typeArgs.Length;
    var methods = type.GetMethods()
        .Where(m => m.Name == name)
        .Where(m => m.GetGenericArguments().Length == typeArity)
        .Select(m => m.MakeGenericMethod(typeArgs));

    return Type.DefaultBinder.SelectMethod(flags, methods.ToArray(), argTypes, null);
}
```
```
However, it requires the type arguments and the correct argument types. Getting that from your
```
propertyExp
```
```
Expression
```
isn't entirely trivial, because the
```
Expression
```
may be of a
```
List<T>
```
type, or some other type, but we need to find the
```
IEnumerable<T>
```
instantiation and get its type argument. I've encapsulated that into a couple of functions:
```
```
static bool IsIEnumerable(Type type)
{
    return type.IsGenericType
        && type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}

static Type GetIEnumerableImpl(Type type)
{
    // Get IEnumerable implementation. Either type is IEnumerable<T> for some T,
    // or it implements IEnumerable<T> for some T. We need to find the interface.
    if (IsIEnumerable(type))
        return type;
    Type[] t = type.FindInterfaces((m, o) => IsIEnumerable(m), null);
    Debug.Assert(t.Length == 1);
    return t[0];
}
```
```
So, given any
```
Type
```
, we can now pull the
```
IEnumerable<T>
```
instantiation out of it - and assert if there isn't (exactly) one.
With that work out of the way, solving the real problem isn't too difficult. I've renamed your method to CallAny, and changed the parameter types as suggested:
```
```
static Expression CallAny(Expression collection, Delegate predicate)
{
    Type cType = GetIEnumerableImpl(collection.Type);
    collection = Expression.Convert(collection, cType);

    Type elemType = cType.GetGenericArguments()[0];
    Type predType = typeof(Func<,>).MakeGenericType(elemType, typeof(bool));

    // Enumerable.Any<T>(IEnumerable<T>, Func<T,bool>)
    MethodInfo anyMethod = (MethodInfo)
        GetGenericMethod(typeof(Enumerable), "Any", new[] { elemType },
            new[] { cType, predType }, BindingFlags.Static);

    return Expression.Call(
        anyMethod,
            collection,
            Expression.Constant(predicate));
}
```
```
Here's a
```
Main()
```
routine which uses all the above code and verifies that it works for a trivial case:
```
```
static void Main()
{
    // sample
    List<string> strings = new List<string> { "foo", "bar", "baz" };

    // Trivial predicate: x => x.StartsWith("b")
    ParameterExpression p = Expression.Parameter(typeof(string), "item");
    Delegate predicate = Expression.Lambda(
        Expression.Call(
            p,
            typeof(string).GetMethod("StartsWith", new[] { typeof(string) }),
            Expression.Constant("b")),
        p).Compile();

    Expression anyCall = CallAny(
        Expression.Constant(strings),
        predicate);

    // now test it.
    Func<bool> a = (Func<bool>) Expression.Lambda(anyCall).Compile();
    Console.WriteLine("Found? {0}", a());
    Console.ReadLine();
}
```
```

s: huggingface

c: devops

d: intermediate


q:
I have 5 HP Compaq t5530 Thin Clients with Windows CE 6.0 installed in 'em. I have a Windows 2003 server. Those 6 PCs should be used for browsing. And a user can browse for an hour and be able to extend time. I need to develop a simple client-server program to control the internet usability.

What would be a suggested route to solve this?

[A]
So you are after a time-controlled browser application, and nothing else?  First question: do you have the BSP (board support package) for this device?
Yes
: Modify the IESAMPLE source code, which is the browser that ships with CE, to have the display you want and remove things like the close button, and maybe even the caption bar.  I'd probably even have it
implement all of the required shell functions
so it could run as the device shell completely. The
IEShell sample
would be a very good start.  Then modify HKLM\Init in your project to have the reworked IESAMPLE launch at device boot and you're done.
No
: It not going to be as easy, but it's still doable.  Create an app using the
IWebBrowser2 COM control
that has the UI elements you want (like the above suggestions).  Modify HKLM\Init to launch your app after explorer.exe (you probably will have to let explorer run to be a shell app) or if you do this in C++, implement the required shell functions.  If you let Explorer run, then you need your app to find, disable and hide the Start bar when it initializes.  How you get your app to persist will be hardware dependent - I know nothing about these devices.


q:
Is there a way to change the connection string of a DataBase object in Enterprise Library at runtime? I've found this link but its a little bit outdated (2005)

I've also found this but it seems to apply to .Net in general, I was wondering if there was something that could be done specifically for EntLib.

I was just passing the connection string name to the CreateDatabase() method in DatabaseFactory object and that worked til yesterday that my project manager asked me to support more than one database instance. It happens that we have to have one database per state (one for CA, one for FL, etc...) so my software needs to cycle through all databases and do something with data but it will use the same config file.

Thanks in advance.

[A]
If you take a look at "
Enterprise Library Docs - Adding Application Code
"
 it says this:
"If you know the connection string for
  the database you want to create, you
  can bypass the application's
  configuration information and use a
  constructor to directly create the
  Database object. Because the Database
  class is an abstract base class, you
  must construct one of its derived
  types. The derived Database type
  determines the ADO.NET data provider.
  For example, the SqlDatabase class
  uses the SqlClientFactory provider,
  the SqlCeDatabase class uses the
  SqlCeProviderFactory provider, and the
  OracleDatabase class uses the
  OracleClientFactory provider. It is
  your responsibility to construct the
  appropriate type of Database class for
  the connection string."
It then goes on to give some examples. This would suggest that you should not be using the DatabaseFactory and you should be creating a new Database class for each of your different connections.


q:
I am a PHP developer who is kind of in a pickle. I'm trying to locate and/or build an API capable of speaking to Hotmail, Yahoo and GMAIL in order to retrieve contact lists (with the user's consent, of course). The one I'm having the most trouble finding is a Hotmail API.

Where would I start to look as far as finding either a working, stable API or the steps I could take to developing one for hotmail? Is there one that covers all of these bases that I could implement? Any help would be greatly appreciated!

Thanks!

EDIT:
I did manage to get a few services up, however, I've been using Open Inviter for at least one client project, and it seems to perform well.

[A]
Rapleaf might have something for you:
http://www.phpclasses.org/browse/package/4436.html
It appears that this service plays cat and mouse with some providers, as not all e-mail providers offer a stable API for communicating with their services.  (It would undermine their business model.)  So, if you use these and the e-mail provider breaks the chain somehow, you're broken until Rapleaf catches up.


q:
I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.

Is there a better/different way to read a file into a string in Java?

private String readFile(String file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader (file));
    String         line = null;
    StringBuilder  stringBuilder = new StringBuilder();
    String         ls = System.getProperty("line.separator");

    try {
        while((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }

        return stringBuilder.toString();
    } finally {
        reader.close();
    }
}

[A]
If you're willing to use an external library, check out
Apache Commons IO
(200KB JAR). It contains an
```
org.apache.commons.io.FileUtils.readFileToString()
```
method that allows you to read an entire
```
File
```
into a
```
String
```
with one line of code.
Example:
```
```
import java.io.*;
import java.nio.charset.*;
import org.apache.commons.io.*;

public String readFile() throws IOException {
    File file = new File("data.txt");
    return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}
```
```


q:
Can someone show me how to fix the width of a column in a datatable with JSF?

My code currently reads:

<h:column>
    <f:facet name="header">
        <h:outputText value="Data Field 1" />
    </f:facet>
    <h:commandLink id="dataLink" action="#{pc_SearchResultsFragment.setField1}">
        <h:outputText value="#{(qi.data1 != null) ? '' : qi.data1}"/>
    </h:commandLink>
</h:column>

Thanks!

[A]
```
```
<h:column>
    <f:facet name="header">
        <h:outputText value="Data Field 1" />
    </f:facet>
    <h:commandLink id="dataLink" action="#{pc_SearchResultsFragment.setField1}">
        <h:outputText value="#{(qi.data1 != null) ? '' : qi.data1}"/>
    </h:commandLink>
    <%-- <f:attribute name="width" value="20" /> fixed width --%>
    <%-- or --%>
    <%-- <f:attribute name="width" value="20%" /> percentage --%>

    <%-- also available (not a complete list, just some of the more
         common supported attributes) --%>
    <%-- <f:attribute name="align" value="left" /> --%>
    <%-- <f:attribute name="height" value="20" /> --%>
    <%-- <f:attribute name="nowrap" value="true" /> --%>
    <%-- <f:attribute name="valign" value="top" /> --%>
    <%-- <f:attribute name="bgcolor" value="red" /> --%>
    <%-- <f:attribute name="style" value="color:White;" /> --%>
</h:column>
```
```


q:
I have an abstract base class and derived class:

type TInterfaceMethod = class
  public
    destructor Destroy; virtual; abstract;
    procedure Calculate; virtual; abstract;
    procedure PrepareForWork; virtual; abstract;
end;
type ConcreteMethod = class(TInterfaceMethod)
  private
    matrix: TMinMatrix;
  public
    constructor Create(var matr: TMinMatrix);
    procedure Calculate; override;
    procedure PrepareForWork; override;
    destructor Destroy;
end;

Do I really need to make base-class destructor virtual, as in C++, or it`ll be OK if it is not virtual?

By the way, did I use "override" right or I need "overload"?

[A]
Override is correct - you are redefining a virtual method.
If you really want TInterfaceMethod's destructor to throw EAbstractError, you'll have to mark it as 'override; abstract;'. (I'm surprised that it works, but I tested with D2007 and it does.) But why would you want to do that?
BTW, there is no need to use separate 'type' block for each declaration. You can format the code as that:
```
```
type
  TInterfaceMethod = class abstract
  public
    destructor Destroy; override; abstract;
    procedure Calculate; virtual; abstract;
    procedure PrepareForWork; virtual; abstract;
  end;

  TConcreteMethod = class(TInterfaceMethod)
  private
    matrix: TMinMatrix;
  public
    constructor Create(var matr: TMinMatrix);
    procedure Calculate; override;
    procedure PrepareForWork; override;
    destructor Destroy; override;
  end;
```
```
Plus you should most probably use interfaces instead of an abstract base class. And you should mark TInterfaceMethod class 'abstract' as above. In theory, that would prevent you to create TInterfaceMethod object directly. (In practice, my D2007 allows that - weird.)


q:
Many of our transactions are comprised of calculations that are comprised of other calculations.  How did you represent the hierarchy / execution graph to users?  Was there a specific control you found that worked well?

How would you project the result of a change to one of the formulas before committing that alteration?  One suggestion was to show the altered formula in a different color.  For a large set off formulas, how would you make alterations prominent?

[A]
I haven't had to do this, but I'd do something like the following:
Use a tree view-type control. Have each inner calculation be separately collapsible. The control can start out with everything collapsed, then the user can click through to see the inner calculations. (If the inner calculations have names, then use these as labels. If they don't, you can use the first few characters from the calculation to represent it).
I'm not sure what you mean by your last question, but would this work? Every time the user changes an inner calculation, mark everything that is affected by it with red. This way it'll be immediately obvious what has changed, and whether there were any unintended side effects.


q:
A remote site is supplying a data structure in a js file.

I can include this file in my page to access the data and display it in my page.

<head>
    <script type="text/javascript" src="http://www.example.co.uk/includes/js/data.js"></script>
</head>

Does anyone know how I use PHP to take this data and store in it a database?

[A]
You should GET that file directly, via, for example,
CURL
. Then parse it, if it comes in JSON, you can use
json-decode
.
Simple example (slightly modified version of code found
here
):
```
```
<?php
$url = "http://www.example.co.uk/includes/js/data.js";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
...

$output = curl_exec($ch);
$info = curl_getinfo($ch);

if ($output === false || $info['http_code'] != 200) {
  $error = "No cURL data returned for $url [". $info['http_code']. "]";
  if (curl_error($ch))
    $error .= "\n". curl_error($ch);
  }
else {
  $js_data = json_decode($output);
  // 'OK' status; save $class members in the database, or the $output directly,
  // depending on what you want to actually do.
  ...
}

//Display $error or do something about it

?>
```
```


q: I was looking into GWT. It seems nice, but our software have the must work without JS requirement. Is it possible?

[A]
No, it isn't. GWT provides a windowing toolkit that is specifically designed to run on the client, not on the server. Degraded (e.g. non-javascript) code would need to deliver complete HTML to the browser, which GWT simply does not do. It compiles your java code to a javascript file that is delivered to the client and builds the UI by DOM-manipulation on the client. Then there's some code to talk back to the server, some implicit, some written by you yourself. This model does not lend itself well to degrading gracefully.
The only way to degrade somewhat gracefully is to provide a second, non-javascript UI or use another toolkit that doesn't render the frontend on the client but delivers HTML. Sorry.


q:
I am looking for the best way to make my desktop java program run in the background (daemon/service?) across most platforms (Windows, Mac OS, Linux [Ubuntu in particular]).

By "best way" I am hoping to find a way that will:

require a minimum amount of platform-specific code.

not require the user to do anything a general computer user couldn't/wouldn't do

not be a resource hog.

I understand that my requirements may be unrealistic but I am hoping there is some sort of "best practice" for this type of situation.

How to go forward?

[A]
You can use the
SystemTray
classes and install your app as any other in the default platform.
For windows it could be an scheduled task that run at startup.
For Linux and OSX I don't know (besides crontab wich is somehow too technical) but I'm pretty sure they both have a way to do the same thing easily.
Unfortunately (as of today) Apple hasn't finished the 1.6 port.
It won't be a real demon, but an app like Google Desktop.
I've heard Quartz is a good option. But I've never used it.


q: I see parallels between MEF and Lua.  Both allow you to register methods and deploy as you need.  Are both MEF and Lua forms of IoC / Dependency Injection?

[A]
MEF has nothing to do with Lua, and is nothing like Lua.
MEF is a framework for extending (basically, an awesome plugin framework).
Lua is a very cool scripting language.
"Both allow you to register methods and deploy as you need." That sentence applies to C, C++, C#, VB, SQL, DI Frameworks, JavaScript, General Motors, Ford, Hospitals...


q:
Now I'm sure we're all well aware of the relative merits of Linux vs Windows Desktop. However I've heard much less about the world of embedded development. I'm mainly interested in solutions for industry and am therefore uninterested about the IPhone or Android and more interested in these two OSes.

What are the relative trade-offs between the two platforms in the embedded world? If you were considering building a box for a specific project with custom hardware, a partially customised OS and a custom app then which would you choose and why?

I would assume that Windows CE wins on tools and Linux wins on both cost and possibly performance. However this is just utter speculation. Does anyone have any facts or experience of the two?

[A]
I worked for several years at a company that provided both CE and Linux for all of their hardware, so I'm fairly familiar with both sides of this equation.
Tools:
Windows CE tools certainly are better than those provided by Linux, though the linux tools are certainly getting better.
Performance:
Windows CE is real-time.  Linux is not.  The linux kernel is not designed for determinism at all.  There are extensions that you can add to get sort-of real time, but CE beats it.
Cost:
This is an area of great misunderstanding.  My general experience is that CE is lower cost out of the box ($1k for Platform Builder and as low as $3 per device for a shipping runtime.  "What?" you ask?  "Linux is free."  Well, not really so much, especially in the embedded arena.  Yes, there are free distributions like Debian.  But there are plenty of pieces that you might need that aren't in that free category.  UI frameworks like QT, Java runtimes and media codecs just as a start.  Also, most Linux distributions with a commercially-backed support system (e.g. MontaVista) are far from free.
Source Availability:
Linux proponents may like to say that CE is a bad choice due to lack of source code.  All I can say is that in over a decade of working with CE, half of which spent doing custom kernel and driver work for custom boards, I've only ever had need for source that didn't ship with CE (they ship a vast majority of it) once.  I like having source too, but Microsoft provides support, so in the rare case you might think you need that source, you can get them to fix the problem (the one time we needed source, Microsoft provided a fix, and for free - which is their model under CE.
Does this mean that CE wins every time?  No.  I wouldn't suggest that at all.  If you are a Linux shop and you have lots of Linux experience and code assets, you'd be foolish to run out and go CE.  However, if you're coming into it from scratch CE usually has a lower TCO.  Developers with Win32/C# experience are more prevalent and consequently less expensive.  You also get a lot more "in the box" with CE than most other distributions, meaning faster time to market if you don't already have these things done in-house already.


q:
If I have srand(2) declared in my main of my driver file,
do I need to declare srand(2) in my code file which is being linked with my driver?

Thanks.

edit

(from user's comment below)

If I do,

srand(2);
srand(2);

will I get the seed as 2? or something else?

[A]
I think you'll have to clarify your question a bit more, but in general, you have to declare (but not define) every function you use in a given translation unit.  If you want to use srand in a .cpp file, you'll have to
```
#include <stdlib.h>
```
in that file.
For the usage of srand - take a look at its
documentation
.  You'll usually only need to call it once in a given process, after which you can expect the same sequence of pseudo-random values each run.  Calling it again with the same seed will restart the sequence of values.  If you're wanting different values each run, try seeding with the current time.
EDIT:
Do you mean that you have two files something like this:
```
```
// Driver.cpp
#include <stdlib.h>
#include "otherfile.h"

int main()
{
    srand(2);
    Somefunc();
}
```
```
And then another file linked in:
```
```
// OtherFile.cpp
#include <stdlib.h>
#include "otherfile.h"

void SomeFunc()
{
    // You don't need to call srand() here, since it's already been called in driver.cpp
   int j = rand();
}
```
```


q:
I have a string with a length that is a multiple of 8 that contains only 0's and 1's.  I want to convert the string into a byte array suitable for writing to a file.  For instance, if I have the string "0010011010011101", I want to get the byte array [0x26, 0x9d], which, when written to file, will give 0x269d as the binary (raw) contents.

How can I do this in Python?


q:
I am using the following jquery code:

$("#top ul li.corner").mouseover(function(){
    $("span.left-corner").addClass("left-corner-hover");
    $("span.right-corner").addClass("right-corner-hover");
    $("span.content").addClass("content-hover");
}).mouseout(function(){
    $("span.left-corner").removeClass("left-corner-hover");
    $("span.right-corner").removeClass("right-corner-hover");
    $("span.content").removeClass("content-hover");

});

But as you see in the selector that is going to do every li.corner that the mouse is over. i am trying to get it to do only the one the mouse is over, how would I achieve that?


q:
I had a discussion with a colleague at work, it was about SQL queries and sorting. He has the opinion that you should let the server do any sorting before returning the rows to the client. I on the other hand thinks that the server is probably busy enough as it is, and it must be better for performance to let the client handle the sorting after it has fetched the rows.

Anyone which strategy is best for the overall performance of a multi-user system?

[A]
In general, you should let the database do the sorting; if it doesn't have the resources to handle this effectively, you need to upgrade your database server.
First off, the database may already have indexes on the fields you want so it may be trivial for it to retrieve data in sorted order.  Secondly, the client can't sort the results until it has all of them; if the server sorts the results, you can process them one row at a time, already sorted.  Lastly, the database is probably more powerful than the client machine and can probably perform the sorting more efficiently.


q: The line-height property usually takes care of vertical alignment, but not with inputs. Is there a way to automatically center text without playing around with padding?

[A]
I've not tried this myself, but try setting:
```
```
height : 36px; //for other browsers
line-height: 36px; // for IE
```
```
Where 36px is the height of your input.


q: I know that most people recommend using HttpRuntime.Cache because it has more flexibility... etc. But what if you want the object to persist in the cache for the life of the application? Is there any big downside to using the Application[] object to cache things?

[A]
As long as you don't abuse the application state, then I don't see a problem in using it for items that you don't want to expire.
Alternatively I would probably use a static variable near the code that uses it. That way you avoid to go through
```
HttpApplicationState
```
and then be forced to have a reference to System.Web if i want to access my data.
But be sure to think through how you use the object(s) that you store in
```
HttpApplicationState
```
. If it's a
```
DataSet
```
which you keep adding stuff to for each request, then at some point you end up eating up too much memory on the web-server. The same could happen if you keep adding items to
```
HttpApplicationState
```
when you process requests, at some point you will force the application to restart.
That's probably the advantage of using Cache in your situation. Consuming larger amounts memory isn't as fatal because you allow ASP.NET to release the items in your cache when memory becomes scarce.


q:
The current top-voted to this question states:

Another one that's not so much a security issue, although it is security-related, is complete and abject failure to grok the difference between hashing a password and encrypting it. Most commonly found in code where the programmer is trying to provide unsafe "Remind me of my password" functionality.

What exactly is this difference? I was always under the impression that hashing was a form of encryption. What is the unsafe functionality the poster is referring to?

[A]
Hashing is a one way function (well, a mapping). It's irreversible, you apply the secure hash algorithm and you cannot get the original string back. The most you can do is to generate what's called "a collision", that is, finding a different string that provides the same hash. Cryptographically secure hash algorithms are designed to prevent the occurrence of collisions. You can attack a secure hash by the use of a
rainbow table
, which you can counteract by applying a
salt
to the hash before storing it.
Encrypting is a proper (two way) function. It's reversible, you can decrypt the mangled string to get original string if you have the key.
The unsafe functionality it's referring to is that if you encrypt the passwords, your application has the key stored somewhere and an attacker who gets access to your database (and/or code) can get the original passwords by getting both the key and the encrypted text, whereas with a hash it's impossible.
People usually say that if a cracker owns your database or your code he doesn't need a password, thus the difference is moot. This is naïve, because you still have the duty to protect your users' passwords, mainly because most of them do use the same password over and over again, exposing them to a greater risk by leaking their passwords.


q:
I'm trying to update a hashtable in a loop but getting an error: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

private Hashtable htSettings_m = new Hashtable();
htSettings_m.Add("SizeWidth", "728");
htSettings_m.Add("SizeHeight", "450");
string sKey = "";
string sValue = "";
foreach (DictionaryEntry deEntry in htSettings_m)
{
    // Get value from Registry and assign to sValue.
    // ...
    // Change value in hashtable.
    sKey = deEntry.Key.ToString();
    htSettings_m[sKey] = sValue;
}

Is there way around it or maybe there is a better data structure for such purpose?

[A]
You cannot change the set of items stored in a collection while you are enumerating over it, since that makes life very difficult for the iterator in most cases.  Consider the case where the collection represents a balanced tree, and may well undergo rotations after an insert.  The enumerate would have no plausible way of keeping track of what it has seen.
However, if you are just trying to update the value then you can write:
```
```
deEntry.Value = sValue
```
```
Updating the value here has no impact on the enumerator.


q:
Is there a shortcut for giving a limit and order when accessing a has_many relation in an ActiveRecord model?

For example, here's what I'd like to express:

@user.posts(:limit => 5, :order => "title")

As opposed to the longer version:

Post.find(:all, :limit => 5, :order => "title", :conditions => ['user_id = ?', @user.id])

I know you can specify it directly in the has_many relationship, but is there a way to do it on the fly, such as showing 10 posts on one page, but only 3 on another?

[A]
I have something similar in a blog model:
```
```
has_many :posts, :class_name => "BlogPost", :foreign_key => "owner_id",
    :order => "items.published_at desc", :include => [:creator] do
      def recent(limit=3)
        find(:all, :limit => limit, :order => "items.published_at desc")
      end
  end
```
```
Usage:
```
```
Blog.posts.recent
```
```
or
```
```
Blog.posts.recent(5)
```
```


q:
I have a python module that defines a number of classes:

class A(object):
    def __call__(self):
        print "ran a"

class B(object):
    def __call__(self):
        print "ran b"

class C(object):
    def __call__(self):
        print "ran c"

From within the module, how might I add an attribute that gives me all of the classes?

dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from within the module.

From outside of the module, I can simply use getattr(mod, 'A'), but I don't have a self kind of module from within the module itself.

This seems pretty obvious.  Can someone tell me what I'm missing?

[A]
```
```
import sys
getattr(sys.modules[__name__], 'A')
```
```


q:
Is there a way in Python to handle XML files similar to the way PHP's SimpleXML extension does them?

Ideally I just want to be able to access certain xml datas from a list object.

[A]
There is a long list of libraries associated with XML processing on the
Python wiki
. Note that a number of them are included in the standard library. Most of them will do what you are looking for:
to access certain xml datas from a list object
which is a bit vague, and perhaps some more concrete use-case might narrow down that list for you.


q:
I know that you cannot return anonymous types from methods but I am wondering how the Select extension method returns an anonymous type. Is it just a compiler trick?

Edit

Suppose L is a List. How does this work?

L.Select(s => new { Name = s })

The return type is IEnumerable<'a> where 'a = new {String Name}

[A]
Well, it's normal type inference for generic method type arguments. For instance:
```
```
List<string> x = new List<string>();

// The compiler converts this:
x.Select(y => y.Length);

// Into this, using type inference:
Enumerable.Select<string, int>(x, y => y.Length);
```
```
The same would be true if
```
x
```
were a list of some anonymous type, or if the inferred return type of the lambda expression were an anonymous type. Don't forget that even though you can't explicitly state the type of a variable which uses an anonymous type, it still does
have
a definite type, known to the compiler.


q:
How can I pass a variable number of args to a yield.
I don't want to pass an array (as the following code does), I'd actually like to pass them as a programmatic number of args to the block.

def each_with_attributes(attributes, &block)
  results[:matches].each_with_index do |match, index|
    yield self[index], attributes.collect { |attribute| (match[:attributes][attribute] || match[:attributes]["@#{attribute}"]) }
  end
end

[A]
Asterisk will expand an array to individual arguments in ruby:
```
```
def test(a, b)
  puts "#{a} + #{b} = #{a + b}"
end

args = [1, 2]

test *args
```
```


q:
Is there any reason that MVC isn't equally useful for desktop apps as for web apps?

What would be required to make an ASP.NET MVC directory tree implementable as a desktop app?

[A]
I've always thought of the term MVC as the same as a n-layer application - so correct me if I'm wrong here folks.
When i develope, I always(unless other instructed) use the following model/structure, also in applications:
GUI(Web, Winform, whatever) ->
Business logic ->
Data layer ->
And also with an underlying "Model"
... Which is a sort of MVC - So yes, it is usefull for desktop apps also. The main advantage with this, is that you can develope web, win and mobile(++) applications based on the same code.
Another thing that could be done, is to create the data/businesslayers as web-services...
I think this aproach would qualify as SOA.
EDIT:
As a note, the four levels of applications are created as seperate projects - and then used as adding reference to either the project, or the DLL, or from the GAC(or wherever you like.....) :) Thus, the need for a directory structure is not needed.


q:
What best practices should be observed when implementing HDL code?

What are the commonalities and differences when compared to more common software development fields?

[A]
The best book on this topic is
Reuse Methodology Manual
.  It covers both VHDL and Verilog.
And in particular some issues that don't have an exact match in software:
No latches
Be careful with resets
Check your internal and external timing
Use only synthesizable code
Register your outputs of all modules
Be careful with blocking vs. non-blocking assignments
Be careful with sensitive lists for combinatorial logic (or use @(*) in Verilog)
Some that are the same include
Use CM
Have code reviews
Test (simulate) your code
Reuse code when appropriate
Have an up-to-date schedule
Have a spec or use cases or an Agile customer


q:
As in the topic...

I was thinking about something like "in memory changes".
On recent blogs by Jaroslaw Kowalski i have found similar approach
but i was thinking about sth much simpler


q: I want to create the 26 neighbors of a cubic-voxel-node in 3-d space. The inputs are the x,y,z position of the node and the size of the cube side . I am trying to do this using a for loop but haven't managed yet. I am quite newbie in programming please help me.


q:
Is there an easy way to parse the user's HTTP_ACCEPT_LANGUAGE and set the locale in PHP?

I know the Zend framework has a method to do this, but I'd rather not install the whole framework just to use that one bit of functionality.

The PEAR I18Nv2 package is in beta and hasn't been changed for almost three years, so I'd rather not use that if possible.

Also nice would be if it could figure out if the server was running on Windows or not, since Windows's locale strings are different from the rest of the world's... (German is "deu" or "german" instead of "de".)

[A]
Nice solution is
on its way
.
Without that you'll need to parse that header. It's a comma-separated list of semicolon-separated locales and attributes.
It can look like this:
```
```
en_US, en;q=0.8, fr_CA;q=0.2, *;q=0.1
```
```
and then try each locale until
```
setlocale()
```
accepts it. Be prepared that none of them may match.
Don't base on it anything too important or allow users to override it, because some users may have misconfigured browsers.
For Windows locale, perhaps you need to convert ISO 639-1 names to ISO 639-2/3?


q: Is there any way to detect, through WSH, which workstations, in a windows domain, has a locked session?

[A]
http://www.microsoft.com/technet/scriptcenter/resources/qanda/nov04/hey1115.mspx
If you scroll down, there is a check if computer is locked script on the page.  The script basically grabs the running processes for the machine and looks for the scrnsave.exe.
It is also worth noting that the author of this script states that he does not know of a foolproof way to determine if a computer is locked.  Hope this helps or at least points you in the right direction.


q:
I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection.  I have used nested functions to hide implementation details of my classes so that only the public API is visible.  I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop.  I have tried calling one of the nested functions like:

def outer():
    def inner():
        pass

outer.inner()

which results in the error message:

AttributeError: 'function' object has no attribute 'inner'

Is there a way for me to write unit tests against these nested functions?  If not, is there a way to trigger the name munging for function names like you can for class variables by prefixing them with __?

[A]
inner doesn't exist until outer makes it.  You should either move inner up to a toplevel function for testability, or have the outer test test all the possible execution paths of itself and inner.
Do note that the inner function isn't a simple function, it's a closure.  Consider this case:
```
```
def outer(a):
    b = compute_something_from(a)
    def inner():
        do_something_with(a, b)
```
```
That's the standard testability trade-off.  If your
cyclomatic complexity
is too high, your tests will be too numerous.


q:
I have a row of buttons, which all create a pdf file which I want to open in a new tab.
This way the button page stays on top, and the pdf's open to get printed. To prevent clicking a button twice I disable the button, like this (I use python):

<input type='submit' value='Factureren' name='submitbutton' id='%s'
onclick="javascript:document.getElementById('%s').disabled=true;
document.getElementById('%s').className='button_disabled';"> % ((but_id,) *3)

In FF3 this works fine, i.e. the form is submitted, the script executed and then the button disables. In IE the button just disables, but the form script isn't executed.

Is there a solution to this IE problem?

[A]
It is easier to do:
```
```
<input type='submit' value='Factureren' name='submitbutton' id='%s'
onclick="this.disabled=true; this.className='button_disabled';"> % ((but_id,) *3)
```
```
I don't know if this solves your problem but it is what I would do in a case like this. I think you don't need "javascript:" anyway.


q:
I am trying to find out how to use usercontrols in asp.net mvc.  I know how to add a usercontrol to a view and how to pass data to it.  What I haven't been able to figure out is how do you do this without having to retrieve and pass the data in every single controller?

For example, if I have a user control that displays the most recent posts on several but not all the pages in the site, how do I write the Controllers so that I get data for that usercontrol and pass it to the user control from only one place in the web site instead of getting and passing data in each of the different controllers that the user control is used in?

I'm not sure if this makes sense or not.  Is there a better or recommended way to handle an "island" of data that you want to display on several pages?

I'm coming from web forms where I could just write a user control that got its own data and displayed data independently from the rest of whatever page it is used on.

[A]
Refactor the code that obtains the view data for this user control into it's own method, maybe even it's own model (class).  Call this method from each controller that needs to populate the control and pass the results in the ViewData with a well-known key.  You might even want to pass the type of the current controller to your method in case it needs to know what data to retrieve based on the base model for the controller.
```
```
ViewData["RecentPosts"] = RecentPosts.GetRecentPosts( this.GetType() );
```
```
In your control, retrieve the data using the well-known key.


q: Is there any provable reason why I should always specify the SQL data type for SqlCommand paramenters?

[A] The only time I've run into a case when I had to specify a data type was when passing in DBNull.  When I wasn't specifying a data type, it defaulted to a Varchar, and ended up crashing because I was trying to set an integer value to Null.


q:
Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:

$("<div></div>");

However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?

This answer has the benchmarks to the suggestions below.

[A]
I think you're using the best method, though you could optimize it to:
```
```
$("<div/>");
```
```


q:
I'm trying to get Cruisecontrol.NET running with Server 2008/IIS7 and when I try and navigate to the dashboard I get the following error:
HTTP Error 404.17 - Not Found
The requested content appears to be script and will not be served by the static file handler.

I'm a bit lost in IIS7 so it could be something pretty straightforward. They (cc.net) do some funny stuff with http handlers in the web.config which may be related to the problem:

Anyone have any pointers?

[A]
Is the dashboard set up as an application in IIS?
I've not used IIS7, but I know in IIS6 you need to enable an application and assign it to an app pool before you can run ASPX code.
EDIT:
This works in IIS6.
Open the IISAdmin tool on the web server.  Expand the web sites folder. Find the virtual directory (directories?) for CruiseControl.  Right-click on it and look at properties.  On the directory tab, create a new application and give it a suitable name.  Enable the application to execute "scripts only".  Assign it to an application pool (you may want to create a new one just for this application -- consult the help documentation for this).  You may also need to change the ASP.NET version   You can do this on the ASP.NET tab -- choose either v1.1 or v2.0, whichever CruiseControl requires.


q:
I have been attempting to create a new directory for my apache server. As I tried to access the new directory, I type:

sudo /etc/init.d/apache2 restart

But I obtain this error in the Ubuntu Terminal:

Syntax Error on line 1 of /etc/apache2/conf.d/fqdn.save:
ServerName takes one argument, the Hostname and port of the server.

As I investigate, the fqdn.save file could not be accessed and is considered unknown. I want to delete this file, but I'm unable to as I believe I need root access.

Does anyone know how to delete this unwanted file in Ubuntu? Or does anyone know how to redirect the apache2 restart to /etc/apache2/conf.d/fqdn (instead of fqdn.save) when I type "sudo /etc/init.d/apache restart" on the terminal

please and thank you

[A]
You need to be inside the group that has permissons to write that file and that would be probably apache and root (both user and group), im not quite sure about the group name of apache in ubuntu but if you are a regular user im afraid you would not be able to just delete the file, ask the system administrator or someone who has permissions over that file.
On the other hand, deleting the file will not work if the init script "apache2" has a link to it, instead you would get probably a different error saying that the file could not be found.
So your problem seems to be that you have the init script of apache trying to access a wrong filename, I believe that the solution is to edit the init script of apache and point it to the right filename and that would be fqdn instead of fqdn.save


q:
web2py to is a Python framework but shares the  "convention over configuration" design that Ruby on Rails has. On the plus side it packages a lot more functionality with its s standard distribution and we claim it is faster and easier to use.

Has any Rails user tried it? What is your impression?

No rants please. Just technical comments.

[A]
I would say the biggest "con" of using webpy over Rails is that there are not a lot of Rails-specific hosting services around, and the huge community based around it (there are Rails plugins and tools for.. everything). The same cannot be said for web2py.
It depends what you want to do with it - if it's something to write your personal site with, and you already have a server to host it on, use whatever you prefer. If it's something to distribute for others to run, Rails has more options for hosting, and a bigger community, so it may be a better choice.
Technical differences are rather irrelevant. Every framework can basically do the same (generate web-pages). What is important is community, ease of use, useful feature-sets, ability to host it and so on - and those are all really subjective.
I still use PHP quite often, not because "it's better", but because I can host it on a huge majority of web-hosts. I also use Rails because as it has a good, and very active community. The actually technicalities of the framework wasn't ever a consideration, really..
I could probably put together a list of why web2py is "better"/"worse" than Rails - Rails may be 0.04sec/request slower at generating templates containing loops, or web2py may have a good DB model generator, or some other technical reason -  but those may not be relevant to you at all


q: How can I enable Emacs key bindings in Microsoft Visual C# 2008 Express Edition?

[A]
It seems that the Emacs keybinding file (
Emacs.vsk
) it's not included on Visual Studio Express Editions, however you might be able to find it and use it :-)


q:
Using Morph Labs' Appspace to deploy a site means no automated way to redirect 'myapp.com' to 'www.myapp.com' (and no access to .htacess).

Is there an in-rails way to do this? Would I need a plugin like subdomain-fu?

More specifically, I'm trying to do something like:

'myapp.com' => 'www.myapp.com'

'myapp.com/session/new' => 'www.myapp.com/session/new'

Basically, I always want the 'www' subdomain prepended on every request (because the SSL cert specifically has a common name of 'www.myapp.com').

[A]
Here is a couple of different ways:
```
```
head :moved_permanently, :location => ‘http://www.newdomain.com’
```
```
another:
```
```
def rails_301
headers["Status"] = "301 Moved Permanently"
redirect_to "http://www.newdomain.com"
end
```
```


q: I really want to use SimpleDB, but I worry that without real locking and transactions the entire system is fatally flawed. I understand that for high-read/low-write apps it makes sense, since eventually the system becomes consistent, but what about that time in between? Seems like the right query in an inconsistent db would perpetuate havoc throughout the entire database in a way that's very hard to track down. Hopefully I'm just being a worry wart...

[A]
This is the pretty classic battle between consistency and scalability and - to some extent - availability.  Some data doesn't always need to be that consistent.  For instance, look at digg.com and the number of diggs against a story.  There's a good chance that value is duplicated in the "digg" record rather than forcing the DB to do a join against the "user_digg" table.  Does it matter if that number isn't perfectly accurate?  Probably not.  Then using something like SimpleDB might be a good fit.  However if you are writing a banking system, you should probably value consistency above all else. :)
Unless you know from day 1 that you have to deal with massive scale, I would stick to simple more conventional systems like RDBMS.  If you are working somewhere with a reasonable business model, you will hopefully see a big spike in revenue if there's a big spike in traffic.  Then you can use that money to help solving the scaling problems.  Scaling is hard and scaling is hard to predict.  Most of the scaling problems that hurt you will be ones that you never expect.
I would much rather get a site off the ground and spend a few weeks fixing scale issues when traffic picks up then spend so much time worrying about scale that we never make it to production because we run out of money. :)


q:
The list sort() method is a modifier function that returns None.

So if I want to iterate through all of the keys in a dictionary I cannot do:

for k in somedictionary.keys().sort():
    dosomething()

Instead, I must:

keys = somedictionary.keys()
keys.sort()
for k in keys:
    dosomething()

Is there a pretty way to iterate through these keys in sorted order without having to break it up in to multiple steps?

[A]
Can I answer my own question?
I have just discovered the handy function "sorted" which does exactly what I was looking for.
```
for k in sorted(somedictionary.keys()):
    dosomething()
```
It shows up in
Python 2.5 dictionary 2 key sort


q: I have been noticing on my trackers that bots are visiting my site ALOT. Should I change or edit my robots.txt or change something? Not sure if thats good, because they are indexing or what?

[A]
Should i change or edit my robots.txt or change something?
Depends on the bot. Some bots will dutifully ignore robots.txt.
We had a similar problem 18 months ago with the google AD bot because our customer was purchasing Soooo many ads.
Google AD bots will (as documented) ignore wildcard (*) exclusions, but listen to explicit ignores.
Remember, bots that honor robots.txt will just not crawl your site. This is undesirable if you want them to get access to your data for indexing.
A better solution is to throttle or supply static content to the bots.
Not sure if thats good, because they are indexing or what?
They could be indexing/scraping/stealing. All the same really. What I think you want is to throttle their http request processing based on UserAgents. How to do this depends on your web server and app container.
As suggested in other answers, if the bot is malicious, then you'll need to either find the UserAgent pattern and send them 403 forbiddens. Or, if the malicious bots dynamically change user agent strings you have a two further options:
White-list UserAgents - e.g. create a user agent filter that only accepts certain user agents. This is very imperfect.
IP banning - the http header will contain the source IP. Or, if you're getting DOS'd (denial of service attack), then you have bigger problems


q:
Now I have a stack of free time on my hands, I wanna get into iphone dev fo real.

But Objective C scares me (a bit). It feels I'm going a bit back in time. I say this because I've spent the last 8 months coding in C++.

JSCocoa looks awesome, but does this actually work on the iphone?

What would need to be done to get this working on the iphone?

[A]
(Hi, I'm the JSCocoa dev)
JSCocoa works on the iPhone simulator. Check out the latest version from Google svn and compile iPhoneTest2.
To work on the iPhone, it needs libffi. I've seen
http://code.google.com/p/iphone-dev/source/browse/trunk/llvm-gcc-4.0-iphone/
and some libffi posts regarding Python for iPhone, but have not tested any further.
Also I don't own an iPhone, so testing will mostly be up to someone who owns one :)


q:
The Daily WTF for 2008-11-28 pillories the following code:

static char *nice_num(long n)
{
    int neg = 0, d = 3;
    char *buffer = prtbuf;
    int bufsize = 20;

    if (n < 0)
    {
        neg = 1;
        n = -n;
    }
    buffer += bufsize;
    *--buffer = '\0';

    do
    {
        *--buffer = '0' + (n % 10);
        n /= 10;
        if (--d == 0)
        {
            d = 3;
            *--buffer = ',';
        }
    }
    while (n);

    if (*buffer == ',') ++buffer;
    if (neg) *--buffer = '-';
    return buffer;
}

How would you write it?

[A]
If you're a seasoned C programmer, you'll realize this code isn't actually that bad.  It's relatively straightforward (for C), and it's blazingly fast.  It has three problems:
It fails on the edge case of LONG_MIN (-2,147,483,648), since negating this number produces itself in twos-complement
It assumes 32-bit integers - for 64-bit longs, a 20-byte buffer is not big enough
It's not thread-safe - it uses a global static buffer, so multiple threads calling it at the same time will result in a race condition
Problem #1 is easily solved with a special case.  To address #2, I'd separate the code into two functions, one for 32-bit integers and one for 64-bit integers.  #3 is a little harder - we have to change the interface to make completely thread-safe.
Here is my solution, based on this code but modified to address these problems:
```
```
static int nice_num(char *buffer, size_t len, int32_t n)
{
  int neg = 0, d = 3;
  char buf[16];
  size_t bufsize = sizeof(buf);
  char *pbuf = buf + bufsize;

  if(n < 0)
  {
    if(n == INT32_MIN)
    {
      strncpy(buffer, "-2,147,483,648", len);
      return len <= 14;
    }

    neg = 1;
    n = -n;
  }

  *--pbuf = '\0';

  do
  {
    *--pbuf = '0' + (n % 10);
    n /= 10;
    if(--d == 0)
    {
      d = 3;
      *--pbuf = ',';
    }
  }
  while(n > 0);

  if(*pbuf == ',') ++pbuf;
  if(neg) *--pbuf = '-';

  strncpy(buffer, pbuf, len);
  return len <= strlen(pbuf);
}
```
```
Explanation: it creates a local buffer on the stack and then fills that in in the same method as the initial code.  Then, it copies it into a parameter passed into the function, making sure not to overflow the buffer.  It also has a special case for INT32_MIN.  The return value is 0 if the original buffer was large enough, or 1 if the buffer was too small and the resulting string was truncated.


q: Is there any supported way of mapping datetimeoffset the new datatype in SQL 2008 to the System.DateTimeOffset using nhibernate?

[A]
(Assuming google didn't turn of anything)
You will probably need to create a simple IUserType to handle this, also I am sure that the NH team would gladly accept it as a patch for everyone to benifit.
Ayende has a good post
here
on this.  He goes though a couple of options to solve his problem so you might want to start from the bottom of the post (not the comments) and go up.


q: I'm planning to write a aspx pages on Windows XP machine. I have IIS 7.0 enabled and virtual directory setup. Are aspx page developments allowed on Win XP?

[A]
Yes, you can develop ASP.NET pages (.aspx) on Windows XP. XP only runs IIS 5.1, however you don't even need IIS installed as Visual Web Developer Express has a built-in web server you can use during development.. To get started, I would go to
http://www.microsoft.com/express/
and download Microsoft Visual Web Developer Express. After doing that, go to
http://www.asp.net/get-started/
to learn the basics. Post any questions or problems you encounter back here on StackOverflow.


q:
How would you write a prepared MySQL statement in PHP that takes a differing number of arguments each time? An example such query is:

SELECT `age`, `name` FROM `people` WHERE id IN (12, 45, 65, 33)

The IN clause will have a different number of ids each time it is run.

I have two possible solutions in my mind but want to see if there is a better way.

Possible Solution 1 Make the statement accept 100 variables and fill the rest with dummy values guaranteed not to be in the table; make multiple calls for more than 100 values.

Possible Solution 2 Don't use a prepared statement; build and run the query checking stringently for possible injection attacks.

[A]
I can think of a couple solutions.
One solution might be to create a temporary table.  Do an insert into the table for each parameter that you would have in the in clause.  Then do a simple join against your temporary table.
Another method might be to do something like this.
```
```
$dbh=new PDO($dbConnect, $dbUser, $dbPass);
$parms=array(12, 45, 65, 33);
$parmcount=count($parms);   // = 4
$inclause=implode(',',array_fill(0,$parmcount,'?')); // = ?,?,?,?
$sql='SELECT age, name FROM people WHERE id IN (%s)';
$preparesql=sprintf($sql,$inclause);  // = example statement used in the question
$st=$dbh->prepare($preparesql);
$st->execute($parms);
```
```
I suspect, but have no proof, that the first solution might be better for larger lists, and the later would work for smaller lists.
To make @orrd happy here is a terse version.
```
```
$dbh=new PDO($dbConnect, $dbUser, $dbPass);
$parms=array(12, 45, 65, 33);
$st=$dbh->prepare(sprintf('SELECT age, name FROM people WHERE id IN (%s)',
                          implode(',',array_fill(0,count($parms),'?'))));
$st->execute($parms);
```
```


q: Does anyone know how the built in dictionary type for python is implemented?  My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.

[A]
Python Dictionaries use
Open addressing
(
reference inside Beautiful code
)
NB!
Open addressing
, a.k.a
closed hashing
should, as noted in Wikipedia, not be confused with its opposite
open hashing!
Open addressing means that the dict uses array slots, and when an object's primary position is taken in the dict, the object's spot is sought at a different index in the same array, using a "perturbation" scheme, where the object's hash value plays part.


q:
I am working on some sort of CRM application which has huge sales data with all the customer leads etc (ASP.NET 2.0/Ajax)

I want to create a dashboard which will have four separate data containers each container will have different sort of data and each container has to update it  self after some configured time interval. so I want to update only that part of page not whole page

What should I used in the above scenario asp.net updatePanel or jQuery implementation (which technique and why)

Because performance is also important here.

[A]
Both ASP.NET UpdatePanel or jQuery (or a mix of both) would serve you fine on this scenario; if you don't have experience with neither, I would recommend the UpdatePanel way because it is closer to the regular ASP.NET code you're used to.
This article
will get you 90% there, all you have to do at the end is to put some simple javascript in place to fire the updates every X seconds; something like
```
window.setTimeout("Button1.click()",5000)
```
if you want to refresh a panel every 5 seconds. If you don't want the button to be available for the users, just make it hidden via CSS.
There are more elegant approaches (using JSON, webservices, client-side templating etc) but that's an easy way to get the job done.


q:
I'm using Junit 4.4 and Ant 1.7.  If a test case fails with an error (for example because a method threw an unexpected exception) I don't get any details about what the error was.

My build.xml looks like this:

<target name="test" depends="compile">
<junit printsummary="withOutAndErr" filtertrace="no" fork="yes" haltonfailure="yes" showoutput="yes">
  <classpath refid="project.run.path"/>
  <test name="a.b.c.test.TestThingee1"/>
  <test name="a.b.c.test.NoSuchTest"/>
</junit>
</target>

When I run "ant test" it says (for example) 2 Test runs, 0 failures, 1 error.  It doesn't say "There is no such test as NoSuchTest" even though this is completely reasonable and would let me figure out the cause of the error.

Thanks!

-Dan

[A]
Figured it out :)
I needed to add a "formatter" inside the junit block.
```
```
<formatter type="plain" usefile="false" />
```
```
What a PITA.
-Dan


q: Why is it not advisable to use JavaScript in JSP? One rationale that I can think of is turning off the feature in browser would stop the code from executing. Is there any other reason behind this?

[A]
JSP is a server side technology. That is - Server parses/compiles all the information and then sends it to the client (i.e. your browser). And then..
If received data contains ANY javascript then browser interprets it in its own javascript VM and server is long forgotten by then since HTTP is stateless protocol.
Considering "not recommending JS in web" I wouldn't bother about it. Most of the sites use JS extensively thus turning it off on the client side would render them mostly useless.


q:
I have a problem redrawing a custom view in simple cocoa application. Drawing is based on one parameter that is being changed by a simple NSSlider. However, although i implement -setParameter: and -parameter methods and bind slider's value to that parameter in interface builder i cannot seem to make a custom view to redraw itself.

The code that does redrawing is like this:

- (void)setParameter:(int)newParameter {
  parameter = newParamter;
  NSLog(@"Updated parameter: %d", parameter);
  [self setNeedsDisplay:YES];
}

I DO get the message about setting the new parameter although the view doesn't redraw itself. Any ideas are welcome!

[A]
The usual syntax is:
```
[self setNeedsDisplay:YES]
```
, although I would assume that that means the same thing. Are you implementing the
```
- (void)drawRect:(NSRect)rect
```
method, or using the
```
drawRect:
```
method of your superclass?


q:
I have two tables with the same columns, and I need to copy one table's rows to the other table's rows to create one big table with all the values from both tables.  Right now I am doing this query to return the same thing:

SELECT col1, col2, col3 from Table1
union
SELECT col1, col2, col3 from Table2

However, it seems horribly inefficient, and on my system is very slow (returns 1210189 records).

[A]
May it work to just do:
```
```
SELECT col1, col2, col3
INTO Table1
FROM Table2
```
```


q:
I doing a function in Javascript like the VisualBasic DateDiff.

You give two dates and the returning time interval (Seconds, Minutes, Days, etc...)

DateDiff(ByVal Interval As Microsoft.VisualBasic.DateInterval, _
  ByVal Date1 As Date, ByVal Date2 As Date) as Long

So what's the best way to calculate the difference of Javascript Dates?

[A]
If you follow this
tutorial
, one way is to use:
```
```
Date.getTime()
```
```
You will find a full
javascript function here
, complete with date validation.
That being said, as commented by
Rafi B.
5 years later, "
Get difference between 2 dates in javascript?
" is more precise.
```
```
var _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
```
```


q:
I have found many tutorials about using Windows Server 2003 as a development machine, and very little information about Windows Server 2008 for the same purpose.

For a nicer experience, I have followed the steps from Convert your Windows Server 2008 to a Workstation.

I am searching for the requirements and installation order for IIS 7 with IIS 6 compatibility mode, .NET Framework 3.5 SP1 (does it require the installation of .NET Framework 3.0 feature, or can be installed directly), SQL Server 2005 SP2 (with Reporting services and Analysis Services), Visual Studio 2008 SP1.

[A]
.NET Framework 3.5 Service Pack 1 - installation order
System Update Readiness Tool
.NET Framework 3.0 (Windows Server 2008 feature)
.NET Framework 3.5 SP1 (full package)
An update for the .NET Framework 3.5 Service Pack 1 is available (KB959209)
.NET Framework 3.5 Service Pack 1 - links
Before you install .NET Framework 3.5 SP1 on Windows Vista or Windows 2008 Server, make sure that Windows Update service is turned on.
Description of the System Update Readiness Tool for Windows Vista and for Windows Server 2008
- Since the .NET Framework 2.0 and 3.0 are OS components on Windows Vista and Windows Server 2008, they rely on the OS component store to be in a good state to be able to install correctly (quoted from
here
)
Unified .NET Framework Troubleshooting Guide


q:
I need to have some information about the Scoping issue in Javascript. I know that it spports lexical(static) scoping, but, does not it support dynamic scoping as well?
If you know anything about the scoping in Javascript, would you please share them with me ?

Thanks

[A]
I think you're confused because Javascript uses static scoping but at function-level, not at block level like usual structured languages.
```
```
var foo = "old";
if (true) {var foo = "new";}
alert (foo == "new")
```
```
So be careful, blocks don't make scope!
That's why you sometimes see loops with functions inside just to enable variables whose scope is inside an iteration:
```
```
functions = [];
for(var i=0; i<10; i++) {
   (function(){
       var local_i = i;
       functions[local_i] = function() {return local_i;}
   })();
}
functions[2]() // returns 2 and not 10
```
```


q:
I'm in the middle of building a pretty big site using asp.net (forms if it's of any interest), and I'm wondering if i need a logging framework such as log4net.
I've used such frameworks before, but i don't see how i could put it to any use in this type of project.
usually i think logging is needed for customer delivered application, where the log could be sent back and then analyzed for errors.
what do you think?

[A]
Heck no - logging is
incredibly
important for web applications. If you log appropriately, it makes troubleshooting
so
much easier.
Log4Net is probably a good bet as a framework. You might also want a way of gathering logs together from multiple servers - and even if you don't use more than one server at the moment, it's probably worth suggesting that you will do so at some point.
One option for the centralisation is to copy the logs into a database - see
this question
for more opinions on that front.


q: I need to stop the execution Is there any procedures for using terminate and suspend activity

[A]
This sample at the microsoft website should help you with the suspend and terminate Activity
http://msdn.microsoft.com/en-us/library/ms742189.aspx


q: In standard ASP.net applications ASP.net offered some protection from XSS attacks with validateRequest throwing detect dangerous input errors if some one tried to. This functionality seems to have been taken out of MVC any idea why?

[A]
This is a hard line to cross. Is your web application just a RESTful web resource like it 'should' be? Or is it trying to do more. Next thing you know you have 100 hidden input fields: __VIEWSTATE, __EVENTTARGET, __EVENTARGUMENT, etc, etc.
As you know, you can still prevent XSS attacks in MVC. Just
google it
to see several examples. But the reason is basically that MVC is a different, 'cleaner' type of web application.
EDIT: I don't know if what I've said above is clear. But the idea is that MVC isn't going to try to be more than what it is (like ASP.NET does). They both have their strong points and reasons.


q:
I've a HTML page with several Div's that will show the time difference between now and each given date.

<div class="dated" onEvent="calculateHTML(this, 'Sat Jun 09 2007 17:46:21')">
30 Minutes Ago</div>

I want that time difference to be dynamic (calculated to all elements when the page loads and also within a time interval)

So, my idea was to go to all div's of class "dated", calculate the time diference for each one and replace the correspondent innerHTML.

Is this the best aproach or should I try a different one?

Edit:

One of the problems I've encountered was, where do I keep within the div, the date that will be used to generate the text?

[A]
Using innerHTML works most (all?) of the time and may frequently be faster than generating a bunch of HTML (i.e. not in this case).
I always prefer using standard methods as shown below, because I know they should never break.  [Note that I don't check the 'class' attribute directly, since an element may have multiple classes.]
```
```
function adjustDates() {
    var i;
    var elms = document.getElementsByTagName("div");
    for (i = 0; i < elms.length; i++) {
        var e = elms[i];

        /* update timestamps with date */
        if (elementHasClass(e, "dated")) {
            var txt = YOUR_DIFFERENCE_CODE(e);
            e.replaceChild(document.createTextNode(txt), e.lastChild);
        }
    }
}
```
```


q:
I would like to show some links only to authenticated users in an asp.net mvc web application.

I use the template for an asp.net mvc web application in Visual Studio 2008 that came with the beta release of asp.net mvc.

I use forms authentication.

I would like to add something like the following to an existing view:

<a href="/Account/ChangePassword">Change password</a>

and only show the link to users who are logged in.

What is the simplest way to do that? I would like something as simple as security trimming of the web.sitemap that I have tried with asp.net web forms. (Can that be used with mvc? Or is it only for web forms?)

[A]
The following should work.  You'll also need to do something similar in the controller action for this in case the user inputs the URL by hand in their browser.  Or, as you say, you could restrict access to the action in the web.config.
```
```
<% if (HttpContext.Current.Request.IsAuthenticated) { %>
    Change password
 <% } %>
```
```


q: I need to quickly build a parser for a very simplified version of a html-like markup language in Java. In python, I would use pyparsing library to do this. Is there something similar for Java? Please, don't suggest libraries already out there for html parsing, my application is a school assignment which will demonstrate walking a tree of objects and serializing to text using visitor pattern, so I'm not thinking in real world terms here. Basically all I need here is tags, attributes and text nodes.

[A]
There are quite a number choices for stringhandling in java.
Maybe the very basic
```
java.util.Scanner
```
and
```
java.util.StringTokenizer
```
Classes are helpfull for you?
Another good choice is maybe
```
the org.apache.commons.lang.text
```
library.
http://commons.apache.org/lang/apidocs/org/apache/commons/lang/text/package-summary.html


q: How do you plot bar charts in gnuplot with text labels?

[A]
```
plot "data.dat" using 2: xtic(1) with histogram
```
Here data.dat contains data of the form
```
title 1
title2 3
"long title" 5
```


q:
I've used NUnit for years and I wanted to try XUnit.  So I installed XUnit and ran the executable that allowed you to run XUnit via TD.net.

I can't seem to run more than one test at a time. With NUnit + TD.net, I could click on the filename in the solution and run all the tests in the file.  I can't seem to do that with XUnit + TD.net.

Is this something I can do?

[A]
Short Answer: Copy the following into a .reg file on your computer, updating the path to where your Xunit dll resides, and then import it into your registry.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\MutantDesign\TestDriven.NET\TestRunners\xunit] @="4"
  "AssemblyPath"="C:\_Files\Programs\Programming\XUnit\xunit-1.1.0\xunit.runner.tdnet.dll"
  "TypeName"="Xunit.Runner.TdNet.TdNetRunner"
Long Answer:
I've run into this problem a couple of times, both on 32 and 64 bit versions of windows. TestDriven.net uses the registry to store a list of test frameworks avaialable. XUnit comes with an installer xunit.installer (run as admin) which is supposed to make the correct registry entries.
Usually I can get TD.net to work with XUnit for awhile, then I loose support. Today I was trying to get it to work on Windows 7 beta for the first time and couldn't get it to work at all.
After some searching I found the registry key that the information about the test framework should be entered in.
HKEY_LOCAL_MACHINE\SOFTWARE\MutantDesign\TestDriven.NET\TestRunners
Now on 64bit systems, there is also a key under the Wow6432Node, which is where it looks like the Xunit installer was setting the registry key.
Anyway, I exported the the the xunit registry key from HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MutantDesign\TestDriven.NET\TestRunners\xunit and, edited it, removing the Wow6432Node and then imported it. After restarting visual studio, everything works. I'll keep the registry file around in case it breaks again.


q:
I have an winforms application that was built using MVC.  The controller is subscribing to all of the events from the view (button clicks, etc) and connects multiple views with the model.

The problem is that the controller is now about 3000 lines of (hard to unit test) code.

What is the best practice to avoid getting controllers to do everything and become so big?

[A]
Depends on the situation, but assuming you are not at a point where a new controller should be created there are several approaches.
Much depends on your setup.  One common approach is to have a service layer or service agent which would do work for the controllers that is not specific.  The use of interfaced helpers or even static ones should remove some of the repetition.  300 lines does not sound to bad at all assuming it is broken into testable methods.
I would be interested too to hear of other opinions other than the oft repeated mantra of creating more controllers.  We use MVP and have experimented with sub controllers but this does rely on careful usage and is probably a bad idea.
It is common to have one controller per module in MVP, which would relate to a logical part of your application.  There should be a few clear ones within your domain and a few that are maybe a bit more difficult to distinguish.


q:
I'm giving my first steps on Python.  I saw that we don't have switch case statement,
so I would you guys implement a text Menu in python?

Thanks

[A]
You can use if...elif. If you have to choose a number, it would be like this:
```
```
n = chosenOption()
if(n == 0):
    doSomething()
elif(n == 1):
    doAnyOtherThing()
else:
    doDefaultThing()
```
```


q:
So far I've read some blog articles about cloud computing and services for hosting applications in the grid.

If I'd wanted to have a web application running in the cloud for as little cost as possible, what would be the best solution?

Let's assume the following configuration:

J2EE web application

Any free database (MySQL, PostgreSQL)

Any web container to deploy the web application to

What application stack would you suggest to be the best combination of services to

host

deploy

run

web applications?

As an additional requirement, the services chosen shouldn't require a lot about server management like firewall settings etc.

[A]
I have investigated
Amazon's ec2
solution recently. It is quite good and there are many pre-built boxes that you can use if you find one that suits your need. I think there will still be some server management involved...you cannot get away from that. But the pre built boxes will make it easier.
The cost is reasonable as you only pay for what you use.
[EDIT] The pre-built boxes are called Amazon Machine Images (AMIs).


q:
I'm trying to scrape a price from a web page using PHP and Regexes. The price will be in the format £123.12 or $123.12 (i.e., pounds or dollars).

I'm loading up the contents using libcurl. The output of which is then going into preg_match_all. So it looks a bit like this:

$contents = curl_exec($curl);

preg_match_all('/(?:\$|£)[0-9]+(?:\.[0-9]{2})?/', $contents, $matches);

So far so simple. The problem is, PHP isn't matching anything at all - even when there are prices on the page. I've narrowed it down to there being a problem with the '£' character - PHP doesn't seem to like it.

I think this might be a charset issue. But whatever I do, I can't seem to get PHP to match it! Anyone have any ideas?

(Edit: I should note if I try using the Regex Test Tool using the same regex and page content, it works fine)

[A]
Have you try to use \ in front of £
```
```
preg_match_all('/(\$|\£)[0-9]+(\.[0-9]{2})/', $contents, $matches);
```
```
I have try this expression with .Net with \£ and it works. I just edited it and removed some ":".
(source:
clip2net.com
)
Read my comment about the possibility of Curl giving you bad encoding (comment of this post).


q:
Is it possible to pump monochrome (graphical data with 1 bit image depth) texture into OpenGL?

I'm currently using this:

glTexImage2D( GL_TEXTURE_2D, 0, 1, game->width, game->height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, game->culture[game->phase] );

I'm pumping it with square array of 8 bit unsigned integers in GL_LUMINANCE mode (one 8 bit channel represents brightness of all 3 channels and full alpha), but it is IMO vastly ineffective, because the onlu values in the array are 0x00 and 0xFF.

Can I (and how) use simple one-bit per pixel array of booleans instead somehow? The excessive array size slows down any other operations on the array :(

[A]
The smallest uncompressed texture-format for luminance images uses 8 bits per pixel.
However, 1 bit per pixel images can be compressed without loss to the S3TC or DXT format. This will still not be 1 bit per pixel but somewhere between 2 and 3 bits.
If you really need 1 bit per pixel you can do so with a little trick. Load 8 1 bit per pixel textures as one 8 bit Alpha-only texture (image 1 gets loaded into bit 1, image 2 into bit 2 and so on). Once you've done that you can "address" each of the sub-textures using the alpha-test feature and a bit of texture environment programming to turn alpha into a color.
This will of only work if you have 8 1 bit per pixel textures and tricky to get right though.


q:
I am migrating a 1.1 winforms app to 2.0.  what are the main things i should immediately change because of generics.  Here what i have so far:

Replace all hashtables with generic dictionaries

Replace all arraylists with List<>

Replace all CollectionBase derive classes with : List<>

Any others that should be done immediately?

thks,
ak

[A]
Any others that should be done immediately?
Generally, change any mention of
```
IEnumerable
```
to
```
IEnumerable<T>
```
, where possible. Migration can be greatly helped by switching the whole namespace, i.e. un-
```
import
```
ing
```
System.Collections
```
in every file and instead importing
```
System.Collections.Generic
```
.
Also, search for mentions of
```
object
```
and/or usage of boxing in your code and consider whether this is still appropriate or should be replaced by generics.
As
jalf
reminded me in the comments, another important change is the switch to the generic version of
```
IComparable
```
where applicable.


q:
Hashtables have a syncroot property but generic dictionaries don't.  If I have code that does this:

lock (hashtable.Syncroot)
{
....
}

How do I replicate this if I am removing the hashtable and changing to generic dictionaries?

[A]
```
```
var dictionary = new Dictionary<int, string>();

lock(((ICollection) dictionary).SyncRoot)
{
    // ...
}
```
```


q:
I'm trying to write a VB.Net program that saves 1-2 million 5-field records (plus an indexed ID) to an MSAccess table every day.  The saving process currently takes 13-20 hours, which obviously can't be right.

Its a flat table with minimal indexing, currently only 156MB.  Except for one double field, the fields are small strings, dates, or longs.  The disk itself is a 15,000 SATA which is used only for this file.  The computer and the program are not doing anything else during the save routine.  The save routine is a simple FOR-NEXT loop that issues a short and simple INSERT statement for each record in the dataset.

Anyone got an ideas on what I need to change to get this to work better?

[A]
(Disclaimer: I know nothing much about Access)
What do any profiling tools say? (task manager will give you some clues - add more columns to the display to see I/Os, VM usage etc)? Is it doing a lot of disk accesses, or is it all CPU? Is it consuming huge amounts of memory?
The mention of an index concerns me since potentially that needs updating after every INSERT - can you turn the index off, do the creation, then index the complete file afterwards?
Is it linear in time? (i.e. if you create a file 10% of the size does it take 10% of the time)?


q:
I am using jquery and the getJSON method and I am wondering if there is a way to display a message saying loading before it loads my content. i know with the jquery ajax calls there is the before submit callbacks where you can have something but the getJSON only has like three options.

Any ideas?

[A]
there is the custom
```
.ajax
```
"before" and "success" events which you can trigger.
Normally however, you would just do something like
```
```
showLoadingAnimation();
  $.getJSON(  ..... function(){
      dontShowLoadingAnimation();
  });
```
```
or something similar.
Your question is however somewhat vauge, and its hard to ascertain what it is you want to do that you wouldn't already be able to do simply with javascript.


q:
I am loading JSON data to my page and using appendTo() but I am trying to fade in my results, any ideas?

$("#posts").fadeIn();
$(content).appendTo("#posts");

I saw that there is a difference between append and appendTo, on the documents.

I tried this as well:

$("#posts").append(content).fadeIn();

I got it, the above did the trick!

But I get "undefined" as one of my JSON values.

[A]
If you hide the content before you append it and chain the fadeIn method to that, you should get the effect that you're looking for.
```
```
// Create the DOM elements
$(content)
// Sets the style of the elements to "display:none"
    .hide()
// Appends the hidden elements to the "posts" element
    .appendTo('#posts')
// Fades the new content into view
    .fadeIn();
```
```


q:
I would like to inject binary data into an object in JavaScript. Is there a way to do this?

i.e.

var binObj = new BinaryObject('101010100101011');

Something to that effect. Any help would be great.

[A]
You can use parseInt:
```
var bin = parseInt('10101010', 2);
```
The second argument (the radix) is the base of the input.


q:
I'd like to create an application that would run on Google's appengine.

However, this application needs to be able to generate PDFs dynamically.

How could I do this?

[A]
You can use the
```
reportlab
```
library
to generate a PDF from Python. You can just include the ReportLab files in with your application's code, or you can include a
zip archive
of the ReportLab code, and insert it into your application's
```
sys.path
```
.


q:
I'm trying to get NAnt 0.86b1 running with VS2008 SP1 and x64 XP.

I have a basic build file (below) which gives the error
Solution format of file 'Solution.sln' is not supported.

<property name="nant.settings.currentframework" value="net-3.5" />

<target name="build" description="Full Rebuild" depends="clean,compile" />

<target name="clean" description="Cleans outputs">
    <delete dir="bin" failonerror="false" />
    <delete dir="obj" failonerror="false" />
</target>

<target name="compile" description="Compiles solution">
    <solution configuration="debug" solutionfile="Solution.sln" />
</target>

Has anyone else experienced this problem? I can't find anything useful out there about this.

[A]
You'll notice that the docs indicate that NAnt's
```
<solution
```
>
task doesn't support solution files newer than VS2003.
I recommend using
the
```
<msbuild>
```
task from nantcontrib
for all projects newer than VS2003.
Also, the .85 version of NAnt only supports framework versions up to 2.0. The purest way to get things working against the 3.5 framework is to use the
.86-beta1
versions of NAnt. You'll then be able to use the
```
<msbuild>
```
task against the 3.5 solution.


q: We are working on an inquiry management system using J2EE. We're looking at a feature, allowing users to send inquiries to particular mail-id and entering into the database. Catch is to automatically allocate it to some categories.


q:
I am very, very new to MYSQL.I tried to create a table named "option".
My SQL Query is :

create table option(

id int not null primary key auto_increment,

choice varchar(30)

)

While executing this query it shows the following error

Error Code : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option(
id int not null primary key auto_increment,
choice varchar(30)
)' at line 1
(0 ms taken)

If I try with the table name as "choice" it is working.

can we have the table name as "option" in mysql?

thanks

[A]
If you want to have a table name Option, you should be able to, just remember that whenever you use the table in a query, you will have to encase it in ` symbols.  Like this.
```
```
`option`
```
```
The ` key on the top left of your keyboard, with the tilde.


q:
This is often situation, but here is latest example:

Companies have various contact data (addresses, phone numbers, e-mails...) when they make job ad, they have checkboxes where they choose how they want to be contacted. It is basically descriptive data. User when reading an ad sees something like "You can apply by mail, in person...", except if it's "through web portal" or "by e-mail" because then appropriate buttons should appear. These options are stored in database, and client (owner of the site, not company making an ad) can change them (e.g. they can add "by telepathy" or whatever), yet if they tamper with "e-mail" and "web-portal" options, they screw their web site.

So how should I handle data where everything behaves same way except "this thing" that behaves this way, and "that thing" that behaves some other way, and data itself is live should be editable by client.

[A]
You've tagged your question as "language-agnostic", and not all languages cleanly support polymorphism, but that's the way I would approach this.
Each option has some type, and different types require different properties to be set. However, every type supports some sort of "render" method that can display the contact method as needed. Since the properties (phone number, or web address, etc.) are type-specific, you can validate the administrator's input when creating these "objects", to make sure that the necessary data is provided and valid. Since you implement the render method, rather than spitting out HTML provided by a user, you can ensure that the rendered page is correct. It's less flexible, but safer and more user friendly.
In the database, you can have one sparsely populated table that holds data for all types of contacts, or a "parent" table with common properties and sub-tables with type-specific properties. It depends on how many types you have and how different they are. In either case, you would have some sort of type indicator, so that you know the type of object to which the data should be be bound.


q:
I have a Java object which is able to configure itself given an XML configuration description (it takes other descriptions as well, but I'm interested in the XML at the moment). I'm wondering if I can embed the XML description directly into a Spring application context description. I'm imagining something like:

<bean id="myXMLConfiguredBean" class="com.example.Foo">
  <constructor-arg type="xml">
    <myconfig xmlns="http://example.com/foo/config">
      <bar>42</bar>
    </myconfig>
  </constructor-arg>
</bean>

but I have no idea if that - or something like it - is possible. I realise I could embed myconfig in a CDATA section, but that seems a bit ugly.

[A]
Spring's
XSD
allows
```
<constructor-arg>
```
to contain any XML through:
```
```
<xsd:element name="constructor-arg">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element ref="description" minOccurs="0" />
        <xsd:choice minOccurs="0" maxOccurs="1">
          <xsd:element ref="bean" />
          <xsd:element ref="ref" />
          <xsd:element ref="idref" />
          <xsd:element ref="value" />
          <xsd:element ref="null" />
          <xsd:element ref="list" />
          <xsd:element ref="set" />
          <xsd:element ref="map" />
          <xsd:element ref="props" />
          <!-- Any XML -->
          <xsd:any namespace="##other" processContents="strict" />
        </xsd:choice>
      </xsd:sequence>
      ...
  </xsd:complexType>
</xsd:element>
```
```
Where the
```
processContents
```
attribitutes can have one of
three values
strict: There must be a top-level declaration for the item available, or the item must have an
```
xsi:type
```
, and the item must be ·valid· as appropriate.
So, so long as your config XML has a schema, and you import it correctly, this should work.
Then, you would need to register a
PropertyEditor
for your XML using
CustomEditorConfigurer
Hope this helps


q:
I have a J2EE-based system which is running currently on Apache Tomcat. We are in discussions to move our production servers to the Glassfish server.

Can someone share their experiences with either of them?

[A]
Here's
quite an old comparison
. As such, the capabilities of each server have doubtless improved.
Edit: Here is
a current comparison.
Both are more than stable enough for production use though. It's really going to come down to features.


q:
I have a model that looks like this:

class Category(models.Model):
    name = models.CharField(max_length=60)

class Item(models.Model):
    name = models.CharField(max_length=60)
    category = models.ForeignKey(Category)

I want select count (just the count) of items for each category, so in SQL it would be as simple as this:

select category_id, count(id) from item group by category_id

Is there an equivalent of doing this "the Django way"? Or is plain SQL the only option? I am familiar with the count( ) method in Django, however I don't see how group by would fit there.

[A]
(
Update
: Full ORM aggregation support is now included in
Django 1.1
. True to the below warning about using private APIs, the method documented here no longer works in post-1.1 versions of Django.  I haven't dug in to figure out why; if you're on 1.1 or later you should use the real
aggregation API
anyway.)
The core aggregation support was already there in 1.0; it's just undocumented, unsupported, and doesn't have a friendly API on top of it yet.  But here's how you can use it anyway until 1.1 arrives (at your own risk, and in full knowledge that the query.group_by attribute is not part of a public API and could change):
```
```
query_set = Item.objects.extra(select={'count': 'count(1)'},
                               order_by=['-count']).values('count', 'category')
query_set.query.group_by = ['category_id']
```
```
If you then iterate over query_set, each returned value will be a dictionary with a "category" key and a "count" key.
You don't have to order by -count here, that's just included to demonstrate how it's done (it has to be done in the .extra() call, not elsewhere in the queryset construction chain).  Also, you could just as well say count(id) instead of count(1), but the latter may be more efficient.
Note also that when setting .query.group_by, the values must be actual DB column names ('category_id') not Django field names ('category').  This is because you're tweaking the query internals at a level where everything's in DB terms, not Django terms.


q:
A simple problem: If i use escape characters for a property such as

<mx:Image  id="img" toolTip="\\foo{\\bar}"

It wont validate toolTip and therefore not compile.

What is the solution ?

[A]
You can use ActionScipt for example in a creationComplete event handler and assign you tooltip and you won't have the same constraints as in MXML.
But you also can avoid these constraints in MXML by using CDATA:
```
```
<mx:Image id="img" source="foo.jpg" width="50" height="50">
<mx:toolTip>
    <![CDATA[\foo{\bar} or any usually forbidden characters as <, >, &, "'"...]]>
</mx:toolTip></mx:Image>
```
```


q:
My goal is to implements different image classification methods to show how they function and the advantages and disadvantages behind such methods. The ones I want to try and implement using Java include;

Minimum distance classifier

k-nearest neighbour classifier.

I was wondering what can be used to accomplish my task that already exists in Java so that I can alter the way the algorithms operates.

[A]
Although not entirely sure this is what you are looking for (sorry, your question is a bit unclear), if what you want is a library / system to help you with the
classification
part of the work, then you may want to look at Weka (
http://www.cs.waikato.ac.nz/ml/weka/
), in my opinion the best Java library for data mining experimentation.
If, instead, you are looking for algorithms that would allow you to analyze images in order to extract features that can, in turn, be used to perform the classification, you may want to start with targeted descriptions of such algorithms in Java, such as those found in the nice on-line book
Java Image Processing Cookbook
by Rafael Santos; here's a
direct link to the section "A Brief Tutorial on Supervised Image Classification"
.


q: I have a list of input words separated by comma.  I want to sort these words by alphabetical and length.  How can I do this without using the built-in sorting functions?

[A]
There is an entire area of study built around
sorting algorithms
.  You may want to choose a simple one and implement it.
Though it won't be the most performant, it shouldn't take you too long to implement a
bubble sort
.


q:
any tool to generate incremental release script for oracle database.

like Redgate DBComparer for SQLServer.

[A]
See
here
.
Other links, tools:
http://www.sqlmanager.net/de/products/oracle/dbcomparer
http://www.sqldelta.com/oraclebeta.html


q:
I have a structure:

struct pkt_
{
  double x;
  double y;
  double alfa;
  double r_kw;
};

typedef struct pkt_ pkt;

A table of these structures:

pkt *tab_pkt;

tab_pkt = malloc(ilosc_pkt * sizeof(pkt));

What I want to do is to sort tab_pkt by tab_pkt.alfa and tab_pkt.r:

qsort(tab_pkt, ilosc_pkt, sizeof(pkt), porownaj);

Where porownaj is a compare function, but how to write it? Here is my "sketch" of it:

int porownaj(const void *pkt_a, const void *pkt_b)
{
  if (pkt_a.alfa > pkt_b.alfa && pkt_a.r_kw > pkt_b.r_kw) return 1;
  if (pkt_a.alfa == pkt_b.alfa && pkt_a.r_kw == pkt_b.r_kw) return 0;
  if (pkt_a.alfa < pkt_b.alfa && pkt_a.r_kw < pkt_b.r_kw) return -1;
}

[A]
There are two parts to the problem - how to write the code, and how to compare the packet types.  You must ensure you always return a value.  Your code should also always be such that:
```
```
porownaj(&pkt_a, &pkt_b) == -porownaj(&pkt_b, &pkt_a)
```
```
Your outline comparison does not handle cases such as:
```
```
pkt_a->alfa >  pkt_b->alfa && pkt_a->r_kw <= pkt_b->r_kw
pkt_a->alfa <  pkt_b->alfa && pkt_a->r_kw >= pkt_b->r_kw
pkt_a->alfa == pkt_b->alfa && pkt_a->r_kw != pkt_b->r_kw
```
```
There is one more problem - is it appropriate to compare floating point values for exact equality?  That will depend on your application.
Mechanically, you have to convert the const void pointers to const structure pointers.  I use the explicit cast - C++ requires it, and I try to make my code acceptable to a C++ compiler even when it is really C code.
```
```
int porownaj(const void *vp1, const void *vp2)
{
     const pkt *pkt_a = (const pkt *)vp1;
     const pkt *pkt_b = (const pkt *)vp2;

     if (pkt_a->alfa >  pkt_b->alfa && pkt_a->r_kw >  pkt_b->r_kw) return 1;
     if (pkt_a->alfa == pkt_b->alfa && pkt_a->r_kw == pkt_b->r_kw) return 0;
     if (pkt_a->alfa <  pkt_b->alfa && pkt_a->r_kw <  pkt_b->r_kw) return -1;
     return 0;
 }
```
```
This does not deal with the bits that I cannot resolve since I am not party to the necessary information.  Note that, in general, multi-dimensional objects (such as complex numbers, or (x,y) or (x,y,z) coordinates) cannot simply be compared for greater than or less than or equal to.