q:
What is the simplest (shortest, fewest rules, and no warnings) way to parse both valid dates and numbers in the same grammar? My problem is that a lexer rule to match a valid month (1-12) will match any occurrence of 1-12. So if I just want to match a number, I need a parse rule like:

number: (MONTH|INT);

It only gets more complex when I add lexer rules for day and year. I want a parse rule for date like this:

date: month '/' day ( '/' year )? -> ^('DATE' year month day);

I don't care if month,day & year are parse or lexer rules, just so long as I end up with the same tree structure. I also need to be able to recognize numbers elsewhere, e.g.:

foo: STRING OP number -> ^(OP STRING number);
STRING: ('a'..'z')+;
OP: ('<'|'>');

[A]
The problem is that you seem to want to perform both syntactical and semantical checking in your lexer and/or your parser.  It's a common mistake, and something that is only possible in very simple languages.
What you really need to do is accept more broadly in the lexer and parser, and then perform semantic checks.  How strict you are in your lexing is up to you, but you have two basic options, depending on whether or not you need to accept zeroes preceding your days of the month: 1) Be really accepting for your INTs, 2) define DATENUM to only accept those tokens that are valid days, yet not valid INTs.  I recommend the second because there will be less semantic checks necessary later in the code (since INTs will then be verifiable at the syntax level and you'll only need to perform semantic checks on your dates.  The first approach:
```
```
INT: '0'..'9'+;
```
```
The second approach:
```
```
DATENUM: '0' '1'..'9';
INT: '0' | SIGN? '1'..'9' '0'..'9'*;
```
```
After accepting using these rules in the lexer, your date field would be either:
```
```
date: INT '/' INT ( '/' INT )?
```
```
or:
```
```
date: (INT | DATENUM) '/' (INT | DATENUM) ('/' (INT | DATENUM) )?
```
```
After that, you would perform a semantic run over your AST to make sure that your dates are valid.
If you're dead set on performing semantic checks in your grammar, however, ANTLR allows semantic predicates in the parser, so you could make a date field that checks the values like this:
```
```
date: month=INT '/' day=INT ( year='/' INT )? { year==null ? (/* First check /*) : (/* Second check */)}
```
```
When you do this, however, you are embedding language specific code in your grammar, and it won't be portable across targets.


q:
The following snippet is supposed to take the value of PROJECT (defined in the Makefile)
and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier_ir.h for PROJECTINCSTR

I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped?

#define PROJECT classifier

#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define MAKEINC(x) x ## _ir.h
#define PROJECTINC MAKEINC(PROJECT)
#define PROJECTINCSTR MAKESTR(PROJECTINC)

#include PROJECTINCSTR

Edit: The compiler should try to include classifier_ir.h, not PROJECT_ir.h.

[A] That barebone example works with gcc (v4.1.2) and tries to include "PROJECT_ir.h"

s: huggingface

c: devops

d: intermediate


q:
This must be a classic .NET question for anyone migrating from Java.

.NET does not seem to have a direct equivalent to java.io.StreamTokenizer, however the JLCA provides a SupportClass that attempts to implement it.  I believe the JLCA also provides a Tokenizer SupportClass that takes a String as the source, which I thought a StreamTokenizer would be derived from, but isn't.

What is the preferred way to Tokenize both a Stream and a String? or is there one? How are streams tokenized in .Net?  I'd like to have the flexibility that java.io.StreamTokenizer provides.  Any thoughts?

[A]
To tokenize a string, use
```
string.Split(...)
```
.


q:
I have been used to working with VS2005 and 2008 - using msbuild, etc, but I have inherited a set of projects that have to remain in vc6.0 for now.  I don't like opening each project in the developer studio and building.  I prefer to build form command line (I am automating the builds).  Is this possible?

I have tried the nmake utility, but I still need to open up the projects and save/export the make file.  This is tedious if the project changes - each time I have to save the make file.  nmake seems to work, but it had a problem when I changed the location of the project in my directory tree (I checked out of svn into a new clean dir to try the build).  It seemed to have hard coded paths in it, but I will have to check on that - it might have been a different problem.

Any alternatives out there?

Eventually I will migrate these to 2008, but for now that is not an option.

[A]
We use automated builds at my work place. Essentially just a batch file i fire off from the command line. Let me make sure i am allowed to post some sample code before i go ahead and post it. But yes, it IS possible to automate the build.
Sample Code:
:::::::: CompileSolution :::::::::::::::::::::::::
call X:\BuildTools\bin\BuildVbProj.bat
%COMPONENTNAME% %SOLUTIONDIR%
%PROJFILE% %BUILDOUTPUTFILE%
%PREBUILDFILE% if %ERRORLEVEL% NEQ 0
goto BuildErrors
goto Cleanup
EDIT:
The BuildVbProj.bat file ultimately calls VB6.exe in the Program Files\MS Visual Studio\VB98\ folder. Try calling it with "VB6.exe /?" or "VB6.exe -?" and it will show you a list of options. You can basically automate your process using those options.
There should be a similar exe for VC in the VC98 folder as well.


q: What are the alternative "design methods" to the Model View Controller? MVC seems to be popular (SO was built with it, I know that much) but is it the only method used?

[A]
There are many others:
Model View Presenter (MVP)
Supervising Controller
Passive View
Model View ViewModel (MVVM)
This is common in WPF applications (though
Prism
uses the MVP pattern (usually))


q:
I'm parsing XML results from an API call using PHP and xpath.

 $dom = new DOMDocument();
 $dom->loadXML($response->getBody());

 $xpath = new DOMXPath($dom);
 $xpath->registerNamespace("a", "http://www.example.com");

 $hrefs = $xpath->query('//a:Books/text()', $dom);

 for ($i = 0; $i < $hrefs->length; $i++) {
      $arrBookTitle[$i] = $hrefs->item($i)->data;
 }

 $hrefs = $xpath->query('//a:Books', $dom);

 for ($i = 0; $i < $hrefs->length; $i++) {
      $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
 }

This works but is there a way I can access both the text and the attribute from one query?  And if so how do you get to those items once query is executed?

[A]
Could you query for the concatenation?
```
```
$xpath->query('concat(//a:Books/text(), //a:Books/@DeweyDecimal)', $dom);
```
```
XSLT is an expression language in itself, and you can construct whatever specific format of return value you want from within the expression.


q:
I'm building a shared library with g++ 3.3.4. I cannot link to the library because I am getting

./BcdFile.RHEL70.so: undefined symbol: _ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE13insert_uniqueERKj

Which c++filt describes as

std::_Rb_tree<unsigned int, unsigned int, std::_Identity<unsigned int>, std::less<unsigned int>, std::allocator<unsigned int> >::insert_unique(unsigned int const&)

I thought this might have come from using hash_map, but I've taken that all out and switched to regular std::map. I am using g++ to do the linking, which is including -lstdc++.

Does anyone know what class would be instantiating this template? Or even better, which library I need to be linking to?

EDIT: After further review, it appears adding the -frepo flag when compiling has caused this, unfortunately that flag is working around gcc3.3 bug.

[A]
```
std::_Rb_Tree
```
might be a red-black tree, which would most likely be from using
```
map
```
. It should be part of
```
libstdc++
```
, unless your library is linking against a different version of
```
libstdc++
```
than the application, which from what you've said so far seems unlikely.
EDIT: Just to clarify, the red-black tree is the underlying data structure in
```
map
```
. All that
```
hash_map
```
does is hash the key before using it, rather than using the raw value.


q:
Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to?  I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working.  Examples would be much appreciated.  Thanks.

EDIT:  Here is what I have unsuccessfully tried:

class Comment(db.Model):
    series = db.ReferenceProperty(reference_class=Series);

    def series_id(self):
        return self._series

And in my template:

<a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a>

The result:

<a href="games/view-series.html?series=#comm59">more</a>

[A]
You're correct - the key is stored as the property name prefixed with '_'. You should just be able to access it directly on the model object. Can you demonstrate what you're trying? I've used this technique in the past with no problems.
Edit: Have you tried calling series_id() directly, or referencing _series in your template directly? I'm not sure whether Django automatically calls methods with no arguments if you specify them in this context. You could also try putting the @property decorator on the method.


q: How do the full text search systems of PostgreSQL and MySQL compare? Is any clearly better than the oder? In which way are they different?

[A]
Update:
Starting in MySQL 5.6, InnoDB
supports fulltext search
I'm not well versed in PostgreSQL unfortunately, but if you use the FULL TEXT search in MySQL you're immediately tied to MyISAM. If you want to use InnoDB (and if ACID compliance means anything to you, you should be using InnoDB) you're stuck using other solutions.
Two popular alternatives that are often rolled out are
Lucene
(an apache project with a Zend module if you're using PHP) and
Sphinx
.


q:
Say I have the following XML...

<root>
  <base>
    <tent key="1" color="red"/>
    <tent key="2" color="yellow"/>
    <tent key="3" color="blue"/>
  </base>
  <bucket>
    <tent key="1"/>
    <tent key="3"/>
  </bucket>
</root>

...what would the XPath be that returns that the "bucket" contains "red" and "blue"?

[A]
I think this will work:
```
```
/root/base/tent[/root/bucket/tent/@key = @key ]/@color
```
```


q:
I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.

IE: given

struct mstct {
    int myfield;
    int myfield2;
};

I could write:

mstct thing;
printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));

And get offset 4 for the output. How can I do it without that mstct thing declaration/allocating one?

I know that &<struct> does not always point at the first byte of the first field of the structure, I can account for that later.

[A]
How about the standard offsetof() macro (in stddef.h)?
Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:
```
```
#define OFFSETOF(type, field)    ((unsigned long) &(((type *) 0)->field))
```
```


q:
I am looking for an app that will let me type in code ON my cellphone. I don't need to compile or anything, and its not to program for the cellphone. Just something nice to have when an idea pops in my head.

