q:
I have several identical elements with different attributes that I'm accessing with SimpleXML:

<data>
    <seg id="A1"/>
    <seg id="A5"/>
    <seg id="A12"/>
    <seg id="A29"/>
    <seg id="A30"/>
</data>

I need to remove a specific seg element, with an id of "A12", how can I do this?  I've tried looping through the seg elements and unsetting the specific one, but this doesn't work, the elements remain.

foreach($doc->seg as $seg)
{
    if($seg['id'] == 'A12')
    {
        unset($seg);
    }
}

[A]
While
SimpleXML
provides
a way to remove
XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the
DOM
extension.
dom_import_simplexml()
will help you with converting your
```
SimpleXMLElement
```
into a
```
DOMElement
```
.
Just some example code (tested with PHP 5.2.5):
```
```
$data='<data>
    <seg id="A1"/>
    <seg id="A5"/>
    <seg id="A12"/>
    <seg id="A29"/>
    <seg id="A30"/>
</data>';
$doc=new SimpleXMLElement($data);
foreach($doc->seg as $seg)
{
    if($seg['id'] == 'A12') {
        $dom=dom_import_simplexml($seg);
        $dom->parentNode->removeChild($dom);
    }
}
echo $doc->asXml();
```
```
outputs
```
```
<?xml version="1.0"?>
<data><seg id="A1"/><seg id="A5"/><seg id="A29"/><seg id="A30"/></data>
```
```
By the way: selecting specific nodes is much more simple when you use XPath (
SimpleXMLElement->xpath
):
```
```
$segs=$doc->xpath('//seq[@id="A12"]');
if (count($segs)>=1) {
    $seg=$segs[0];
}
// same deletion procedure as above
```
```


q:
On Ubuntu Linux with Gnome, running my Swing application by double clicking on the jar file in Gnomes file browser leads to errors because required libraries that are dynamically loaded via the Java Plugin Framework (residing in subdirectories) are not found.

The base libraries for the framework itself are resolved correctly, as stated in my executable jar's manifest file.
However, once the framework launches, no plugins (not even the one specifying my platform) are found.

Launching the application from the terminal via

java -jar myjar.jar

works like a charm, ad does running the application by double-clicking a shell-script.

However, I'd like to avoid a terminal window. (I'm a Windows person, maybe it won't annoy linux people as it does annoy those on windows.)

The problem is reproducible across several Linux systems.
Is there something I need to do so Java resolves the libraries correctly?

[A]
Java loads jars in order in its classpath, i.e. jar1:jar2:jar3... Most java applications ship with some sort of script which sets all of this up by specifying a classpath and a list of jars that the application will need.
What you want to do is probably not terribly advisable, as it means globally specifying a collection of jars that you want to load with every java application, and you're liable to create conflicts with whatever libraries ship with the application.
This isn't really a problem, the easiest solution is probably to throw together a little shell script launcher.

s: huggingface

c: devops

d: intermediate


q:
I'm working on a stripes app that uses a bit of jQuery to make the UI more dynamic/usable.

I set up an Error Resolution, so if an error is thrown, the user is redirected to an error.jsp page.

However, if an error is thrown during a jQuery Ajax call, instead of redirecting to the error.jsp page, I get html printed to the page where the result of the call should have been instead.

How do I tell jQuery to redirect if an exception was thrown instead of printing to the page?

An example of the offending Ajax:

$.post("SendStatusEmail.action",
            {status: newstatus, id : id },
            function(data) {
                column.text(data);
                column.addClass("redfont");
                column.parent().fadeOut(3000, function(){column.parent().remove()});

[A]
```
```
$(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) {
    // redirect here.
}
```
```
I should add that I don't redirect when there is an exception in an Ajax call.  Instead, I have the server return an error description in JSON format and display that in the page.


q:
In my spring application context file, I have something like:

<util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String">
    <entry key="some_key" value="some value" />
    <entry key="some_key_2" value="some value" />
</util:map>

In java class, the implementation looks like:

private Map<String, String> someMap = new HashMap<String, String>();
someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");

In Eclipse, I see a warning that says:

Type safety: Unchecked cast from Object to HashMap<String,String>

What went wrong?

[A]
Well, first of all, you're wasting memory with the new
```
HashMap
```
creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:
```
```
private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
```
```
Secondly, the compiler is complaining that you cast the object to a
```
HashMap
```
without checking if it is a
```
HashMap
```
. But, even if you were to do:
```
```
if(getApplicationContext().getBean("someMap") instanceof HashMap) {
    private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
}
```
```
You would probably still get this warning. The problem is,
```
getBean
```
returns
```
Object
```
, so it is unknown what the type is. Converting it to
```
HashMap
```
directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a
```
HashMap<String, String>
```
.
HashMaps are really maps that take an object as a key and have an object as a value,
```
HashMap<Object, Object>
```
if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a
```
HashMap<String, String>
```
because you could have
```
HashMap<Date, Calendar>
```
because the non-generic representation that is returned can have any objects.
If the code compiles, and you can execute
```
String value = map.get("thisString");
```
without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a
```
ClassCastException
```
at runtime, because the generics cannot block this from happening in this case.


q:
After "check-in" of a .docx file to SharePoint and editing it the RevNum property is set to 2.

This does not make sense, can someone explain why this is?


q: How to make a shadow to main window widget on windows using Qt?

[A]
Correct, the second example is in violation of the strict aliasing rules, so if you compile with the
```
-fstrict-aliasing
```
flag, there's a chance you may get incorrect object code.  The fully correct solution would be to use a union here:
```
```
union
{
  SocketMsgToRecv msg;
  char msgBuff[100];
};

recv(socket, msgBuff, 100);

printf("Got Msg: a: %i, b: %i", msg.a, msg.b);
```
```


q:
In an actionscript function (method) I have access to arguments.caller which returns a Function object but I can't find out the name of the function represented by this Function object.
Its toString() simply returns [Function] and I can't find any other useful accessors that give me that...
Help :-/

[A]
A function is just an object like any other - it doesn't have a "name" in and of itself; it only has a name in the sense that you might make one or more references to it. If what you're asking is how to get the name of the reference by which the function was called, then there's no general way to do that. (After all the function could be declared anonymously, in which case it has no name at all.)
It would probably be best to examine why you need to know the function's name, and figure out some other way to pass in or access the information you're trying to derive from that name. Passing in an additional parameter might be one approach, but it depends on what you're doing.


q: Which component is best to use for receiving HTTP requests in Delphi application?

[A]
Indy
is the way to go. but you need a server component, not a client one.
TIDHTTPServer
should fit the bill


q:
From the Mozilla Developer Network:

[1,4,9].map(Math.sqrt)

will yield:

[1,2,3]

Why then does this:

['1','2','3'].map(parseInt)

yield this:

[1, NaN, NaN]

I have tested in Firefox 3.0.1 and Chrome 0.3 and just as a disclaimer, I know this is not cross-browser functionality (no IE).

I found out that the following will accomplish the desired effect. However, it still doesn’t explain the errant behavior of parseInt.

['1','2','3'].map(function(i){return +i;}) // returns [1,2,3]

[A]
I'm going to wager that it's something funky going on with the parseInt's 2nd parameter, the radix.  Why it is breaking with the use of Array.map and not when you call it directly, I do not know.
```
```
//  Works fine
parseInt( 4 );
parseInt( 9 );

//  Breaks!  Why?
[1,4,9].map( parseInt );

//  Fixes the problem
[1,4,9].map( function( num ){ return parseInt( num, 10 ) } );
```
```


q:
Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely.   E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point?

Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.

[A]
As in almost all languages:
```
```
while True:
  # check what you want and eventually break
  print nextValue()
```
```
The second part of your question is more interesting:
Also, if it is based on time then is there anyway I could just extend the time and start it going from that point again rather than having to start again from 0
you can use a
```
yield
```
instead of
```
return
```
in the function
```
nextValue()
```


q: Is there a way to search Microsoft Visual SourceSafe 6.0d for all files tagged with a specific label?

[A]
I don't think you can search by label, but you can get by label.
From MSDN:
To get a version by label:
Make sure that you have set a working folder in Visual SourceSafe Explorer. See How to: Set the Working Folder.
Ensure that you have set the history options. See How to: View History.
Select the project that contains the file to retrieve.
On the Tools menu, click Show History.
In the History Options dialog box, select the version of the file to retrieve and click OK.
In the History of  dialog box, click Get to retrieve the version of the file that you have chosen.
In the Get dialog box, make any additional entries needed and click OK to retrieve the file.


q: I need to programmatically enable READ COMMITTED SNAPSHOT in SQL Server. How can I do that?

[A]
```
```
ALTER DATABASE [dbname] SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK AFTER 20 SECONDS
```
```


q:
I want to use the same functionality available when a Panel.AutoScroll is true, but with the scrollbars invisible.

To do so I need to know how can I scroll to left/right up/down using functions in my code.

[A]
You should be able to use the VerticalScroll and HorizontalScroll properties of the component:
```
```
c.HorizontalScroll.Value += 100;
c.VerticalScroll.Value = c.VerticalScroll.Maximum;
```
```


q:
You can define a number in various ways in C#,

1F // a float with the value 1
1L // a long with the value 1
1D // a double with the value 1

personally I'm looking for which would a short, however to make the question a better reference for people, what are all the other post-fix's to number literals you can apply?

[A]
for money:
```
```
decimal mon = 1m;
```
```
for output:
```
```
string curr = String.Format("{0:C}", mon);  //output $1.00
```
```


q:
Is there a way for me to loop over a Javascript Object's built-in properties?

for...in gets me close to where I want to go, but "A for...in loop does not iterate over built-in properties."

[A]
This will work with JSON. It hasn't been tested much:
```
```

```
```


q: See question above.

[A]
Yes, use IKVM.
http://www.ikvm.net/
And it's incredibly easy to use:
```
```
ikvmc myjar.jar
```
```
outputs myjar.dll


q:
At what point in a team's growth must process change drastically?  A lone coder can get away with source control and a brain. A team trying to ship large prepackaged software to local and international markets must have a bit more in place.

If you've experienced a large transition in 'process':  Was the team's process successfully changed with the current members or was the team itself mostly replaced by the time the process change came?  What were the important aspects that changed, were some unnecessary?

[A]
If memory serves me correctly anything above five people is where things get dicey.  The number of paths of comunication between the team gets really large after that.
(2 people = 1 path, 3 = 3 paths, 4 = 6 paths, 5 = 10 paths and so on).
The last three places I've been the IT team went through a massive process change.  Yes, you will lose people, probably some of the better ones too.  it's not that they are stubborn and trying to stick to the old ways, it's just that a change like this will cause a mass amount of stress.  There are deadlines to hit and a need for quality to be met.  People will get confused about what process they are supposed to do, and many will fall back to the "old ways." (i've  been guilty of this too I admit.)
The key to succeeding is to take it slow and in small steps.  People need to take time to understand why the process is changing and how it benefits them.  That is huge, if you don't take time to do this, it won't succeed, and key people will end up quitting causing turmoil.
One of the things to absolutely remember is that ultimately some turnover is good.  It brings new ideas and people with different (and sometimes better) skill sets.  You shouldn't try and force change onto people rapidly, but they shouldn't be a barrier either.  If they don't agree with what is going on, they should either try and come to a middle ground with the people making the process or leave.  One of the real eye openers I learned at my first job is that in reality everyone is replaceable.  Someone will eventually be able to step in take the reigns.


q:
I use div tags to define areas within my web pages.  I set all the obvious things like background, size, padding, etc.  But it is all very square.

How can I use only CSS to round the corners?

[A]
You would use the border-radius property.  However, this is only supported in CSS3, which no browser implements yet.  If you only need it to work in a couple browsers you could use -webkit-border-radius and -moz-border-radius which would let it work in Safari and Firefox respectively.
If you are not opposed to using images.  Here's s method I came up with for
making rounded borders
.


q:
I currently have 2 BufferedReaders initialized on the same text file. When I'm done reading the text file with the first BufferedReader, I use the second one to make another pass through the file from the top. Multiple passes through the same file are necessary.

I know about reset(), but it needs to be preceded with calling mark() and mark() needs to know the size of the file, something I don't think I should have to bother with.

Ideas? Packages? Libs? Code?

Thanks
TJ

[A]
What's the disadvantage of just creating a new
```
BufferedReader
```
to read from the top? I'd expect the operating system to cache the file if it's small enough.
If you're concerned about performance, have you proved it to be a bottleneck? I'd just do the simplest thing and not worry about it until you have a specific reason to. I mean, you could just read the whole thing into memory and then do the two passes on the result, but again that's going to be more complicated than just reading from the start again with a new reader.


q:
We currently use VSS 6, this is not going to change I am afraid.

I am attempting to write a script that will allow a user to quickly copy all files that they have checked out to another directory tree. In order to do this I need to get a list of all the files that the user has checked out, and the directory that the file is checked out to. This is easy enough to do using status search in the GUI. But I need a way of doing it from the command line utility ss.exe.

[A]
See
here
for the command line usage of Status command. The command
```
```
ss.exe Status $/ -R -U
```
```
shows every file in the system that is checked out by the current user.


q: Is there a canonical way to set up a JS onHover event with the existing onmouseover, onmouseout and some kind of timers?  Or just any method to fire an arbitrary function if and only if user has hovered over element for certain amount of time.

[A]
Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?
That said, I think what you probably want is...
```
```
var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};
```
```
Or
```
addEventListener
```
/
```
attachEvent
```
or your favorite library's event abstraction method.


