Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is it good practice to let abstract classes define instance variables?
```
public abstract class ExternalScript extends Script {
String source;
public abstract void setSource(String file);
public abstract String getSource();
}
```
The sub class, ExternalJavaScript.class, would then automatically get th... | I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.
```
public abstract class ExternalScript extends Script {
private String source;
public void setSource(St... | Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer... | Java - Abstract class to contain variables? | [
"",
"java",
"class",
"variables",
"abstract",
""
] |
I have a problem with a simple included file.
The file being included is in two MFC programs - one of which is a dll, and it also compiles itself into a non-mfc dll.
Recently I was using the larger dll which wraps around the *source* of the smaller dll when I wanted access to some of the features of the original code... | This doesn't have anything to do with the way you include files, it's a syntax error that you get because you didn't nest `(` and `)` correctly. | Build using the /P option, which will create a preprocessed file (usually with the .i extension).
In Visual Studio, the option will be on the properties for the project under something like:
```
C/C++ - Preprocessor - Generate Preprocessed File
```
With that you can see exactly how macros are being expanded. Yo... | Weird #include problem | [
"",
"c++",
"dll",
"include",
"visual-c++-6",
""
] |
I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords. | Try changing your session code as this is the best way to do this.
For example:
## index.php
```
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
echo '<a href="nextpage.php">Click to contin... | I Agree with carson, sessions should work for this. Make sure you are calling [session\_start()](https://www.php.net/session_start) before anything else on any page you want to use the session variables.
Also, I would not store password info directly, rather use some kind of authentication token mechanism. IMHO, it is... | Transfer variables between PHP pages | [
"",
"php",
"variables",
""
] |
I've been asked by my team leader to investigate MSMQ as an option for the new version of our product. We use SQL Service Broker in our current version. I've done my fair share of experimentation and Googling to find which product is better for my needs, but I thought I'd ask the best site I know for programming answer... | Having just migrated my application from Service Broker to MSMQ, I would have to vote for using MSMQ. There are several factors to take into account, but most of which have to do with how you are using your data and where the processing lives.
* If processing is done in the database? **Service Broker**
* If it is just... | I've used MSMQ before and the only item I'd add to your list is a prerequisite check for versioning. I ran into an issue where one site had Win 2000 Server and therefore MSMQ v.2, versus Win 2003 Server and MSMQ v3. All my .NET code targeted v.3 and they aren't compatible... or at least not easily so.
Just a considera... | Should I use MSMQ or SQL Service Broker for transactions? | [
"",
"sql",
"transactions",
"msmq",
"service-broker",
""
] |
I know that this question has already been asked [HERE](https://stackoverflow.com/questions/41207/javascript-interactive-shell-with-completion) but sadly none of the answers suggest a javascript standalone shell that has auto completion. I am reopening this question again, in the hope that some new answers might be fou... | **edit**: after using the node REPL a bit more, I've discovered this evaluation to be overly positive. There are some serious problems with its implementation, including an inability to yank killed text, issues with editing lines that are longer than the terminal width, and some other problems. It might be better to ju... | According to [this blog post](http://blog.norrisboyd.com/2008/03/better-line-editing-for-rhino-shell.html), autocompletion is now available for [Rhino](https://developer.mozilla.org/en/Rhino_Shell), as long as the [JLine](http://jline.sourceforge.net/) library is included. | Javascript shell? | [
"",
"javascript",
"shell",
""
] |
I haven't been able to find an adequate answer to what exactly the following error means:
`java.net.SocketException: Software caused connection abort: recv failed`
Notes:
* This error is infrequent and unpredictable; although getting this error means that all future requests for URIs will also fail.
* The only solut... | This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywh... | This also happens if your TLS client is unable to be authenticate by the server configured to require client authentication. | java.net.SocketException: Software caused connection abort: recv failed | [
"",
"java",
"sockets",
""
] |
I have the following problem in my *Data Structures and Problem Solving using Java* book:
> Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.
I'm not putting it up here because I want somebody to do my homework, I just can't seem to und... | Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:
```
List temp = new ArrayList(src);
Collections.reverse(... | First, I believe it is asking you to write a method. Like:
```
void printReverseList(Collection col) {}
```
Then there are many ways to do this. For example, only using the Collection API, use the toArray method and use a for loop to print out all the items from the end. Make sense?
As for the various classes using ... | Printing out items in any Collection in reverse order? | [
"",
"java",
"collections",
""
] |
In following code, I want to extend the behaviour of a class by deriving/subclassing it, and make use of an event of the base class:
```
public class A
{
public event EventHandler SomeEvent;
public void someMethod()
{
if(SomeEvent != null) SomeEvent(this, someArgs);
}
}
public class B : A
{
... | The standard practice here is to have a protected virtual method OnSomeEvent on your base class, then call that method in derived classes. Also, for threading reasons you will want to keep a reference to the handler before checking null and calling it.
For an explanation of the why read [Jon Skeet's](https://stackover... | Others have explained how to get round the issue, but not why it's coming up.
When you declare a public field-like event, the compiler creates a public event, and a private field. Within the same class (or *nested* classes) you can get at the field directly, e.g. to invoke all the handlers. From other classes, you onl... | Why events can't be used in the same way in derived classes as in the base class in C#? | [
"",
"c#",
"events",
""
] |
I wanted to try a little design by contract in my latest C# application and wanted to have syntax akin to:
```
public string Foo()
{
set {
Assert.IsNotNull(value);
Assert.IsTrue(value.Contains("bar"));
_foo = value;
}
}
```
I know I can get static methods like this from a unit test fra... | > ## C# 4.0 Code Contracts
Microsoft has released a library for design by contract in version 4.0 of the .net framework. One of the coolest features of that library is that it also comes with a static analysis tools (similar to FxCop I guess) that leverages the details of the contracts you place on the code.
Here are... | [Spec#](http://en.wikipedia.org/wiki/Spec_sharp) is a popular [microsoft research project](http://research.microsoft.com/SpecSharp/) that allows for some DBC constructs, like checking post and pre conditions. For example a binary search can be implemented with pre and post conditions along with loop invariants. [This e... | 'Design By Contract' in C# | [
"",
"c#",
"design-by-contract",
""
] |
Is it possible to configure two separate web apps (WAR) in a J2EE application (EAR) to access a shared session context?
Further info:
I ended up creating a shared class from the EAR which stored the required information in static members. This did the trick, even if it seemed like a dirty hack. | Not directly. Most containers put each WAR in a separate classloader with the EAR classloader as their parent. Each app's sessions are separate. You can put something provided by the parent EAR in each session. If you need them to share something, make it a EAR function. | As far as i've read and seen, it is not possible to share sessions across different webapps. You can only serialize a session for transfer between instances of the same webapp. | Access session of another web application | [
"",
"java",
"session",
"war",
"httpsession",
""
] |
For example, suppose I have a class:
```
class Foo
{
public:
std::string& Name()
{
m_maybe_modified = true;
return m_name;
}
const std::string& Name() const
{
return m_name;
}
protected:
std::string m_name;
bool m_maybe_modified;
};
```
And somewhere else in th... | Two answers spring to mind:
1. The non-const version is a closer match.
2. If it called the const overload for the non-const case, then under what circumstances would it *ever* call the non-const overload?
You can get it to use the other overload by casting `a` to a `const Foo *`.
**Edit:** From [C++ Annotations](ht... | Because a is not a const pointer. Therefore, a non-const function is a closer match. Here is how you can call the const function:
```
const Foo* b = a;
std::string name = b->Name();
```
If you have both a const and a non-const overload, and want to call the const one on a non-const object, this might be an indication... | In c++, why does the compiler choose the non-const function when the const would work also? | [
"",
"c++",
"constants",
"overload-resolution",
"const-reference",
"function-qualifier",
""
] |
Here is the input (html, not xml):
```
... html content ...
<tag1> content for tag 1 </tag1>
<tag2> content for tag 2 </tag2>
<tag3> content for tag 3 </tag3>
... html content ...
```
I would like to get 3 matches, each with two groups. First group would contain the name of the tag and the second group would contain ... | I don't see why you would want to use match group names for that.
Here is a regular expression that would match tag name and tag content into numbered sub matches.
```
<(tag1|tag2|tag3)>(.*?)</$1>
```
Here is a variant with .NET style group names
```
<(?'name'tag1|tag2|tag3)>(?'value'.*?)</\k'name'>.
```
EDIT
Reg... | Is the data proper xml, or does it just look like it?
If it is html, then the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) is worth investigation - this provides a DOM (similar to XmlDocument) that you can use to query the data:
```
string input = @"<html>...some html content <b> etc </b> ...
<user> h... | Regex for specifig tags and their content, groupped by the tag name | [
"",
"c#",
"regex",
"tags",
""
] |
I provide a web service to my organisation. i was wondering would anyone recommeding the use of apache cactus for setting up a testing framework or has anyone worked with any other web service frameworks that may be useful?
Thanks
Damien | As you are dealing with a web service you would not need to use Jakarta Cactus and could get away with writing plain old JUnit tests.
The tests would take two forms:
**1. Does the underlying functionality work as expected?**
This has nothing to do with the web service itself but the underlying functionality it provi... | There is an open source application called SoapUI(<http://www.soapui.org/>). With this application, you can do
1) manual testing of webservices OR
2) use groovy (a java like scripting) language to do functional testing.
It works pretty well and a lot of organizations are using it. They have an open source version as w... | Java Webservice testing | [
"",
"java",
"web-services",
"testing",
""
] |
In our office, we regularly enjoy some rounds of foosball / table football after work. I have put together a small java program that generates random 2vs2 lineups from the available players and stores the match results in a database afterwards.
The current prediction of the outcome uses a simple average of all previou... | Use the TrueSkill algorithm, it is very good at this. I've implemented it for foosball and chess and it works very well. Coworkers have told me that it's almost *too* good at this.
For complete details on how it works as well as a link to my implementation, see my "[Computing Your Skill](http://www.moserware.com/2010/... | Why use a neuralnet? Use statistics, probably the correlation between each player would be good measure. | Foosball result prediction | [
"",
"java",
"mysql",
"prediction",
""
] |
We have a TIBCO EMS solution that uses built-in server failover in a 2-4 server environment. If the TIBCO admins fail-over services from one EMS server to another, connections are supposed to be transfered to the new server automatically at the EMS service level. For our C# applications using the EMS service, this is n... | *This post should sum up my current comments and explain my approach in more detail...*
The TIBCO 'ConnectionFactory' and 'Connection' types are heavyweight, thread-safe types. TIBCO suggests that you maintain the use of **one** ConnectionFactory (per server configured factory) and **one** Connection per factory.
The... | First off, yes, I am answering my own question. Its important to note, however, that without ajmastrean, I would be nowhere. thank you so much!
ONE:
ConnectionFactory.SetReconnAttemptCount, SetReconnAttemptDelay, SetReconnAttemptTimeout should be set appropriately. I think the default values re-try too quickly (on the... | TIBCO EMS Failover reconnect for C# (TIBCO.EMS.dll) | [
"",
"c#",
"tibco",
"tibco-ems",
"ems",
""
] |
I have written a few MSBuild custom tasks that work well and are use in our CruiseControl.NET build process.
I am modifying one, and wish to unit test it by calling the Task's Execute() method.
However, if it encounters a line containing
```
Log.LogMessage("some message here");
```
it throws an InvalidOperationExce... | You need to set the .BuildEngine property of the custom task you are calling.
You can set it to the same BuildEngine your current task is using to include the output seamlessly.
```
Task myCustomTask = new CustomTask();
myCustomTask.BuildEngine = this.BuildEngine;
myCustomTask.Execute();
``` | I have found that the log instance does not work unless the task is running inside msbuild, so I usually wrap my calls to Log, then check the value of BuildEngine to determin if I am running inside msbuild. As below.
Tim
```
private void LogFormat(string message, params object[] args)
{
if (this.BuildEngine != nu... | Unit test MSBuild Custom Task without "Task attempted to log before it was initialized" error | [
"",
"c#",
"msbuild",
"msbuild-task",
"invalidoperationexception",
""
] |
I have a select query that currently produces the following results:
```
Description Code Price
Product 1 A 5
Product 1 B 4
Product 1 C 2
```
Using the following query:
```
SELECT DISTINCT np.Description, p.promotionalCode, p.Price
FROM Price AS p INNER JOIN
... | ```
SELECT
np.Id,
np.Description,
MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',
MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',
MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'
FROM
Price AS p
INNER JOIN nProduct AS np ON p.nProduc... | If you're using SQL Server 2005, you can use the new PIVOT operator.
Simple PIVOT -- the number of orders a customer places for individual products.
Structure of a simple Order table:
```
CREATE TABLE Sales.[Order]
(Customer varchar(8), Product varchar(5), Quantity int)
```
The table contains the following valu... | Rows in their own columns depending on their value | [
"",
"sql",
"select",
""
] |
I have a web application that's branded according to the user that's currently logged in. I'd like to change the favicon of the page to be the logo of the private label, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before?
I'm picturing having a dozen icons in a... | Why not?
```
var link = document.querySelector("link[rel~='icon']");
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';
``` | Here’s some code that works in Firefox, Opera, and Chrome (unlike every other answer posted here). Here is a different [demo of code that works in IE11](http://www.enhanceie.com/test/favicon/dynamic.htm) too. The following example might not work in Safari or Internet Explorer.
```
/*!
* Dynamically changing favicons ... | Changing website favicon dynamically | [
"",
"javascript",
"html",
"dom",
"favicon",
""
] |
I have a web page with `DIV`s with a `mouseover` handler that is intended to show a pop-up information bubble. I don't want more than one info bubble to be visible at a time. But when the user moves the mouse rapidly over two items, I sometimes get two bubbles. This should not happen, because the code for showing a pop... | Yes, Javascript is single-threaded. Even with browsers like Google Chrome, there is one thread per tab.
Without knowing how you are trying to cancel one pop-up from another, it's hard to say what is the cause of your problem.
If your DIVs are nested within one another, you may have an [event propagation](http://www.g... | I don't know the library you are using, but if you are only trying to display one tooltip of somesort at a time... use a flyweight object. Basically a flyweight is something that is made once and used over and over again. Think of a singleton class. So you call a class statically that when first invoked automatically c... | Is JavaScript single threaded? If not, how do I get synchronized access to shared data? | [
"",
"javascript",
"multithreading",
"browser",
"dhtml",
"simile",
""
] |
If you are using php5 and mysql5, is there a substantial advantage to using stored procs over prepared statements? ( i read somewhere you may not get substantial performance gains from mysql5 stored proc) | They are not really the same thing - with stored procedures, your database logic resides inside the database. Prepared statements basically avoid re-parsing queries if they are called multiple times - the performance benefit can vary greatly.
The choice to use one or the other is really dependent on your specific situ... | Stored procedures make sense for professional-grade (IE enterprise-grade) applications where you:
1. Want to allow your database engineer to optimize queries for performance
2. Want to abstract complexity of queries to simple API's
3. WANT your logic distributed, because some of what happens in the database might be i... | Prepared Statement vs. Stored Procedure | [
"",
"php",
"mysql",
"stored-procedures",
"prepared-statement",
""
] |
The examples I've seen online seem much more complex than I expected *(manually parsing &/?/= into pairs, using regular expressions, etc).* We're using asp.net ajax *(don't see anything in their client side reference)* and would consider adding jQuery if it would really help.
I would think there is a more elegant solu... | There is indeed a [QueryString plugin](http://plugins.jquery.com/project/query-object) for jQuery, if you're willing to install the jQuery core and the plugin it could prove useful. | I am using this function in case i don't want to use a plugin:
```
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
... | What is the easiest way to read/manipulate query string params using javascript? | [
"",
"javascript",
"query-string",
""
] |
We're currently running with php 5.2.5. We have now encountered a bug that creates a seg fault. Our first idea at the solution is upgrading to version 5.2.6 but are skeptical of problems that it will create. We are running Apache and host a dozen or so sites.
* Will any existing code break?
* Are there any significant... | It's impossible for any of us to say definitely yes or no about your existing code breaking without performing an analysis on it first.
This is exactly what test environments are for. If you have a test environment set up, you can perform the upgrade, then do regression testing to see if anything breaks. Without this ... | With modern Virtual Machine options [VMware Server](http://www.vmware.com/freedownload/login.php?product=server20), [Microsft Virtual Server](http://www.microsoft.com/windowsserversystem/virtualserver/), [Microsoft Virtual PC](http://www.microsoft.com/windows/downloads/virtualpc/default.mspx) and others, why not set up... | Will upgrading Php 5.2.5 to 5.2.6 result in any problems? | [
"",
"php",
"upgrade",
""
] |
So I am just starting out developing PHP web applications and have finished setting up my server with the following:
* Ubuntu Server
* Apache2
* PHP
* MySQL
* VSFTPD
* and all the other goodies...
Currently when I edit files, I have two methods to update/upload them to the server. I can use vi on the server to make s... | I don't like very much the idea about making changes directly on the server, I can recommend you another approach: Use a version control system, there you check in all the changes that you do to your code, then you can easily checkout or export all the modifications when you deploy, and in that way you'll have the comp... | You can basically use anything that has the feature set you want. Here are but a few options:
* Full blown IDE's
+ [Netbeans](http://www.netbeans.org/)
+ [Eclipse](http://www.eclipse.org/pdt/)
* Lesser IDE's
+ [Anjuta](http://anjuta.sourceforge.net/)
+ [gPHPEdit](http://www.gphpedit.org/)
* Graphical text edit... | What program do you use to edit php remotely and then upload to your server? | [
"",
"php",
"linux",
"ide",
""
] |
I have a string from an email header, like `Date: Mon, 27 Oct 2008 08:33:29 -0700`. What I need is an instance of GregorianCalendar, that will represent the same moment. As easy as that -- how do I do it?
And for the fastest ones -- this is **not** going to work properly:
```
SimpleDateFormat format = ... // whatever... | I'd recommend looking into the Joda Time library, if that's an option. I'm normally against using a third-party library when the core platform provides similar functionality, but I made this an exception because the author of Joda Time is also behind JSR310, and Joda Time is basically going to be rolled into Java 7 eve... | > And for the fastest ones -- this is not going to work properly ...
> because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return -7 \* milisInAnHour.
Well technically this does work, because while it will return... | Convert a string to GregorianCalendar | [
"",
"java",
"calendar",
"timezone",
""
] |
I'm starting a project using a Restful architecture implemented in Java (using the new JAX-RS standard)
We are planning to develop the GUI with a Flex application. I have already found some problems with this implementation using the HTTPService component (the response error codes, headers access...).
Any of you guys... | The problem here is that a lot of the web discussions around this issue are a year or more old. I'm working through this same research right now, and this is what I've learned today.
This [IBM Developer Works article from August 2008](http://www.ibm.com/developerworks/websphere/library/techarticles/0808_rasillo/0808_r... | As many have pointed out `HTTPService` is a bit simplistic and doesn't do all that you want to do. However, `HTTPService` is just sugar on top of the `flash.net.*` classes like `URLLoader`, `URLRequest` and `URLRequestHeader`. Using these you can assemble most HTTP requests.
When it comes to support for other methods ... | Is it feasible to create a REST client with Flex? | [
"",
"java",
"apache-flex",
"rest",
""
] |
The case goes as following:
You have a Boolean property called FullScreenEnabled. You enter some method, and the code within this method is executed iff FullScreenEnabled is true. Which of the 2 approaches below do you use in your everyday programming:
```
private bool FullScreenEnabled { get; set; }
// Check ... | ```
private void MyMethod(bool arg){
if(arg)
return;
//do stuff
};
```
(for voting) | I generally prefer the first version (bailing at the start of the method). It leads to less nesting, which slightly increases readability. Should you decide you don't need to check for the condition in the future, it's also easier to remove the if condition in the first version, especially if you have several such chec... | What is the best practice when having a terminate clause...see explanation :) | [
"",
"c#",
""
] |
For a upcoming project, there are plans to port the existing C++ code that compiles on Windows and Linux to the MacOS(leopard). The software is command line application, but a GUI front end might be planned. The MacOS uses the g++ compiler. By having the same compiler as Linux, it does not seem like there would be any ... | Does your app have a GUI, and which one (native / Qt / Gtk+)?
If not, the issues to watch out for (compared to Linux) are mainly in the dynamic linkage area. OS X uses '-dylib' and '-bundle' and in fact has two kinds of dynamic libraries (runtime loadable and the normal ones). Linux has only one kind (-shared), and is... | You don't need to recode *everything* to Objective-C. There's a strange bastardization of C++ and Objective-C that will allow you to use C++ code from Objective-C, so you could intelligently split up the model code in C++ and view/controller code in Objective-C. To use Objective-C, just suffix your source code files wi... | What are some recommendations for porting C++ code to the MacOS? | [
"",
"c++",
"macos",
"g++",
"portability",
""
] |
Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)
(If there's no platform/filesystem-agn... | Here's code to get the full path to the executing app:
Variable declarations:
```
char pBuf[256];
size_t len = sizeof(pBuf);
```
Windows:
```
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;
```
Linux:
```
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
... | If you fetch the current directory when your program first starts, then you effectively have the directory your program was started from. Store the value in a variable and refer to it later in your program. This is distinct from [the directory that holds the current executable program file](https://stackoverflow.com/q/... | How do I get the directory that a program is running from? | [
"",
"c++",
"c",
"executable-path",
""
] |
This is rather the inverse of [What can you use Python generator functions for?](https://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially use... | **Use a list instead of a generator when:**
1) You need to access the data **multiple** times (i.e. cache the results instead of recomputing them):
```
for i in outer: # used once, okay to be a generator or return a list
for j in inner: # used multiple times, reusing a list is better
...
... | In general, don't use a generator when you need list operations, like len(), reversed(), and so on.
There may also be times when you don't want lazy evaluation (e.g. to do all the calculation up front so you can release a resource). In that case, a list expression might be better. | When is not a good time to use python generators? | [
"",
"python",
"optimization",
"iterator",
"generator",
""
] |
I have the following class in C++:
```
class a {
const int b[2];
// other stuff follows
// and here's the constructor
a(void);
}
```
The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is `co... | Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead.
```
int* a = new int[N];
// fill a
class C {
const std::vector<int> v;
public:
C():v(a, a+N) {}
};
``` | With C++11 the answer to this question has now changed and you can in fact do:
```
struct a {
const int b[2];
// other bits follow
// and here's the constructor
a();
};
a::a() :
b{2,3}
{
// other constructor work
}
int main() {
a a;
}
``` | initialize a const array in a class initializer in C++ | [
"",
"c++",
"initialization",
"c++03",
"array-initialize",
""
] |
I'm looking for a KDTree implementation in Java.
I've done a google search and the results seem pretty haphazard. There are actually lots of results, but they're mostly just little one-off implementations, and I'd rather find something with a little more "production value". Something like apache collections or the ex... | In the book [Algorithms in a Nutshell](http://oreilly.com/catalog/9780596516246/) there is a kd tree implementation in java along with a few variations. All of the code is on [oreilly.com](http://examples.oreilly.com/9780596516246/) and the book itself also walk you through the algorithm so you could build one yourself... | for future seekers. Java-ml library has a kd-tree implementation that work fine.
<http://java-ml.sourceforge.net/> | KDTree Implementation in Java | [
"",
"java",
"data-structures",
"kdtree",
""
] |
I'm a long time Windows developer, and it looks like I'm going to be involved in porting a Windows app to the Mac.
We've decided to use Flex/Air for the gui for both sides, which looks really slick BTW.
My Windows application has a C++ DLL that controls network adapters (wired and wireless). This is written using the... | Xcode is the IDE for Mac OS X, you can download the latest version by joining the Apple Developer Connection with a free Online membership.
I don't believe there are any supported APIs for controlling wireless networking adaptors. The closest thing would be the System Configuration framework, but I don't know if it wi... | The de-facto OS X IDE and compiler is [Xcode](http://developer.apple.com/tools/xcode/). It comes with every Mac, you just install it from the OS X install CD.
[Apple's developer site](http://developer.apple.com/mac/) is the place to get more information on OS X APIs | Porting C++ code from Windows to the Mac | [
"",
"c++",
"macos",
"cross-platform",
""
] |
I was just wondering what (if any) the difference was between the following two message traps in MFC for the function, OnSize(..).
# 1 - Via Message map:
```
BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd)
...
ON_WM_SIZE()
..
END_MESSAGE_MAP()
```
# 2 - Via afx\_message:
```
afx_msg type OnSize(...);
```
They seem... | Both parts are necessary to add a message handler to a class. The message map should be declared inside your class, together with declarations for any message handler functions (e.g, `OnSize`).
```
class CClassWnd : public CBaseClassWnd {
...
afx_msg void OnSize(UINT nType, int cx, int cy);
DECLARE_MESSAGE... | afx\_msg is just an empty macro, it's basically just there to denote that the method is an MFC message handler for readability purposes. Even with afx\_msg there you still need to have an entry in the message map. | Trapping messages in MFC - Whats the difference? | [
"",
"c++",
"windows",
"mfc",
"message",
""
] |
With our next major release we are looking to globalize our ASP.Net application and I was asked to think of a way to keep track of what code has been already worked on in this effort.
My thought was to use a custom Attribute and place it on all classes that have been "fixed".
What do you think?
Does anyone have a be... | Using an attribute to determine which classes have been globalized would then require a tool to process the code and determine which classes have and haven't been "processed", it seems like it's getting a bit complicated.
A more traditional project tracking process would probably be better - and wouldn't "pollute" you... | How about writing a unit test for each page in the app? The unit test would load the page and perform a
```
foreach (System.Web.UI.Control c in Page.Controls)
{
//Do work here
}
```
For the work part, load different globalization settings and see if the .Text property (or relevant property for your app) is differ... | Tracking Globalization progress | [
"",
"c#",
"globalization",
""
] |
I have a weird date rounding problem that hopefully someone can solve. My client uses a work week that runs from Monday through Sunday. Sunday's date is considered the end of the week, and is used to identify all records entered in a particular week (so anything entered last week would have a WEEKDATE value of '10/26/2... | ```
public DateTime WeekNum(DateTime now)
{
DateTime NewNow = now.AddHours(-11).AddDays(6);
return (NewNow.AddDays(- (int) NewNow.DayOfWeek).Date);
}
public void Code(params string[] args)
{
Console.WriteLine(WeekNum(DateTime.Now));
Console.WriteLine(WeekNum(new DateTime(2008,10,27, 10, 00, 00)));... | This passes for me as well:
```
[Test]
public void Test()
{
DateTime sunday = DateTime.Parse("10/26/2008");
DateTime nextSunday = DateTime.Parse("11/2/2008");
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/21/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/22/2008")));
Assert.AreEq... | How do you do end-of-week rounding on a date field in C# (without using LINQ)? | [
"",
"c#",
".net",
"datetime",
""
] |
Is there a good way to remove HTML from a Java string? A simple regex like
```
replaceAll("\\<.*?>", "")
```
will work, but some things like `&` won't be converted correctly and non-HTML between the two angle brackets will be removed (i.e. the `.*?` in the regex will disappear). | Use a HTML parser instead of regex. This is dead simple with [Jsoup](https://jsoup.org).
```
public static String html2text(String html) {
return Jsoup.parse(html).text();
}
```
Jsoup also [supports](https://jsoup.org/cookbook/cleaning-html/safelist-sanitizer) removing HTML tags against a customizable whitelist, ... | If you're writing for **Android** you can do this...
androidx.core.text.HtmlCompat.fromHtml(instruction,HtmlCompat.FROM\_HTML\_MODE\_LEGACY).toString() | Remove HTML tags from a String | [
"",
"java",
"html",
"regex",
"parsing",
""
] |
I have tried the following two statements:
* `SELECT col FROM db.tbl WHERE col (LIKE 'str1' OR LIKE 'str2') AND col2 = num` results in a syntax error
* `SELECT col FROM db.tbl WHERE page LIKE ('str1' OR 'str2') AND col2 = num` results in "Truncated incorrect DOUBLE value: str1" and "Truncated incorrect DOUBLE value: s... | ```
SELECT col FROM db.tbl WHERE (col LIKE 'str1' OR col LIKE 'str2') AND col2 = num
``` | I believe you need `WHERE ((page LIKE 'str1') OR (page LIKE 'str2'))` | How do you OR two LIKE statements? | [
"",
"sql",
"mysql",
""
] |
I'm working on a fiddly web interface which is mostly built with JavaScript. Its basically one (very) large form with many sections. Each section is built based on options from other parts of the form. Whenever those options change the new values are noted in a "registry" type object and the other sections re-populate ... | Thanks for the comments guys. I've gone with the following:
```
var EntriesRegistry = (function(){
var instance = null;
function __constructor() {
var
self = this,
observations = {};
this.set = function(n,v)
{
self[n] = v;
if( observa... | As far as I know, there are no events fired on Object attribute changes (edit: except, apparently, for `Object.watch`).
Why not use event delegation wherever possible? That is, events on the form rather than on individual form elements, capturing events as they bubble up?
For instance (my jQuery is rusty, forgive me ... | Is it possible to listen for changes to an object's attributes in JavaScript? | [
"",
"javascript",
"dom-events",
""
] |
I am currently using JUnit 4 and have a need to divide my tests into groups that can be run selectively in any combination. I know TestNG has a feature to annotate tests to assign them to groups, but I can't migrate to TestNG right now. It seems this could easily be accomplished in JUnit with some custom annotations an... | Check out Spring's [SpringJUnit4ClassRunner](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html). I've used it to optionally run tests based on a System property, using the [IfProfileValue](http://static.springframework.org/spring/docs/2.5.x/api/... | JUnit has no such runner at the moment. Addressing the underlying issue, the need to get reasonable assurance from a test suite in a limited amount of time, is our highest development priority for the next release. In the meantime, implementing a Filter that works through annotations seems like it wouldn't be a big pro... | Is there a JUnit TestRunner for running groups of tests? | [
"",
"java",
"unit-testing",
"junit",
""
] |
Ok so I thought it was fixed, but I'm getting totally inconsistent results.
I rewrote it kind of from scratch to start fresh and here are my results. I get no errors, no crashing, it just doesn't remove them. It just totally messes up the tree and gives me a ton more leaves, and mixes everything up. Not sure where else... | Are each T found in the tree unique? It looks like they are from your code...
It looks like this should work:
In the else case deleting the root node:
```
Node<T> *tmp_r = root->left;
Node<T> *parent = root;
while (tmp_r->right != NULL)
{
parent = tmp_r;
tmp_r = tmp_r->right;
}
Node<T> *tmp_l = tmp_r;
while ... | What actually was happening is that might searches were reversed so it would actually just keep going right but the data wasn't really matching correctly and so it would hit a wall it seems.
```
if (root->data < x)
remove(root->left, x);
else
remove(root->right, x);
```
should have been
```
if(x... | Binary Search Tree Deletion (Inorder Pred method) C++ | [
"",
"c++",
"binary-search-tree",
""
] |
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out.
My problem is the Javascript validator. If I define a class in one JS file in my project, the... | Looks like this problem is due to the default browser for Eclipse not having the required libraries.
Try below steps to add the required library:
Project -> Properties -> JavaScript -> JavaScript Libraries -> Libraries(tab) -> Add Runtime Library -> select 'Internet Explorer Library'
This should resolve the issue. It... | Unfortunately, you might just have to scrap the JavaScript validation.
In my experience, the JavaScript tools which come bundled with Eclipse 3.4 have a hard time... well, *understanding* JavaScript at all, generating bogus warnings and errors as a result.
For example, the common practice of using an `Object` as a po... | Eclipse 3.4 Ganymede Javascript Validation Issue | [
"",
"javascript",
"eclipse",
"validation",
"eclipse-3.4",
"ganymede",
""
] |
Is it possible in C# to see the traces in a separate console. For example, I am having a window based application in which there are trace statements that will write the currently executed method name in to the console. When I run this application, it should automatically open a console and start the traces. Is this po... | If you set the project type of your window application to Console, it will open a console window when you run it. | You can create a console window by calling the Win32 AllocConsole API through P/Invoke.
<http://pinvoke.net/default.aspx/kernel32/AllocConsole.html> | How to see the trace in a separate console | [
"",
"c#",
"debugging",
"trace",
""
] |
We currently do a fair amount or dynamic image generation of png's in ASP.NET using the GDI+ classes in .Net with a no major issues. I had hoped to take advantage of many of the new drawing, FormattedText, RenderTargetBitmap, optimization algorithms, etc. in WPF in our ASP.NET application, but apparently this is not su... | Apparently Microsoft are working on a fix:
<http://forums.asp.net/t/1299963.aspx>
How long until it's ready?... No idea. | I'm not sure, it should be possible I think. I know you can use the WindowInteropHelper class to get the Handle to a WPF window. The rest should be about the same you'd think. | Using WPF in IIS7 or a windows service? | [
"",
"c#",
"asp.net",
"wpf",
"iis-7",
""
] |
I would like to have a Java component which has a resize icon on the bottom right of the component so that when I drag that icon, the component will automatically resize with it.
By resize icon, I mean the following:
 [PixelPushing](http://today.java.net/pub/a/today/2005/06/07/pixelpushing.html)
 | the JStatusBar ? | Resizable Java component | [
"",
"java",
"resize",
"components",
""
] |
I am using a fictional example for this. Say, I have a Widget class like:
```
abstract class Widget
{
Widget parent;
}
```
Now, my other classes would be derived from this Widget class, but suppose I want to put some constraint in the class while defining the derived types such that only a particular "type" of widget... | You should be able to use the code you've got by still having the non-generic class `Widget` and making `Widget<T>` derive from it:
```
public abstract class Widget
{
}
public abstract class Widget<T> : Widget where T : Widget
{
}
```
You then need to work out what belongs in the generic class and what belongs in th... | Use interfaces:
```
interface IContainerWidget { }
class Widget
{
private IContainerWidget Container;
}
class ContainerWidget : Widget, IContainerWidget
{
}
``` | Generic Parent For Generic Class | [
"",
"c#",
"generics",
""
] |
I'm trying to bring myself up to speed on C#, having never developed for it before. In a previous question I asked about good book review sites, and through that I found a very positive (beginner-oriented) review for "Essential C#" but it was for a previous edition.
While I'm sure that it will still be a good book eve... | Start with the latest. If you need to work with code built on a previous version, you can then learn the differences between version X and version Y. | I would suggest you start a project with the latest.
You do not necessarily need to learn all the newest enhancements, but they will be readily available to you when you are ready.
3.5 is actually the 2.0 framework, with 'additions'.
Also if you are in the process of actually working through the samples, they *should... | Which version of C# (and .Net) should I begin with? | [
"",
"c#",
""
] |
How can I replace multiple spaces in a string with only one space in C#?
Example:
```
1 2 3 4 5
```
would be:
```
1 2 3 4 5
``` | ```
string sentence = "This is a sentence with multiple spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
``` | I like to use:
```
myString = Regex.Replace(myString, @"\s+", " ");
```
Since it will catch runs of any kind of whitespace (e.g. tabs, newlines, etc.) and replace them with a single space. | How do I replace multiple spaces with a single space in C#? | [
"",
"c#",
"regex",
"string",
""
] |
I want to load the data into session so that when the next button is clicked in crystal report viewer then in should load the data from the datatable instead retrieving the data again from the database. Here goes my code...
```
ReportDocument rpt = new ReportDocument();
DataTable resultSet = new DataTable();
... | I think you'd want to use the Cache object with a unique key for each user instead of Session here.
Pseudo code:
```
var data = Cache["Record_999"] as DataTable;
if (data == null) {
// get from db
// insert into cache
}
SetDataSource(data);
``` | The problem lies not in with using Session, it lies with the logic used to determine when to retrieve data. Session is the correct approach to use here as Cache is shared across requests - that is, User A would see the report User B just configured if User B was the first user to execute code that used Cache instead of... | Using Session[] with Page Load | [
"",
"c#",
"session",
"web-applications",
""
] |
How do I generate an audio sine or square wave of a given frequency?
I am hoping to do this to calibrate equipment, so how precise would these waves be? | You can use [NAudio](https://github.com/naudio/NAudio) and create a derived WaveStream that outputs sine or square waves which you could output to the soundcard or write to a [WAV](http://en.wikipedia.org/wiki/WAV) file. If you used 32-bit floating point samples you could write the values directly out of the sin functi... | This lets you give frequency, duration, and amplitude, and it is 100% .NET CLR code. No external DLL's. It works by creating a WAV-formatted `MemoryStream` which is like creating a file in memory only, without storing it to disk. Then it plays that `MemoryStream` with `System.Media.SoundPlayer`.
```
using System;
usin... | Creating sine or square wave in C# | [
"",
"c#",
"audio",
"signal-processing",
""
] |
I was hoping to do something like this, but it appears to be illegal in C#:
```
public Collection MethodThatFetchesSomething<T>()
where T : SomeBaseClass
{
return T.StaticMethodOnSomeBaseClassThatReturnsCollection();
}
```
I get a compile-time error:
> 'T' is a 'type parameter', which is not valid in the giv... | In this case you should just call the static method on the constrainted type directly. C# (and the CLR) do not support virtual static methods. So:
```
T.StaticMethodOnSomeBaseClassThatReturnsCollection
```
...can be no different than:
```
SomeBaseClass.StaticMethodOnSomeBaseClassThatReturnsCollection
```
Going thro... | To elaborate on a previous answer, I think reflection is closer to what you want here. I could give 1001 reasons why you should or should not do something, I'll just answer your question as asked. I think you should call the GetMethod method on the type of the generic parameter and go from there. For example, for a fun... | Calling a static method on a generic type parameter | [
"",
"c#",
"generics",
""
] |
I have a form that has multiple fields, and for testing purposes is there a way I could print out the values entered in all the fields, without having to individually print each value. | You should be able to do a `var_dump($_REQUEST);`
<https://www.php.net/manual/en/reserved.variables.request.php>
<https://www.php.net/manual/en/function.var-dump.php> | For extra credit, I always have:
```
function pre($data) {
print '<pre>' . print_r($data, true) . '</pre>';
}
```
Whenever I need to debug an array - which is very often - I just do pre($arr); to get a nicely formatted dump. | Print out post values | [
"",
"php",
""
] |
I launch a child process in Java as follows:
```
final String[] cmd = {"<childProcessName>"};
Process process = Runtime.getRuntime().exec(cmd);
```
It now runs in the background. All good and fine.
If my program now crashes (it *is* still in dev :-)) the child process still seems to hang around. How can I make it au... | As you said, [addShutdownHook](https://web.archive.org/web/20080310051714/http://www.onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html?page=2) is the way to go.
BUT:
* There's no real guarantee that your shutdown hooks are executed if the program terminates. Someone could kill the Java process and in that case you... | I worked it out myself already. I add a shutdown hook, as follows:
```
final String[] cmd = {"<childProcessName>"};
final Process process = Runtime.getRuntime().exec(cmd);
Runnable runnable = new Runnable() {
public void run() {
process.destroy();
}
};
Runtime.getRuntime().addShutdownHook(new Thread(ru... | How do I get rid of Java child processes when my Java app exits/crashes? | [
"",
"java",
"runtime",
"subprocess",
"shutdown",
"process-management",
""
] |
I am trying to do a search in my Eclipse (Java) workspace to find all instances of static variables that are not final.
I tried various regexes but they do not result in any matches. Can someone suggest a regex that will match all lines containing `static` and not containing `final`, and not ending in a `{`?
The last... | This pattern works:
```
[^(final)] static [^(final)][^(\})]*$
```
Here is a test:
```
$ cat test.txt
private int x = "3";
private static x = "3";
private final static String x = "3";
private static final String x = "3";
private static String x = "3";
public static void main(String args[]) {
blah;
}
$ grep "... | Instead of checking for the absence of a brace, I would look for a semicolon at the end:
```
^(?![ \t]*import\b)(?!.*\bfinal\b).*\bstatic\b.*;[ \t]*$
``` | Regex to find static (non final) variables | [
"",
"java",
"regex",
"eclipse",
""
] |
Let's say I have the following table:
```
CustomerID ParentID Name
========== ======== ====
1 null John
2 1 James
3 2 Jenna
4 3 Jennifer
5 3 Peter
6 5 Alice
7 5 Steve
8 1 Larry
```
I want to re... | On SQL Server 2005 you can use [CTEs (Common Table Expressions)](https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml) :
```
with Hierachy(CustomerID, ParentID, Name, Level)
as
(
select CustomerID, ParentID, Name, 0 as Level
from Customers c
where c.CustomerID = 2 -- ... | For bottom up use mathieu's answer with a little modification:
```
with Hierachy(CustomerID, ParentID, Name, Level)
as
(
select CustomerID, ParentID, Name, 0 as Level
from Customers c
where c.CustomerID = 2 -- insert parameter here
union all
select c.CustomerID, c.ParentID, c.Name, ch.Level + 1
fro... | How do I create a recursive query in MSSQL 2005? | [
"",
"sql",
"sql-server",
"database",
"recursion",
""
] |
I'm currently working on a project which needs to persist any kind of object (of which implementation we don't have any control) so these objects could be recovered afterwards.
We can't implement an ORM because we can't restrict the users of our library at development time.
Our first alternative was to serialize it w... | The easiest thing for you to do is still to use serialization, IMO, but put more thought into the serialized form of the classes (which you really ought to do anyway). For instance:
1. Explicitly define the SerialUID.
2. Define your own serialized form where appropriate.
The serialized form is part of the class' API ... | It's 2011, and in a commercial grade REST web services project we use the following serializers to offer clients a variety of media types:
* [XStream](http://x-stream.github.io/) (for XML but not for JSON)
* [Jackson](https://github.com/FasterXML/jackson) (for JSON)
* [Kryo](https://github.com/EsotericSoftware/kryo) (... | Which is the best alternative for Java Serialization? | [
"",
"java",
"serialization",
"xml-serialization",
""
] |
Does anyone know of a script to colorize C++ code the same as the default MSVC IDE does? | Try the open source project [Highlight](http://www.andre-simon.de/).
It's not a script-per-se -- but it is scriptable. The nice thing is that it parses code and the style-sheet is very easy to customize colors, bold and italics, etc.... | If it's for the web I can recommend you [prettify](http://code.google.com/p/google-code-prettify/), it's the script that StackOverflow uses for code colorization, and it's really easy to get it working... | Looking for a script to colorize C++ code | [
"",
"c++",
"visual-studio",
""
] |
Which method is preferred?
```
Session.Remove("foo");
Session["foo"] = null;
```
Is there a difference? | > Is there a difference?
There is.
`Session.Remove(key)` deletes the entry (both key & value) from the dictionary while `Session[key] = null` assigns a value (which happens to be null) to a key. After the former call, the key won't appear in the `Session#Keys` collection. But after the latter, the key can still be fou... | I know this is old thread but definitely stick with `Session["key"] = null` - it's much more faster! I've done some tests (on InProc Session State), removing 1000 items in row (elapsed time is for 1000 items totally, so if you want average time for one item, just divide it with 1000):
Removing 1000 existing items:
``... | ASP.NET removing an item from Session? | [
"",
"c#",
"asp.net",
".net",
"session",
"session-variables",
""
] |
I'm using Hibernate for a Java-based Web Application and want to add full-text search via Compass. Compass is supposed to support that, but fails to provide any useful Getting Started guide.
I could figure out that I have to annotate my Entities with @Searchable and the various @SearchableXXX variations and accessing ... | I'm wondering why you chose Compass to go Hibernate. We looked at Compass and Hibernate-Search and we chose the latter as it has excellent integration.
You can query the test index in exactly the same way you do an SQL database with HQL or Critera.
If you were using iBatis or JDBC then Compass would of course be the ... | The best resource to review would be to check the petclinic example provided with the compass distribution (with dependencies). If by default the listener is not configured then you will have to set the EventListener. | Configuring Compass with Annotated Hibernate | [
"",
"java",
"hibernate",
"spring",
"lucene",
"compass-lucene",
""
] |
I'll simplify the problem as much as possible:
I have an oracle table:
```
row_priority, col1, col2, col3
0, .1, 100, {null}
12, {null}, {null}, 3
24, .2, {null}, {null}
```
Desired result:
```
col1, col2, col3
.2, 100, 3
```
So according to the priority of the row, it overrides previous row values, if given.
I'm... | You need to put rownum = 1 OUTSIDE the analytical query
```
SELECT *
FROM ( select last_value(col1 ignore nulls) over () col1,
last_value(col2 ignore nulls) over () col2,
last_value(col3 ignore nulls) over () col3
from (select * from TH... | The COALESCE function may be of help to you here. Perhaps like ...
```
select first_value(coalesce(col1,0) ignore nulls) over () col1,
first_value(coalesce(col2,0) ignore nulls) over () col2,
first_value(coalesce(col3,0) ignore nulls) over () col3
from THE_TABLE
``` | How do I compress this Oracle resultset into values according to row priority, ignoring nulls? | [
"",
"sql",
"database",
"oracle",
"analytic-functions",
""
] |
I have an associative array in the form `key => value` where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for th... | ```
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
``` | The way you would do this and preserve the ordering of the array is by putting the array keys into a separate array, find and replace the key in that array and then combine it back with the values.
Here is a function that does just that:
```
function change_key( $array, $old_key, $new_key ) {
if( ! array_key_exi... | Replace keys in an array based on another lookup/mapping array | [
"",
"php",
"arrays",
"mapping",
"key",
"associative-array",
""
] |
I am trying to setup a multi module SpringMVC appfuse applicaiton in Eclipse but it seems that I'm facing lots of errors in Eclipse after I import the project in Eclipse. Can anyone please help me with a step by step guideline showing the ideal way to setup such application in Eclipse? | Have you tried using maven eclipse plugin?
You can just go to the project root folder (the one that contains your pom.xml file) and run "mvn eclipse:eclipse" from the command line.
This will build project files for each of your modules and also create inter-dependencies. You can just treat your multi-module project li... | From what I recall for multi-module projects, eclipse just does not handle this well. It would help to see the specific errors you're getting, and then to start from there. | How to properly setup a multi module SpringMVC application created by appfuse in Eclipse? | [
"",
"java",
"eclipse",
"spring",
"maven-2",
"appfuse",
""
] |
I have an ASP.NET web page with a Login control on it. When I hit Enter, the Login button doesn't fire; instead the page submits, doing nothing.
The standard solution to this that I've found online is to enclose the Login control in a Panel, then set the Panel default button. But apparently that doesn't work so well i... | This should be helpful: <http://weblogs.asp.net/jgalloway/archive/2007/10/03/asp-net-setting-the-defaultbutton-for-a-login-control.aspx>
You can use the following to reference the button within the Login control template:
```
DefaultButton="Login$LoginButton"
```
Basically, you can define a DefaultButton not just on... | Great answer by **Blend Master**! Essentially just use Panel.DefaultButton, but I want to clear up the confusion about what exactly you need to set it to. It's not just ".ID" or ".UniqueID" - the documentation is a bit lacking on this.
You must set it to the UniqueID of the button, *relative to* the Panel's naming con... | Submit Login control button when I hit Enter | [
"",
"c#",
"asp.net",
".net",
"login-control",
"defaultbutton",
""
] |
The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from `the_base_class`.
```
class the_base_class:
somedata = {}
somedata['was_false_in_base'] = False
class subclassthing(the_base_class):
def __init__(self):
print self.somedata... | You are right, `somedata` is shared between all instances of the class and it's subclasses, because it is created at class *definition* time. The lines
```
somedata = {}
somedata['was_false_in_base'] = False
```
are executed when the class is defined, i.e. when the interpreter encounters the `class` statement - **not... | Note that part of the behavior you’re seeing is due to `somedata` being a `dict`, as opposed to a simple data type such as a `bool`.
For instance, see this different example which behaves differently (although very similar):
```
class the_base_class:
somedata = False
class subclassthing(the_base_class):
def ... | Why do attribute references act like this with Python inheritance? | [
"",
"python",
"class",
"inheritance",
""
] |
I need a SQL query that returns ContactDate, SortName, City, ContactType, and Summary from the tables below. If any value is null, I need it to return the text “No Entry”.
**ContactTable**
* *ContactID*
* ContactDate
* UserID
* Summary
* ContactType
* SortName
**UserTable**
* *UserID*
* FirstName
* LastName
* Addre... | ```
SELECT COALESCE(CAST(CONVERT(VARCHAR(10), ContactTable.ContactDate, 101) AS VARCHAR(10)), 'No Entry') AS ContactDate,
COALESCE(ContactTable.SortName, 'No Entry') AS SortName,
COALESCE(AddressTable.City, 'No Entry') AS City,
COALESCE(ContactTable.ContactType, 'No Entry') AS ContactType
FROM Cont... | COALESCE() on any platform that is worth its weight in salt.
Make sure to handle casting issues.
Such as:
```
--(SQL Server)
SELECT
C.ContactID,
COALESCE(CAST(CONVERT(varchar(10), C.ContactDate, 101) AS varchar(10), 'No Entry') AS ContactDate,
COALESCE(SorName, 'No Entry') AS SortName
```
etc., etc. | A SQL query that replaces null values. | [
"",
"sql",
"null",
""
] |
I'm having a bit of trouble trying to get class variables to work in javascript.
I thought that I understood the prototype inheritance model, but obviously not. I assumed that since prototypes will be shared between objects then so will their variables.
This is why this bit of code confuses me.
What is the correct w... | ```
I assumed that since prototypes will be shared between objects then so will their variables.
```
They are, but this:
```
a.shared++
```
is not doing what you think it's doing. It's in fact (approximately) sugar syntax for:
```
(a.shared= a.shared+1)-1
```
(the -1 being to return the pre-increment value, not th... | **Static (class level) variables can be done like this**:
```
function classA(){
//initialize
}
classA.prototype.method1 = function(){
//accessible from anywhere
classA.static_var = 1;
//accessible only from THIS object
this.instance_var = 2;
}
classA.static_var = 1; //This is the same variable ... | Class Variables in Javascript | [
"",
"javascript",
"oop",
"inheritance",
""
] |
I'm using VS2008 for a C++ project. The code is quite old and has passed through many hands. There are several classes hierarchies, functions, enums and so on which are no longer being used.
Is there a way to get the compiler/linker to list out identifiers which have been declared or defined but are not being referred... | PC-Lint "whole project" analysis (which analyses multiple files together) can do this. Please feel free to contact me if you need help setting it up. | VS will warn about identifiers declared within a function and not used, you may need to move to warning level 4, but for global variables, and a hunt for many other potential problems, you would do well to try [lint](http://www.gimpel.com/) or [visual lint](http://www.riverblade.co.uk/products/visual_lint/index.html) | Use Compiler/Linker for C++ Code Clean-up | [
"",
"c++",
"visual-studio-2008",
"static-analysis",
""
] |
Many C++ books contain example code like this...
```
std::cout << "Test line" << std::endl;
```
...so I've always done that too. But I've seen a lot of code from working developers like this instead:
```
std::cout << "Test line\n";
```
Is there a technical reason to prefer one over the other, or is it just a matter... | The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.
The only difference is that [`std::endl`](http://en.cppreference.com/w/cpp/io/manip/endl) flushes ... | The difference can be illustrated by the following:
```
std::cout << std::endl;
```
is equivalent to
```
std::cout << '\n' << std::flush;
```
So,
* Use `std::endl` If you want to force an immediate flush to the output.
* Use `\n` if you are worried about performance (which is probably not the case if you are using... | "std::endl" vs "\n" | [
"",
"c++",
"iostream",
"c++-faq",
""
] |
I have been asked to setup a course leaflet system for a college. For whatever reason in the past their current system is not linked to their actual course file, they wish to close this link so course leaflets are related to actual course codes. Unfortunately their course file is a ms access database linked to many of ... | Just how often does the course file change? Fifty times a day? Once a month?
What about creating the appropriate tables in the SQL Server database? Then every so often (as often as necessary to stay reasonably current), clear those tables out and repopulate them from the Access database. You could set this to run ever... | Why do you need the Access file to the SQL server to create a Linked Server? Just put it on a network share with appropriate security and create your linked server like that. | c# query ms access against sql server | [
"",
"c#",
"sql-server",
"database",
"linq",
"ms-access",
""
] |
If I declare a temporary auto deleted character buffer using
```
std::auto_ptr<char> buffer(new char[n]);
```
then the buffer is automatically deleted when the buffer goes out of scope. I would assume that the buffer is deleted using delete.
However the buffer was created using new[], and so strictly speaking the bu... | The behaviour of calling delete on a pointer allocated with new[] is [undefined](https://isocpp.org/wiki/faq/freestore-mgmt#delete-array). As you assumed, auto\_ptr [does call delete](http://www.gotw.ca/conv/001.htm) when the smart pointer goes out of scope. It's not just memory leaks you have to worry about -- crashes... | I would use a vector of char as the buffer.
```
std::vector<char> buffer(size);
read(input,&buffer[0],size);
```
Basically you don't even want to call new if you don't need to.
A vector provides a run-time sized buffer that you can use just like an array (buffer).
The best part is that the vector cleans up aft... | Is it wrong to use auto_ptr with new char[n] | [
"",
"c++",
"stl",
"memory-leaks",
"auto-ptr",
""
] |
Talking from a 'best practice' point of view, what do you think is the best way to insert HTML using PHP. For the moment I use one of the following methods (mostly the latter), but I'm curious to know which you think is best.
```
<?php
if($a){
?>
[SOME MARKUP]
<?php
}
else{
?>
[SOME OTHER MARKUP]
<?php
}
?>
``... | If you are going to do things that way, you want to separate your logic and design, true.
But you don't need to use Smarty to do this.
Priority is about mindset. I have seen people do shocking things in Smarty, and it eventually turns into people developing sites **in** Smarty, and then some bright spark will decide ... | -1 for the typical hysterical ‘use [my favourite templating system] instead!’ posts. Every PHP post, even if the native PHP answer is a one-liner, always degenerates into this, just as every one-liner JavaScript question ends up full of ‘use [my favourite framework] instead!’. It's embarrassing.
Seriously, we *know* a... | What is the best way to insert HTML via PHP? | [
"",
"php",
"html",
"template-engine",
""
] |
Assuming a Read Committed Snapshot transaction isolation setting, is the following statement "atomic" in the sense that you won't ever "lose" a concurrent increment?
```
update mytable set counter = counter + 1
```
I would assume that in the general case, where this update statement is part of a larger transaction, t... | Read Committed Snapshot only deals with locks on selecting data from tables.
In t1 and t2 however, you're UPDATEing the data, which is a different scenario.
When you UPDATE the counter you escalate to a write lock (on the row), preventing the other update from occurring. t2 could read, but t2 will block on its UPDATE... | According to the MSSQL Help, you could do it like this:
```
UPDATE tablename SET counterfield = counterfield + 1 OUTPUT INSERTED.counterfield
```
This will update the field by one, and return the updated value as a SQL recordset. | In MS SQL Server, is there a way to "atomically" increment a column being used as a counter? | [
"",
"sql",
"sql-server-2005",
"transactions",
""
] |
Can you mix .net languages within a single project? So pre-compiled, I would like to call classes and methods of other source files.
For both web and apps?
In particular I'd be interested in F# and C#. | You can mix languages in a single assembly with [ILMerge](http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en) and [MSBuild](http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx).
[Here](http://www.hanselman.com/blog/MixingLanguagesInASingleAssemblyInVisualStud... | Yes, you can, but Visual Studio does not support it directly. What you will do is compile code to netmodules, then combine them into a single assembly. The compilers support the "/target:module" option which generates these netmodules.
You can then use the compilers to reference other netmodules when building, or use ... | Can you mix .net languages within a single project? | [
"",
"c#",
".net",
"f#",
""
] |
Suppose I have a drop-down list like:
```
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
```
Given the value `'2'` (i.e., using a specific value, *not necessarily the selected one*), what selector can I use to get "O... | It's looking for an element with id `list` which has a property `value` equal to `2`.
What you want is the `option` child of the `list`:
```
$("#list option[value='2']").text()
``` | If you'd like to get the option with a value of 2, use
```
$("#list option[value='2']").text();
```
---
If you'd like to get whichever option is currently selected, use
```
$("#list option:selected").text();
``` | jQuery get specific option tag text | [
"",
"javascript",
"jquery",
"jquery-selectors",
"html-select",
""
] |
I usually never see test for new in C++ and I was wondering why.
`Foo *f = new Foo;`
`// f is assumed as allocated, why usually, nobody test the return of new?` | As per the current standard, *new* never returns *NULL*, it throws a std::bad\_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with "*(std::nothrow)*".
i.e.
```
Foo* foo = new (std::nothrow) Foo;
```
Of course, if you have a very old or... | It all depends on your complier VC++ up to version 6 gives NULL if the new operator fails, on a non MFC application.
Now the problem gets bigger when you use for example STL with VC++ 6, because the STL goes with the standards it will never test for NULL when he needs to get some memory, and guess what will happen und... | Is it useful to test the return of "new" in C++? | [
"",
"c++",
"new-operator",
""
] |
I am creating a tool that will check dynamically generated XHTML and validate it against expected contents.
I need to confirm the structure is correct and that specific attributes exist/match. There may be other attributes which I'm not interested in, so a direct string comparison is not suitable.
One way of validati... | I've just released an open source project which is a W3C CSS Selectors Level 3 implementation in Java. Please give it a try. I was looking for the same thing and decided to implement my own engine. It's inspired by the code in WebKit etc.
<http://github.com/chrsan/css-selectors/tree> | I don't know of a Java library itself, but there is a Ruby library called [Hpricot](http://code.whytheluckystiff.net/hpricot/) that does exactly what you're looking for. In conjunction with the Ruby implementation on the Java platform, [JRuby](http://jruby.codehaus.org/), it should be relatively straightforward to call... | server-side css selectors | [
"",
"java",
"html",
"coldfusion",
"css-selectors",
""
] |
How do you calculate the number of `<td>` elements in a particular `<tr>`?
I didn't specify id or name to access directly, we have to use the `document.getElementsByTagName` concept. | You can use something like the following:
```
var rowIndex = 0; // rowindex, in this case the first row of your table
var table = document.getElementById('mytable'); // table to perform search on
var row = table.getElementsByTagName('tr')[rowIndex];
var cells = row.getElementsByTagName('td');
var cellCount = cells.len... | document.getElementsByTagName returns an array of elements, so you should be able to do something like this:
```
var totals = new Array();
var tbl = document.getElementById('yourTableId');
var rows = tbl.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
totals.push(rows[i].getElementsByTagName('... | Find the number of <td>s in a <tr> without using id or name | [
"",
"javascript",
""
] |
I have a website built in PHP 4 with a framework made by hand by me. The code is 3 years old and I am limited (well it requires a lot of effort to make changes).
I decided to do new version of this website. My knowledge has since increased, and now I know that a lot of frameworks exist and that **IOC** is there and **... | If you made the whole framework yourself, I would suggest you just upgrade it for PHP 5 and go forward from there. Most PHP 4 code will "just work" in PHP 5; the exceptions are code that uses the new reserved words, and code that relies on the way PHP 4 differs from PHP 5 -- which means a few things in classes and refe... | If it is a hobby project and you feel a bit unhappy about the current state of the project I'd say: definitely try .net - for the same reason I would suggest jsp or almost any other kind of feasible language/platform/runtime: the fun and the experience. Even if after some time you decide to revert to php you'll keep th... | Website version 2, keep in PHP or move to .Net? | [
"",
".net",
"php",
"frameworks",
""
] |
What is the most efficient way to enumerate every cell in every sheet in a workbook?
The method below seems to work reasonably for a workbook with ~130,000 cells. On my machine it took ~26 seconds to open the file and ~5 seconds to enumerate the cells . However I'm no Excel expert and wanted to validate this code snip... | Excel PIA Interop is really slow when you are doing things cell by cell.
You should select the range you want to extract, like you did with the `Worksheet.UsedRange` property and then read the value of the whole range in one step, by invoking `get_Value()` (or just simply by reading the `Value` or `Value2` property, I... | There is an open source implementation of an Excel reader and writer called [Koogra](http://sourceforge.net/projects/koogra/). It allows you to read in the excel file and modify it using pure managed code.
This would probably be much faster than the code you are using now. | Efficient method to enumerate cells in an Excel workbook using c# | [
"",
"c#",
"excel",
"automation",
""
] |
I apologize in advance for the long post...
I used to be able to build our VC++ solutions (we're on VS 2008) when we listed the STLPort include and library directories under VS Menu > Tools > Options > VC++ Directories > Directories for Include and Library files. However, we wanted to transition to a build process tha... | Raymond Chen recently talked about this at [The Old New Thing](http://blogs.msdn.com/oldnewthing/archive/2008/12/29/9255240.aspx)-- one cause of these problems is that the library was compiled with one set of switches, but your app is using a different set. What you have to do is:
Get the exact symbol that the linker ... | As mentioned in other answers, this is a linker error and likely the result of the library and the application being compiled with different options. There are a few solutions on tracking this down already (one of them as the chosen answer, currently). These solutions ***will*** work. However, there are a few tools tha... | LNK2001 error when compiling apps referencing STLport-5.1.4 with VC++ 2008 | [
"",
"c++",
"visual-studio-2008",
"visual-c++",
"linker",
"stlport",
""
] |
I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For CalculateListOfPoints, which returns a generic List, I could return an empty list and require the caller to check this; however Point is a value ty... | Personally, I think I'd use the same idea as TryParse() : using an out parameter to output the real value, and returning a boolean indicating whether the call was successful or not
`public bool CalculatePoint(... out Point result);`
I am not a fan of using exception for "normal" behaviors (if you expect the function ... | Why would they fail? If it's because of something the caller has done (i.e. the arguments provided) then throwing ArgumentException is entirely appropriate. A Try[...] method which avoids the exception is fine.
I think it's a good idea to provide the version which throws an exception though, so that callers who expect... | How to indicate that a method was unsuccessful | [
"",
"c#",
"methods",
"return-value",
""
] |
I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.
The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the u... | Using [cPickle](http://www.python.org/doc/2.5.2/lib/module-cPickle.html) on the dictionary would be my choice. Dictionaries are a natural fit for these kind of data, so given your requirements I see no reason not to use them. That, unless you are thinking about reading them from non-python applications, in which case y... | I would use the [ConfigParser](http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html) module, which produces some pretty readable and user-editable output for your example:
```
[bob]
colour_scheme: blue
british: yes
[joe]
color_scheme: that's 'color', silly!
british: no
```
The following code would produce the... | Store simple user settings in Python | [
"",
"python",
"database",
"web",
"settings",
""
] |
For a random event generator I'm writing I need a simple algorithm to generate random ranges.
So, for example:
I may say I want 10 random intervals, between 1/1 and 1/7, with no overlap, in the states (1,2,3) where state 1 events add up to 1 day, state 2 events add up to 2 days and state 3 events add up to the rest.
... | Here is my current implementation that seems to work ok and accounts for all time. This would be so much cleaner if I didn't have to target .net 1.1
```
public class Interval
{
public Interval(int state)
{
this.State = state;
this.Duration = -1;
this.Date = DateTime.MinValue;
}
... | First use DateTime.Subtract to determine how many minutes/seconds/whatever between your min and max dates. Then use Math.Random to get a random number of minutes/seconds/whatever in that range. Then use the result of that to construct another TimeSpan instance and add that to your min DateTime. | Getting Random Durations within a range in C# | [
"",
"c#",
"algorithm",
"date-range",
""
] |
I'd like to create a tree structure from JSON, but with multiple columns that can be sorted. I've seen lots of implementations of trees and grids but never one mixed.
Does anyone know of a plugin or feature for any Javascript toolkit that can make this happen so I don't have to re-invent the wheel here? | This seems pretty nice: <http://www.max-bazhenov.com/dev/ux.maximgb.treegrid/index.html>
Uses ExtJS, which has some licensing limitations you have to consider. | I found all these components:
* [Coqsoft Treegrid](http://www.coqsoft.com/treegrid/www/), commercial, seems the non plus ultra!
* [Ext JS](http://www.sencha.com/products/js/), commercial:
+ [Column Tree](http://dev.sencha.com/deploy/dev/examples/tree/column-tree.html) component \*
+ [Nested Grid](http://mikhailsta... | Creating a sortable tree/grid in Javascript | [
"",
"javascript",
"json",
"extjs",
"treetable",
""
] |
What's the best way to embed Ruby as a scripting language in C++? Using ruby.h? SWIG? Something else? What I need is to expose some C++ objects to Ruby and have the Ruby interpreter evaluate scripts that access these objects. I don't care about extending Ruby or accessing it in C++.
I've found this [article on embeddi... | swig is probablly the way to go..... but ruby doesnt embed too well......
if you want a language that embeds nicely into C++, try lua | [Rice](http://jasonroelofs.github.io/rice/) is looking very promising. | How to embed Ruby in C++? | [
"",
"c++",
"ruby",
"scripting",
"embedded-language",
""
] |
I remember reading somewhere on the internets about a half-assed tiny django CMS app, which was basically built on 'snippets' of text.
The idea was, that in the admin, you make a snippet (say a description of a product), give it a name (such as 'google\_desc') and call it in a template with something like {% snippet g... | Sounds like [django-chunks](https://github.com/clintecker/django-chunks) to me. | Are you talking about [Django Simplepages](http://www.punteney.com/writes/django-simplepages-basic-page-cms-system/)? Official site [here](http://code.google.com/p/django-simplepages/).
Another project that sounds similar to what you're after is [django-page-cms](http://code.google.com/p/django-page-cms/). | 'Snippit' based django semi-CMS | [
"",
"python",
"django",
"content-management-system",
""
] |
There are two databases in SQL Server 2005: One called "A" and another one called "A\_2".
"A" is a variable name to be entered by the user, the "\_2" prefix for the second database is always known. (So databases could be "MyDB" and "MyDB\_2", etc)
How to access the other database from within a stored procedure wit... | You can try to use a new SQL Server 2005 feature, called synonyms.
You would need to [CREATE SYNONYM](http://msdn.microsoft.com/en-us/library/ms177544.aspx), then compile and save the stored procedure using the synonym. This would leave you with the possibility to change the synonym "on the fly" later on. Obviously, i... | I don't think that it is possible.
The name is a variable and you cannot use variables as database names.
So the only way is to put the whole command to a string and exec it, which you would like to avoid.
What is the purpose of the whole thing? What happens if you name your databases on your logic, but somewhere st... | Accessing another database with dynamic name in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
From C#, I want to do the equivalent of the following:
```
arp -a |findstr 192.168.1.254
```
Alternatively, the answer could call the [SendARP](http://msdn.microsoft.com/en-us/library/aa366358.aspx) function and get the results.
This will allow my application to do some other processing that requires the MAC address... | SendARP P/Invoke goes like this:
```
[DllImport("iphlpapi.dll", ExactSpelling=true)]
public static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen );
```
[PInvoke.NET](http://www.pinvoke.net/default.aspx/iphlpapi/SendARP.html) has this example:
```
IPAddress dst = IPAddress.Parse(... | Here is my solution.
```
public static class MacResolver
{
/// <summary>
/// Convert a string into Int32
/// </summary>
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
/// <summary>
/// The main funtion
/// </summary>
[DllImport("Iphlpapi.dll")]
... | How do I obtain the physical (MAC) address of an IP address using C#? | [
"",
"c#",
"networking",
""
] |
Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via `<script src="...">`, not pasted into the HTML itself.
Where’s the best place to put this in the HTML?
```
<html>
<head>
<!-- here? -->
<link rel="stylesheet" href="s... | The Yahoo! Exceptional Performance team recommend [placing scripts at the bottom of your page](http://developer.yahoo.com/performance/rules.html#js_bottom) because of the way browsers download components.
Of course Levi's comment "just before you need it and no sooner" is really the correct answer, i.e. "it depends". | The best place for it is just before you need it and no sooner.
Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.
Is your js script a commonly used lib like jQuery or prototype? If so, there a... | Where to place JavaScript in an HTML file? | [
"",
"javascript",
"html",
"optimization",
""
] |
I have seen the following methods of putting JavaScript code in an `<a>` tag:
```
function DoSomething() { ... return false; }
```
1. `<a href="javascript:;" onClick="return DoSomething();">link</a>`
2. `<a href="javascript:DoSomething();">link</a>`
3. `<a href="javascript:void(0);" onClick="return DoSomething();">li... | I quite enjoy [Matt Kruse's Javascript Best Practices article](http://web.archive.org/web/20190822202858/http://www.javascripttoolbox.com/bestpractices/). In it, he states that using the `href` section to execute JavaScript code is a bad idea. Even though you have stated that your users must have JavaScript enabled, th... | Why would you do this when you can use `addEventListener`/`attachEvent`? If there is no `href`-equivalent, don't use an `<a>`, use a `<button>` and style it accordingly. | What is the difference between the different methods of putting JavaScript code in an <a>? | [
"",
"javascript",
"html",
"href",
""
] |
I have a dialog where each entry in a JTree has its corresponding options in a different panel, which is updated when the selection changes. If options for one of the entries is set to an invalid state, when the user attempts to change to a different entry in the tree, I want there to be an error dialog and have the se... | Not sure it's best practice, but maybe you could put a FocusListener on the component(s) you want to validate... call your validation when the event is called and then consume then event if you don't want the focus to be moved because the validation fails?
Later Edit:
At least with java 8 (I didn't check earlier vers... | I did not find a better way, but this approach works fine for me.
I know in Delphi it was a very convenient event: "before changing selection" where you could very easily stop changing selection.
here is my java code with prevention of infinite recursion problem
```
navTree.addTreeSelectionListener(new TreeSelect... | Best way to stop a JTree selection change from happening? | [
"",
"java",
"swing",
"design-patterns",
"error-handling",
""
] |
So far I've been using `public void run() {}` methods to execute my code in Java. When/why might one want to use `main()` or `init()` instead of `run()`? | This is a peculiar question because it's not supposed to be a matter of choice.
When you launch the JVM, you specify a class to run, and it is the `main()` of this class where your program starts.
By `init()`, I assume you mean the JApplet method. When an applet is launched in the browser, the `init()` method of the ... | The `main` method is the entry point of a Java application.
Specifically、when the Java Virtual Machine is told to run an application by specifying its class (by using the `java` application launcher), it will look for the `main` method with the signature of `public static void main(String[])`.
From Sun's [`java` comm... | Entry point for Java applications: main(), init(), or run()? | [
"",
"java",
"jvm",
""
] |
I'm running SQL Server 2000 and I need to export the SQL Statement from all the DTS objects so that they can be parsed and put into a wiki documentation if needed.
Is there a way to do that?
maybe dumping each DTS object out into a text file with the object name as the file name with the name of the process and the d... | I have a [Python 2.6](http://www.python.org/) script (easily portable to Python 2.5) that dumps the SQL from the tasks in a DTS package that has been saved as Visual Basic code.
Refer to ConcernedOfTunbridgeWells' post to find out how to save the DTS package to a VB file. After you save a VB file, run this function on... | There is an API with an object model for the DTS packages. You can get the SQL text through this. The Books on Line docs describe this to some extent [Here.](http://msdn.microsoft.com/en-us/library/aa298646(SQL.80).aspx) You can get examples of the object model usage by [Saving the DTS package to a Visual BASIC file](h... | How do I export the SQL statement from a DTS object? | [
"",
"sql",
"sql-server",
"dts",
""
] |
I made a custom ValueObject class with properties (getters/setters) and I need this class for data binding of elements on form. So I want to drag it to "other components" on matisse editor so I can bind it - and nothing happens.... Any similar experiences? The same issue is happening both on NetBeans 6.5 and MyEclipse ... | The usual method for adding components to the control palette is through the Palette Manager: right-click the palette (the 'other components' area for example) and select Palette Manager, then add it from the appropriate place (your current project by the sound of it.)
Your project needs to compile cleanly to do this. | yes, I've concluded this, you can add only compiled class, it was even successfull once, but now I have regular class (which implements one interface) compiled, it wouldn't drop in. I put it first on custom palette area as widget and from there it went onto form.
Thanks, will try to find some workaround.. hope soon... | Swing Matisse GUI - cannot add custom made bean to "Other components" | [
"",
"java",
"user-interface",
"data-binding",
"javabeans",
"matisse",
""
] |
I have OS X 10.5 set up with the precompiled versions of PHP 5 and Apache 2. I'm trying to set up the Zend Debugger, but with no luck. Here's what I did:
* I downloaded `ZendDebugger-5.2.14-darwin8.6-uni.tar`
* I created the directory `/Developer/Extras/PHP` and set the permissions to:
+ Permissions: `drwxrwxr-x`
... | If I remember correctly, this problem is do to the fact that the Zend Debugger is compiled for 32-bit Apache while the Apache that comes with Max OS 10.5 is compiled as 64-bit application. Until Zend comes out with a 64-bit version, you have two options:
1) [Restart Apache manually into 32-bit](http://www.entropy.ch/p... | Restarting in 32-bit mode did the trick. For those of you who want to be able to do this easily, here's a little bit of AppleScript:
```
do shell script "apachectl stop" with administrator privileges
do shell script "arch -i386 /usr/sbin/httpd" with administrator privileges
```
It's nice to have sitting somewhere so ... | PHP w/ Zend Debugger on OS X 10.5 | [
"",
"php",
"macos",
"osx-leopard",
"php-5.2",
"zend-debugger",
""
] |
I'm interested in putting together my first online game using Flash as the client and writing a back-end application in C++ where the actual game state is kept.
I've done lots of games in C++ before using SDL, SFML, Allegro, etc etc but never gotten around to using the network libraries. I was just interested in some ... | Although it's primarily written for C, it's still great for C++:
[Beej's guide to networ programming.k](http://beej.us/guide/bgnet/)
It covers all the basics, and has a section on changes needed for Win32 :)
Also I seem to recall that Flash needed terminating null-bytes on each packet, so instead of send(socket,s... | Use boost::asio for network programming | (C++) Game Server, (Flash) Client | [
"",
"c++",
"flash",
"client-server",
""
] |
I'm trying to do the classic Insert/Update scenario where I need to update existing rows in a database or insert them if they are not there.
I've found a [previous question on the subject](https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server), but it deals with stored procedures, which I'm... | The most efficient way is to do the `UPDATE`, then do an `INSERT` if `@@rowcount` is zero, [as explained in this previous answer](https://stackoverflow.com/questions/108403/solutions-for-insert-or-update-on-sql-server#108416). | (First of all - I would not try to avoid stored procedures, if there is no strong reason. The give a good benefit in most cases.)
**You could do it this way:**
* create a (temporary) table
* fill in your rows
* run a INTERSECT that identifies the extisting rows
* update your table with them
* run a EXCEPT that identi... | Insert/Update on SQL Server 2005 without using Stored Procedures | [
"",
"sql",
"sql-server-2005",
"insert-update",
""
] |
I have two DataTables, `A` and `B`, produced from CSV files. I need to be able to check which rows exist in `B` that do not exist in `A`.
Is there a way to do some sort of query to show the different rows or would I have to iterate through each row on each DataTable to check if they are the same? The latter option see... | > would I have to iterate through each row on each DataTable to check if they are the same.
Seeing as you've loaded the data from a CSV file, you're not going to have any indexes or anything, so at some point, something is going to have to iterate through every row, whether it be your code, or a library, or whatever.
... | Assuming you have an ID column which is of an appropriate type (i.e. gives a hashcode and implements equality) - string in this example, which is slightly pseudocode because I'm not that familiar with DataTables and don't have time to look it all up just now :)
```
IEnumerable<string> idsInA = tableA.AsEnumerable().Se... | Compare two DataTables to determine rows in one but not the other | [
"",
"c#",
"datatable",
""
] |
As far as I can tell there's no simple way of retrieving a character offset from a TextRange object in Internet Explorer. The W3C Range object has a node, and the offset into the text within that node. IE seems to just have pixel offsets. There are methods to create, extend and compare ranges, so it would be possible t... | I'd suggest [IERange](http://code.google.com/p/ierange/), or just the `TextRange`-to-`DOM Range` algorithm from it.
## Update, 9 August 2011
I'd now suggest using my own [Rangy](http://code.google.com/p/rangy) library, which is similar in idea to IERange but much more fully realized and supported. | I use a method based on this caret position trick:
```
// Assume r is a range:
var offsetFromBody = Math.abs( r.moveEnd('character', -1000000) );
```
Since moveEnd returns the number of characters actually moved, offset should now be the offset from the start of the document. This works fine for testing primitive car... | Character offset in an Internet Explorer TextRange | [
"",
"javascript",
"html",
"internet-explorer",
"dom-selection",
""
] |
I need to match something in the form
```
<a href="pic/5" id="piclink"><img src="thumb/5" /></a>
```
to find the number, in this case 5, using JavaScript. I have no idea how to use regexes, so I was wondering if anyone here could help out. | Just to make sure you know what's going on, the pattern you posted in your own answer will match exactly **one** digit between 0 and 9.
If you want to match integers with one or more digits, you might try the pattern
```
/[0-9]+/
```
Check out [Wikipedia's article on Regular Expressions](http://en.wikipedia.org/wiki... | Nevermind, I solved it with a simple
```
'<a href="pic/5" id="piclink"><img src="thumb/5" /></a>'.match(/[0-9]/);
``` | Match Regex with JavaScript | [
"",
"javascript",
"regex",
""
] |
Here's the situation:
I have one VS2005 solution with two projects: MyDll (DLL), MyDllUnitTest (console EXE).
In MyDll I have a class called MyClass which is internal to the DLL and should not be exported. I want to test it in MyDllUnitTest, so I added a test suite class called MyClassTest, where I create instances o... | I don't understand why you don't want to build it in your dll project. As long as both projects are using the same source file, they will both generate the same object file (assuming compiler options are set the same way).
If you want to test the dll without exporting the class itself (I presume this is because export... | Here is an alternative approach to achieve what your trying to do BUT I believe that it will meet your requirements...
Use the InternalsVisibleToAttribute attribute on the assembly that contains the classes you want to test. Then if you reference this assembly you'll be able to test the class even though to other asse... | Reusing object files in Visual Studio 2005 | [
"",
"c++",
"visual-studio-2005",
"visual-c++-2005",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.