Am I completely overlooking a simple code editor for Symbian S60v3 phones?

I am looking for something similar to CEdit which is for Windows Mobile.

[A]
You can use visual studio :
http://wiki.forum.nokia.com/index.php/Using_Visual_Studio_6.0_with_S60_3rd_Edition


q:
I'm looking to create an ValidationRule class that validates properties on an entity type object.  I'd really like to set the name of the property to inspect, and then give the class a delegate or a lambda expression that will be evaluated at runtime when the object runs its IsValid() method.  Does anyone have a snippet of something like this, or any ideas on how to pass an anonymous method as an argument or property?

Also, I'm not sure if I'm explaining what I'm trying to accomplish so please ask questions if I'm not being clear.

[A]
```
```
class ValidationRule {
    public delegate bool Validator();

    private Validator _v;

    public ValidationRule(Validator v) { _v = v; }

    public Validator Validator {
        get { return _v; }
        set { _v = value; }
    }

    public bool IsValid { get { return _v(); } }
}

var alwaysPasses = new ValidationRule(() => true);
var alwaysFails = new ValidationRule(() => false);

var textBoxHasText = new ValidationRule(() => textBox1.Text.Length > 0);
```
```
That should get you started. But, really, inheritance is far more appropriate here. The problem is simply that the
```
Validator
```
doesn't have access to any state that it doesn't close over, this means that it isn't as reusable as say
```
ValidationRules
```
that contain their own state. Compare the following class to the previous definition of
```
textBoxHasText
```
.
```
```
interface IValidationRule {
    bool IsValid { get; }
}

class BoxHasText : IValidationRule {
    TextBox _c;

    public BoxHasText(TextBox c) { _c = c; }

    public bool IsValid {
        get { return _c.Text.Length > 0; }
    }
}
```
```


q:
Basically I want to know how to set center alignment for a cell using VBScript...

I've been googling it and can't seem to find anything that helps.

[A]
There are many ways to select a cell or a range of cells, but the following will work for a single cell.
```
```
'Select a Cell Range
Range("D4").Select

'Set the horizontal and vertical alignment
With Selection
    .HorizontalAlignment = xlCenter
    .VerticalAlignment = xlBottom
End With
```
```
The HorizontalAlignment options are xlLeft, xlRight, and xlCenter


q: Is there a query in SQL Server 2005 I can use to get the server's IP or name?

[A]
```
```
select @@servername
```
```


q:
I'm an experienced programmer but just starting out with Flash/Actionscript. I'm working on a project that for certain reasons requires me to use Actionscript 2 rather than 3.

When I run the following (I just put it in frame one of a new flash project), the output is a 3 rather than a 1 ? I need it to be a 1.

Why does the scope of the 'ii' variable continue between loops?

var fs:Array = new Array();

for (var i = 0; i < 3; i++){

    var ii = i + 1;
    fs[i] = function(){
        trace(ii);
    }
}

fs[0]();

[A]
Unfortunately Actionscript 2.0 does not have a strong scope... especially on the time line.
```
```
var fs:Array = new Array();

for (var i = 0; i < 3; i++){

    var ii = i + 1;
    fs[i] = function(){
        trace(ii);
    }
}

fs[0]();
trace("out of scope: " + ii + "... but still works");
```
```


q:
How do I locate resources on the classpath in java?
Specifically stuff that ends in .hbm.xml.

My goal is to get a List of all resources on the classpath that end with ".hbm.xml".

[A]
You have to get a
classloader
, and test whether it's a URLClassLoader. If so, downcast and
get its URLs
. From there, open each as a JarFile and look at its
entries
. Apply a
regex
to each entry and see if it's one that interests you.
Clearly, this isn't fast. It's best to be given a name to be looked up in the classpath, perhaps listed in a standard file name in the META-INF directory of each classpath element, similar to the technique used by the
ServiceProvider facility
. Note that you can
list all files
with a given name on the classpath.


q: I wonder if They can work perfectly together...

[A] The simple answer is yes - I have both installed on the machine I'm replying to this question from. :=)


q:
This code works (C# 3)

double d;
if(d == (double)(int)d) ...;

Is there a better way to do this?

For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good)

Note: Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me.

[A]
You don't need the extra (double) in there. This works:
```
```
if (d == (int)d) {
 //...
}
```
```


q:
Is there a way to get the C/C++ preprocessor or a template or such to mangle/hash the __FILE__ and __LINE__ and perhaps some other external input like a build-number into a single short number that can be quoted in logs or error messages?

(The intention would be to be able to reverse it (to a list of candidates if its lossy) when needed when a customer quotes it in a bug report.)

[A]
Well, if you're displaying the message to the user yourself (as opposed to having a crash address or function be displayed by the system), there's nothing to keep you from displaying exactly what you want.
For example:
```
```
typedef union ErrorCode {
    struct {
        unsigned int file: 15;
        unsigned int line: 12; /* Better than 5 bits, still not great
                                  Thanks commenters!! */
        unsigned int build: 5;
    } bits;
    unsigned int code;
} ErrorCode;

unsigned int buildErrorCodes(const char *file, int line, int build)
{
    ErrorCode code;
    code.bits.line=line   & ((1<<12) - 1);
    code.bits.build=build & ((1<< 5) - 1);
    code.bits.file=some_hash_function(file) & ((1<<15) - 1);

    return code.code;
}
```
```
You'd use that as
```
```
buildErrorCodes(__FILE__, __LINE__, BUILD_CODE)
```
```
and output it in hex.  It wouldn't be very hard to decode...
(Edited -- the commenters are correct, I must have been nuts to specify 5 bits for the line number.  Modulo 4096, however, lines with error messages aren't likely to collide.  5 bits for build is still fine - modulo 32 means that only 32 builds can be outstanding AND have the error still happen at the same line.)


q:
If I have a UIView (or UIView subclass) that is visible, how can I tell if it's currently being shown on the screen (as opposed to, for example, being in a section of a scroll view that is currently off-screen)?

To maybe give you a better idea of what I mean, UITableView has a couple of methods for determining the set of currently visible cells. I'm looking for some code that can make a similar determination for any given UIView.

[A]
Not tried any of this yet. But
```
CGRectIntersectsRect()
```
,
```
-[UIView convertRect:to(from)View]
```
and
```
-[UIScrollView contentOffset]
```
seem to be your basic building blocks here.


q: I'm looking for books or online resources that go in detail over programming techniques for high performance computing using C++.

[A]
Take a look at
The ADAPTIVE Communication Environment (ACE)
.  It's a library of templates and objects for high performance applications in C++.  It has great cross-platform primitives for threading, networking, etc.


q:
What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?

I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.

Type type = typeof(FooBar)
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
type.GetConstructors(flags)
    .Where(constructor => constructor.GetParameters().Length == 0)
    .First();

[A]
```
```
type.GetConstructor(Type.EmptyTypes)
```
```


q: What are the best JVM settings you have found for running Eclipse?

[A]
Here's what I use (though I have them in the shortcut instead of the settings file):
eclipse.exe -showlocation -vm "C:\Java\jdk1.6.0_07\bin\javaw.exe" -vmargs -Xms256M -Xmx768M -XX:+UseParallelGC -XX:MaxPermSize=128M


q:
I have a method lets say:

private static String drawCellValue(
    int maxCellLength, String cellValue, String align) { }

and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?

Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.

Any ideas?

[A]
This should do it:
```
```
private enum Alignment { LEFT, RIGHT };
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}
```
```


q:
I'm setting up a server to offer JIRA and SVN.  I figure, I'll use LDAP to keep the identity management simple.

So, before I write one....  is there a good app out there to let users change their ldap password?  I want something that lets a user authenticate with ldap and update their password.  A form with username, old password, new password and verification would be enough.

I can write my own, but it seems silly to do so if there's already a good app out there that handles this....

Thanks for the help.


q:
There are many scenarios where it would be useful to call a Win32 function or some other DLL from a PowerShell script. to Given the following function signature:

bool MyFunction( char* buffer, int* bufferSize )

I hear there is something that makes this easier in PowerShell CTP 2, but I'm curious how this is best done in PowerShell 1.0. The fact that the function needing to be called  is using pointers could affect the solution (yet I don't really know).

So the question is what's the best way to write a PowerShell script that can call an exported Win32 function like the one above?

Remember for PowerShell 1.0.

[A]
There isn't any mechanism in PowerShell 1.0 to directly call Win32 API's. You could of course write a C# or VB.NET helper class to do this for you and call that from PowerShell.
Update: Take a look at -
http://blogs.msdn.com/powershell/archive/2006/04/25/583236.aspx
http://www.leeholmes.com/blog/ManagingINIFilesWithPowerShell.aspx


q:
Is there such a thing as unit test generation? If so...

...does it work well?

...What are the auto generation solutions that are available for .NET?

...are there examples of using a technology like this?

...is this only good for certain types of applications, or could it be used to replace all manually written unit testing?

[A]
Take a look at
Pex
. Its a Microsoft Research project. From the website:
Pex generates Unit Tests from hand-written Parameterized Unit Tests through Automated Exploratory Testing based on Dynamic Symbolic Execution.
UPDATE for 2019:
As mentioned in the comments, Pex is now called
IntelliTest
and is a feature of Visual Studio Enterprise Edition. It supports emitting tests in MSTest, MSTest V2, NUnit, and xUnit format and it is extensible so you can use it with other unit test frameworks.
But be aware of the following caveats:
Supports only C# code that targets the .NET Framework.
Does not support x64 configurations.
Available in Visual Studio
Enterprise Edition only


q: What are some methods of utilising Eclipse for Dependency Management?

[A]
I really like the
The Maven Integration for Eclipse (m2eclipse, Eclipse m2e)
. I use it purely for the dependency management feature. It's great not having to go out and download a bunch of new jars new each time I set up a project.