q:
1) user A goes to the site, creates an account, and logs in
2) user b goes to the site.  Rather than having to log in, user b enters as though user b is user a.  User b gets access to all of user a's data and can brows the site as user a.

Note: user b does not log in.  User b just hits the site, and the site returns as if user b is already logged in as user a.

Note 2: user a and user b are on distinct computers.  Also, static variables are not involved in the code.

Setup:
IIS 6
.Net 2.0
OutputCache off for the pages in the site

[A]
This question seems quite similar to
Apache/Tomcat error - wrong pages being delivered
. As
my answer
to that question mentions, if you use session cookies, check if your
```
Vary
```
header is correct.


q:
I'm working on a project and I want to store some easily enumerated information in a table.  MySql's enum data type does exactly what I want: http://dev.mysql.com/doc/refman/5.0/en/enum.html .  Is there an equivalent in SQL Server 2005?

I know I could store the possible values in a type table with a key, but I'd rather not have to link back to it for descriptions.  Our database standards don't allow us to link on non-integer or uniqueidentifier fields, so storing the possible keys as characters is out as well.

[A]
Does this work for you?
From
http://blechie.com/wtilton/archive/2007/08/24/303.aspx
Create table...
MySQL:
```
```
ColumnName ENUM('upload', 'open', 'close', 'delete', 'edit', 'add')
   DEFAULT 'open'
```
```
SQL Server:
```
```
ColumnName varchar(10)
   CHECK(ColumnName IN ('upload', 'open', 'close', 'delete', 'edit', 'add'))
   DEFAULT 'open'
```
```


q: Have you ever worked on a (full-time) project where using Agile methodologies actually allowed you to accomplish a 40-hour work-week? If so, what were the most valuable agile practices?

[A]
Scrum and management that is willing to buy into it.
Fair sprint planning.  When you negotiate your own sprint you can choose what  your team can accomplish rather than have tasks being handed down from above. Having your sprint commitment locked in (management can't change it mid-sprint) gives freedom from the every changing whims of people.
A well maintained, prioritized backlog that is maintained
cooperatively
by the product owner and upper management is very useful.  It forces them to sit down and think about the features they want, when they want them and the costs involved.  They will often say they need a feature
now
, but when they realized they have to give up something else to get what they want their expectations become more realistic.
Time boxing. if you are running into major problems start removing features from the sprint rather than working extra hours.
You need managerial support for you process without it agile is just a word.
Did I mentioned enlightened management?


q:
I cannot find the translated file after running the solution in BizTalk 2006 Tutorial Lesson 3: Run the EDI-to-XML Solution.

It should be placed in the c:\Program Files\Microsoft BizTalk Server 2006 \EDI\Adapter\Getting Started with EDI\Northwind\In folder.

The Base EDI adapter picks up the file in c:\Documents and Settings\All Users\Application Data\Microsoft\BizTalk Server 2006 \EDI\Subsystem\Documents\PickupEDI folder, but I cannot find the translated file in the X-12 4010 850 document format.


q: When would you call Java's thread.run() instead of thread.start()?

[A]
Call
```
thread.start()
```
, it will in turn call
```
thread.run()
```
.  Can't think of a case when you would want to bypass
```
thread.start()
```
and go directly to
```
thread.run()
```


q:
I know that in JavaScript, creating a for loop like this: for(int i = 0; i < arr.length; i++) is costly as it computes the array length each time.
Is this behavior costly in c# for lists and arrays as well. Or at compile-time is it optimized?  Also what about other languages such as Java, how is this handled?

[A]
It is
not
costly in C#. For one thing, there is no “calculation“: querying the length is basically an elementary operation thanks to inlining. And secondly, because (
according to its developers
), the compiler recognizes this pattern of access and will in fact optimize any (redundant) boundary checks for access on array elements.
And by the way, I believe that something similar is true for modern JavaScript virtual machines, and if it isn't already, it will be very soon since this is a trivial optimization.


q:
I'm trying to convert my sites from CF8 to openBD.  I have a cfloop in a site that loops over a date range.

In essence, I want to insert a new record into the db for every 2 weeks (step) of a date range (from and to)

my loop looks like this...

<cfloop
  from  = "#form.startDate#"
  to    = "#form.endDate#"
  index = "i"
  step  = "#theStep#"
>

This works perfectly in CF8, in openBD, I get this error...
Data not supported: value [11/05/09] is not a number

Any ideas of a work around?

Thx

[A]
I can't see your code, but here's my first suggestion:
```
```
<cfset current = [your begin date]>
<cfloop condition = "datecompare(enddate, current)">
  [do stuff]
  <cfset current = dateadd('d', 14, current)>
</cfloop>
```
```
HTH.


q:
I have a RegEx that is working for me but I don't know WHY it is working for me. I'll explain.

RegEx: \s*<in.*="(<?.*?>)"\s*/>\s*

Text it finds (it finds the white-space before and after the input tag):

<td class="style9">
      <input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value="<?php echo $data[guarantor4]; ?>"  />    </td>
</tr>

The part I don't understand:

<in.*=" <--- As I understand it, this should only find up to the first =" as in it should only find <input name="

It actually finds: <input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value=" which happened to be what I was trying to do.

What am I not understanding about this RegEx?

[A]
```
.*
```
is greedy. You want
```
.*?
```
to find up to only the first
```
=
```
.


q:
I have a web server that runs my web application.

If I want to outsource my email to another provider, is it possible if they are on their on network/data center?

[A]
Yes. To do this, you will need access to the DNS records for your domain. The MX record allows you to set up a mail server that's separate from the web server.
Google offers a service that will manage your domain's email through GMail, and the instructions on how to reconfigure your DNS for this service can be found
here
.


q: I'm working on a project for school, and I'm implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I'm gonna have a GUI for it, and I will be using a JProgressBar widget, which I would like to show the current progress of the download. For that I would need to know the size of the file. How do you get the size of the file prior to downloading the file.

[A]
Any HTTP response is
supposed
to contain a Content-Length header, so you could query the URLConnection object for this value.
```
```
//once the connection has been opened
List values = urlConnection.getHeaderFields().get("content-Length")
if (values != null && !values.isEmpty()) {

    // getHeaderFields() returns a Map with key=(String) header
    // name, value = List of String values for that header field.
    // just use the first value here.
    String sLength = (String) values.get(0);

    if (sLength != null) {
       //parse the length into an integer...
       ...
    }
```
```
It might not always be possible for a server to return an accurate Content-Length, so the value could be inaccurate, but at least you would get
some
usable value most of the time.
update:
Or, now that I look at the URLConnection javadoc more completely, you could just use the
getContentLength()
method.


q:
I am looking for any and all suggestions of the best and effective resources that the StackOverflow community has used to better learn MSBuild with an emphasis on integrating unit tests and later static code analysis tools such as FxCop and StyleCop into the build process.

I have tried to find good clear documentation on adding unit tests into my build but I still am searching - even Google searches have come up empty or with just bits and pieces.  Ideally I want to add unit tests, report results, and eventually add code coverage statistics, etc into the build results.

I know it has to be in MSDN somewhere but I seem unable to find anything which explains and teaches well.  I am using Visual Studio Team System 2008.

[A]
Continuous Integration From Theory to Practice
by Carel Lotz.  It covers the entire scope of your problem, and then some.  Well written, complete, and a full sample are all there.
Hands down best resource.  Use it as a tutorial first, then use it as a guide, then use it as a reference.
MSDN and others are good for clarifying (or confusing) the details.
Edit:
The guide by Carel Lotz uses MBUnit for unit tests (see his earlier document version for NUnit, though you can replace the MBUnit with NUnit pretty easily if you follow the NUnit help files).
Also, it is written to use Cruise Control.NET to run the MSBuild script in various configurations.
Personally, I run unit tests in a secondary MSBuild script, but have found that wrapping the NUnit calls in MSBuild gives more flexibility than running from CCNet directly.


q:
I'm currently developing an html/ajax air app and am about to invest some effort into making animations using jQuery. I could do this quite a bit easier using the css animations if air had that recent a version of WebKit.

I know some people have alpha/beta versions of air 1.5. If you do, can you let me know?

[A] I don't know offhand what AIR 1.5's CSS capabilities are, but it is a build with SquirrelFish, if that helps you track it down.


q: Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes

[A]
Java's answer to multiple inheritance is the ability to implement multiple interfaces.  Of course, this means you'll get the method declarations, but not the logic.
You could try emulating mixins by composition: your Java class could define member variables that represent other classes that perform some common business logic.
In designing Java classes, I have not found the lack of C++ style multiple inheritance to inhibit the design of my architecture.  You will find a way to achieve what you want to do.


q:
I'm writing an image bank with Django, and I want to add a  button to get a hi-res version of an image (the low-res is shown in the details page).  If I put just an <a> link, the browser will open the image instead of downloading it.  Adding an HTTP header like:

Content-Disposition: attachment; filename="beach008.jpg"

works, but since it's an static file, I don't want to handle the request with Django.  Currently, I'm using NGINX to serve static files, and dynamic pages are redirected via FastCGI to the Django process.  I'm thinking about using NGINX add-header command, but could it set the filename="xx" part?.  Or maybe there's some way to handle the request in Django, but make NGINX serve the content?

[A]
I wrote a simple decorator, for django.views.static.serve view
Which works for me perfectly.
```
```
def serve_download(view_func):
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        response['Content-Type'] = 'application/octet-stream';
        import os.path
        response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(kwargs['path'])
        return response
    return _wrapped_view_func
```
```
Also you can play with nginx mime-types
http://wiki.codemongers.com/NginxHttpCoreModule#types
This solution didn't work for me, because I wanted to have both direct link for the file (so user can view images, for example), and download link.


q: You used to be able to get the package a Delphi component was installed under from the palette. That functionality doesn't seem to be in the lastest versions, though.  How can I find which package a component belongs to under D2007 or D2009?

[A] I don't know of any way to do this through the Delphi IDE. However, you can do a search in your registry for the component name. For instance, to find the package that TBitBtn belongs to, open RegEdit and do a search (on Keys only) for TBitBtn. The entry for TBitBtn has a value called "Package Name". This is the internal name of the package, which is probably still not quite what you are looking for. Copy the "Package Name" value (dclstd100.bpl in my case), and do a search from the top (on Values this time) for that value. Once this entry is found you will see the "friendly" package name in the "Data" column.


q:
I am looking for a backend solution for an application written in Ruby on Rails or Merb to handle data with several billions of records. I have a feeling that I'm supposed to go with a distributed model and at the moment I looked at

HBase with Hadoop

Couchdb

Problems with HBase solution as I see it -- ruby support is not very strong, and  Couchdb did not reach 1.0 version yet.

Do you have suggestion what would you use for such a big amount of data?

Data will require rather fast imports sometimes of 30-40Mb at once, but imports will come in chunks. So ~95% of the time data will be read only.

[A]
There's a number of different solutions people have used. In my experience it really depends more on your usage patterns related to that data and not the sheer number of rows per table.
For example, "How many inserts/updates per second are occurring." Questions like these will play into your decision of what back-end database solution you'll choose.
Take Google for example: There didn't really exist a storage/search solution that satisfied their needs, so they created their own based on a Map/Reduce model.


q:
In a tightly looped test application that prints out the value of DateTime.UtcNow.Ticks, I notice that the value will jump a remarkable amount once every hour or so.  Look closely at the following sample data:

1:52:14.312 PM - 633614215343125000
1:52:14.359 PM - 633614215343593750
1:52:14.421 PM - 633614215344218750
1:52:14.468 PM - 633614215344687500
1:52:14.515 PM - 633614215998593750 <-- WAY different

The delta is 653906250 ticks (65.390 seconds).  The only reason I can come up with is that the Windows Time service is doing some synchronization from underneath my feet.

Are there any experts out there that can confirm this?

Drifting a minute or so in about an hour seems pretty bad to me, but is that the case here?

[A]
Can you post code to show how you generated this data?  And provide details about the machine you are running this on?
Using the following, I'm not getting what you are getting.
```
```
for (int i = 0; i < 10; i++)
        {

            Console.WriteLine(DateTime.Now.ToLongTimeString().ToString() + " - " + DateTime.UtcNow.Ticks.ToString());

            Thread.Sleep(10);
        }
```
```


q:
I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it.

I have the id of the element, and the CSS class that I'm looking for.  I just need to be able to, in an if statement, do a comparison based on the existence of that class on the element.

[A]
Use the
```
hasClass
```
method:
```
```
jQueryCollection.hasClass(className);
```
```
or
```
```
$(selector).hasClass(className);
```
```
The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).
Note:
If you pass a
```
className
```
argument that contains whitespace, it will be matched literally against the collection's elements'
```
className
```
string. So if, for instance, you have an element,
```
```
<span class="foo bar" />
```
```
then this will return
```
true
```
:
```
```
$('span').hasClass('foo bar')
```
```
and these will return
```
false
```
:
```
```
$('span').hasClass('bar foo')
$('span').hasClass('foo  bar')
```
```


q:
Is there a way, within the .net framework, to check to see if two different shared folders are actually pointing to the same physical directory?  Do directories in Windows have some sort of unique identifier?  Google-fu is failing me.

(I mean, aside from writing a temp file to one and seeing if it appears in the other)

Edit: I think I've discovered what I need,with thanks to Brody for getting me pointed in the right direction in the System.Management namespace.

[A]
You can examine the share definition itself by using the System.Management namespace but it is not easy to use.
it starts something like
```
```
ManagementClass management = new ManagementClass("\\\\.\\root\\cimv2", "Win32_Share", null)
```
```
And it gets much worse after that.  I have used it to create a share.  Hopefully you can use it to the path for each share and compare.


q:
I have a Ruby script that generates a UTF8 CSV file remotely in a Linux machine and then transfers the file to a Windows machine thru SFTP.

I then need to open this file with Excel, but Excel doesn't get UTF8, so I always need to open the file in a text editor that has the capability to convert UTF8 to ANSI.

I would love to do this programmatically using Ruby and avoid the manual conversion step. What's the easiest way to do it?

PS: I tried using iconv but had no success.

[A]
```
```
ascii_str = yourUTF8text.unpack("U*").map{|c|c.chr}.join
```
```
assuming that your text really does fit in the ascii character set.


q:
I'm writing a program in C# that runs in the background and allows users to use a hotkey to switch keyboard layouts in the active window.  (Windows only supports CTRL+SHIFT and ALT+SHIFT)

I'm using RegisterHotKey to catch the hotkey, and it's working fine.

The problem is that I can't find any API to change the keyboard layout for the focused window.

ActivateKeyboardLayout and LoadKeyboardLayout  can only change the keyboard layout for the calling thread.

Does anyone know how to change the keyboard layout for a different thread (the way the Language Bar does)?

[A]
I think the trick is to get your code to execute in the context of the thread whose keyboard layout you wish to change. You'll need to do some win32 interop here and learn about DLL Injection to get your code to execute in the remote thread.
A
keyboard hook handler
looks like a good option for you here.
Take a look at
http://www.codeproject.com/KB/threads/winspy.aspx


q:
I'm looking for a clean C++ way to parse a string containing expressions wrapped in ${} and build a result string from the programmatically evaluated expressions.

Example:  "Hi ${user} from ${host}" will be evaluated to "Hi foo from bar" if I implement the program to let "user" evaluate to "foo", etc.

The current approach I'm thinking of consists of a state machine that eats one character at a time from the string and evaluates the expression after reaching '}'. Any hints or other suggestions?

Note: boost:: is most welcome! :-)

Update Thanks for the first three suggestions! Unfortunately I made the example too simple! I need to be able examine the contents within ${} so it's not a simple search and replace. Maybe it will say ${uppercase:foo} and then I have to use "foo" as a key in a hashmap and then convert it to uppercase, but I tried to avoid the inner details of ${} when writing the original question above... :-)

[A]
How many evaluation expressions do intend to have?  If it's small enough, you might just want to use brute force.
For instance, if you have a
```
std::map<string, string>
```
that goes from your
```
key
```
to its
```
value
```
, for instance
```
user
```
to
```
Matt Cruikshank
```
, you might just want to iterate over your entire map and do a simple replace on your string of every
```
"${" + key + "}"
```
to its
```
value
```
.