q:
I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this:

#ifdef OSisWindows
// do Windows-specific stuff
#else
// do Unix-specific stuff
#endif

Is there a way to do this? Is there a better way to do the same thing?

[A]
Some compilers will generate #defines that can help you with this. Read the compiler documentation to determine what they are.
MSVC
defines one that's
```
__WIN32__
```
,
GCC
has some you can see with
```
touch foo.h; gcc -dM foo.h
```


q: Is it possible to highlight text inside of a textarea using javascript? Either changing the background of just a portion of the text area or making a portion of the text selected?

[A]
Try this piece of code I wrote this morning, it will highlight a defined set of words:
```
```

        <title></title>

                <textarea cols="30" rows="10">

                </textarea>

```
```
This was written for another post (http://facebook.stackoverflow.com/questions/7497824/how-to-highlight-friends-name-in-facebook-status-update-box-textarea/7597420#7597420), but it seems to be what you're searching for.


q:
The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?

The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.

[A]
This sounds like modifying the
```
__builtin__
```
name space.  To do it:
```
```
import __builtin__
__builtin__.foo = 'some-value'
```
```
Do not use the
```
__builtins__
```
directly (notice the extra "s") - apparently this can be a dictionary or a module.  Thanks to ΤΖΩΤΖΙΟΥ for pointing this out, more can be found
here
.
Now
```
foo
```
is available for use everywhere.
I don't recommend doing this generally, but the use of this is up to the programmer.
Assigning to it must be done as above, just setting
```
foo = 'some-other-value'
```
will only set it in the current namespace.


q: Is there a way to deploy a given war file on Tomcat server? I want to do this without using the web interface.

[A]
you can edit the conf/server.xml and add an entry like this pointing to your war directory
```
```
<Context path="/strutsDisplayTag"
        reloadable="true"
        docBase="C:\work\learn\jsp\strutsDisplayTag"
        workDir="C:\work\learn\jsp\strutsDisplayTag\work" />
```
```
ELSE
 you can copy your .WAR file to the webapps directory of tomcat.


q: I have pushed my .htaccess files to the production severs, but they don't work. Would a restart be the next step, or should I check something else.

[A]
No
:
Apache allows for decentralized management of configuration via special files placed inside the web tree. The special files are usually called
```
.htaccess
```
, but any name can be specified in the
AccessFileName
directive... Since .htaccess files are read on every request, changes made in these files take immediate effect...


q:
I have a site, from which you can download an HTML file. This HTML file contains a form with hidden fields, which is right away posted back to the site using JavaScript. This is a way of allowing users to download to their own machine data that they edit on the site.

On some machines, you get an IE "yellow bar" when trying to open the file you saved. The "yellow bar" in IE is warning that the HTML is trying to run an Active X (which it is not, there is only JavaScript doing a submit() on a form). However if you receive the exact same HTML file by email, save it, and open it, you don't have this problem. (It looks like IE is putting some more constraint on what can be done in a HTML file you saved from web site.)

My question is: where can I find documentation on this IE security mechanism, and possibly how can I get around it?

Alex

[A]
I don't 100% follow what your JavaScript is submitting to, but if you're submitting back to the original site from the downloaded copy you'll have a problem using JavaScript as all browsers treat cross-domain JavaScript as a security violation.
JavaScript isn't allowed to read or write to any site not on the current domain


q:
I have a Button inside an UpdatePanel.  The button is being used as the OK button for a ModalPopupExtender.  For some reason, the button click event is not firing.  Any ideas?  Am I missing something?

<asp:updatepanel id="UpdatePanel1" runat="server">
    <ContentTemplate>
        <cc1:ModalPopupExtender ID="ModalDialog" runat="server"
            TargetControlID="OpenDialogLinkButton"
            PopupControlID="ModalDialogPanel" OkControlID="ModalOKButton"
            BackgroundCssClass="ModalBackground">
        </cc1:ModalPopupExtender>
        <asp:Panel ID="ModalDialogPanel" CssClass="ModalPopup" runat="server">
            ...
            <asp:Button ID="ModalOKButton" runat="server" Text="OK"
                        onclick="ModalOKButton_Click" />
        </asp:Panel>
    </ContentTemplate>
</asp:updatepanel>

[A]
It appears that a button that is used as the OK or CANCEL button for a ModalPopupExtender cannot have a click event.  I tested this out by removing the
```
```
OkControlID="ModalOKButton"
```
```
from the ModalPopupExtender tag, and the button click fires.  I'll need to figure out another way to send the data to the server.


q:
I have  DocumentRoot /var/www/test    in my .htaccess file. This is causing the apache server to give me a 500 internal server error.

The error log file shows:
alert] [client 127.0.0.1] /var/www/.htaccess: DocumentRoot not allowed here

AllowOveride All is set in my conf file.

Any idea why this is happening?

[A]
The
DocumentRoot
directive cannot appear in a
```
.htaccess
```
file. Put it in
```
httpd.conf
```
instead.


q:
Are there any unit testing solutions for Flex? or actionscript 3?

If so, what are their features? Any UI testing abilities? Functional testing? Any pointers, examples, libraries or tools that you can share?

[A]
FlexUnit is pretty awesome -
http://opensource.adobe.com/wiki/display/flexunit/FlexUnit
Also ASUnit -
http://asunit.org
They are both pretty similiar and both haven taken quite a bit from frameworks like JUnit.
FlexMonkey (
http://code.google.com/p/flexmonkey/
) although I haven't used it myself seems to do UI unit testing.


q:
You know those websites that let you type in your checking account number and the routing number, and then they can transfer money to and from your account?

How does that work?  Any good services or APIs for doing that?  Any gotchas?

[A]
The banks do have APIs for doing this, but only approved people/companies are allowed to interface with these systems.  Because it actually involves transferring money around, the security requirements are pretty high in terms of how you handle the account numbers on your system.
Many sites that offer this feature for buying goods actually use a third party system to handle the actual money transfer into their account.   This lowers the amount of trouble to implement the API, as well as putting the burden of security on the third party handling the money transfers.
If you are serious about setting up a system where you can accept bank account numbers, and exchange funds, you should contact your bank, and see what the actual requirements for implementing such a system.  Each bank has their own system, along with their own rate regarding the cost of these transactions.
Some third parties I'm aware of are
Moneris
Cactus
Beanstream
I'm in Canada, although I think Moneris and Cactus operate in the US.  I think Beanstream doesn't.  Again, you can talk to your bank, and they can probably get you in touch with a third party who will help you with the transactions.


q:
A legacy embedded system is implemented using a cooperative multi-tasking scheduler.

The system essentially works along the following lines:

Task A does work

When Task A is done, it yields the processor.

Task B gets the processor and does work.

Task B yields

...

Task n yields

Task A gets scheduled and does work

One big Circular Queue: A -> B -> C -> ... -> n -> A

We are porting the system to a new platform and want to minimize system redesign.

Is there a way to implement that type of cooperative multi-tasking in vxWorks?

[A]
While VxWorks is a priority based OS, it is possible to implement this type of cooperative multi-tasking.
Simply put all the tasks at the
same
priority.
In your code, where you do your
yield
, simply insert a 'taskDelay(0);'
Note that you have to make sure the kernel time slicing is disabled (kernelTimeSlice(0)).
All tasks at the same priority are in a Queue.  When a task yields, it gets put at the end of the queue.  This would implement the type of algorithm described.


q:
I've heard that the automotive industry has something called MISRA C.

What are the relevant standards for other high reliability/availability/security industries, such as

Space

Aircraft

Banking/financial

Automotive

Medical

Defense/Military

???

-Adam

[A]
if you're asking specifically about coding, the MISRA presents some guidelines for avoiding common mistakes in C.
however, there's a lot more to good software than coding. The "bible" of the aviation industry for sw development is DO-178B. It tells you what questions need to be addressed in the various design phases and how the answers should be documented. It's an ENORMOUS amount of paperwork, but if you're trying to keep planes in the air, you want the weakest point to be the human (pilot), not the software.


q:
I want to do something like the following in spring:

<beans>
    ...
    <bean id="bean1" ... />
    <bean id="bean2">
        <property name="propName" value="bean1.foo" />
...

I would think that this would access the getFoo() method of bean1 and call the setPropName() method of bean2, but this doesn't seem to work.

[A]
I think you have to inject bean1, then get
```
foo
```
manually because of a timing issue. When does the framework resolve the value of the target bean?
You could create a pointer bean and configure that.
```
```
class SpringRef {
  private String targetProperty;
  private Object targetBean;

  //getters/setters

  public Object getValue() {
    //resolve the value of the targetProperty on targetBean.
  }
}
```
```
Common-BeanUtils
should be helpful.


q:
I recently asked a question about tracing Linq-to-Entities

I think that one of the answers was not right, as they refer to using the DataContext. Is there a DataContext for LINQ-to-Entities? If so, how do I get it?

[A]
Apparently, LinqToEntities uses an
ObjectContext
instead of DataContext.
It is hilarious that the object team made a DataContext and the data team made an ObjectContext (and on to DataQuery vs ObjectQuery, etc.) "Naming is Hard!"
Update, for .net 4 with EF4.1, you might also be interested in
DbContext
when working with LinqToEntities.  See
also
.


q:
I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this.

Thanks
Dirk

[A]
With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version:
First, install 2.6rc2. You can download the source from the
Python website
. Standard
```
./configure && make && sudo make install
```
installation style.
Next, remove the
```
/usr/bin/python
```
symlink. Do
not
remove
```
/usr/bin/python2.5
```
. Add a symlink to 2.6 with
```
ln -s /usr/local/bin/python2.6 /usr/bin/python
```
.
Once again, I think this is a terrible idea. There is almost certainly a better way to do whatever you're trying to accomplish.
Migrating installed libraries is a much longer process. Look in the
```
/usr/lib/python2.5/site-packages/
```
and
```
/usr/local/lib/python2.5/site-packages/
```
directories. Any libraries installed to them will need to be re-installed with 2.6. Since you're not using a packaged Python version, you cannot use Ubuntu's packages -- you'll have to manually upgrade all the libraries yourself. Most of them can probably be installed with
```
sudo easy_install <name>
```
, but some like PyGTK+ are not so easy. You'll have to follow custom installation procedures for each such library.