q: I'm reading The C++ Programming Language and in it Stroustrup states that the int value of a char can range from 0 to 255 or -127 to 127, depending on implementation. Is this correct? It seems like it should be from -128 to 127.  If not, why are their only 255 possible values in the second implementation possibility, not 256.

[A]
You're stuck in
two's complement
thinking - The C++ standard does not define the representation used for negative numbers!
If your computer (god forbid) uses
ones's complement
to represent negative numbers, you have a range of -127 to + 127 in an 8-bit byte. On the upside, you have two different possible representations for zero...
However, in the real world,
you're unlikely to meet a one's complement computer
.


q: Right now I'm not sure...

[A]
I'd say yes.  I'm using it.  I know for a fact that Universal are using it on some of their (thousands of) sites.  I will add some caveats, however:
There are serious problems with setting it up, especially if you want to debug into the libraries.
The helper functions favour prototype, as opposed to the more modern jQuery.  This is changing rapidly, however.
The documentation is a bit chaotic, again the Castle Team are working on that.
I'm not guaranteeing every last "out-there" feature works, but the point of the system is actually to keep it simple.
Compared to vanilla ASP.NET, it's an absolute joy.  I assure you that you won't miss viewstate.


q:
In .NET, the GetHashCode method is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when determining equality.

Is there a standard algorithm or best practice on how to implement GetHashCode for my custom classes so I don't degrade performance?

[A]
I usually go with something like the implementation given in Josh Bloch's
fabulous
Effective Java
. It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do:
```
```
public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        // Suitable nullity checks etc, of course :)
        hash = hash * 23 + field1.GetHashCode();
        hash = hash * 23 + field2.GetHashCode();
        hash = hash * 23 + field3.GetHashCode();
        return hash;
    }
}
```
```
As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-
FNV
example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant
is
prime though. I don't know quite how important that is.)
This is better than the common practice of
```
XOR
```
ing hashcodes for two main reasons. Suppose we have a type with two
```
int
```
fields:
```
```
XorHash(x, x) == XorHash(y, y) == 0 for all x, y
XorHash(x, y) == XorHash(y, x) for all x, y
```
```
By the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types.
This page
gives quite a few options. I think for most cases the above is "good enough" and it's incredibly easy to remember and get right. The
FNV
alternative is similarly simple, but uses different constants and
```
XOR
```
instead of
```
ADD
```
as a combining operation. It looks
something
like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above.
```
```
// Note: Not quite FNV!
public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = (int) 2166136261;
        // Suitable nullity checks etc, of course :)
        hash = (hash * 16777619) ^ field1.GetHashCode();
        hash = (hash * 16777619) ^ field2.GetHashCode();
        hash = (hash * 16777619) ^ field3.GetHashCode();
        return hash;
    }
}
```
```
Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code.
As per the
documentation
:
You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:
You can compute the hash code from fields that are not mutable; or
You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.
The link to the
FNV
article is broken but here is a copy in the Internet Archive:
Eternally Confuzzled - The Art of Hashing


q:
Imagine the following REBOL code:

foo: context [bar: 3]

I now have a context foo in which 'bar is defined. How can I dynamically inject a new word into this context? Is it possible?

I've tried:

set/any in foo 'baz 3

But that doesn't work because the expression in foo 'baz fails because there is no word 'baz defined in the foo context.

I should add that I realize one way to do this is as follows:

foo-prototype: [bar: 3]
foo: context foo-prototype
foo: context head append foo-prototype [baz: 3]

But what if you don't have access to foo's prototype block?

[A]
You can achieve the same by using the existing object as a prototype to create a new object.
```
```
>> foo: make object! [bar: 3]
>> foo: make foo [baz: 3]
>> probe foo
make object! [
    bar: 3
    baz: 3
]
```
```


q:
I have a Java server that accepts SSL connections using JSSE and uses a simple XML message format inside the stream.  I would like the server to read a complete message and then send a reply.  This turns out to be quite difficult because org.xml.sax.XMLReader wants to read the entire stream and then call close().  I know it seems strange, but in Java 6 with the Sun JSSE provider this really does close both ends of the SSLSocket so no message can go back.  I tried using the shutdownOutput() method of Socket on the client side, but this is unsupported with JSSE.

My solution was to pass an InputStream wrapped in a custom class that silently ignores close requests and indicates that the stream is closed when it encounters the first blank line.  This constrains the XML beyond what is normally valid, but the client can easily filter out blank lines in the input if necessary.  Is there a better solution?

[A]
I'm guessing that you are already doing dynamic assembly resolution and loading? If so, then you could try substituting a fake assembly name in place of the real assembly name i n the Xaml - you can then use that in your assembly resolution code to load up and return the right assembly. e.g. if your original source Xaml is:
```
```
xmlns:myassembly="clr-namespace:MyApp.MyAssembly;assembly=MyAssembly"
```
```
and you know that Xaml wants v2 of MyAssembly, replace the assembly ref in the Xaml string before parsing it to:
```
```
xmlns:myassembly="clr-namespace:MyApp.MyAssembly;assembly=MyAssembly.v2"
```
```
.. then in your assembly resolution / load code, when you see the ".v2" bit on the end you look for and load that assembly instead.
Please let me know if I've misunderstood the question, or you aren't current doing any custom assembly resolution - that would certainly be the key in this situation I think.


q:
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.

Example - I have the following list:

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I want to have

result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]

So far what I've come up with is:

def add_list(array):
    number_items = len(array[0])
    result = [0] * number_items
    for index in range(number_items):
        for line in array:
            result[index] += line[index]
    return result

But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?


q:
I have a C# .NET web project that I'm currently working on.  What I'm trying to do is read some files that I dropped into a dir which is at the same level as fileReader.cs which is attempting to read them.  On a normal desktop app the following would work:

DirectoryInfo di = new DirectoryInfo(./myDir);

However because it's a web project the execution context is different, and I don't know how to access these files?

Eventually fileReader will be called in an installation routine.  I intend to override one of the Installer.cs' abstract methods so will this affect the execution context?

[A]
Use
```
Server.MapPath
```
to get the local path for the currently executing page.


q:
I wish to dynamically change the scroll position of a Silverlight ListBox from C#, and I need to know how to access the ScrollViewer element of a ListBox control from C#?

Thanks guys,
Jeff

[A]
Good question. I didn't find a way to do it directly, but came fairly close by looking at the Silverlight Controls project (they use the scrollviewer on the items control in some of the classes). Here is how you can get it, but it requires a custom listbox:
```
```
public class TestBox : ListBox
{
    private ScrollViewer _scrollHost;

    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {
        var itemsHost = VisualTreeHelper.GetParent(element) as Panel;

        for (DependencyObject obj = itemsHost; obj != item && obj != null; obj = VisualTreeHelper.GetParent(obj))
        {
            ScrollViewer viewer = obj as ScrollViewer;
            if (viewer != null)
            {
                _scrollHost = viewer;
                break;
            }
         }

        base.PrepareContainerForItemOverride(element, item);
    }
}
```
```
There might be another way to hook into that event (or another way to get that panel), If you look at the template for the ListBox you will see the scroll viewer is actually named "ScrollViewer", however the GetTemplateChild method is protected so you would still need to create a custom class.


q:
In a forms model, I used to get the current logged-in user by:

Page.CurrentUser

How do I get the current user inside a controller class in ASP.NET MVC?

[A]
I use:
```
```
Membership.GetUser().UserName
```
```
I am not sure this will work in ASP.NET MVC, but it's worth a shot :)


q:
I am using the following code to determine free space on a volume.
The folder was provided using NSOpenPanel.  The item selected was a mounted volume and the path returned is \Volumes\Name

NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder];

unsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue];

Is there a better method to determine the free space on a mounted volume using Cocoa?

Update: This is in fact the best way to determine the free space on a volume.  It appeared it wasn't working but that was due to the fact that folder was actually /Volumes rather  than /Volume/VolumeName

[A]
statfs is consistent with results from df. In theory NSFileSystemFreeSize comes from statfs, so your problem should not exist.
You may want to run statfs as below as a replacement for NSFileSystemFreeSize:
```
```
#include <sys/param.h>
#include <sys/mount.h>

int main()
{
    struct statfs buf;

    int retval = statfs("/Volumes/KINGSTON", &buf);

    printf("KINGSTON Retval: %d, fundamental file system block size %ld, total data blocks %d, total in 512 blocks: %ld\n",
            retval, buf.f_bsize, buf.f_blocks, (buf.f_bsize / 512) * buf.f_blocks);
    printf("Free 512 blocks: %ld\n",  (buf.f_bsize / 512) * buf.f_bfree);
    exit(0);
}
```
```


q:
We just switched from TFS to SVN, and so far we're loving it.

However, it did introduce a few new issues.

One is the way project files (.vbproj specifically) are handled. The .vbproj file is of course always changing as files and references are changed, and if a few people are collaberating there will be conflicts.

Oddly, in TFS we never had to deal with managing those conflicts, that particular piece was automagically handled. Now in SVN, we're mucking through XML in the merge tool and there have already been some mistakes.

How do you handle this? Any tips?

EDIT: by the way, we're using VisualSVN.

[A]
This particular issue occurs if multiple developers add files to the same project.
To resolve a conflict when multiple developers have added files to the same project, you can usually make it work by resolving using "mine before theirs" option. It'll add both your changes together.
This issue and other merge issues are alleviated by committing and updating often. Commit once a day or more if possible. The longer you go without updating and committing, the more pain you and your team will feel.


q:
I'm trying to use SubSonic for a new project with an existing database but when I try to build the project after generating the SubSonic files I'm getting these same two exceptions on different classes:

Partial declarations of 'MyData.UserCollection' must not specify different base classes

Type 'MyData.UserCollection' already defines a member called 'UserCollection' with the same parameter types

I'm able to successfully build a new project using the Northwind DB so I believe the error has something to do with the way the tables are setup but I'm not sure where to go from there.  Any help is appreciated.