q:
From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story).

I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task.  I just don't understand how they get set up and how they actually work.  Any examples would be appreciated.

[A]
Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function
```
on_event()
```
and data pointers to a framework function
```
watch_events()
```
(for example). When an event happens, your function is called with your data and some event-specific data.
Callbacks are also used in GUI programming. The
GTK+ tutorial
has a nice section on the
theory of signals and callbacks
.


q:
I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#.

Example:

2748 to "ABC"


q:
My zune just updated to 3.0 (didn't even realize they were releasing something new!) and the update came with two games, but the Zune marketplace does not have games.

Where do I go to get started, and what are the capabilities of the Zune in terms of games/apps?

[A]
Well, first, you must download the Microsoft XNA 3.0 CTP. Read the documentation, which will explain the capabilities. But, from memory:
No hardware accelerated 3d (obviously, you can create a software 3d engine and then render the result to a 2d sprite, but... Don't expect much in terms of performance ;))
No XACT, you must use a new sound API


q:
I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the only way to assign the events is to programmatically write

myUserControl.MyCustomEvent += new MyUserControl.MyCustomEventHandler(EventHandlerFunction);

this is fine for me I guess but when someone else comes to use my UserControl they are not going to know that these events exist (unless they read the library doco...yeah right). I know the event will show up using Intellisense but it would be great if it could show in the properties window too.

[A]
Make sure your events are exposed as public. For example...
```
```
[Browsable(true)]
public event EventHandler MyCustomEvent;
```
```


q:
I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread.

I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can't remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework.

Is there any good general purpose way to indefinitely pause a worker thread in C# .NET.

I haven't had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I'm open to any new features (if any) that exist in the .NET 3.5 framework, but I'd like to know of solution that also works in the 2.0 framework since that's what I use at work and it would be good to know just in case.

[A]
The
Threading in C#
ebook summarises Thread.Suspend and Thread.Resume thusly:
The deprecated Suspend and Resume methods have two modes – dangerous and useless!
The book recommends using a synchronization construct such as an
AutoResetEvent
or
Monitor.Wait
to perform thread suspending and resuming.


q:
I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.

Is there some kind of configuration that needs to be done somewhere for this work?

[A]
Sure. From a
mindless technology article called "Make Python Scripts Droppable in Windows"
, you can add a drop handler by adding a registry key:
Here’s a registry import file that you can use to do this. Copy the
  following into a .reg file and run it
  (Make sure that your .py extensions
  are mapped to Python.File).
```
```
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler]
@="{60254CA5-953B-11CF-8C96-00AA00B8708C}"
```
```
This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with
```
86C86720-42A0-1069-A2E8-08002B30309D
```
.
A comment in that post indicates that one can enable dropping on "no console Python files (
```
.pyw
```
)" or "compiled Python files (
```
.pyc
```
)" by using the
```
Python.NoConFile
```
and
```
Python.CompiledFile
```
classes.


q: How do I change Oracle from port 8080? My Eclipse is using 8080, so I can't use that.

[A]
I assume you're talking about the Apache server that Oracle installs.  Look for the file httpd.conf.
Open this file in a text editor and look for the line
Listen 8080
or
Listen {ip address}:8080
Change the port number and either restart the web server or just reboot the machine.


q:
I started playing around with Linq today and ran into a problem I couldn't find an answer to. I was querying a simple SQL Server database that had some employee records. One of the fields is the full name (cn). I thought it would be interesting to group by the first name by splitting the full name at the first space. I tried

group by person.cn.Split(separators)[0]

but ran into a lengthy runtime exception (looked a lot like a C++ template instantiation error).

Then I tried grouping by a few letters of the first name:

group by person.cn.Substring(0,5)

and that worked fine but is not what I want.

I'm wondering about two things:

Why does the first example not work when it looks so close to the second?

Knowing that behind the scenes it's SQL stuff going on, what's a good way to do this kind of thing efficiently

Thanks,

Andrew

[A]
Split has no translation into SQL.
So, how to do this string manipulation without split?  Cheat like hell (untested):
```
```
string oneSpace = " ";
string fiftySpace = "                                                  ";

var query =
  from person in db.Persons
  let lastname = person.cn.Replace(oneSpace, fiftySpace).SubString(0, 50).Trim()
  group person by lastname into g
  select new { Key = g.Key, Count = g.Count };
```
```


q:
I remember seeing the code for a Highpass filter a few days back somewhere in the samples, however I can't find it anywhere now! Could someone remember me where the Highpass filter implementation code was?

Or better yet post the algorithm?

Thanks!

[A]
From the idevkit.com forums:
```
```
#define kFilteringFactor 0.1
static UIAccelerationValue rollingX=0, rollingY=0, rollingZ=0;

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

    // Calculate low pass values

    rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));
    rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor));
    rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor));

    // Subtract the low-pass value from the current value to get a simplified high-pass filter

    float accelX = acceleration.x - rollingX;
    float accelY = acceleration.y - rollingY;
    float accelZ = acceleration.z - rollingZ;

    // Use the acceleration data.

}
```
```


q:
Functional languages are good because they avoid bugs by eliminating state, but also because they can be easily parallelized automatically for you, without you having to worry about the thread count.

As a Win32 developer though, can I use Haskell for some dlls of my application? And if I do, is there a real advantage that would be taken automatically for me?  If so what gives me this advantage, the compiler?

Does F# parallelize functions you write across multiple cores and cpu's automatically for you?  Would you ever see the thread count in task manager increase?

Basically my question is, how can I start using Haskell in a practical way, and will I really see some benefits if I do?

[A]
I'm currently learning Haskell myself, when you start out learning it, it doesn't seem very intriguing because the learning experience is NOTHING like learning a language like C#, it's a whole new world, but I noticed I could write very very complex expressions in just a few lines of code, when I looked back at the code it was much more concise, it was small and tight. I'm absolutely loving it! You can indeed write real-world programs that will be smaller, easier to maintain, and much more complex then most other languages allow, I vote for you to learn it!!
Good luck.


q:
I have a series of ASCII flat files coming in from a mainframe to be processed by a C# application. A new feed has been introduced with a Packed Decimal (COMP-3) field, which needs to be converted to a numerical value.

The files are being transferred via FTP, using ASCII transfer mode. I am concerned that the binary field may contain what will be interpreted as very-low ASCII codes or control characters instead of a value - Or worse, may be lost in the FTP process.

What's more, the fields are being read as strings. I may have the flexibility to work around this part (i.e. a stream of some sort), but the business will give me pushback.

The requirement read "Convert from HEX to ASCII", but clearly that didn't yield the correct values.  Any help would be appreciated; it need not be language-specific as long as you can explain the logic of the conversion process.

[A]
I apologize if I am way off base here, but perhaps this code sample I'll paste here could help you. This came from VBRocks...
```
```
Imports System
Imports System.IO
Imports System.Text
Imports System.Text.Encoding

'4/20/07 submission includes a line spacing addition when a control character is used:
'   The line spacing is calculated off of the 3rd control character.
'
'   Also includes the 4/18 modification of determining end of file.

'4/26/07 submission inclues an addition of 6 to the record length when the 4th control
'   character is an 8.  This is because these records were being truncated.

'Authored by Gary A. Lima, aka. VBRocks

''' <summary>
''' Translates an EBCDIC file to an ASCII file.
''' </summary>
''' <remarks></remarks>
Public Class EBCDIC_to_ASCII_Translator

#Region " Example"

    Private Sub Example()
        'Set your source file and destination file paths
        Dim sSourcePath As String = "c:\Temp\MyEBCDICFile"
        Dim sDestinationPath As String = "c:\Temp\TranslatedFile.txt"

        Dim trans As New EBCDIC_to_ASCII_Translator()

        'If your EBCDIC file uses Control records to determine the length of a record, then this to True
        trans.UseControlRecord = True

        'If the first record of your EBCDIC file is filler (junk), then set this to True
        trans.IgnoreFirstRecord = True

        'EBCDIC files are written in block lengths, set your block length (Example:  134, 900, Etc.)
        trans.BlockLength = 900

        'This method will actually translate your source file and output it to the specified destination file path
        trans.TranslateFile(sSourcePath, sDestinationPath)

        'Here is a alternate example:
        'No Control record is used
        'trans.UseControlRecord = False

        'Translate the whole file, including the first record
        'trans.IgnoreFirstRecord = False

        'Set the block length
        'trans.BlockLength = 134

        'Translate...
        'trans.TranslateFile(sSourcePath, sDestinationPath)

        '*** Some additional methods that you can use are:

        'Trim off leading characters from left side of string (position 0 to...)
        'trans.LTrim = 15

        'Translate 1 EBCDIC character to an ASCII character
        'Dim strASCIIChar as String = trans.TranslateCharacter("S")

        'Translate an EBCDIC character array to an ASCII string
        'trans.TranslateCharacters(chrEBCDICArray)

        'Translates an EBCDIC string to an ASCII string
        'Dim strASCII As String = trans.TranslateString("EBCDIC String")

    End Sub

#End Region    'Example

    'Translate characters from EBCDIC to ASCII

    Private ASCIIEncoding As Encoding = Encoding.ASCII
    Private EBCDICEncoding As Encoding = Encoding.GetEncoding(37)  'EBCDIC

    'Block Length:  Can be fixed (Ex:  134).
    Private miBlockLength As Integer = 0
    Private mbUseControlRec As Boolean = True        'If set to False, will return exact block length
    Private mbIgnoreFirstRecord As Boolean = True    'Will Ignore first record if set to true  (First record may be filler)
    Private miLTrim As Integer = 0

    ''' <summary>
    ''' Translates SourceFile from EBCDIC to ASCII.  Writes output to file path specified by DestinationFile parameter.
    ''' Set the BlockLength Property to designate block size to read.
    ''' </summary>
    ''' <param name="SourceFile">Enter the path of the Source File.</param>
    ''' <param name="DestinationFile">Enter the path of the Destination File.</param>
    ''' <remarks></remarks>
    Public Sub TranslateFile(ByVal SourceFile As String, ByVal DestinationFile As String)

        Dim iRecordLength As Integer     'Stores length of a record, not including the length of the Control Record (if used)
        Dim sRecord As String = ""         'Stores the actual record
        Dim iLineSpace As Integer = 1    'LineSpace:  1 for Single Space, 2 for Double Space, 3 for Triple Space...

        Dim iControlPosSix As Byte()      'Stores the 6th character of a Control Record (used to calculate record length)
        Dim iControlRec As Byte()          'Stores the EBCDIC Control Record (First 6 characters of record)
        Dim bEOR As Boolean                'End of Record Flag
        Dim bBOF As Boolean = True      'Beginning of file
        Dim iConsumedChars As Integer = 0     'Stores the number of consumed characters in the current block
        Dim bIgnoreRecord As Boolean = mbIgnoreFirstRecord   'Ignores the first record if set.

        Dim ControlArray(5) As Char         'Stores Control Record (first 6 bytes)
        Dim chrArray As Char()              'Stores characters just after read from file

        Dim sr As New StreamReader(SourceFile, EBCDICEncoding)
        Dim sw As New StreamWriter(DestinationFile)

        'Set the RecordLength to the RecordLength Property (below)
        iRecordLength = miBlockLength

        'Loop through entire file
        Do Until sr.EndOfStream = True

            'If using a Control Record, then check record for valid data.
            If mbUseControlRec = True Then
                'Read the Control Record (first 6 characters of the record)
                sr.ReadBlock(ControlArray, 0, 6)

                'Update the value of consumed (read) characters
                iConsumedChars += ControlArray.Length

                'Get the bytes of the Control Record Array
                iControlRec = EBCDICEncoding.GetBytes(ControlArray)

                'Set the line spacing  (position 3 divided by 64)
                '   (64 decimal = Single Spacing; 128 decimal = Double Spacing)
                iLineSpace = iControlRec(2) / 64

                'Check the Control record for End of File
                'If the Control record has a 8 or 10 in position 1, and a 1 in postion 2, then it is the end of the file
                If (iControlRec(0) = 8 OrElse iControlRec(0) = 10) AndAlso _
                    iControlRec(1) = 1 Then

                    If bBOF = False Then
                        Exit Do

                    Else
                        'The Beginning of file flag is set to true by default, so when the first
                        '   record is encountered, it is bypassed and the bBOF flag is set to False
                        bBOF = False

                    End If    'If bBOF = Fals

                End If    'If (iControlRec(0) = 8 OrElse

                'Set the default value for the End of Record flag to True
                '   If the Control Record has all zeros, then it's True, else False
                bEOR = True

                'If the Control record contains all zeros, bEOR will stay True, else it will be set to False
                For i As Integer = 0 To 5
                    If iControlRec(i) > 0 Then
                        bEOR = False

                        Exit For

                    End If    'If iControlRec(i) > 0

                Next    'For i As Integer = 0 To 5

                If bEOR = False Then
                    'Convert EBCDIC character to ASCII
                    'Multiply the 6th byte by 6 to get record length
                    '   Why multiply by 6?  Because it works.
                    iControlPosSix = EBCDICEncoding.GetBytes(ControlArray(5))

                    'If the 4th position of the control record is an 8, then add 6
                    '    to the record length to pick up remaining characters.
                    If iControlRec(3) = 8 Then
                        iRecordLength = CInt(iControlPosSix(0)) * 6 + 6

                    Else
                        iRecordLength = CInt(iControlPosSix(0)) * 6

                    End If

                    'Add the length of the record to the Consumed Characters counter
                    iConsumedChars += iRecordLength

                Else
                    'If the Control Record had all zeros in it, then it is the end of the Block.

                    'Consume the remainder of the block so we can continue at the beginning of the next block.
                    ReDim chrArray(miBlockLength - iConsumedChars - 1)
                    'ReDim chrArray(iRecordLength - iConsumedChars - 1)

                    'Consume (read) the remaining characters in the block.
                    '   We are not doing anything with them because they are not actual records.
                    'sr.ReadBlock(chrArray, 0, iRecordLength - iConsumedChars)
                    sr.ReadBlock(chrArray, 0, miBlockLength - iConsumedChars)

                    'Reset the Consumed Characters counter
                    iConsumedChars = 0

                    'Set the Record Length to 0 so it will not be processed below.
                    iRecordLength = 0

                End If    ' If bEOR = False

            End If    'If mbUseControlRec = True

            If iRecordLength > 0 Then
                'Resize our array, dumping previous data.  Because Arrays are Zero (0) based, subtract 1 from the Record length.
                ReDim chrArray(iRecordLength - 1)

                'Read the specfied record length, without the Control Record, because we already consumed (read) it.
                sr.ReadBlock(chrArray, 0, iRecordLength)

                'Copy Character Array to String Array, Converting in the process, then Join the Array to a string
                sRecord = Join(Array.ConvertAll(chrArray, New Converter(Of Char, String)(AddressOf ChrToStr)), "")

                'If the record length was 0, then the Join method may return Nothing
                If IsNothing(sRecord) = False Then

                    If bIgnoreRecord = True Then
                        'Do nothing - bypass record

                        'Reset flag
                        bIgnoreRecord = False

                    Else
                        'Write the line out, LTrimming the specified number of characters.
                        If sRecord.Length >= miLTrim Then
                            sw.WriteLine(sRecord.Remove(0, miLTrim))

                        Else
                            sw.WriteLine(sRecord.Remove(0, sRecord.Length))

                        End If    ' If sRecord.Length >= miLTrim

                        'Write out the number of blank lines specified by the 3rd control character.
                        For i As Integer = 1 To iLineSpace - 1
                            sw.WriteLine("")

                        Next    'For i As Integer = 1 To iLineSpace

                    End If    'If bIgnoreRecord = True

                    'Obviously, if we have read more characters from the file than the designated size of the block,
                    '   then subtract the number of characters we have read into the next block from the block size.
                    If iConsumedChars > miBlockLength Then
                        'If iConsumedChars > iRecordLength Then
                        iConsumedChars = iConsumedChars - miBlockLength
                        'iConsumedChars = iConsumedChars - iRecordLength

                    End If

                End If    'If IsNothing(sRecord) = False

            End If    'If iRecordLength > 0

            'Allow computer to process  (works in a class module, not in a dll)
            'Application.DoEvents()

        Loop

        'Destroy StreamReader (sr)
        sr.Close()
        sr.Dispose()

        'Destroy StreamWriter (sw)
        sw.Close()
        sw.Dispose()

    End Sub

    ''' <summary>
    ''' Translates 1 EBCDIC Character (Char) to an ASCII String
    ''' </summary>
    ''' <param name="chr"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ChrToStr(ByVal chr As Char) As String
        Dim sReturn As String = ""

        'Convert character into byte
        Dim EBCDICbyte As Byte() = EBCDICEncoding.GetBytes(chr)

        'Convert EBCDIC byte to ASCII byte
        Dim ASCIIByte As Byte() = Encoding.Convert(EBCDICEncoding, ASCIIEncoding, EBCDICbyte)

        sReturn = Encoding.ASCII.GetString(ASCIIByte)

        Return sReturn

    End Function

    ''' <summary>
    ''' Translates an EBCDIC String to an ASCII String
    ''' </summary>
    ''' <param name="sStringToTranslate"></param>
    ''' <returns>String</returns>
    ''' <remarks></remarks>
    Public Function TranslateString(ByVal sStringToTranslate As String) As String
        Dim i As Integer = 0
        Dim sReturn As New System.Text.StringBuilder()

        'Loop through the string and translate each character
        For i = 0 To sStringToTranslate.Length - 1
            sReturn.Append(ChrToStr(sStringToTranslate.Substring(i, 1)))

        Next

        Return sReturn.ToString()

    End Function

    ''' <summary>
    ''' Translates 1 EBCDIC Character (Char) to an ASCII String
    ''' </summary>
    ''' <param name="sCharacterToTranslate"></param>
    ''' <returns>String</returns>
    ''' <remarks></remarks>
    Public Function TranslateCharacter(ByVal sCharacterToTranslate As Char) As String

        Return ChrToStr(sCharacterToTranslate)

    End Function

    ''' <summary>
    ''' Translates an EBCDIC Character (Char) Array to an ASCII String
    ''' </summary>
    ''' <param name="sCharacterArrayToTranslate"></param>
    ''' <returns>String</returns>
    ''' <remarks>Remarks</remarks>
    Public Function TranslateCharacters(ByVal sCharacterArrayToTranslate As Char()) As String
        Dim sReturn As String = ""

        'Copy Character Array to String Array, Converting in the process, then Join the Array to a string
        sReturn = Join(Array.ConvertAll(sCharacterArrayToTranslate, _
                            New Converter(Of Char, String)(AddressOf ChrToStr)), "")

        Return sReturn

    End Function

    ''' <summary>
    ''' Block Length must be set.  You can set the BlockLength for specific block sizes (Ex:  134).
    ''' Set UseControlRecord = False for files with specific block sizes (Default is True)
    ''' </summary>
    ''' <value>0</value>
    ''' <returns>Integer</returns>
    ''' <remarks></remarks>
    Public Property BlockLength() As Integer
        Get
            Return miBlockLength

        End Get
        Set(ByVal value As Integer)
            miBlockLength = value

        End Set
    End Property

    ''' <summary>
    ''' Determines whether a ControlKey is used to calculate RecordLength of valid data
    ''' </summary>
    ''' <value>Default value is True</value>
    ''' <returns>Boolean</returns>
    ''' <remarks></remarks>
    Public Property UseControlRecord() As Boolean
        Get
            Return mbUseControlRec

        End Get
        Set(ByVal value As Boolean)
            mbUseControlRec = value

        End Set
    End Property

    ''' <summary>
    ''' Ignores first record if set (Default is True)
    ''' </summary>
    ''' <value>Default is True</value>
    ''' <returns>Boolean</returns>
    ''' <remarks></remarks>
    Public Property IgnoreFirstRecord() As Boolean
        Get
            Return mbIgnoreFirstRecord

        End Get

        Set(ByVal value As Boolean)
            mbIgnoreFirstRecord = value

        End Set
    End Property

    ''' <summary>
    ''' Trims the left side of every string the specfied number of characters.  Default is 0.
    ''' </summary>
    ''' <value>Default is 0.</value>
    ''' <returns>Integer</returns>
    ''' <remarks></remarks>
    Public Property LTrim() As Integer
        Get
            Return miLTrim

        End Get

        Set(ByVal value As Integer)
            miLTrim = value

        End Set
    End Property