[A]
Search for UserCollection in your project. SubSonic generated a partial class for this in the User.cs generated file. You either have a UserCollection of your own in which case you should probably rename it or put it in another namespace. Either that, or you tried to add functionality to the UserCollection and you derive it from another type.
Last possibility is that you have a User table and a Users table. SubSonic will change Users to User. I'm not sure, but it might cause generation errors. I haven't tried it though.


q:
In the following table structure:

Fruits
(
    fruit_id,
    fruitName
)

Vegetables
(
    vegetable_id,
    vegetableName
)

favoriteFoods
(
     food_id,
     foodName,
     type_id (References either a fruit or a vegetable)
)

I realize that I could forgo using a foreign key constraint on the favoriteFoods table and then simply add a type field to the favoriteFoods table to differentiate between fruits and vegetables.  But how would you structure the tables so that you could actually create the necessary foreign key constraints?

[A]
I would only use 2 tables instead.  Instead of having a separate Fruits and Vegetables table, why not have a table of Foods.  Then have a foreign key constraint on fkfood_id to food_id.  Then if for some reason you ever have to add meat, it would be much easier to maintain the application that uses this.
```
```
Food
    (
    food_id,
    foodName,
    foodType
    )

favoriteFoods
    (
    favoritefood_id,
    fkfood_id
    )
```
```


q:
I am evaluating VintaSoft .net control and Atalasoft DotTwain Image Capture. And I am very but very lost with the most of the definitions and keywords.

So I am asking this because I think I am in Lala land. Is it possible to listen or have the scanner tell my app that there is a scanned image and I can process it?

The idea is to have a winservice that is waiting for the scanner to scan something and when that happens process the image.

[A]
[edit - if it was me, I'd look at adzm's answer ;-p]
As I understand it, regular TWAIN is a "pull", not a "push" from the scanner. I could well be wrong...
I expect such interfaces do exist for high end, high volume scanners (you know, the ones the size of a billiard table) - but not (AFAIK) for regular consumer scanners.
For use with .NET (and before that, COM), I've always managed with
ImageMan
.


q:
I'm wondering how slow it's going to be switching between 2 databases on every call of every page of a site. The site has many different databases for different clients, along with a "global" database that is used for some general settings. I'm wondering if there would be much time added for the execution of each script if it has to connect to the database, select a DB, do a query or 2, switch to another DB and then complete the page generation. I could also have the data repeated in each DB, I just need to mantain it (will only change when upgrading).

So, in the end, how fast is mysql_select_db()?