End Class
```
```


q: I am developing a TCP/IP client that has to deal with a proprietary binary protocol. I was considering using user-defined types to represent the protocol headers, and using CopyMemory to shuffle data to and from the UDT and a byte array. However, it appears that VB6 adds padding bytes to align user-defined types. Is there any way to force VB6 to not pad UDT's, similar to the #pragma pack directive available in many C/C++ compilers? Perhaps a special switch passed to the compiler?

[A]
No.
Your best bet is to write the low level code in C or C++ (where you do have
```
#pragma pack
```
), then expose the interface via COM.


q:
ToolStripItems show Active highlighting when you mouse over them, even if the form they are in is not in focus.   They do not, however, show their tooltips, unless the form is  focused.   I have seen the ToolStrip 'click-though' hack.  Anyone know how to make a ToolStripButton show its tooltip when its parent form is not in focus?

Thanks!

[A]
Perhaps one of the two approaches in this code will kick you off in the right direction...
```
```
public Form1()
{
    InitializeComponent();

    tooltip = new ToolTip();
    tooltip.ShowAlways = true;
}

private ToolTip tooltip;
private void toolStripButton_MouseHover(object sender, EventArgs e)
{
    if (!this.Focused)
    {
        ToolStripItem tsi = (ToolStripItem)sender;
        tooltip.SetToolTip(toolStrip1, tsi.AutoToolTip ? tsi.ToolTipText : tsi.Text);
        /*tooltip.Show(tsi.AutoToolTip ? tsi.ToolTipText : tsi.Text, this,
            new Point(toolStrip1.Left, toolStrip1.Bottom));*/
    }
}

private void toolStripButton_MouseLeave(object sender, EventArgs e)
{
    tooltip.RemoveAll();
}
```
```
The problem with the first is you can't set it to the button directly, it doesn't inherit from Control, and the tooltip won't show up unless you're over the strip but not over a button.
The problem with the second (commented out way) is it doesn't display at all. Not quite sure why, but maybe you can debug it out.


q:
I've recently seen the light of EventWaitHandle's powerful behavior in C# and decided to move some functionality in a sister application to do the same. The only problem is that the sister app is written in C.

No big deal, I'm using pthreads, which have a pthread_cond_t datatype that allows for signalling. My only question is, is it possible for a cond to be 'signalled' before something is waiting on it?

Right now my testing says no. That is, if ThreadA fires a signal before ThreadB is waiting, ThreadB will wait indefinately. Is there another pthread type that I can use that behaves closer to the functionality of the EventWaitHandle in C#? An object is signalled, meaning that the first thread to wait on it, will pass immediately, and set it to unsignalled.

Wrapping the pthread_cond into another data structure wouldn't be too hard to achieve this. But again, is this functionality already available in the pthread library?

[A]
If you're using condition variables correctly, this won't matter.
The basic flow of your code should be (in pseudocode):
```
```
lock(lockobj);
while (!signalled) {
    wait(condvar);
}
signalled = false;
unlock(lockobj);
```
```
on the waiting side, and:
```
```
lock(lockobj);
signalled = true;
notify(condvar);
unlock(lockobj);
```
```
on the signalling side. (Of course, the lock object and condition variable used have to be the same on both sides.) Hope this helps!


q:
Possible Duplicate:

  Emacs, switch to previous window

other-window advances me to the next window in the current frame, but I also want a way to move back to the previous window.

Emacs has next-buffer and previous-buffer, but no analogous interactive functions for window navigation.  Just other-window.

[A]
Put this in your .emacs, and bind it to whatever key you like
```
(defun back-window ()
  (interactive)
  (other-window -1))
```


q:
Windbg fans claim that it is quite powerful and I tend to agree. But when it comes to debugging STL containers, I am always stuck. If the variable is on the stack, the !stl extension sometimes figures it out, but when a container with a complex type (e.g. std::vector<TemplateField, std::allocator<TemplateField> >) is on the heap or part of some other structure, I just don't know how to view its contents.

Appreciate any tips, pointers.

[A]
I often find debugger support for STL data types inadequate.  For this reason I'm increasingly using
logging frameworks and logging statements
.  I used to think that these are for people who can't use a debugger, but I now realize that they offer real value.  They allow you to embed portable debugging knowledge in your code and maintain it together with the code.  In contrast, work you do in the debugger is typically ephemeral.


q:
I'm trying to print out the date in a certain format:

NSDate *today = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateStr = [dateFormatter stringFromDate:today];

If the iPhone is set to 24 hour time, this works fine, if on the other hand the user has set it to 24 hour time, then back to AM/PM (it works fine until you toggle this setting) then it appends the AM/PM on the end even though I didn't ask for it:

20080927030337 PM

Am I doing something wrong or is this a bug with firmware 2.1?

Edit 1: Made description clearer

Edit 2 workaround: It turns out this is a bug, to fix it I set the AM and PM characters to "":

[dateFormatter setAMSymbol:@""];
[dateFormatter setPMSymbol:@""];

[A]
Using the code you posted on both the simulator and a phone with the 2.1 firmware and 24-hour time set to off, I never had an AM/PM appended to dateStr when I do:
```
```
NSLog(@"%@", dateStr);
```
```
Are you doing anything else with dateStr that you didn't post here? How are you checking the value?
Follow up
Try turning the am/pm setting on then off. I didn't have the problem either, until I did that. I am printing it out the same way you are.
Okay, I see it when I do this also. It's gotta be a bug. I recommend you
file a bug report
and just check for and filter out the unwanted characters in the meantime.


q:
Is it possible to use PHP's SimpleXML functions to create an XML object from scratch?  Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?

I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.

I've done it using the DOMDocument functions, although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)

[A]
Sure you can.  Eg.
```
```
<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
```
```
Output
```
```
<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>
```
```
Have fun.


q: Using C / C++ socket programming, and the "read(socket, buffer, BUFSIZE)" method.  What exactly is the "buffer" I know that char and byte are the same thing, but does it matter how many elements the byte array has in it? Does the buffer need to be able to hold the entire message until the null character?

[A]
BUFSIZE should be equal to the size of your buffer in bytes. read() will stop reading when the buffer is full. Here is an example:
```
```
#define MY_BUFFER_SIZE 1024

char mybuffer[MY_BUFFER_SIZE];
int nBytes = read(sck, mybuffer, MY_BUFFER_SIZE);
```
```


q:
My company has a subsidiary with a slow Internet connection. Our developers there suffer to interact with our central Subversion server. Is it possible to configure a slave/mirror  for them? They would interact locally with the server and all the commits would be automatically synchronized to the master server.

This should work as transparently as possible for the developers. Usability is a must.

Please, no suggestions to change our version control system.

[A]
You should try
The SVK version control system
SVK
is a decentralized version control system built with the robust Subversion filesystem. It supports repository mirroring, disconnected operation, history-sensitive merging, and integrates with other version control systems, as well as popular visual merge tools.
On this link there is text about
Using SVK to Synchronize SVN Repositories


q:
Can anyone tell me, where on the web I can find an explanation for Bron-Kerbosch algorithm for clique finding or explain here how it works?

I know it was published in "Algorithm 457: finding all cliques of an undirected graph" book, but I can't find free source that will describe the algorithm.

I don't need a source code for the algorithm, I need an explanation of how it works.

[A]
Try finding someone with an ACM student account who can give you a copy of the paper, which is here:
http://portal.acm.org/citation.cfm?doid=362342.362367
I just downloaded it, and it's only two pages long, with an implementation in Algol 60!


q:
I'm trying to copy a bunch of files below a directory and a number of the files have spaces and single-quotes in their names.  When I try to string together find and grep with xargs, I get the following error:

find .|grep "FooBar"|xargs -I{} cp "{}" ~/foo/bar
xargs: unterminated quote

Any suggestions for a more robust usage of xargs?

This is on Mac OS X 10.5.3 (Leopard) with BSD xargs.

[A]
```
find . -print0 | grep --null 'FooBar' | xargs -0 ...
```
I don't know about whether
```
grep
```
supports
```
--null
```
, nor whether
```
xargs
```
supports
```
-0
```
, on Leopard, but on GNU it's all good.


q:
If you have a project, that releases a library and an application, how you handle version-numbers between the two.

Example: Your project delivers a library, that convert different file-formats into each other. The library is released for inclusion into other applications. But you also release a command-line-application, that uses this library and implements an interface to the functionality.

New releases of the library lead to new releases of the application (to make use of all new features), but new releases of the application may not trigger new releases of the library. Now how are the versions numbers handled: Completely independent or should library- and application-version be dependent in some way?

[A]
Completely independent version numbers, but the command line (or any other dependent) app should say which version of the library it was compiled against in the help section or a banner.
That way you will be able to tell which functionality will the apps have and reduce potential confusion, especially given that somebody could compile a newer app version against an old library for any reason. Also, you decouple them and can add features on the library without depending on release of a new app version and so on.
If you are sure you will always want all the apps and library to go in lockstep then you could use same numbers, but that's adding a constraint for not a strong reason.


q:
Do you do automated testing on a complex workflow system like K2?

We are building a system with extensive integration between Sharepoint 2007 and K2. I can't even imagine where to start with automated testing as the workflow involves multiple users interacting with Sharepoint, K2 workflows and custom web pages.

Has anyone done automated testing on a workflow server like K2? Is it more effort than it's worth?

[A]
I'm having a similar problem testing workflow-heavy MOSS-based application. Workflows in our case are based on WWF.
My idea is to mock pretty much everything that you can't control from unit tests - documents storage, authentication, user rights and actions, sharepoint-specific parts of workflows for sharepoint (these mocks should be thoroughly tested to mirror behavior of real components).
You use inversion of control to make code choose which component to use at runtime - real or mock.
Then you can write system-wide tests to test workflows behavior - setting up your own environment, checking how workflow engine reacts. These tests are too big to call them unit-tests, still it is automated testing.
This approach seems to work on trivial cases, but I still have to prove it is worthy to use in real-world workflows.


q:
I have a pretty complicated Linq query that I can't seem to get into a LinqDataSsource for use in a GridView:

IEnumerable<ticket> tikPart = (
    from p in db.comments where
        p.submitter == me.id &&
        p.ticket.closed == DateTime.Parse("1/1/2001") &&
        p.ticket.originating_group != me.sub_unit
    select p.ticket
    ).Distinct();

How can I get this into a GridView?  Thank you!

[A]
```
```
gridview.DataSource = tikPart.ToList();
gridview.DataBind();
```
```


q: I want to obtain the current number of window handles and the system-wide window handle limit in C#. How do I go about this?

[A]
As Raymond Chen put it some time ago, if you're thinking about window handle limits, you're probably doing something wrong :)
Anyway, I bet there's no special C# way to do it, because it's very system-specific. You can use the same functions that you would use in a C++ application. Call the functions using P/Invoke. To learn how to write the imports, go to
pinvoke.net
.
Edit: As I understand your question, I assume you already know how to do that in a Win32 application.


q:
I've been trying to display text using a Quartz context, but no matter what I've tried I simply haven't had luck getting the text to display (I'm able to display all sorts of other Quartz objects though). Anybody knows what I might be doing wrong?

example:

-(void)drawRect:(CGRect)rect
{
  // Drawing code
  CGContextRef  context = UIGraphicsGetCurrentContext();
  CGContextSelectFont(context, "Arial", 24, kCGEncodingFontSpecific);
  CGContextSetTextPosition(context,80,80);
  CGContextShowText(context, "hello", 6);
  //not even this works
  CGContextShowTextAtPoint(context, 1,1, "hello", 6);
}

[A]
Here is a fragment of code that I'm using.
```
```
UIColor *mainTextColor = [UIColor whiteColor];
[mainTextColor set];
drawTextLjust(@"Sample Text", 8, 50, 185, 18, 16);
```
```
And:
```
```
static void drawTextLjust(NSString* text, CGFloat y, CGFloat left, CGFloat right,
                          int maxFontSize, int minFontSize) {
    CGPoint point = CGPointMake(left, y);
    UIFont *font = [UIFont systemFontOfSize:maxFontSize];
    [text drawAtPoint:point forWidth:right - left withFont:font
       minFontSize:minFontSize actualFontSize:NULL
       lineBreakMode:UILineBreakModeTailTruncation
       baselineAdjustment:UIBaselineAdjustmentAlignBaselines];
}
```
```


q:
The heart of any good web app is it's offline capability and JavaScript functionality. Currently what tools and wrappers are availability for the desktop web app maker to cross over to the mobile market? What would be the necessary read ups for such a team?

Clarifications:
I am searching for information on how much offline capabilities and JavaScript functionality has improved on the Mobile phones. I know that the term 'mobile phones' are too broad. I am aware of offline solutions like Gears, Adobe AIR, Silverlight etc. But are these really for mobile phones?

How much has JavaScript improved on Mobile Webkit Browsers such as iPhone and Symbians? OperaMini also claims some JavaScript functionality.

[A]
I'm not totally sure I understand your question, but you'll probably want to take a look at the
iPhone Dev Center
and the
Google Android SDK
to start.
Blackberry
also has a Development Program. Beyond that, you may want to look into
WAP and WML
.
Google Gears
,
Adobe Air
, and
Mozilla's XUL
will give you some offline capability, but to my knowledge they won't wrap an existing desktop app and make it available for the web.


q:
I have a flash application running Flash 9 (CS3).  Application is able to control the Softkeys when this flash application is loaded in the supported mobile device.  But, the application doesn't have control when the same is embedded in HTML page and browsed via supported mobile device.  Any ideas how to make this work?

Thanks
Keerthi

[A]
There is no special way to receive soft key events when embedded in HTML - if the browser/OS gives the events to Flash, then you can catch them like any other key event:
```
```
var myListener = new Object();
myListener.onKeyDown = function() {
    var code = Key.getCode();
    if (code==ExtendedKey.SOFT1) {
        trace("I got a soft key event");
    }
}
Key.addListener(myListener);
```
```
However, you'll find that most phones/browsers will not give you soft key events when your SWF is embedded in HTML. This isn't part of the Flash Lite spec - strictly speaking I believe they could give you those events if they wanted to, but most phones simply use those keys for browser functions, and consume them before they get to Flash.
Note that you can check at runtime whether or not softkeys are available:
```
```
trace(System.capabilities.hasMappableSoftKeys);
trace(System.capabilities.softKeyCount);
```
```


q: As per the title. For those who don't know, it's basically Ada for .Net.

[A]
According to [wikipedia](
http://en.wikipedia.org/wiki/A_Sharp_(.NET))
, A#.Net has been folded into "GNAT for .Net" for future releases
AdaCore
has taken over this development, and announced "GNAT for .NET", which is a fully supported .NET product with all of the features of A# and more.


q: One of the stated goals of the PureMVC framework is to avoid platform dependencies in order to be portable. Considering that because of language and API differences application code will always be heavily dependent on the platform, and that avoiding platform dependencies makes the framework reinvent the wheel and/or only provide a least-common-denominator feature set, in what way does the portability of the framework benefit me as an application developer?

[A]
I've worked with PureMVC. They're trying to implement their stuff in quite a lot of languages. You may be right about the least common denominator, but overall, it's not a bad framework, and I've seen a really nice AS3 app in PureMVC.
I don't think they're talking about portability in terms of porting actual code. The idea there is more that you're using a generalized MVC architecture, which you could apply to other projects and other languages.
They're trying to say that if you become familiar with the PureMVC pattern, you could potentially come into a new PureMVC codebase, even if it's another language, and you would already know the lay of the land.
You might also say that developers who develop good PureMVC skills are likely to develop good habits which will translate as they go from language to language.  But then again, maybe not.. for the reasons you mentioned.


q:
What are the differences in implementing interfaces implicitly and explicitly in C#?

When should you use implicit and when should you use explicit?

Are there any pros and/or cons to one or the other?

Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.

I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.

Could anyone touch on that aspect as well?

[A]
Implicit
is when you define your interface via a member on your class.
Explicit
is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean:
```
IList.CopyTo
```
would be implicitly implemented as:
```
```
public void CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}
```
```
and explicitly as:
```
```
void ICollection.CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}
```
```
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
```
```
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
```
```
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the
next post
in this thread for excellent reasoning behind each.


q:
I want to change the title showing in a page based on information I pick up from within the page (eg to show the number of inbox messages)

document.getElementsByTagName('title')[0].innerHTML="foo"; does change the title tag, but firefox does not update the displayed title (in window and tags) when this happens.

Is this possible?

[A]
Try using this instead:
```
document.title = "MyTitle";
```


q:
I've recently read the Yahoo manifesto Best Practices for Speeding Up Your Web Site. They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.

But where exactly and when?

Should we put it before closing </html> or after ? And above all, when should we still put it in the <head> section?

[A]
If you put it at the bottom, it loads last, hence speeding up the speed that the user can see the page. It does need to be before the final
```
</html>
```
though otherwise it won't be part of the DOM.
If the code is needed instantly though, then put it in the head.
It's best to put things like blog widgets at the bottom so that if they don't load, it doesn't affect the usability of the page.


q: I'm using netbeans on ubuntu, I would like to add some fonts to it. Could anyone tell me how this is done ?


q:
In MySQL, If I have a list of date ranges (range-start and range-end). e.g.

10/06/1983 to 14/06/1983
15/07/1983 to 16/07/1983
18/07/1983 to 18/07/1983

And I want to check if another date range contains ANY of the ranges already in the list, how would I do that?

e.g.

06/06/1983 to 18/06/1983 = IN LIST
10/06/1983 to 11/06/1983 = IN LIST
14/07/1983 to 14/07/1983 = NOT IN LIST

[A]
This is a classical problem, and it's actually easier if you reverse the logic.
Let me give you an example.
I'll post one period of time here, and all the different variations of other periods that overlap in some way.
```
```
|-------------------|          compare to this one
               |---------|                contained within
           |----------|                   contained within, equal start
                   |-----------|          contained within, equal end
           |-------------------|          contained within, equal start+end
     |------------|                       not fully contained, overlaps start
                   |---------------|      not fully contained, overlaps end
     |-------------------------|          overlaps start, bigger
           |-----------------------|      overlaps end, bigger
     |------------------------------|     overlaps entire period