Edit: Yes, I could connect to each DB separately, but as this is often the slowest part of any PHP script, I'd like to avoid this, especially since it's on every page. (It's slow because PHP has to do some kind of address resolution (be it an IP or host name) and then MySQL has to check the login parameters both times.)

[A]
Assuming that both databases are on the same machine, you don't need to do the mysql_select_db. You can just specify the database in the queries. For example;
```
```
SELECT * FROM db1.table1;
```
```
You could also open two connections and use the DB object that is returned from the connect call and use those two objects to select the databases and pass into all of the calls. The database connection is an optional parameter on all of the mysql db calls, just check the docs.


q:
A Java version of this question was just answered, and, well, I don't know how to do this in .net.

So how do you calculate the display width of a string in C# / .net?

[A]
You've got the same problem in this question as was present in the Java question - not enough information! It will differ between WinForms and WPF.
For WinForms:
Graphics.MeasureString
For WPF I'm not sure, but I suspect it will depend on the exact way you're drawing the text...


q:
Is there any Ruby equivalent for Python's builtin zip function? If not, what is a concise way of doing the same thing?

A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had zip, I could have written something like:

zip(a, b).all? {|pair| pair[0] === pair[1]}

I'd also accept a clean way of doing this without anything resembling zip (where "clean" means "without an explicit loop").

[A]
Ruby has a zip function:
```
```
[1,2].zip([3,4]) => [[1,3],[2,4]]
```
```
so your code example is actually:
```
```
a.zip(b).all? {|pair| pair[0] === pair[1]}
```
```
or perhaps more succinctly:
```
```
a.zip(b).all? {|a,b| a === b }
```
```


q:
I've inherited a ASP/VB6 code base (not my forte... yet) and I'm trying tease it apart to figure out the cause on an error message I'm receiving when running the app.

I've traced it back through an event that is being raised in on of my classes. Is there away in windows I can search the bulk of the code base for where it is being consumed?
Ctrl-F (and selecting Current Project) has not sufficed.

The linux geek in me is saying dump it to a insert distro box and just grep for the sucker. But there's got to be some way in the IDE to do it... right?

[A]
But there's got to be some way in the IDE to do it... right?
No. There are some plugins for the IDE, such as the
MZ Tools
that
might
help. Otherwise, just use the
```
find
```
tool from the Windows command line. Not nearly as comfortable as using
```
grep
```
, of course.


q: I've been having performance issues with a high traffic ASP.NET 2.0 site running on Windows 2000.  While editing the web.config file I noticed that the authentication mode was set to 'Windows'.  I changed it to 'None'.  The only users this site has are anonymous and it gets 25,000+ page views at day.  Could this have been a caused performance issues?


q:
I have a multidimensional array. I need to search it for a specific range of values, edit those values and return the edited data.

Example array:

array(3) {
  ["first"]=>
  array(1) {
    [0]=>
    string(4) "baz1"
  }
  ["second"]=>
  array(1) {
    [0]=>
    string(4) "foo1"
  }
  ["third"]=>
  array(1) {
    [0]=>
    string(4) "foo2"
  }

Now I want to find any values that match foo (foo1 and foo2 in the example array), insert "-bar" into them (foo-bar1, foo-bar2) and return that value. What are the best ways to approach this?

EDIT I should have mentioned that foo could actually be anythingfoo (ex. examplefoo1, somethingelsefoo2, blahblahfoo3). I think this rules out str_replace.

[A]
How about something like this:
```
```
function addDashBar($arr)
{
    foreach ($arr as $key => $value)
    {
       if (is_array($value))
           $arr[$key] = addDashBar($value)
       else
       {
           $arr[$key] = str_replace($value, "foo", "foo-bar");
       }
    }

    return $arr;
}
```
```


q:
In eclipse, I have a javaproject (not a web project), though it does provide reusable tag files.

layout

+src

+++META-INF

----my.tld

+++++++++++tags

---------------include.jsp

I keep on getting Fragment "/META-INF/tags/include.jsp" was not be found at expected path /Project/META-INF/tags/taginclude.jsp

How can I modify the path eclipse is looking for? I need to tell it to include "src" in the lookup

[A]
Josh, if you're working with .jsp and .tld files, then you really shouldn't be doing this as a "Java Project", but instead a "Dynamic Web Project" in Eclipse.  Nonetheless, I'll try to answer your question.
Based on the diagram of your file system, your files are laid out incorrectly.  If you're trying to create a web app (a .war file), then you need a WEB-INF directory.  Under the WEB-INF directory you'll need a web.xml file (google for web.xml to see what needs to be in there), a tags directory, and a classes and lib directory.
Compiled class files must go in the WEB-INF/classes directory.
Jar files that you depend on must go in the WEB-INF/lib directory.
Tablibs must go in the WEB-INF/tags directory.
Finally, your .jsp files must go in src directory (the parent dir of WEB-INF).
So, your layout should look like this:
```
myproject/
`-- src
    |-- WEB-INF
    |   |-- classes
    |   |   `-- MyClass.class
    |   |-- lib
    |   |   `-- my.jar
    |   |-- tags
    |   |   `-- my.tld
    |   `-- web.xml
    `-- include.jsp
```
Hope this helps.
-Bryan


q:
There's a requirement that we will need to support querying a local SQL Server database for new data when the database is updated.  Since these are external SQL Server databases, we may not be able to use SQL Server Notification Services nor can we make any changes to the database.

My basic idea is to watch for data being written to the database to trigger a query (instead of polling at set intervals).  However, I'm having a tough time trying to figure out how I could get the WriteFile call from the SqlServr.exe process (as can be monitored in tools such as Sysinternals' Process Monitor).  Can anyone direct me to which Win32 functions may be able to help me with this?

[A]
I don't think going through the file system would be the best option. Even if you could get access to file system activity, I would think it would be difficult to discern what file operation added data vs any other type of file activity like maintenance, index defrags, etc.
A possible alternative would be to look into the
Microsoft.SqlServer.Management.Trace Namespace
as a mechanism to hook into SQL Server and look for the specific events that you want to respond to. I would be cautions however of the performance impact this may cause.


q: Currently I have subversion set up so that when I make changes in Eclipse PDT, I can commit the changes and they will be saved in /home/administrator/Project File.  This file has the /branches /tags and /trunk directories recommended by subversion.  I have no problem properly uploading files to the repository, but do I have to "mv" the files in Linux to /var/www in order to make them live on the server?  Is there an automatic process to do this that I am missing?  I'm assuming we don't want to make the /var/www directory (which is live on the machine) the repository, but I don't know.

[A]
You can do an
```
svn export
```
into your www directory. That will give you a "clean" version of your repo, without the .svn directories.
```
```
cd /var/www
svn export /home/administrator/MyProject/trunk MyProject
```
```
Edit: adding in some good ideas from the comments...
Some options for when you want to update your exported copy:
run
```
svn export --force /home/...../ MyProject
```
this will stop it complaining about overwriting the existing files. This method will mean that if you delete a file from your repository, it'll still remain in your www folder.
change your SVN command to export into a new directory each time:
```
svn export /home/..../ MyProject_20081105
```
and then create a symlink to that folder:
```
ln -s MyProject_20081105 MyProject
```
Just delete and recreate the symlink each time you "release". In this case, the export directory doesn't need to be in the
```
www
```
folder at all.


q:
I have 15 stored procedures that return data from a common table and then join that table with a specific table to retrieve inventory.

Example:

Common: tblCommon
Specific: tblSpecific

Is there way I can pass the name "tblSpecific" into a single stored procedure as a variable, like the following?

SELECT ....
FROM tblCommon c
INNER JOIN @TABLE s on c.primaryKey = s.foreignKey

[A]
Yep, you can generate an SQL statement dynamically and then execute it.
For example,
```
```
DECLARE @specificTableName nvarchar(50)
DECLARE @specificColumnName nvarchar(50)

SET @specificTableName = 'tblSpecific'
SET @specificColumnName = 'colSpecific'

DECLARE @sql nvarchar(4000)

set @sql = 'SELECT ... FROM tblCommon c INNER JOIN ' +
@specificTableName + ' s ON c.PrimaryKey = s.' + @specificColumnName

exec (@sql)
```
```


q:
Alright. I have a query that looks like this:

SELECT
    SUM(`order_items`.`quantity`) as `count`,
    `menu_items`.`name`
FROM
    `orders`,
    `menu_items`,
    `order_items`
WHERE
    `orders`.`id` = `order_items`.`order_id` AND
    `menu_items`.`id` = `order_items`.`menu_item_id` AND
    `orders`.`date` >= '2008-11-01' AND
    `orders`.`date` <= '2008-11-30'
GROUP BY
    `menu_items`.`id`

The purpose of this query is to show the amount of items sold in a given date range. Although this works, I now need it to show a count of 0 if a particular item has no sales in the date range. I tried using COALESCE around the SUM but that didn't do the trick, and I didn't really expect it to. Anyhow, does anyone know how I would go about accomplishing this? I'm having one of those moments where I feel like I should know this but I can't think of it.

Cheers

[A]
Randy's answer is close, but the where statement removes any mention of those items not part of any orders in that date range.
Note that "left join" is different to linking tables in the where clause in the manner you have done (i.e. inner joins). I suggest you read up on the different types of SQL joins (inner, outer, cross).
In essense, you need to join the data you get from Randy's query against your source list of items. Using a subselect will do this:
```
```
SELECT
    name
    , nvl(count, 0) as count
FROM
    menu_items items
    LEFT JOIN (
        SELECT
            menu_items.id
            , SUM(order_items.quantity) as count
        FROM
            menu_items
            LEFT JOIN order_items ON menu_items.id = order_items.menu_item_id
            LEFT JOIN orders ON orders.id = order_items.order_id
        WHERE
            "date" between to_date('2008-11-01','YYYY-MM-DD') and to_date('2008-11-30','YYYY-MM-DD')
        GROUP BY
            menu_items.id
    ) counts on items.id = counts.id;
```
```
This is in Oracle 10g BTW. I doubt you're using Oracle, so you'll need to convert to your own database.
Running a test shows the following:
```
```
SQL> create table menu_items ( id number, name varchar2(10));
create table order_items (order_id number, menu_item_id number, quantity number);
create table orders (id number, "date" date);

Table created.

SQL>
Table created.

SQL>
Table created.

SQL>
insert into menu_items values (1, 'bread');
insert into menu_items values (2, 'milk');
insert into menu_items values (3, 'honey');
insert into menu_items values (4, 'cheese');
SQL>
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL>
insert into orders values (1, to_date('2008-11-02', 'YYYY-MM-DD'));
insert into orders values (2, to_date('2008-11-03', 'YYYY-MM-DD'));
insert into orders values (3, to_date('2008-10-29', 'YYYY-MM-DD'));SQL>
1 row created.

SQL>
1 row created.

SQL>
insert into order_items values (1, 1, 1);
insert into order_items values (1, 3, 1);
1 row created.

SQL>
1 row created.

SQL>
insert into order_items values (2, 1, 1);
insert into order_items values (2, 2, 1);
insert into order_items values (2, 3, 1);

insert into order_items values (3, 4, 10);
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL> SQL>

1 row created.

SQL>
SELECT
    name
    , nvl(count, 0) as count
FROM
    menu_items items
    LEFT JOIN (
        SELECT
            menu_items.id
            , SUM(order_items.quantity) as count
        FROM
            menu_items
            LEFT JOIN order_items ON menu_items.id = order_items.menu_item_id
            LEFT JOIN orders ON orders.id = order_items.order_id
        WHERE
            "date" between to_date('2008-11-01','YYYY-MM-DD') and to_date('2008-11-30','YYYY-MM-DD')
        GROUP BY
            menu_iteSQL>   2    3    4    5    6    7  ms.id
    ) counts on items.id = counts.id;  8    9   10   11   12   13   14   15   16   17   18

NAME            COUNT
---------- ----------
bread               2
milk                1
honey               2
cheese              0

SQL>
drop table menu_items;
drop table order_items;
drop table orders;SQL>
Table dropped.

SQL>
Table dropped.

SQL>

Table dropped.

SQL>
```
```
PS: It's bad practice to use 'date' as a column name as it is (in most cases) a type name and can cause problems to queries and parses.


q:
The first batch file launches a command prompt, i need the second command to be in the ccontext of the first.  how can I do this in python?

As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes devenv without the necessary context.

os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')

think of it as in i'm in bash, and i need to execute a command in a perl context, so i type perl -c 'asdf'.  executing perl and asdf back to back won't work, i need to get the devenv inside of the perl context.

[A]
You could append the devenv command onto the end of the original batch file like so:
```
```
'%comspec% /k "...vcvarsall.bat" x86 && devenv asdf.sln /rebuild ...'
```
```
(obviously I have shortened the commands for simplicity's sake)


q: Is there a way to create a Distinct query in HQL.  Either by using the "distinct" keyword or some other method.  I am not sure if distinct is a valid keywork for HQL, but I am looking for the HQL equivalent of the SQL keyword "distinct".

[A]
Here's a snippet of hql that we use. (Names have been changed to protect identities)
```
```
String queryString = "select distinct f from Foo f inner join foo.bars as b" +
                " where f.creationDate >= ? and f.creationDate < ? and b.bar = ?";
        return getHibernateTemplate().find(queryString, new Object[] {startDate, endDate, bar});
```
```


q:
I have been searching for a way to allow one element of my FileHelpers mapping class to be an array of specific length.

For instance, I have a class like this:

[DelimitedRecord(",")]
public class Example
{
    public string code;
    public int month;
    public int day;
    public double h1;
    public double h2;
    public double h3;
    public double h4;
}

The values h1-h4 would really make more sense as an array simply called 'h'.  It would make processing the file a little easier as well.
I also know that the file I am reading will always have these, and only these, fields in it.

Has anyone figured out a way to include arrays in your FileHelper mapping classes?

[A]
I don't know anything about the tool in question, but (assuming it isn't a limitation of the tool) I
really
doubt the wisdom of public fields. Properties would also give you the opportunity to shim the values:
```
```
[DelimitedRecord(",")]
public class Example
{
    public string Code {get;set;}
    public int Month {get;set;}
    public int Day {get;set;}

    private readonly double[] h = new double[4];

    public double H1 {get {return h[0];} set {h[0] = value;}}
    public double H2 {get {return h[1];} set {h[1] = value;}}
    public double H3 {get {return h[2];} set {h[2] = value;}}
    public double H4 {get {return h[3];} set {h[3] = value;}}
}
```
```
Again - I have no idea if the tool would support this, but it would be a viable way of implementing it. Of course, the "h" values would do just as well (actually, slightly more efficient - no array on the heap and no de-reference) as direct members:
```
```
public double H1 {get;set;}
    public double H2 {get;set;}
    public double H3 {get;set;}
    public double H4 {get;set;}
```
```


q:
AlertEvent::AlertEvent(const std::string& text) :
    IMEvent(kIMEventAlert, alertText.c_str()),
    alertText(text)
{
    //inspection at time of crash shows alertText is a valid string
}

IMEvent::IMEvent(long eventID, const char* details)
{
    //during construction, details==0xcccccccc
}

on a related note, the monospace font looks really terrible in chrome, whats up with that?

[A]
The IMEvent constructor is called before alertText's constructor is called. In particular therefore its argument
```
alertText.c_str()
```
is evaluated before alertText's constructor is called. This ain't good.
Initializer expressions are called in the order that the things being initialized are declared (not necessarily the order the initializers are listed). So parent classes first, then members. Compilers sometime helpfully warn you if you don't list the initializers in the order they will actually be executed. So provided you get that right, the rule is "don't use anything you haven't initialized". This code uses alertText before it is initialized.


q: I am trying to get the DataGridView to render the "insert new row" row as the first row in the grid instead of the last row. How do I go about doing that, is it even possible in the control?

[A]
I don't think there is any way to move the "new row" row to the top of the data grid.
But, what if you left the top row empty and as the data filled in move the row down as appropriate?  In other words, make your own "new row" row, which is just first row in the grid and add new blank rows above when editing is over.
```
```
Dim myrow = existingDataTable.NewRow

    existingDataTable.Rows.Add(myrow)

    adp.Fill(existingDataTable)
    With DataGridView1
        .DataSource =existingDataTable
    End With
```
```


q:
I have N items of 2D image data that will be rectangular and I want to pack them into a single power of 2 texture as efficiently as possible.

A simple non-efficient and naive implementation of an algorithm to pack these rects would be easy to whip up, but I'm sure people have come up with algorithms to do this as space efficiently as possible.  I've found various references to lightmap packing which is similar to what I'm looking for, but the algorithms for lightmapping tend to take non-rectangular images into account which actually complicates things more than I need them to be.

Does anyone have hints? Names of algorithms or paper authors I should google?

Thanks.

[A]
Your problem in 1D is called Bin Packing. Perhaps that's a good start for your search.
Note that the problem you want to solve is really hard (it is NP-hard). So you should not search for the optimal solution, but some clever heuristical algorithm.
I think bottom-up dynamic programming is possible for 1D bin packing, but not for the 2D case.
You could think of simplifying your problem by only solving the 1D problem, making restrictions like cutting the textures into several (variable sized) slices in 1 dimension.
Another possiblity is running meta-heuristic optimization on it, like Evolutionary Algorithms or Particle Swarm Optimization.


q:
For my small wiki application, I mostly need to have the textarea used to edit the contents to use soft (or virtual) wrapping. However, in some cases, not wrapping the content would be preferable. I thought I would do this by simply having a button to turn off wrapping. Here is the simplified code:

  <form name="wikiedit" action="[[script_name]]" method="post">
    <textarea name="content" rows="25" cols="90" wrap="virtual">[[content]]</textarea>
    <input type="button" onclick="document.wikiedit.content.wrap='off';" value="No Wrap"> &nbsp;
    <input type="submit" value="Save">
  </form>

It works with IE, but not with Firefox or Opera. How should I do this?

[A]
According to
the HTML 4.01 spec
,
```
wrap
```
isn't a valid attribute for
```
<textarea>
```
s which would explain why it's so difficult and strange. It looks as though Firefox actually does use the
```
wrap
```
attribute, but it won't let you change it.
I do have a solution though! It's pretty awful, but here it is. Completely replace the textarea with a new one.
```
```
// this is the onclick handler for your button
document.getElementById("nowrapButton").onclick = function() {
  var oldOne = this.form.content;  // the old textarea
  var newOne = document.createElement('textarea'); // the new textarea
  var attrs = ['name', 'rows', 'cols']; // these are the attributes to keep
  for (var i = 0; i < attrs.length; ++i) {
    // copy the attributes to the new one
    newOne.setAttribute(attrs[i], oldOne.getAttribute(attrs[i]));
  }

  // toggle the wrapping on and off
  if (oldOne.getAttribute('wrap') != 'off') {
    newOne.setAttribute('wrap', 'off');
  }

  // copy the text over
  newOne.value = oldOne.value;

  // add the new one
  oldOne.parentNode.insertBefore(newOne, oldOne);
  // get rid of the old one
  oldOne.parentNode.removeChild(oldOne);
  return false;
};
```
```
Here's a working version of this you can play with:
http://jsbin.com/ugepa
As usual, this'd be much nicer in jQuery. :)


q:
In the following code I loop through a map and test if an element needs to be erased.  Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?

map<string, SerialdMsg::SerialFunction_t>::iterator pm_it;
for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++)
{
    if (pm_it->second == delete_this_id) {
        port_map.erase(pm_it->first);
    }
}