```
```
on the other hand, let me post all those that doesn't overlap:
```
```
|-------------------|          compare to this one
     |---|                                ends before
                                 |---|    starts after
```
```
So if you simple reduce the comparison to:
```
```
starts after end
ends before start
```
```
then you'll find all those that doesn't overlap, and then you'll find all the non-matching periods.
For your final NOT IN LIST example, you can see that it matches those two rules.
You will need to decide wether the following periods are IN or OUTSIDE your ranges:
```
```
|-------------|
   |-------|                       equal end with start of comparison period
                         |-----|   equal start with end of comparison period
```
```
If your table has columns called range_end and range_start, here's some simple SQL to retrieve all the matching rows:
```
```
SELECT *
FROM periods
WHERE NOT (range_start > @check_period_end
           OR range_end < @check_period_start)
```
```
Note the
NOT
in there. Since the two simple rules finds all the
non-matching
rows, a simple NOT will reverse it to say:
if it's not one of the non-matching rows, it has to be one of the matching ones
.
Applying simple reversal logic here to get rid of the NOT and you'll end up with:
```
```
SELECT *
FROM periods
WHERE range_start <= @check_period_end
      AND range_end >= @check_period_start
```
```


q:
This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?

try {
  // Do something
} catch(IOException e) {
  throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
  // Will the ApplicationException be caught here?
}

I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.

[A]
No, since the new
```
throw
```
is not in the
```
try
```
block directly.


q: I have written an application which has a modal form. How can I ensure that this form does not lose the focus even when an other application is started?

[A]
Actually, this is exactly the sort of thing you shouldn't be doing.
There's too many programs around that assume they control the computer they're installed on.  It is the user of your application that should be in control.
That's why later versions of Windows disallowed stealing of focus instead insisting on just blinking the entry in the task list bar.
You may well find a way to do it (though I doubt it), but I urge you to rethink it.  I'd be interested in knowing why you thought it was necessary.


q:
My company releases a small software product for which I've recently been taking over the development side.  It is a C# Windows Forms application.

One of the things I've noticed is that much of the information about how the software is used is filtered through my superiors and I get the feeling that I'm missing important detail in some of the messages.

I realise I'll have to work on the management issues with this situation, however in order to give another view on the problem I've been considering a technological solution.  Perhaps something similar to the "Microsoft Customer Experience Improvement Program".

I was wondering if anyone out there had any experience or advice monitoring and reporting on user behaviour in their applications?

[A]
I would suggest you get your application to write its "usage information" somewhere and then,
with the users permission
, transmit it electronically every so often.
Note the emphasis above.  Depending on your jurisdiction, you could get into serious trouble transmitting any sort of data from someone else's computer without permission.
You're more likely to get permission if:
1/ You make it clear, on install or update, that your program will collect information and transmit it only with permission.
2/ You explain clearly what the information is and that it only holds "usage information", nothing that can be traced back to the user of the software (NO serial numbers, etc).
3/ You request permission to transmit infrequently.  If I had an obnoxious program that asked me daily, I'd soon stop using it altogether.


q:
Is there a way of comparing two bitmasks in Transact-SQL to see if any of the bits match? I've got a User table with a bitmask for all the roles the user belongs to, and I'd like to select all the users that have any of the roles in the supplied bitmask. So using the data below, a roles bitmask of 6 (designer+programmer) should select Dave, Charlie and Susan, but not Nick.

User Table
----------
ID  Username  Roles
1   Dave      6
2   Charlie   2
3   Susan     4
4   Nick      1

Roles Table
-----------
ID  Role
1   Admin
2   Programmer
4   Designer

Any ideas? Thanks.

[A]
Use the Transact-SQL
bitwise AND operator
"&" and compare the result to zero.  Even better, instead of coding the roles as bits of an integer column, use boolean columns, one for each role.  Then your query would simply be designer AND programmer friendly.  If you expect the roles to change a lot over the lifetime of your application, then use a many-to-many table to map the association between users and their roles.  both alternatives are more portable than relying on the existence of the bitwise-AND operator.


q: In PHP, a string enclosed in "double quotes" will be parsed for variables to replace whereas a string enclosed in 'single quotes' will not. In Python, does this also apply?

[A]
No
:
2.4.1. String and Bytes literals
...In plain English: Both types of literals can be enclosed in matching single quotes (
```
'
```
) or double quotes (
```
"
```
). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (
```
\
```
) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character...


q:
I have a simple message box in a WPF application that is launched as below:

private void Button_Click(object sender, RoutedEventArgs e)
{
   MessageBox.Show("Howdy", "Howdy");
}

I can get white to click my button and launch the message box.

UISpy shows it as a child of my window I couldn't work out the method to access it.

How do I get access to my MessageBox to verify its contents?

[A]
Found it! The window class has a MessageBox method that does the trick:
```
```
var app = Application.Launch(@"c:\ApplicationPath.exe");
        var window = app.GetWindow("Window1");
        var helloButton = window.Get<Button>("Hello");
        Assert.IsNotNull(helloButton);
        helloButton.Click();
        var messageBox = window.MessageBox("Howdy");
        Assert.IsNotNull(messageBox);
```
```


q:
How do you do your own fonts?  I don't want a heavyweight algorithm (freetype, truetype, adobe, etc) and would be fine with pre-rendered bitmap fonts.

I do want anti-aliasing, and would like proportional fonts if possible.

I've heard I can use Gimp to do the rendering (with some post processing?)

I'm developing for an embedded device with an LCD.  It's got a 32 bit processor, but I don't want to run Linux (overkill - too much code/data space for too little functionality that I would use)

C.  C++ if necessary, but C is preferred.  Algorithms and ideas/concepts are fine in any language...

-Adam

[A]
In my old demo-scene days I often drew all characters in the font in one big bitmap image. In the code, I stored the (X,Y) coordinates of each character in the font, as well as the width of each character. The height was usually constant throughout the font. If space isn't an issue, you can put all characters in a grid, that is - have a constant distance between the top-left corner of each character.
Rendering the text then becomes a matter of copying one letter at a time to the destination position. At that time, I usually reserved one color as being the "transparent" color, but you could definitely use an alpha-channel for this today.
A simpler approach, that can be used for small b/w fonts, is to define the characters directly in code:
```
```
LetterA  db 01111100b
         db 11000110b
         db 11000110b
         db 11111110b
         db 11000110b
         db 11000110b
```
```
The XPM file format is actually a file format with C syntax that can be used as a hybrid solution for storing the characters.


q:
I know most people think that as a bad practice but when you are trying to make your class public interface only work with references, keeping pointers inside and only when necessary, I think there is no way to return something telling that the value you are looking doesn't exist in the container.

class list {
    public:
        value &get(type key);
};

Let's think that you don't want to have dangerous pointers being saw in the public interface of the class, how do you return a not found in this case, throwing an exception?

What is your approach to that? Do you return an empty value and check for the empty state of it? I actually use the throw approach but I introduce a checking method:

class list {
   public:
      bool exists(type key);
      value &get(type key);
};

So when I forget to check that the value exists first I get an exception, that is really an exception.

How would  you do it?

[A]
Interesting question. It's a problem in C++ to exclusively use references I guess - in Java the references are more flexible and can be null. I can't remember if it's legal C++ to force a null reference:
```
```
MyType *pObj = nullptr;
return *pObj
```
```
But I consider this dangerous. Again in Java I'd throw an exception as this is common there, but I rarely see exceptions used so freely in C++.
If I was making a puclic API for a reusable C++ component and had to return a reference, I guess I'd go the exception route.
My real preference is to have the API return a pointer; I consider pointers an integral part of C++.


q:
According to this article Silverlight 2 Beta 2 supports the DataContractJsonSerializer object. But, when I try to use it VS says

"Type 'DataContractJsonSerializer' is not defined".

I have a method marked as ScriptableMember that gets called from JavaScript and is passed an Object. Inside this method I need to serialize the object to a string (preferably JSON) and then save it in isolated storage.

Does Silverlight 2 Beta 2 really support DataContractJsonSerializer? Or would anyone recommend a different method of saving the JavaScript created ScriptObject in the Isolated Storage?

[A]
For now, the only solution to this that I have found is to use the ASP.NET AJAX JavaScriptSerializer to do the JSON serialization/deserialization in JavaScript, and then just use Silverlight to store/retrieve the resulting string.
```
```
Sys.Serialization.JavaScriptSerializer.serialize(obj);
Sys.Serialization.JavaScriptSerializer.deserialize(json);
```
```


q: Can I use JavaScript to check (irrespective of scrollbars) if an HTML element has overflowed its content? For example, a long div with small, fixed size, the overflow property set to visible, and no scrollbars on the element.

[A]
Try comparing
```
element.scrollHeight
```
/
```
element.scrollWidth
```
to
```
element.offsetHeight
```
/
```
element.offsetWidth
```
http://developer.mozilla.org/en/DOM/element.offsetWidth
http://developer.mozilla.org/en/DOM/element.offsetHeight
http://developer.mozilla.org/en/DOM/element.scrollWidth
http://developer.mozilla.org/en/DOM/element.scrollHeight


q:
this wiki page gave a general idea of how to convert a single char to ascii http://en.wikibooks.org/wiki/Ruby_Programming/ASCII

But say if I have a string and I wanted to get each character's ascii from it, what do i need to do?

"string".each_byte do |c|
      $char = c.chr
      $ascii = ?char
      puts $ascii
end

It doesn't work because it's not happy with the line $ascii = ?char

syntax error, unexpected '?'
      $ascii = ?char
                ^

[A]
The
```
c
```
variable already contains the char code!
```
```
"string".each_byte do |c|
    puts c
end
```
```
yields
```
```
115
116
114
105
110
103
```
```