UPDATE: Of course, I then read this question which I didn't think would be related but answers my question.

[A]
C++11
This has been fixed in C++11 (or erase has been improved/made consistent across all container types).
The erase method now returns the next iterator.
```
```
auto pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    if (pm_it->second == delete_this_id)
    {
        pm_it = port_map.erase(pm_it);
    }
    else
    {
        ++pm_it;
    }
}
```
```
C++03
Erasing elements in a map does not invalidate any iterators.
(apart from iterators on the element that was deleted)
Actually inserting or deleting does not invalidate any of the iterators:
Also see this answer:
Mark Ransom Technique
But you do need to update your code:
In your code you increment pm_it after calling erase. At this point it is too late and is already invalidated.
```
```
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    if (pm_it->second == delete_this_id)
    {
        port_map.erase(pm_it++);  // Use iterator.
                                  // Note the post increment.
                                  // Increments the iterator but returns the
                                  // original value for use by erase
    }
    else
    {
        ++pm_it;           // Can use pre-increment in this case
                           // To make sure you have the efficient version
    }
}
```
```


q:
Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?

I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

Is there a better way to accomplish this?

[A]
Do:
```
```
var isTrueSet = (myValue === 'true');
```
```
using the identity operator (
```
===
```
), which doesn't make any implicit type conversions when the compared variables have different types.
This will set
```
isTrueSet
```
to a boolean
```
true
```
if the string is "true" and boolean
```
false
```
if it is string "false" or not set at all.
Don't:
You should probably
be cautious about using these two methods
for your specific needs:
```
```
var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true
```
```
Any string which isn't the empty string will evaluate to
```
true
```
by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.


q:
What's the best way to convert NetBeans (Matisse) .form files into .java files, without using the NetBeans IDE itself? Ideally I'd like to package the .form files along with my source code, and generate the .java files at build time. This will prevent developers from "accidentally" adding code to the generated .java file using some other IDE, which could then get overwritten by NetBeans the next time the form itself is edited in the GUI designer.

I've searched Google and all I can find is people saying, "Use the NetBeans IDE to generate the .java file," which is kind of difficult to do at build-time.

[A]
Well, actually having to fight with "accidental" addition of codes is more a problem of process rather than a problem with technology. My steps would be:
Prevent committing the generated .java files in the CVS/SVN repository
Embed matisse form generation in a continuous integration project.
For step 1:
Use a sensible naming convention and stick with the standard for all the gui object, e.g.: put all the forms inside a common package and use the .svnignore directive on java files in it.
For step 2:
Fabrizio Giudici has a nice tutorial on how to build a netbeans project (yes using matisse) inside a continuous integration environment.
http://weblogs.java.net/blog/fabriziogiudici/archive/2006/11/setting_up_netb.html
Note that he talks about installing netbeans first on a machine with a gui then moving the jar files in an headless machine. IIRC it was possible to install Netbeans version 4.x in an headless environment without using the gui (since it is a java application, the only steps to do were to unzip the files and create a sensible shell file launching the application with the correct jvm/classpath combo).
Anyway, if you can't enforce both rules, or you can't find how to generate the matisse artifacts in the CI server, consider the possibility to scrap the use of matisse entirely.


q:
Yeah, I know the title is a mouthful...

What I mean is to say is how do you communicate with a subject matter expert who needs a theory coded and tested?

For example, weather simulation is a collaboration between meteorologists, computer scientists, and software engineers.  The computer scientists and software engineers generally speak the same language, but he meteorologist is in a completely different world.

How do you increase the level of communication and understanding between disciplines?  And not necessarily just for weather, other sciences too.

[A]
The shortest possible answer is Continuous customer involvement.
All the pretty UML diagrams, crayola UI mockups, explanations-to-four-year-olds and other techniques will never give the full experience of using a working application. Keeping the consumer in the loop allows for a feedback cycle both to the client, and from the client to you.  This symbiotic relationship has the greatest likelyhood of producing a product that will be useful to them.
If you go into a box and come out with a product that you think they need it will likely be a whole lot of what they don't want.  By regularly demoing your product you limit the impact of any misunderstanding, so that you don't spend too much time going down the wrong path.
It can be compared to dead reckoning. If you blindfold yourself and try to navigate through an area you know, the error between where you are and where you think you are will accumulate with time.  If, however, you take off the blindfold periodically you can update your mental location.  There will still be an error factor, but you are eliminating the accumulating error factor.
Even if you think your communication/explanatory skills are top notch, you still have to account for error in the way they communicate.


q:
I have a Delphi 5 executable that calls into a .NET assembly via the free Delphi .NET code, and for the most part, this works great.  However, one of the requirements of my application is that our clients be able to use this from a networked share as well as local.  On my test machine, I can't get this to work, I just get an error message.  The .NET code has it's permissions set to full, but some error comes back that Delphi can't seem to get or interpret.  On a local drive, the application and assembly communicate flawlessly.

Can anyone tell me how to at least get the error messages back from this?  Or if possible, can anyone tell me why I would get errors this way?  Thanks.

[A]
You say that you have given the code full permissions, but have you assigned FullTrust to the network share? In .NET, network shares are part of the local intranet domain, so you lose some trust. Run something like;
```
```
CasPol.exe -m -ag 1.2 -url file://\\ShawnFa-Srv/Tools/* FullTrust
```
```
For more info see this post about the topic,
Using CasPol to Fully Trust a Share


q:
I don't want to include relations in my edmx entity framework, I want to have the foreign key field as a normal property in my entity.

How can I do that?

[A]
http://www.thedatafarm.com/blog/2007/09/11/EntityDataModelAssociationsWheresMyForeignKey.aspx
I found the article describing the error in our ways...
basically we never supposed to be querying tables via foreign keys instead
take a bit more relational approach
```
```
(From o In nw.Orders
 Where o.OrderID = 10281
 Select o.Customers
).First
```
```


q:
I find it much easier to write MXML classes with embedded Script than trying to make an actionscript file.

I was wondering however what kind of overhead there is of using an MXML file - in terms of file size. I'm not especially concerned about performance, but if that is relevant would be interested in any findings.

Obviously I'm talking about UI components that have layout. MXML is MUCH easier to visualize and modify but I'm unclear exactly what it compiles down too. I'm hoping there is a negligible difference.

[A]
If you're going for the same functionality, MXML is not going to make your swf any bigger.
The thing that's affecting size is using the Flex SDK and its components. Whether you declare them with MXML or AS3, you're using them and their code is being built into the swf. By the same token, if you're referencing the Flex RSL, and thus avoiding building the Flex stuff directly into your swf, it will be the same size either way. Data Binding does create a lot of events and listeners, so that might cause some bloat, but not any more than if you declared the data binding mechanism with the AS3 utility functions.
Since MXML does generate intermediate AS3 code, it might be more verbose than you would care to write on your own, so you could see some additional size from that. To peek at it (which is good for understanding in general) you can look at with the compiler directive to keep the generated code.
From:
http://www.flashguru.co.uk/flex-2-compilation-hidden-goodies
Right-click a Flex Project in the Navigator Panel.
Select Properties from the Context Menu.
Select Flex Compiler in the Properties Window.
Enter -keep-generated-actionscript into the ‘Additional compiler
  arguments’ field.
Click ‘OK’ to apply the changes.
Build your Flex Project by clicking the Run button.
Right-click your Flex Project again in the Navigator Panel.
Choose Refresh from the Context-Menu.
A new folder should appear under your Flex Project in the Navigator
  Panel, named ‘generated’
This is a good thing to do once you get into debugging and profiling your project, since you can really see where the compiler is doing the right (or wrong) thing.


q:
For example:

First, say I have a Silverlight app with Windowless=true so that I can place ASP.NET controls on top of it.  Then I place an ASP.NET button on the page.  How can I have say the text of a control in the Silverlight app change when the user presses the ASP.NET button?  How would I send the Silverlight app an update message from the C# code that catches the Click of the ASP.NET button?

Thanks,
Jeff

[A]
Splitting the content of your file into multiple files - one file per class may help.
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=283434
Up-to-date link:
https://developercommunity.visualstudio.com/content/problem/389773/vs-2017-keeps-removing-and-re-adding-aspxcodebehin.html


q:
What is the most efficient way to cacluate the closest power of a 2 or 10 to another number? e.g.

3.5 would return 4 for power of 2 and 1 for power of 10

123 would return 128 for power of 2 and 100 for power of 10

0.24 would return 0.25 for power of 2 and 0.1 for power of 10

I'm just looking for the algorithm and don't mind the language.

[A]
```
```
n^round(log_n(x))
```
```
where log_n is the logarithm to base n. You may have to modify the round() depending on how you define "closest".
Note that
```
log_n(x)
```
can be implemented as:
```
```
log_n(x) = log(x) / log(n)
```
```
where
```
log
```
is a logarithm to any convenient base.


q:
How can I make:

DELETE FROM foo WHERE id=1 AND bar not contains id==1

To elaborate, how can I remove a row with id = 1, from table foo, only if there is not a row in table bar with id = 1.

[A]
```
```
DELETE FROM foo WHERE id=1 AND NOT EXISTS (SELECT * FROM bar WHERE id=1)
```
```
I'm assuming you mean that foo and bar are tables, and you want to remove a record from foo if it doesn't exist in bar.


q:
I have a program that when it starts, opens a winform (it is the one specified in Application.Run(new ...). From this form I open another form:

OtherForm newForm=new OtherForm();
newForm.Show();

How can i communicate from the new winform with the form that opened it? So that I can add some items in it.

[A]
The simplest way is to override the constructor, eg,
```
OtherForm newForm=new OtherForm(string title, int data);
```
. This also works for reference types (which would be a simple way to send the data back).


q:
We've got an application we'd like our users to download.  Currently they click a link and download the EXE.  What we'd like to do is have a launchpad/downloader application that would be small and fast to download, which would then download and install the main application.

In a perfect world the downloader would be a MSI (so we could modify some MSI databases).

I'm a seriosu MSi newbie, so I've got no real ideas on where ot even start looking.  Any help or pointers woudl be much appreciated!

Thanks

Andy

[A]
You'll need to write a bootstrap EXE, there's a little bit of documentation in
Windows Installer SDK
or if you're wanting to take the lazy route, it looks like
MSI Factory
includes WiX compatibility and a customizable bootstrap EXE including HTTP download options.
Alternatively if you're sticking to Open-Source, checkout ClickThrough in WiX. Doesn't seem to be much info on the WiX site, so I'm guessing it's part of WiX 3. But the description sounds similar to what you need.


q: How can I fetch more than 1000 record from data store and put all in one single list to pass to django?

[A]
You can't.
Part of the FAQ states that there is no way you can access beyond row 1000 of a query, increasing the "OFFSET" will just result in a shorter result set,
ie: OFFSET 999 --> 1 result comes back.
From Wikipedia:
App Engine limits the maximum rows
  returned from an entity get to 1000
  rows per Datastore call. Most web
  database applications use paging and
  caching, and hence do not require this
  much data at once, so this is a
  non-issue in most scenarios.[citation
  needed] If an application needs more
  than 1,000 records per operation, it
  can use its own client-side software
  or an Ajax page to perform an
  operation on an unlimited number of
  rows.
From
http://code.google.com/appengine/docs/whatisgoogleappengine.html
Another example of a service limit is
  the number of results returned by a
  query. A query can return at most
  1,000 results. Queries that would
  return more results only return the
  maximum. In this case, a request that
  performs such a query isn't likely to
  return a request before the timeout,
  but the limit is in place to conserve
  resources on the datastore.
From
http://code.google.com/appengine/docs/datastore/gqlreference.html
Note: A LIMIT clause has a maximum of
  1000. If a limit larger than the maximum is specified, the maximum is
  used. This same maximum applies to the
  fetch() method of the GqlQuery class.
Note: Like the offset parameter for
  the fetch() method, an OFFSET in a GQL
  query string does not reduce the
  number of entities fetched from the
  datastore. It only affects which
  results are returned by the fetch()
  method. A query with an offset has
  performance characteristics that
  correspond linearly with the offset
  size.
From
http://code.google.com/appengine/docs/datastore/queryclass.html
The limit and offset arguments control
  how many results are fetched from the
  datastore, and how many are returned
  by the fetch() method:
The datastore fetches offset + limit results to the application. The first offset results are
not
skipped by the datastore itself.
The fetch() method skips the first offset results, then returns the rest (limit results).
The query has performance characteristics that correspond
  linearly with the offset amount plus the limit.
What this means is
If you have a singular query, there is no way to request anything outside the range 0-1000.
Increasing offset will just raise the 0, so
```
```
LIMIT 1000  OFFSET 0
```
```
Will return 1000 rows,
and
```
```
LIMIT 1000 OFFSET 1000
```
```
Will return
0 rows
, thus, making it impossible to, with a single query syntax, fetch 2000 results either manually or using the API.
The only plausible exception
Is to create a numeric index on the table, ie:
```
```
SELECT * FROM Foo  WHERE ID > 0 AND ID < 1000

 SELECT * FROM Foo WHERE ID >= 1000 AND ID < 2000
```
```
If your data or query can't have this 'ID' hardcoded identifier, then you are
out of luck


q:
I've been reading on the blogosphere for the past week that Linq to SQL is dead [and long live EF and Linq to Entities].  But when I read the overview on MSDN, it appeared to me Linq to Entities generates eSQL just the way Linq to SQL generates SQL queries.

Now, since the underlying implementation (and since SQL Server is not yet an ODBMS) is still a Relational store, at some point the Entity framework has to make the translation into SQL queries.  Why not fix the Linq to SQL issues (m:m relationships, only SQL server support etc.) and use Linq to SQL in as the layer that generates these queries?

Is this because of performance or EF uses a different way of transforming the eSQL statement into SQL?

It seemed to me - at least for my unlearned mind - a natural fit to dogfood Linq to SQL in EF.

Comments?

[A]
It is worth noting that Entity Framework has (at least) three ways of being consumed:
LINQ to Entities over Object Services over Entity Client
Entity SQL over Object Services over Entity Client
Entity SQL using Entity Client command objects (most similar to classic ADO.NET)
Entity Client ultimately spits out a representation of the ESQL command (in a canonical, database agnostic form) which the ADO.NET Provider for the specific RDBMS is responsible for converting into store specific SQL. This is the right model IMHO as over the years a lot of time has been invested (and will continue to be invested) in producing great ADO.NET Providers for each store.
As Entity Framework needs to work with many stores and therefore many ADO.NET Providers there is less scope for them to easily optimise what the Entity Client generates on a per store basis (at least - thats where we are with v1). The LINQ to SQL team had a much smaller problem to solve - "works only with SQL Server" and hence could do store specific stuff more easily. I know the EF team are aware that there are cases where EF to SQL Server is producing TSQL less efficiently than L2S and are working on improving this for V2.
Interestingly this model allows new capabilities to be added between the Entity Client and the ADO.NET Provider for a store. These "wrapping providers" can add services such as logging, auditing, security, caching. This is discussed as a V2 feature over at
http://blogs.msdn.com/efdesign/archive/2008/07/09/transparent-caching-support-in-the-entity-framework.aspx
If you look therefor at the bigger picture you can see that it would be horribly difficult and indeed restrictive to try and somehow retrofit L2S TSQL generation into the archiecture of the Entity Framework.


q:
I am looking to use quartz to schedule emails, but I'm not sure which approach to take:

Create a new job and trigger whenever an email is scheduled OR

Create a single job, and create a new trigger each time an email is scheduled

I need to pass the message/recipient etc either way, and I'm not sure whether creating heaps of jobs will start adding considerable memory overheads, as there will quite possibly be thousands of emails scheduled.

Update: These emails will be scheduled by users, not by me - so I will be adding these programmatically at runtime, they aren't scheduled to go out at any particular time.

[A]
You might consider queuing or otherwise grouping a set of emails and have a single, or maybe a few, periodic (or scheduled) job(s) that then takes care of the 'batch'.
You could even have the Quartz job queue the emails for a collection of workers to consume and send.
I would not recommend thousands of Quartz jobs/triggers - it just isn't the intended use of the tool (IMHO).
EDIT: In response to the comment below:
I would not recommend thousands of Quartz jobs/triggers when used as part of a framework executing an application in the same JVM, The jobs/triggers will be competing for resources with the rest of the application.


q: How do you determine what to put in .rhosts file in an VAX openvms system when trying to remotely access the server using a remote shell from Cygwin on windows XP ? .rlogin and rsh are the only methods that can be used to access the VAX server and it must be using Cygwin to remote in to the VAX server. SSH is not an option. When the VAX server is accessed from a Sun server it works fine. I have tried many combination's of possible things that Cygwin could be sending the VAX as far as a user name an address of origin.

[A]
In lib/gzip.py, we find the method that builds the header, including the part that does indeed contain a timestamp. In Python 2.5, this begins on line 143:
```
```
def _write_gzip_header(self):
    self.fileobj.write('\037\213')             # magic header
    self.fileobj.write('\010')                 # compression method
    fname = self.filename[:-3]
    flags = 0
    if fname:
        flags = FNAME
    self.fileobj.write(chr(flags))
    write32u(self.fileobj, long(time.time())) # The current time!
    self.fileobj.write('\002')
    self.fileobj.write('\377')
    if fname:
        self.fileobj.write(fname + '\000')
```
```
As you can see, it uses time.time() to fetch the current time. According to the online module docs, time.time will "return the time as a floating point number expressed in seconds since the epoch, in UTC." So, if you change this to a floating-point constant of your choosing, you can always have the same headers written out. I can't see a better way to do this unless you want to hack the library some more to accept an optional time param that you use while defaulting to time.time() when it's not specified, in which case, I'm sure they'd love it if you submitted a patch!