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 the source variable but I feel it's easier to read the code if all the sub classes themselves define the source, instead of from inheritance.
What is your advice?
/Adam
|
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(String file) {
source = file;
}
public String getSource() {
return source;
}
}
```
Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code.
There are a few other reasons to think about too:
* If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.
* If your getter/setter methods aren't getting and setting, then describe them as something else.
Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.
|
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 to [Interface vs Base class](https://stackoverflow.com/questions/56867/interface-vs-base-class)
|
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 that isn't exposed by the larger dll.
Since this was a test I simply added the source to my project and called the functions. I got this error: **syntax error : missing ')' before ';'**
The file is correctly included, and I have both the .cpp and the .h in the source folder, and within the project but it wouldn't compile.
I eventually created a very small test project, main.cpp, spooler.cpp and spooler.h (the spooler is a wrapper around the comms) and tried to compile that. Same issue.
So I ripped out all the dll related stuff just in case there is a weird issue going on with that and it still won't compile.
I can't think of the life of me what is wrong. Does anyone else have any ideas?
p.s. Jeff you really need to add the ability to attach files because the source would fill up too many screens with data.
|
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. You may need to run the .i file through the compiler to find the exact line that causes the syntax error. It can be a pain to read the post-preprocessed file, but it should show what's going on.
|
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 continue.</a>';
} else {
// form
}
?>
```
## nextpage.php
```
<?php
session_start();
if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
} else {
header('Location: index.php');
}
?>
```
However I'd probably store something safer like a userid in a session rather than the user's login credentials.
|
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 not *intrinsically* unsafe to store password data in a session, but if there is no need to do so, you should probably try to avoid it.
|
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 answers.
Some details:
* Our client is .NET 1.1 and 2.0 code; this is where the message will be sent from.
* The target in a SQL Server 2005 instance. All messages end up being database updates or inserts.
* We will send several updates that must be treated as a transaction.
* We have to have perfect message recoverability; no messages can be lost.
* We have to be asynchronous and able to accept messages even when the target SQL server is down.
* Developing our own queuing solution isn't an option; we're a small team.
Things I've discovered so far:
* Both MSMQ and SQL Service Broker can do the job.
* It appears that service broker is faster for transactional messages.
* Service Broker requires a SQL server running somewhere, whereas MSMQ needs any configured Windows machine running somewhere.
* MSMQ appears to be better/faster/easier to set up/run in clusters.
Am I missing something? Is there a clear winner here? Any thoughts, experiences, or links would be valued. Thank you!
EDIT: We ended up sticking with service broker because we have a custom DB framework used in some of our client code (we handle transactions better). That code captured SQL for transactions, but not . The client code was also all version 1.1 of .NET, so we'd have to upgrade all the client code. Thanks for your help!
|
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 data move? **Service Broker**
* Is processing done in .NET/COM code? **MSMQ**
* Do you need remote distributed transactions (for example, processing on a box different than SQL)? **MSMQ**
* Do you need to be able to send messages while the destination is down? **MSMQ**
* Do you want to use nServiceBus, MassTransit, Rhino-ESB, etc.? **MSMQ**
Things to consider no matter what you choose
* How do you know the health of your queue? Both options handle failover differently. For example **Service Broker** will disable your queue in certain scenarios which can take down your application.
* How will you perform reporting? If you already use SQL Tables in your reports, **Service Broker** can easily fit in as it's just another dynamic table. If you are already using Performance Monitor **MSMQ** may fit in nicer. **Service Broker** does have a lot of performance counters, so don't let this be your only factor.
* How do you measure uptime? Is it merely making sure you don't lose transactions, or do you need to respond synchronously? I find that the distributed nature of **MSMQ** allows for higher uptime because the main queue can go offline and not lose anything. Whereas with **Service Broker** your database must be online or else you lose out.
* Do you already have experience with one of these technologies? Both have a lot of implementation details that can come back and bite you.
* No mater what choice you make, how easy is it to switch out the underlying Queueing technology? I recommend having a generic IQueue interface that you write a concrete implementation against. This way the choice you make can easily be changed later on if you find that you made the wrong one. After all, a queue is just a queue and should not lock you into a specific implementation.
|
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 consideration if you go the MSMQ route.
|
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 found.
|
**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 just use rhino.
The [node.js](http://nodejs.org/) [REPL](http://en.wikipedia.org/wiki/REPL) (`node-repl` on a system with node installed) is the best terminal-based, system-context shell I've seen so far. I'm comparing it to rhino and the built-in v8 shell. It provides tab-completion and line editing history, as well as syntax-colouring of evaluations. You can also import [CommonJS](http://commonjs.org/) modules, or at least those modules implemented by node.
Downside is that you have to build node. This is not a huge deal, as building apps goes, but might be a challenge if you don't normally do such things.
|
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 solution that works (also, only occasionally) is to reboot Tomcat and/or the actual machine (Windows in this case).
* The URI is definitely available (as confirmed by asking the browser to do the fetch).
Relevant code:
```
BufferedReader reader;
try {
URL url = new URL(URI);
reader = new BufferedReader(new InputStreamReader(url.openStream())));
} catch( MalformedURLException e ) {
throw new IOException("Expecting a well-formed URL: " + e);
}//end try: Have a stream
String buffer;
StringBuilder result = new StringBuilder();
while( null != (buffer = reader.readLine()) ) {
result.append(buffer);
}//end while: Got the contents.
reader.close();
```
|
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 anywhere, that is another source for these kind of errors.
|
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 understand exactly what it is asking for me to code!
When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).
If anybody could guide me in the right direction, I would greatly appreciate it.
|
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(temp);
System.out.println(temp);
```
I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the *src* collection to the constructor which initializes the list withj the contents of the *src* in the collection natural order. Then you pass the list to the *Collections.reverse()* method which reverses the list and finally you print it.
|
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 the Collection interface, it will automatically work for all of those since they must implement the interface (provided they implement it in a sane way;).
|
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
{
public void someOtherMethod()
{
if(SomeEvent != null) SomeEvent(this, someArgs); // << why is this not possible?
//Error: The event 'SomeEvent' can only appear on the left hand side of += or -=
//(except when used from within the type 'A')
}
}
```
Why isn't it possible?
And what is the common solution for this kind of situation?
|
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://stackoverflow.com/questions/253757/why-events-cant-be-used-in-the-same-way-in-derived-classes-as-in-the-base-class#253803) answer or the [C# specification](http://msdn.microsoft.com/en-us/library/aa664454(VS.71).aspx) which describes how the compiler automatically creates a private field.
Here is one possible work around.
```
public class A
{
public event EventHandler SomeEvent;
public void someMethod()
{
OnSomeEvent();
}
protected void OnSomeEvent()
{
EventHandler handler = SomeEvent;
if(handler != null)
handler(this, someArgs);
}
}
public class B : A
{
public void someOtherMethod()
{
OnSomeEvent();
}
}
```
**Edit:** Updated code based upon [Framework Design Guidelines section 5.4](http://msdn.microsoft.com/en-us/library/cf18x51d(VS.71).aspx) and [reminders](https://stackoverflow.com/questions/253757/why-events-cant-be-used-in-the-same-way-in-derived-classes-as-in-the-base-class#253806) by others.
|
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 only see the event, which only allows subscription and unsubscription.
|
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 framework, but I wanted to know if something like this was already built-in to the language or if there was already some kind of framework floating around. I can write my own Assert functions, just don't want to reinvent the wheel.
|
> ## 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 some Microsoft resources:
* [The main Microsoft Research site](http://research.microsoft.com/en-us/projects/contracts/)
* [The user manual](http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf)
* [The 2008 PDC presentation](http://channel9.msdn.com/pdc2008/TL51/)
* [The 2009 PDC presentation](http://microsoftpdc.com/Sessions/VTL01)
Here are some other resources:
* [Code Contracts for .NET 4.0 - Spec# Comes Alive](http://codebetter.com/blogs/matthew.podwysocki/archive/2008/11/08/code-contracts-and-net-4-0-spec-comes-alive.aspx)
* [.NET Code Contracts and TDD Are Complementary](http://codebetter.com/blogs/matthew.podwysocki/archive/2008/11/14/net-code-contracts-and-tdd-are-complementary.aspx)
* [Code Contracts Primer – Part 5: Utilizing Object Invariants](http://devlicio.us/blogs/derik_whittaker/archive/2009/07/01/code-contracts-primer-part-5-utilizing-object-invariants.aspx)
* [Code Contracts Primer – Part 6 Interface Contracts](http://devlicio.us/blogs/derik_whittaker/archive/2010/05/14/code-contracts-primer-part-6-interface-contracts.aspx)
|
[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 example and more:](http://www.rosemarymonahan.com/specsharp/)
```
public static int BinarySearch(int[]! a, int key)
requires forall{int i in (0: a.Length), int j in (i: a.Length); a[i] <= a[j]};
ensures 0 <= result ==> a[result] == key;
ensures result < 0 ==> forall{int i in (0: a.Length); a[i] != key};
{
int low = 0;
int high = a.Length - 1;
while (low <= high)
invariant high+1 <= a.Length;
invariant forall{int i in (0: low); a[i] != key};
invariant forall{int i in (high+1: a.Length); a[i] != key};
{
int mid = (low + high) / 2;
int midVal = a[mid];
if (midVal < key) {
low = mid + 1;
} else if (key < midVal) {
high = mid - 1;
} else {
return mid; // key found
}
}
return -(low + 1); // key not found.
}
```
Note that using the Spec# language yields *compile time checking* for DBC constructs, which to me, is the best way to take advantage of DBC. Often, relying on runtime assertions becomes a headache in production and people generally elect to [use exceptions](https://stackoverflow.com/questions/117171/design-by-contract-tests-by-assert-or-by-exception) instead.
There are [other languages](http://en.wikipedia.org/wiki/Design_by_contract#Language_support) that embrace DBC concepts as first class constructs, namely [Eiffel](http://en.wikipedia.org/wiki/Eiffel_(programming_language)) which is also available for the .NET platform.
|
'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 the code, I have something like this:
```
Foo *a;
// Do stuff...
std::string name = a->Name(); // <-- chooses the non-const version
```
Does anyone know why the compiler would choose the non-const version in this case?
This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point.
|
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](http://www.icce.rug.nl/documents/cplusplus/cplusplus07.html)
> Earlier, in section 2.5.11 the concept
> of function overloading was
> introduced. There it noted that member
> functions may be overloaded merely by
> their const attribute. In those cases,
> the compiler will use the member
> function ***matching most closely the
> const-qualification of the object:***
|
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 of bad design.
|
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 the inner text of the tag. There are just those three tags, so it doesn't need to be universal.
In other words:
```
match.Groups["name"] would be "tag1"
match.Groups["value"] would be "content for tag 2"
```
Any ideas?
|
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
RegEx adapted as per question author's clarification.
|
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> hello <b>mitch</b> </user>
...some html content <b> etc </b> ...
<message> some html <i>message</i> <a href....>bla</a> </message>
...some html content <b> etc </b> ...</html>";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(input);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//user | //message"))
{
Console.WriteLine("{0}: {1}", node.Name, node.InnerText);
// or node.InnerHtml to keep the formatting within the content
}
```
This outputs:
```
user: hello mitch
message: some html message bla
```
If you want the formatting tags, then use .InnerHtml instead of .InnerText.
If it is xml, then to code with the full spectrum of xml, it would be better to use an xml parser. For small-to-mid size xml, loading it into a DOM such as XmlDocument would be fine - then query the nodes (for example, "//\*"). For huge xml, XmlReader might be an option.
If the data doesn't have to worry about the full xml, then some simple regex shouldn't be too tricky... a simplified example (no attributes, no namespaces, no nested xml) might be:
```
string input = @"blah <tag1> content for tag 1 </tag1> blop
<tag2> content for tag 2 </tag2> bloop
<tag3> content for tag 3 </tag3> blip";
const string pattern = @"<(\w+)>\s*([^<>]*)\s*</(\1)>";
Console.WriteLine(Regex.IsMatch(input, pattern));
foreach(Match match in Regex.Matches(input, pattern)) {
Console.WriteLine("{0}: {1}", match.Groups[1], match.Groups[2]);
}
```
|
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 provides. e.g. Does your Data access objects retrieve/process data correctly? Hopefully your web service interface and the underlying functionality are not tightly coupled.
**2. Does the live web service (be it SOAP/REST/XMLRPC) function correctly?**
In this case a good way to test this is to build a web service client and write tests to see whether this client works correctly against the web service. e.g. Use Axis/CXF/XFire to build the web service client and then write JUnit tests for the data it returns.
Also remember to target your testing towards what the end users of this web service will be using. If you have written a Java web service but it is being consumed by .Net clients then make sure you test the service against a .Net client. SOAP services are especially troublesome when it comes to consistent cross-platform behavior.
|
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 well as a commercial (with more functionality and support) version. Check it out.
|
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 previous match results from the 4 involved players. This gives a very rough estimation, but I'd like to replace it with something more sophisticated, taking into account things like:
* players may be good playing as attacker but bad as defender (or vice versa)
* players do well against a specific opponent / bad against others
* some teams work well together, others don't
* skills change over time
What would be the best algorithm to predict the game outcome as accurately as possible?
Someone suggested using a neural network for this, which sounds quite interesting... but I do not have enough knowledge on the topic to say if that could work, and I also suspect it might take too many games to be reasonably trained.
EDIT:
Had to take a longer break from this due to some project deadlines. To make the question more specific:
Given the following mysql table containing all matches played so far:
```
table match_result
match_id int pk
match_start datetime
duration int (match length in seconds)
blue_defense int fk to table player
blue_attack int fk to table player
red_defense int fk to table player
red_attack int fk to table player
score_blue int
score_red int
```
How would you write a function predictResult(blueDef, blueAtk, redDef, redAtk) {...}
to estimate the outcome as closely as possible, executing any sql, doing calculations or using external libraries?
|
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/03/computing-your-skill.html)" blog post.
|
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 not happening - our user connections are not being transfered to the new server after failover and we're not sure why.
Our application connection to EMS at startup only so if the TIBCO admins failover after users have started our application, they users need to restart the app in order to reconnect to the new server (our EMS connection uses a server string including all 4 production EMS servers - if the first attempt fails, it moves to the next server in the string and tries again).
I'm looking for an automated approach that will attempt to reconnect to EMS periodically if it detects that the connection is dead but I'm not sure how best to do that.
Any ideas? We are using TIBCO.EMS.dll version 4.4.2 and .Net 2.x (SmartClient app)
Any help would be appreciated.
|
*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 server also *appears* to be responsible for in-place 'Connection' failover and re-connection, so let's confirm it's doing its job and then lean on that feature.
Creating a client side solution is going to be slightly more involved than fixing a server or client setup problem. All sessions you have created from a failed connection need to be re-created (not to mention producers, consumers, and destinations). There are no "reconnect" or "refresh" methods on either type. The sessions do not maintain a reference to their parent connection either.
You will have to manage a lookup of connection/session objects and go nuts re-initializing everyone! or implement some sort of session failure event handler that can get the new connection and reconnect them.
So, for now, let's dig in and see if the client is setup to receive failover notification (tib ems users guide pg 292). And make sure the raised exception is caught, contains the failover URL, and is being handled properly.
|
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 order of 1/2 second between retries). Our EMS servers can take a long time to failover because of network storage, etc - so 5 retries at 1/2s intervals is nowhere near long enough.
TWO:
I believe its important to enable the client-server and server-client heartbeats. Wasn't able to verify but without those in place, the client might not get the notification that the server is offline or switching in failover mode. This, of course, is a server side setting for EMS.
THREE:
you can watch for failover event by setting Tibems.SetExceptionOnFTSwitch(true); and then wiring up a exception event handler. When in a single-server environment, you will see a "Connection has been terminated" message. However, if you are in a fault-tolerant multi-server environment, you will see this: "Connection has performed fault-tolerant switch to ". You don't strictly need this notification, but it can be useful (especially in testing).
FOUR:
Apparently not clear in the EMS documentation, connection reconnect will NOT work in a single-server environment. You need to be in a multi-server, fault tolerant environment. There is a trick, however. You can put the same server in the connection list twice - strange I know, but it works and it enables the built-in reconnect logic to work.
some code:
```
private void initEMS()
{
Tibems.SetExceptionOnFTSwitch(true);
_ConnectionFactory = new TIBCO.EMS.TopicConnectionFactory(<server>);
_ConnectionFactory.SetReconnAttemptCount(30); // 30retries
_ConnectionFactory.SetReconnAttemptDelay(120000); // 2minutes
_ConnectionFactory.SetReconnAttemptTimeout(2000); // 2seconds
_Connection = _ConnectionFactory.CreateTopicConnectionM(<username>, <password>);
_Connection.ExceptionHandler += new EMSExceptionHandler(_Connection_ExceptionHandler);
}
private void _Connection_ExceptionHandler(object sender, EMSExceptionEventArgs args)
{
EMSException e = args.Exception;
// args.Exception = "Connection has been terminated" -- single server failure
// args.Exception = "Connection has performed fault-tolerant switch to <server url>" -- fault-tolerant multi-server
MessageBox.Show(e.ToString());
}
```
|
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 InvalidOperationException:
*Task attempted to log before it was initialized. Message was...*
Any suggestions? (In the past I have mostly unit-tested Internal static methods on my custom tasks to avoid such problems.)
|
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 != null)
{
this.Log.LogMessage(message, args);
}
else
{
Console.WriteLine(message, args);
}
}
```
|
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
nProduct AS np ON p.nProduct = np.Id
```
I want to produce the following:
```
Description A B C
Product 1 5 4 2
```
|
```
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.nProduct = np.Id
GROUP BY
np.Id,
np.Description
```
---
Here is a simple test example:
```
DECLARE @temp TABLE (
id INT,
description varchar(50),
promotionalCode char(1),
Price smallmoney
)
INSERT INTO @temp
select 1, 'Product 1', 'A', 5
union
SELECT 1, 'Product 1', 'B', 4
union
SELECT 1, 'Product 1', 'C', 2
SELECT
id,
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
@temp
GROUP BY
id,
description
```
|
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 values:
```
Customer Product Quantity
Mike Bike 3
Mike Chain 2
Mike Bike 5
Lisa Bike 3
Lisa Chain 3
Lisa Chain 4
```
Ex: a PIVOT operation on the Order table:
```
SELECT *
FROM Sales.[Order]
PIVOT (SUM(Quantity) FOR Product IN ([Bike],[Chain])) AS PVT
```
The expected output from this query is:
```
Customer Bike Chain
Lisa 3 7
Mike 8 2
```
If you aren't using SQL Server, you might search for "pivot" for your database.
|
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 folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?
|
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 with JavaScript
* Works in all A-grade browsers except Safari and Internet Explorer
* Demo: http://mathiasbynens.be/demo/dynamic-favicons
*/
// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head = document.head || document.getElementsByTagName('head')[0];
function changeFavicon(src) {
var link = document.createElement('link'),
oldLink = document.getElementById('dynamic-favicon');
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = src;
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
}
```
You would then use it as follows:
```
var btn = document.getElementsByTagName('button')[0];
btn.onclick = function() {
changeFavicon('http://www.google.com/favicon.ico');
};
```
[Fork away](http://gist.github.com/428626) or [view a demo](http://mathiasbynens.be/demo/dynamic-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-up cancels the previous pop-up.
If this were a multi-threaded system then the problem would be obvious: there are two threads trying to show a pop-up, and they both cancel existing pop-ups then pop up their own pop-ups. But I assumed JavaScript is always run single-threaded, which would prevent this. Am I wrong? Are event handlers running asynchronously, in which case I need synchronized access to shared data, or should I instead be looking for bugs in the library code for cancelling pop-ups?
Edited to add:
* The library in question is [SIMILE Timeline](http://code.google.com/p/simile-widgets/) and its Ajax library;
* The event handler does call `SimileAjax.DOM.cancelEvent(domEvt)`, which I assume based on the name cancels the bubbling of events;
* Just to make thing s more complicated, what I am actually doing is starting a timeout that if not cancelled by a `moustout` shows the pop-up, this being intended to prevent pop-ups flickering annoyingly but annoyingly having the reverse effect.
I'll have another poke at it and see if I can work out where I am going wrong. :-)
|
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.google.com/search?hl=en&client=firefox-a&rls=com.ubuntu:en-US:unofficial&hs=qp1&pwst=1&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=javascript+event+propagation&spell=1) issue.
|
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 creates an object of itself and stores it. One this happens every static all references the same object and because of this you don't get multiple tooltips or conflicts.
I use ExtJS and they do tooltips, and message boxes as both flyweight elements. I'm hoping that your frameworks had flyweight elements as well, otherwise you will just have to make your own singleton and call it.
|
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 situation. I don't really use stored procs anymore as I like having all of my logic in one place.
|
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 intellectual property that you don't want to expose to other parties
4. WANT your logic distributed, because that is the nature of distributed, n-tier computing
5. you might want the database engineer or DBA to modify schema without modifying application code (stored procs, by virtue of providing API's, provide a layer of abstraction)
There are other reasons.
Prepared statements are better for work done within a session. But if you are taking the time to create a prepared statement, you have essentially done everything necessary to create a stored procedure. The difference is that the stored procedure is available across multiple sessions (subject to GRANTS in the database).
What I can not figure out is that if you have the option for stored proc vs. prepared statement, why you would bother with prepared statements. Most of the SP vs PS discussions seem to focus on what the differences are between them, not on why to use one vs the other. That always appears to boil down to "depends on what you are trying to do." But I haven't seen a well organized description of: use a proc if you need VS use a statement if you need....
|
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 solution out there - so far [this is the best code I've found](http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx) but I would love to find something more along the lines of the HttpRequest.QueryString object *(asp.net server side)*. Thanks in advance,
Shane
|
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) {
return pair[1];
}
}
return null;
}
```
|
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 changes to be aware of. I was reading the change log but didn't notice any.
* Is it easy to revert back to 5.2.5 if something goes wrong?
* Anything else to be aware of?
|
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 environment, you're making a gamble.
@Grant Wagner: Great point on virtualization. Setting up a good test environment doesn't have to be difficult.
|
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 a virtual environment running your existing platform, then upgrade and test that?
If you are willing to spend money, you can buy tools to do P2V (Physical-to-Virtual) that will take your existing setup and provide you with a virtualized copy of it (this could be valuable if you've done a lot of customization to the configuration that might be difficult to produce to a virtualized version that matches the original well enough to do proper testing).
|
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 small changes or I can use NetBeans 6.5 RC2 and then use VSFTPD to upload them to my home directory and 'mv' the file to the proper location (/var/www).
**My questions:** What method should I use to edit PHP and upload them to the server? Is NetBeans ideal? Does vi really have as few features as I've found (basic text editor commands with no PHP IDE functions). What am I missing? From the amount of material I've discovered just as I've begun to write a PHP application, I know there must be a better solution but haven't found one yet.
(Note: I have meddled around in setting `chroot_local_user=NO` but realized that if I upload something that ends up breaking my site I have no backup copy.)
|
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 complete history about all the changes that have been done on each file, you can have full control of your code...
I use [Subversion](http://subversion.tigris.org/), and it is very easy to deploy your versioned source code to the production server...
|
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 editors
+ [GEdit](http://www.gnome.org/projects/gedit/)
* Terminal Editors
+ [VIM](http://www.vim.org/)
+ [Emacs](http://www.gnu.org/software/emacs/)
You need to decide what set of features you want, and which editor you are more comfortable with.
VI is **very** feature rich, but it has a steep learning curve. [Read](http://www.scribd.com/doc/263139/VIM-for-PHP-Programmers) [up](http://www.digilife.be/quickreferences/QRC/Vi%20Reference%20Card.pdf)(PDF) [on](http://www.vim.org/tips/tip.php?tip_id=305) [it](http://www.vim.org/6k/features.en.txt), and try it again.
Personally I use Anjuta, as I dont use / like all of the functionality of the full IDE's. I sometimes use gedit if I want to quickly edit something, or VI if I'm in a terminal and want do to something.
And like source control is a ***very*** good idea!
|
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 you want
Date date = format.parse(myString)
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date)
```
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`.
|
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 eventually.
<http://joda-time.sourceforge.net/>
So anyway, if Joda Time is an option, something like this *should* work:
```
DateTimeFormatter formatter =
DateTimeFormat.forPattern("your pattern").withOffsetParsed();
DateTime dateTime = formatter.parseDateTime("your input");
GregorianCalendar cal = dateTime.toGregorianCalendar();
```
I hope this helps.
|
> 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 an object with TimeZone equal to the current system TimeZone, the time will be modified to account for the offset.
This code:
```
String dateString = "Mon, 27 Oct 2008 08:33:29 -0700";
DateFormat df = new SimpleDateFormat("E, dd MMM yyyy hh:mm:ss Z");
Date parsed = df.parse(dateString);
System.out.println("parsed date: " + parsed);
Calendar newCalendar = Calendar.getInstance();
newCalendar.setTime(parsed);
```
outputs:
> parsed date: Mon Oct 27 11:33:29 EDT 2008
which technically is correct, since my system timezone is EDT / UTC minus four hours (which is three hours ahead of yours). If you express time as the number of milliseconds since January 1, 1970, 00:00:00 GMT (which is how the `Date` object stores it's date/time), then these date/times are equal, it's just the TimeZone that is different.
Your issue is really *How do I convert a Date/Calendar into my timezone?* For that, take a look at my response to the previous question [How to handle calendar TimeZones using Java?](https://stackoverflow.com/questions/230126/how-to-handle-calendar-timezones-using-java#230383)
|
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 have some experience in a similar project. Is it feasible?
|
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_rasillo.html) by Jorge Rasillo and Mike Burr shows how to do a Flex front-end / RESTful back-end app (examples in PHP and Groovy). Nice article. Anyway, here's the take away:
* Their PHP/Groovy code *uses and expects* PUT and DELETE.
* But the Flex code has to use POST, but sets the HTTP header X-Method-Override to DELETE (you can do the same for PUT I presume).
* Note that this is *not* the Proxy method discussed above.
```` ```
// Flex doesn't know how to generate an HTTP DELETE.
// Fortunately, sMash/Zero will interpret an HTTP POST with
// an X-Method-Override: DELETE header as a DELETE.
deleteTodoHS.headers['X-Method-Override'] = 'DELETE';
``` ````
What's happening here? the IBM web server intercepts and interprets the "POST with DELETE" as a DELETE.
So, I dug further and found this [post and discussion with Don Box](http://www.pluralsight.com/community/blogs/dbox/archive/2007/01/16/45725.aspx) (one of the original SOAP guys). Apparently this is a fairly standard behavior since some browsers, etc. do not support PUT and DELETE, and is a work-around that has been around a while. Here's a snippet, but there's much more discussion.
> "If I were building a GData client, I honestly wonder why I'd bother using DELETE and PUT methods at all given that X-HTTP-Method-Override is going to work in more cases/deployments."
My take away from this is that if your web side supports this X-Method-Override header, then you can use this approach. The Don Box comments make me think it's fairly well supported, but I've not confirmed that yet.
Another issue arises around being able to read the HTTP response headers. Again, from [a blog post in 2007 by Nathan de Vries](http://www.atnan.com/2007/6/11/can-as3-do-rest-or-not), we see this discussed. He followed up that blog post and discussion with his own comment:
> "The only change on the web front is that newer versions of the Flash Player (certainly those supplied with the Flex 3 beta) now support the responseHeaders property on instances of HTTPStatusEvent."
I'm hoping that means it is a non-issue now.
|
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 than GET and POST the problem mostly lies in that some browsers (for example Safari) don't support these, and Flash Player relies on the browser for all it's networking.
|
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 if FullScreenEnabled is false and return;
private void Case1()
{
if (FullScreenEnabled == false)
{
return;
}
// code to be executed goes here!
}
// Surround the code by an if statement.
private void Case2()
{
if (FullScreenEnabled)
{
// code to be executed goes here!
}
}
```
|
```
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 checks. Plus, it could be easily be written in a single line: if (!FullScreenEnabled) return;
|
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 issues, but there always are.
Are there any recommendations or problems to watch out for during the port?
|
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 looser on this anyways.
If your app has a GUI, you'll need to recode the whole thing in Cocoa, using Objective-C. Meaning you'll be into a new *language* as well. Some people (like MS) have used Carbon (C++ API), but it's being phased out. I wouldn't recommend that to new projects.
Your best luck is using Qt or Gtk+. A native Gtk+ port has been (re)announced just some days ago (see [Imendio](http://osnews.com/story/20326/Binary_Build_for_Native_Gtk_Mac_OS_X_Port_Released)).
p.s.
OS X does of course run X11 binaries, too, but pushing that to any of your customers might be a hard road. They're used to Aqua interface, and productive with that. Consider X11 only a very short term solution.
p.p.s. The number of open source addon libs coming with OS X is limited, and their versions might lack behind. Whereas in Linux you can easily require users to have 'libxxx v.y.y' installed, in OS X there are multiple packaging approaches (fink, macports) and for a commercial tool the required libraries are expected to be contained in the application. OS X offers 'application bundles' and 'frameworks' for this (local copies, making the application self-sufficient). Linux does not have such a concept. This will have a great effect on your build system as well; maybe you'll want to try something like [SCons](http://www.scons.org/) for all platforms?
|
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 with .mm instead of .m, and you can intermix most legal C++ and Objective-C syntax even on the same line.
|
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-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)
|
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)
pBuf[bytes] = '\0';
return bytes;
```
|
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/933850/33732). It isn't necessarily the same directory; if someone runs the program from a command prompt, then the program is being *run from* the command prompt's current working directory even though the program file lives elsewhere.
getcwd is a POSIX function and supported out of the box by all POSIX compliant platforms. You would not have to do anything special (apart from incliding the right headers unistd.h on Unix and direct.h on windows).
Since you are creating a C program it will link with the default c run time library which is linked to by ALL processes in the system (specially crafted exceptions avoided) and it will include this function by default. The CRT is never considered an external library because that provides the basic standard compliant interface to the OS.
On windows getcwd function has been deprecated in favour of \_getcwd. I think you could use it in this fashion.
```
#include <stdio.h> /* defines FILENAME_MAX */
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
{
return errno;
}
cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
printf ("The current working directory is %s", cCurrentPath);
```
|
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 useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files.
**So when is it *not* a good time to use a generator, or a generator expression, or an `itertools` function?**
* When should I prefer `zip()` over `itertools.izip()`, or
* `range()` over `xrange()`, or
* `[x for x in foo]` over `(x for x in foo)`?
Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking.
We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off?
I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of [list comprehension performance vs. map() and filter()](http://www.gossamer-threads.com/lists/python/python/76267). ([alt link](https://mail.python.org/pipermail//python-list/2001-December/096256.html))
|
**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
...
```
2) You need **random access** (or any access other than forward sequential order):
```
for i in reversed(data): ... # generators aren't reversible
s[i], s[j] = s[j], s[i] # generators aren't indexable
```
3) You need to **join** strings (which requires two passes over the data):
```
s = ''.join(data) # lists are faster than generators in this use case
```
4) You are using **PyPy** which sometimes can't optimize generator code as much as it can with normal function calls and list manipulations.
|
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 `const`?
This doesn't work:
```
a::a(void) :
b([2,3])
{
// other initialization stuff
}
```
Edit: The case in point is when I can have different values for `b` for different instances, but the values are known to be constant for the lifetime of the instance.
|
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 excellent C5 collection library for .NET. Something where I can see the public bug tracker and check to see when the last SVN commit happened. Also, in an ideal world, I'd find a nice well-designed API for spatial data structures, and the KDTree would be just one class in that library.
For this project, I'll only be working in either 2 or 3 dimensions, and I'm mostly just interested in a good nearest-neighbors implementation.
|
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 standard library and Boost, so most of it should work cross platform.
On the Mac, what IDE/complier do most folks use if they want to write C++? Also, can someone provide a pointer to whatever APIs the Mac has that can control WiFi adapters (associate, scan, disconnect, etc)?
|
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 will let you do everything you want.
Also, I would strongly recommend **against** trying to use Flex/Air for your application's user experience. It may look slick to you on Windows as a Windows developer, but when it comes to providing a full Macintosh user experience such technologies aren't always a great choice.
For one example, I think Air applications don't support the full range of Mac OS X text editing keystrokes. While not all Mac users will use all keystrokes, for those people used to them trying to type in a text field that doesn't handle (say) control-A and control-E to go to the beginning and end of field is like swimming through syrup.
For a new application that needs to be cross-platform, I'd strongly consider building the core logic in C++ while using Cocoa on the Mac and WPF on Windows to get the best user experience on each platform. Both Mac OS X and Windows have modern native user experience technologies that their respective users are getting used to, and also have good ways for C++ code to interoperate with these technologies.
|
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 to be used interchangeably, which one should be used or does it depend on other factors?
|
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_MAP
};
```
`afx_msg` is just an empty placeholder macro - it doesn't actually do anything, but is always included by convention.
The message map is then defined in the class's .cpp file:
```
BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd)
ON_WM_SIZE()
END_MESSAGE_MAP()
```
These macros generate a lookup table for the class which allows messages received by the window to be dispatched to the corresponding handler functions. The `ON_WM_SIZE` macro allows the `wParam` and `lParam` message parameters in the `WM_SIZE` message to be decoded into more meaningful values for the message handler function (`nType`, `cx`, and `cy` in this case). MFC provides macros for most window messages (`WM_LBUTTONDOWN`, `WM_DESTROY`, etc).
You can find more information on how message maps work in MFC [here](http://msdn.microsoft.com/en-us/library/0x0cx6b1.aspx) on MSDN.
|
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 better idea?
|
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" your code with attributes/other markup that have no functional meaning beyond the end of the globalisation project. How about having a defect raised for each class that requires work, and tracking it that way?
|
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 different.
My assumption would be that no language should come out the same in all but the simplest cases.
Use the set of unit tests that sucessfully complete to track your progress.
|
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/2008', which is Sunday's date).
One little twist is that users enter records for the previous week up until 11 AM on the Monday of the current week.
So I need a function that starts with DateTime.Now and returns the week-ending date (no time part) according to the rules above. Thanks for your help. I have a solution that works, but I'm too embarassed to post it.
Oh, and I can't use LINQ.
|
```
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)));
Console.WriteLine(WeekNum(new DateTime(2008,10,27, 12, 00, 00)));
Console.WriteLine(WeekNum(new DateTime(2008,10,28)));
Console.WriteLine(WeekNum(new DateTime(2008,10,25)));
}
```
You may hard-code DateTime.Now instead of passing a DateTime object. It just made testing easier this way.
|
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.AreEqual(sunday, GetSunday(DateTime.Parse("10/23/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/24/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/25/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/26/2008")));
Assert.AreEqual(sunday, GetSunday(DateTime.Parse("10/27/2008 10:59 AM")));
Assert.AreEqual(nextSunday, GetSunday(DateTime.Parse("10/27/2008 11:00 AM")));
}
private DateTime GetSunday(DateTime date)
{
if (date.DayOfWeek == DayOfWeek.Monday && date.Hour < 11)
return date.Date.AddDays(-1);
while (date.DayOfWeek != DayOfWeek.Sunday)
date = date.AddDays(1);
return date.Date;
}
```
|
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, which is very useful if you want to allow only e.g. `<b>`, `<i>` and `<u>`.
### See also:
* [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)
* [What are the pros and cons of the leading Java HTML parsers?](https://stackoverflow.com/questions/3152138/what-are-the-pros-and-cons-of-the-leading-java-html-parsers)
* [XSS prevention in JSP/Servlet web application](https://stackoverflow.com/questions/2658922/xss-prevention-in-jsp-servlet-web-application)
|
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: str2" for what looks like every result. However, no results are actually returned.
I figured one of the two statements would work, but they aren't.
|
```
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 accordingly.
Having event listeners on the many form fields is starting to slow things down, and refreshing the whole form for each change would be too heavy/slow for the user.
I'm wondering whether its possible to add listeners to the registry object's attributes rather than the form elements to speed things up a bit? And, if so, could you provide/point me to some sample code?
Further information:
* This is a plug-in for jQuery, so any functionality I can build-on from that library would be helpful but not essential.
* Our users are using IE6/7, Safari and FF2/3, so if it is possible but only for "modern" browsers I'll have to find a different solution.
|
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( observations[n] )
for( var i=0; i < observations[n].length; i++ )
observations[n][i].apply(null, [v, n]);
}
this.get = function(n)
{
return self[n];
}
this.observe = function(n,f)
{
if(observations[n] == undefined)
observations[n] = [];
observations[n].push(f);
}
}
return new function(){
this.getInstance = function(){
if (instance == null)
{
instance = new __constructor();
instance.constructor = null;
}
return instance;
}
}
})();
var entries = EntriesRegistry.getInstance();
var test = function(v){ alert(v); };
entries.set('bob', 'meh');
entries.get('bob');
entries.observe('seth', test);
entries.set('seth', 'dave');
```
Taking on-board your comments, I'll be using event delegation on the form objects to update the registry and trigger the registered observing methods.
This is working well for me so far... can you guys see any problems with this?
|
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 for using Prototype instead, but I'm sure you'll be able to adapt it easily):
```
$(form).observe('change', function(e) {
// To identify changed field, in Proto use e.element()
// but I think in jQuery it's e.target (as it should be)
});
```
You can also capture `input` and `keyup` and `paste` events if you want it to fire on text fields before they lose focus. My solution for this is usually:
1. **Gecko/Webkit-based browsers:** observe `input` on the `form`.
2. **Also in Webkit-based browsers:** observe `keyup` and `paste` events on `textarea`s (they do not fire `input` on `textarea`s for some reason).
3. **IE:** observe `keyup` and `paste` on the `form`
4. Observe `change` on the `form` (this fires on `select`s).
5. For `keyup` and `paste` events, compare a field's current value against its default (what its value was when the page was loaded) by comparing a text field's `value` to its `defaultValue`
Edit: Here's example code I developed for preventing unmodified form submission and the like:
[What is the best way to track changes in a form via javascript?](https://stackoverflow.com/questions/194101/what-is-the-best-way-to-track-changes-in-a-form-via-javascript#194347)
|
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 and a custom JUnit TestRunner. I've checked both the JUnit docs and searched the web but couldn't find such a thing. Is anyone aware of such a TestRunner?
Update: Thanks for your replies regarding test suites. I should have addressed these in my original question. Here we go: I don't want to use test suites because they would require me to manually create and manage them, which means touching ALL my tests and arranging them into suites manually (too much work and a maintenance nightmare). All I need to do is run all unit tests, except a few that are really integration tests. So I want to annotate these, and run all others. At other times, I want to just run the integration tests. I also have the need to put a unit test into multiple groups, which is not possible with suites. Hope this helps to clear things up.
Update 2: If JUnit doesn't have this OOB, I'm looking for an Open Source library that adds this to JUnit (annotations + custom JUnit Test Runner).
|
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/org/springframework/test/annotation/IfProfileValue.html) annotation.
This:
```
@IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"})
public void testWhichRunsForUnitOrIntegrationTestGroups() {
// ...
}
```
Will run if the System property 'test-groups' is set to either 'unit-tests' or 'integration-tests'.
Update: [JUnitExt](http://junitext.sourceforge.net/) has `@Category` and `@Prerequisite` annotations and looks like it should do what you need. However, I've never used it myself, so I can't vouch for it.
|
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 project, although I'm biased.
|
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 to go
```
template <class T>
void BST<T>::remove(struct Node<T>*& root, const T& x)
{
Node<T>* ptr = root;
bool found = false;
Node<T>* parent;
while (ptr != NULL && !found)
{
if (x < ptr->data)
{
parent = ptr;
ptr = ptr->left;
}
else if (x > ptr->data)
{
parent = ptr;
ptr = ptr->right;
}
else
found = true;
}
if (found == false)
return;
else
{
if(ptr->left != NULL && ptr->right != NULL)
{
Node<T>* inOrderPtr = ptr->left;
parent = ptr;
while (inOrderPtr->right != NULL)
{
parent = inOrderPtr;
inOrderPtr = inOrderPtr->right;
}
ptr->data = inOrderPtr->data;
ptr = inOrderPtr;
}
Node<T>* subPtr = ptr->left;
if (subPtr == NULL)
subPtr = ptr->right;
else if (parent->left == ptr)
parent->left = subPtr;
else
parent->right = subPtr;
delete ptr;
}
```
|
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 (tmp_l->left != NULL)
tmp_l = tmp_l->left;
tmp_l->left = root->left;
tmp_r->right = root->right;
parent->right = NULL;
parent = root;
root = tmp_r;
delete parent;
```
|
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 < root->data)
remove(root->left, x);
else
remove(root->right, 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, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys.
Another problem is that this code:
```
var m_dialogFrame = document.getElementById(m_dialogId);
```
Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding
```
/**
* @type Element
*/
```
Before it, but that, also, will be messy.
Also, both:
```
new XMLHttpRequest();
```
And
```
new ActiveXObject("Microsoft.XMLHTTP");
```
Get red squiggles saying "x cannot be resolved to a type"
The last problem is with:
if (m\_options.width != "auto")
Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String"
How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
|
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 did for me.
|
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 poor man's namespace causes it to get completely lost. Here's [a screenshot of the kind of mess it makes](http://www.jonathanbuchanan.plus.com/images/eclipsejs.png) when trying to understand [this JavaScript file](http://code.google.com/p/js-forms/source/browse/trunk/time.js) - note the useless outline view and the spurious (and incorrect) warnings and errors (including not seeming to understand than `String.split` returns an `Array`).
|
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 possible?
|
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 supported and came to a grinding halt with .Net 3.5sp1 ([WPF running under IIS no more](http://www.ktsc.com/blogs/ChristopherKeslin/?p=12) and [connect.microsoft.com](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361469)). We we are running Server 2008 x64.
I understand that "technically" GDI+ wasn't supported in ASP.NET applications but it does work and there are even commercial offerings available that are built on it.
So my question is whether anyone is successfully using WPF in an ASP.NET or Windows Service application? Does anyone have any suggested workarounds or alternatives?
|
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:

The above image contains the resize icon in the Google Talk messenger's main window. Is there any Java component which provides this facility?
|
You will find in this article how to add an icon looking like the resize icon you are referring to.
 [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 can be parent to a particular type of Widget.
For example, I have derived two more widgets from the Widget class, WidgetParent and WidgetChild. While defining the child class, I want to define the type of parent as WidgetParent, so that I dont have to type cast the parent every time I use it.
Precisely, what I would have liked to do is this:
```
// This does not works!
class Widget<PType>: where PType: Widget
{
PType parent;
}
class WidgetParent<Widget>
{
public void Slap();
}
class WidgetChild<WidgetParent>
{
}
```
So that when I want to access the parent of WidgetChild, instead of using it this way:
```
WidgetParent wp = wc.parent as WidgetParent;
if(wp != null)
{
wp.Slap();
}
else throw FakeParentException();
```
I want to use it this way(if I could use generics):
```
wc.parent.Slap();
```
|
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 the non-generic... from experience, this can be a tricky balancing act. Expect to go back and forth a fair amount!
|
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 even if the quality dropped between versions, it raises an interesting question for me:
When beginning a new language, is it best to start with the latest version (e.g. C# 3.0/.Net 3.5) or should I go back a version or two and try to learn what got added to the language afterward?
The former seems better from the point of view of being up to date immediately, but the latter seems more pragmatic in that it's probably more likely a shop will be using a slightly older version of the language.
|
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* work in the latest. Then as you are comfortable, you can look for areas to enhance using the latest version. E.G. Maybe a Loop with Nested IF's could be enhanced to use LINQ.
|
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();
string reportpath = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString.Get("id") == "5")
{
string publication = Request.QueryString.Get("pub");
DateTime date = DateTime.Parse(Request.QueryString.Get("date"));
int pages = int.Parse(Request.QueryString.Get("pages"));
int sort = int.Parse(Request.QueryString.Get("sort"));
if (sort == 0)
{
reportpath = Server.MapPath("IssuesReport.rpt");
rpt.Load(reportpath);
DataTable resultSet1 = RetrievalProcedures.IssuesReport(date, publication, pages);
Session["Record"] = resultSet1;
}
DataTable report = (DataTable)Session["Record"];
rpt.SetDataSource(report);
CrystalReportViewer1.ReportSource = rpt;
```
I am trying this code but when i clicked the next button it gives me the error that invalid report source..i guess the session is null thats why its giving me this error.
Any sugesstions how can I solve this...
|
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 Session.
```
if (!Page.IsPostBack)
{
if (Request.QueryString.Get("id") == "5")
{
string publication = Request.QueryString.Get("pub");
DateTime date = DateTime.Parse(Request.QueryString.Get("date"));
int pages = int.Parse(Request.QueryString.Get("pages"));
int sort = int.Parse(Request.QueryString.Get("sort"));
// fixed the statement below to key off of session
if (Session["Record"] == null)
{
reportpath = Server.MapPath("IssuesReport.rpt");
rpt.Load(reportpath);
Session["Record"] = RetrievalProcedures.IssuesReport(date, publication, pages);
}
rpt.SetDataSource((DataTable)Session["Record"]);
CrystalReportViewer1.ReportSource = rpt;
// ....
}
}
```
|
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 function without having to scale as it already goes between -1 and 1.
As for accuracy, do you mean exactly the right frequency, or exactly the right wave shape? There is no such thing as a true square wave, and even the sine wave will likely have a few very quiet artifacts at other frequencies. If it's accuracy of frequency that matters, you are reliant on the stability and accuracy of the clock in your sound card. Having said that, I would imagine that the accuracy would be good enough for most uses.
Here's some example code that makes a 1 kHz sample at a 8 kHz sample rate and with 16 bit samples (that is, not floating point):
```
int sampleRate = 8000;
short[] buffer = new short[8000];
double amplitude = 0.25 * short.MaxValue;
double frequency = 1000;
for (int n = 0; n < buffer.Length; n++)
{
buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * frequency) / sampleRate));
}
```
|
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;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)
{
var mStrm = new MemoryStream();
BinaryWriter writer = new BinaryWriter(mStrm);
const double TAU = 2 * Math.PI;
int formatChunkSize = 16;
int headerSize = 8;
short formatType = 1;
short tracks = 1;
int samplesPerSecond = 44100;
short bitsPerSample = 16;
short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
int bytesPerSecond = samplesPerSecond * frameSize;
int waveSize = 4;
int samples = (int)((decimal)samplesPerSecond * msDuration / 1000);
int dataChunkSize = samples * frameSize;
int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
// var encoding = new System.Text.UTF8Encoding();
writer.Write(0x46464952); // = encoding.GetBytes("RIFF")
writer.Write(fileSize);
writer.Write(0x45564157); // = encoding.GetBytes("WAVE")
writer.Write(0x20746D66); // = encoding.GetBytes("fmt ")
writer.Write(formatChunkSize);
writer.Write(formatType);
writer.Write(tracks);
writer.Write(samplesPerSecond);
writer.Write(bytesPerSecond);
writer.Write(frameSize);
writer.Write(bitsPerSample);
writer.Write(0x61746164); // = encoding.GetBytes("data")
writer.Write(dataChunkSize);
{
double theta = frequency * TAU / (double)samplesPerSecond;
// 'volume' is UInt16 with range 0 thru Uint16.MaxValue ( = 65 535)
// we need 'amp' to have the range of 0 thru Int16.MaxValue ( = 32 767)
double amp = volume >> 2; // so we simply set amp = volume / 2
for (int step = 0; step < samples; step++)
{
short s = (short)(amp * Math.Sin(theta * (double)step));
writer.Write(s);
}
}
mStrm.Seek(0, SeekOrigin.Begin);
new System.Media.SoundPlayer(mStrm).Play();
writer.Close();
mStrm.Close();
} // public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)
```
|
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 given context.
Given a generic type parameter, how can I call a static method on the generic class? The static method has to be available, given the constraint.
|
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 through the generic type parameter is an unneeded indirection and hence not supported.
|
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 function:
```
public void doSomething<T>() where T : someParent
{
List<T> items=(List<T>)typeof(T).GetMethod("fetchAll").Invoke(null,new object[]{});
//do something with items
}
```
Where T is any class that has the static method fetchAll().
Yes, I'm aware this is horrifically slow and may crash if someParent doesn't force all of its child classes to implement fetchAll but it answers the question as asked.
|
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 automatically end when the parent Java process dies?
If it helps, I'm using Mac OS X 10.5
|
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 your shutdown hook will not be executed. (as said in this [SO question](https://stackoverflow.com/questions/191215/how-to-stop-java-process-gracefully))
* some of the standard libraries have their own hooks which may run before yours.
* beware of deadlocks.
Another possibility would be to [wrap your java program in a service](http://wrapper.tanukisoftware.org/doc/english/index.html).
|
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(runnable));
```
|
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 part about not ending with a `{` will eliminate static methods.
An example:
```
public class FlagOffendingStatics {
private static String shouldBeFlagged = "not ok";
private static final String ok = "this is fine";
public static void methodsAreOK() {
}
}
```
|
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 "[^(final)] static [^(final)][^(\})]*$" test.txt
private static x = "3";
private static String x = "3";
```
(I realize that `private static x = "3";` isn't valid syntax, but the pattern still holds ok.)
The pattern accounts for the fact that `final` can appear before or after `static` with `[^(final)] static [^(final)]`. The rest of the pattern, `[^(\})]*$`, is meant to prevent any `{` characters from appearing in the remainder of the line.
This pattern will not work however if anyone likes to write their method statements like this:
```
private static void blah()
{
//hi!
}
```
|
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 retrieve in one query all the descendants of James (Jenna,Jennifer,Peter, Alice, Steve).
Thanks,
Pablo.
|
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 -- insert parameter here
union all
select c.CustomerID, c.ParentID, c.Name, ch.Level + 1
from Customers c
inner join Hierachy ch
on c.ParentId = ch.CustomerID
)
select CustomerID, ParentID, Name
from Hierachy
where Level > 0
```
|
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
from Customers c
inner join Hierachy ch
-- EDITED HERE --
on ch.ParentId = c.CustomerID
-----------------
)
select CustomerID, ParentID, Name
from Hierachy
where Level > 0
```
|
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 with the Java default serialization but we had a lot of trouble recovering the objects when the users started to pass different versions of the same object (attributes changed types, names, ...).
We have tried with the XMLEncoder class (transforms an object into a XML), but we have found that there is a lack of functionality (doesn't support Enums for example).
Finally, we also tried JAXB but this impose our users to annotate their classes.
Any good alternative?
|
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 and careful thought should be put into its design.
I won't go into a lot of details, since pretty much everything I have said comes from Effective Java. I'll instead, refer you to it, specifically the chapters about Serialization. It warns you about all the problems you're running into, and provides proper solutions to the problem:
[http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683](https://rads.stackoverflow.com/amzn/click/com/0321356683)
---
With that said, if you're still considering a non-serialization approach, here are a couple:
**XML marshalling**
As many has pointed out is an option, but I think you'll still run into the same problems with backward compatibility. However, with XML marshalling, you'll hopefully catch these right away, since some frameworks may do some checks for you during initialization.
**Conversion to/from YAML**
This is an idea I have been toying with, but I really liked the YAML format (at least as a custom toString() format). But really, the only difference for you is that you'd be marshalling to YAML instead of XML. The only benefit is that that YAML is slightly more human readable than XML. The same restrictions apply.
|
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) (a fast, compact binary serialization format)
* [Smile](https://github.com/FasterXML/jackson-dataformat-smile) (a binary format that comes with Jackson 1.6 and later).
* Java Object Serialization.
We experimented with other serializers recently:
* [SimpleXML](http://simple.sourceforge.net/) seems solid, runs at 2x the speed of XStream, but requires a bit too much configuration for our situation.
* [YamlBeans](http://code.google.com/p/yamlbeans/) had a couple of bugs.
* [SnakeYAML](http://code.google.com/p/snakeyaml/) had a minor bug relating to dates.
Jackson JSON, Kryo, and Jackson Smile were all significantly faster than good old Java Object Serialization, by about 3x to 4.5x. XStream is on the slow side. But these are all solid choices at this point. We'll keep monitoring the other three.
|
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 found in the key collection.
|
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:
```
Session[key] = null; - 0.82380000000000009 ms
Session.Remove(key); - 59.960100000000004 ms
```
Removing 1000 NOT existing items:
```
Session[key] = null; - 1.5368000000000002 ms
Session.Remove(key); - 0.6621 ms
```
Removing 500 existing and 500 not existing items:
```
Session[key] = null; - 1.0432000000000001 ms
Session.Remove(key); - 33.9502 ms
```
Here is a piece of code for first test:
```
Session.Clear();
for (int i = 0; i < 1000; i++)
Session[i.ToString()] = new object();
Stopwatch sw1 = Stopwatch.StartNew();
for (int i = 0; i < 1000; i++)
Session[i.ToString()] = null;
sw1.Stop();
Session.Clear();
for (int i = 0; i < 1000; i++)
Session[i.ToString()] = new object();
Stopwatch sw2 = Stopwatch.StartNew();
for (int i = 0; i < 1000; i++)
Session.Remove(i.ToString());
sw2.Stop();
```
|
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 Compass in my service code via HibernateHelper.getCompass(sessionFactory).
I end up with a HibernateException saying "Compass event listeners not configured, please check the reference documentation and the application's hibernate.cfg.xml".
The [reference documentation](http://www.compass-project.org/docs/2.1.0/reference/html/gps-embeddedhibernate.html) again hints and hibernate.cfg.xml, while I configure Hibernate with Spring's AnnotationSessionFactoryBean. For that case, the documetantation mentions: "If Hibernate Annotations or Hibernate EntityManager (JPA) are used, just dropping Compass jar file to the classpath will enable it (make sure you don't have Hibernate Search in the classpath, as it uses the same event class name)." That doesn't work for me.
Any ideas whats I'm missing or a good resource for getting started?
|
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 better fit. Hibernate search is a better fit with JTA.
Is it me or is Compass suffering from a distinct lack of activity?
|
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 attempting to work out a solution using analytical functions over the table, but it just isn't behaving...
I try:
```
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 THE_TABLE order by row_priority)
where rownum = 1
```
or the inverse:
```
select first_value(col1 ignore nulls) over () col1,
first_value(col2 ignore nulls) over () col2,
first_value(col3 ignore nulls) over () col3
from (select * from THE_TABLE order by row_priority desc)
where rownum = 1
```
And neither seem to ignore nulls. Any hints?
|
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 THE_TABLE ORDER BY ROW_PRIORITY)
)
WHERE ROWNUM = 1
```
which results in (using your values above):
```
COL1 COL2 COL3
------ ------- ----
0.2 100 3
```
|
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 the key, without changing the value.
I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?
|
```
$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_exists( $old_key, $array ) )
return $array;
$keys = array_keys( $array );
$keys[ array_search( $old_key, $keys ) ] = $new_key;
return array_combine( $keys, $array );
}
```
|
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 like a workspace with multiple projects.
Most of the errors that appear at load time, after mvn eclipse:eclipse are because of the repository variable. You can configure this by using "mvn -Declipse.workspace= eclipse:add-maven-repo".
More info on maven eclipse plugin at <http://maven.apache.org/plugins/maven-eclipse-plugin/>.
Regards,
Bogdan
|
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 if the page has a master page. I've tried setting the default button in code with *control*.ID, *control*.ClientID, and *control*.UniqueID, and in each case I get:
> The DefaultButton of panelName must be the ID of a control of type IButtonControl.
I'm sure there's a way to do this with JavaScript, but I'd really like to do it with plain old C# code if possible. Is it possible?
|
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 the Form level, but also on individual Panel level, as long as the focus is within the panel, the default button for the panel will be used if you hit "Enter"
|
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 container UniqueID. For example, if your panel UniqueID is"Body$Content$pnlLogin" and your login button's UniqueID is "Body$Content$ucLogin$btnLogin" (because it's inside a control called "ucLogin") then you need to set Panel.DefaultButton to "ucLogin$btnLogin".
You can work this out in code as follows. (I couldn't find any class library method for this, but let me know if you find one.)
```
void SetDefaultButton(Panel panel, IButtonControl button)
{
string uniqueId = ((Control)button).UniqueID;
string panelIdPrefix = panel.NamingContainer.UniqueID + Page.IdSeparator;
if (uniqueId.StartsWith(panelIdPrefix))
{
uniqueId = uniqueId.Substring(panelIdPrefix.Length);
}
panel.DefaultButton = uniqueId;
}
```
|
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
first = subclassthing()
{'was_false_in_base': False}
first.somedata['was_false_in_base'] = True
second = subclassthing()
{'was_false_in_base': True}
>>> del first
>>> del second
>>> third = subclassthing()
{'was_false_in_base': True}
```
Defining `self.somedata` in the `__init__` function is obviously the correct way to get around this (so each class has it's own `somedata` dict) - but when is such behavior desirable?
|
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** when the instance is created (think static initializer blocks in Java). If an attribute does not exist in a class instance, the class object is checked for the attribute.
At class definition time, you can run arbritrary code, like this:
```
import sys
class Test(object):
if sys.platform == "linux2":
def hello(self):
print "Hello Linux"
else:
def hello(self):
print "Hello ~Linux"
```
On a Linux system, `Test().hello()` will print `Hello Linux`, on all other systems the other string will be printed.
In constrast, objects in `__init__` are created at *instantiation* time and belong to the instance only (when they are assigned to `self`):
```
class Test(object):
def __init__(self):
self.inst_var = [1, 2, 3]
```
Objects defined on a class object rather than instance can be useful in many cases. For instance, you might want to cache instances of your class, so that instances with the same member values can be shared (assuming they are supposed to be immutable):
```
class SomeClass(object):
__instances__ = {}
def __new__(cls, v1, v2, v3):
try:
return cls.__insts__[(v1, v2, v3)]
except KeyError:
return cls.__insts__.setdefault(
(v1, v2, v3),
object.__new__(cls, v1, v2, v3))
```
Mostly, I use data in class bodies in conjunction with metaclasses or generic factory methods.
|
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 __init__(self):
print self.somedata
>>> first = subclassthing()
False
>>> first.somedata = True
>>> print first.somedata
True
>>> second = subclassthing()
False
>>> print first.somedata
True
>>> del first
>>> del second
>>> third = subclassthing()
False
```
The reason this example behaves differently from the one given in the question is because here `first.somedata` is being given a new value (the object `True`), whereas in the first example the dict object referenced by `first.somedata` (and also by the other subclass instances) is being modified.
See Torsten Marek’s comment to this answer for further clarification.
|
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
* AddressID
**AddressTable**
* *AddressID*
* City
* Street
* State
* Zip
|
```
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 ContactTable
LEFT OUTER JOIN UserTable ON ContactTable.UserID = UserTable.UserID
LEFT OUTER JOIN AddressTable ON UserTable.AddressID = AddressTable.AddressID
```
[Here](http://www.blackwasp.co.uk/SQLDateTimeFormats.aspx) is a chart of SQL DateTime formats for the CONVERT statement above.
|
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 way to implement class variables?
```
function classA() {};
classA.prototype.shared = 0;
a = new classA;
//print both values to make sure that they are the same
classA.prototype.shared;
a.shared;
//increment class variable
classA.prototype.shared++;
//Verify that they are each 1 (Works)
classA.prototype.shared;
a.shared;
//now increment the other reference
a.shared++;
//Verify that they are each 2 (Doesn't Work)
classA.prototype.shared;
a.shared;
```
UPDATE:
So it seems that everyone is confirming the fact that by incrementing the instance's variable we don't affect the prototype. This is fine, this is what I have documented in my example, but doesn't this seem like an error in the design of the language? Why would this behavior be desirable? I find it weird that when the instance's var is undefined we follow the hidden link to the prototype where we get the value of the var, but we copy it into the instance object.
I also understand that this isn't java/c++/ruby/python, it's a different language. I'm just curious as to why this behavior might be good.
|
```
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 that you're actually using the retrun value, but still.)
So this is actually doing an assigment to a.shared. When you assign to an instance member you are always writing to that instance's own members, *not* touching any members of any of its prototypes. It's the same as saying:
```
classA.prototype.shared= 1;
a.shared= 2;
```
So your new a.shared hides the prototype.shared without altering it. Other instances of classA would continue to show the prototype's value 1. If you deleted a.shared you would once again be able to see the prototype's variable that was hidden behind it.
|
**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 that is accessed in method1()
```
Your output seems strange **because of the way javascript handles prototypes**. Calling any method / retreiving a variable of an instantiated object **checks the instance first, THEN the prototype**. i.e.
```
var a = new classA();
classA.prototype.stat = 1;
// checks a.stat which is undefined, then checks classA.prototype.stat which has a value
alert(a.stat); // (a.stat = undefined, a.prototype.stat = 1)
// after this a.stat will not check the prototype because it is defined in the object.
a.stat = 5; // (a.stat = 5, a.prototype.stat = 1)
// this is essentially a.stat = a.stat + 1;
a.stat++; // (a.stat = 6, a.prototype.stat = 1)
```
|
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 to anywhere?
|
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 of coding style?
|
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 output buffer, and `'\n'` doesn't. If you don't want the buffer flushed frequently, use `'\n'`. If you do (for example, if you want to get all the output, and the program is unstable), use `std::endl`.
|
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 the `<<` operator).
I use `\n` on most lines.
Then use `std::endl` at the end of a paragraph (but that is just a habit and not usually necessary).
Contrary to other claims, the `\n` character is mapped to the correct platform end of line sequence only if the stream is going to a file (`std::cin` and `std::cout` being special but still files (or file-like)).
|
"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 their existing systems (cannot easily be upgraded/moved). Since the course leaflets are going on the web it is a requirement with their hosting to use a sql server database.
This means I need to query between the two internally so they can work out what courses they have without a leaflet, I would not like to add ad hoc queries to the access database to do this.
What is the best way to do this in C#, I think LINQ can do it but have not learnt it yet, should I learn it for this project or is there an easier way?
I thought about a linked server to the ms access db but this would require moving the db to the sql server. Another difficult task as from what I can tell links to the database are hard coded.
|
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 every morning at 3 a.m. or whatever. Or you could just do it periodically whenever the tables change significantly.
|
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 buffer should be deleted using delete[].
What possibility is there that this mismatch might cause a memory leak?
|
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 and other odd behaviours are possible.
If you don't need to transfer the ownership of the pointer, Boost's [scoped\_array](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/scoped_array.htm) class might be what you're looking for.
|
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 after itself and the standard guarantees that all element in the vector will be in contigious storage. Perfect for a buffer.
Or more formaly the guarantee is:
```
(&buffer[0]) + size == (&buffer[size])
```
|
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
}
?>
```
Opposed to:
```
<?php
unset($out);
if($a) $out = '[SOME MARKUP]';
else $out = '[OTHER MARKUP]';
print $out;
?>
```
|
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 they need to write a template engine in Smarty (Never underestimate the potential of a dumb idea).
If you break your code into two parts and force yourself to adhere to a standard, then you'll get much better performance.
PageLogic.php
```
<?php
$pageData = (object)(array()); // Handy trick I learnt.
/* Logic Goes here */
$pageData->foo = SomeValue;
ob_start();
require("layout.php");
ob_end_flush();
```
Layout.php
```
<html>
<!-- etc -->
<?php for ( $i = 1; $i < 10; $i++ ){ ?>
<?php echo $pageData->foo[$i]; ?>
<?php } ?>
<!-- etc -->
</html>
```
PHP Was written as a templating engine, so you at least should *try* to use it for its designed task before assessing whether or not you need to delve into Smarty.
---
Moreover, if you decide to use a templating engine, try get one that escapes HTML by **default** and you "opt out" instead of "opt in." You'll save yourself a lot of XSS headaches. Smarty is weak in this respect, and because of this, there are a lot of content-naïve templates written in it.
```
{if $cond}
{$dangerous_value}
{else}
{$equally_dangerous_value}
{/if}
```
Is generally how Smarty templates go. The problem is $dangerous\_value can be arbitrary HTML and this just leads to even **more** bad coding practices with untraceable spaghetti code everywhere.
Any template language you consider **should** cater to this concern. e.g.:
```
{$code_gets_escaped}
{{$code_gets_escaped_as_a_uri}}
{{{$dangerous_bare_code}}}
```
This way, your potential doorways for exploitation are easily discernible in the template, as opposed to the doorway to exploitation being the **DEFAULT** behaviour.
|
-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* about separating business logic and presentation concerns. You can do that — or *not* do that — in any templating system, whether PHP, Smarty or something completely different. No templating system magically separates your concerns without a bunch of thinking.
(In fact a templating system that is too restrictive can end up with you having to write auxiliary code that is purely presentational, cluttering up your business logic with presentational concerns. This is not a win!)
To answer the question that was asked, the first example is OK, but very difficult to read due to the bad indentation. See monzee's example for a more readable way; you can use the : notation or {}s, whichever you prefer, but the important thing for readability is to keep your HTML and PHP as a single, ‘well-formed’ indented hierarchy.
And a final plea: remember htmlspecialchars(). Every time plain text needs to go in to a web page, this *must* be used, or it's XSS all over the floor. I know this question isn't directly related to that, but every time we post example code including < ?php echo($title) ?> or a framework equivalent without the escaping, we're encouraging the continuation of the security disaster area that most PHP apps have become.
|
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, that it wouldn't be. For example, I think this scenario is possible:
* update the counter within transaction #1
* do some other stuff
in transaction #1
* update the counter
with transaction #2
* commit
transaction #2
* commit transaction #1
In this situation, wouldn't the counter end up only being incremented by 1? Does it make a difference if that is the only statement in a transaction?
How does a site like stackoverflow handle this for its question view counter? Or is the possibility of "losing" some increments just considered acceptable?
|
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 until t1 is done, and t2 won't be able to commit before t1 (which is contrary to your timeline). Only one of the transactions will get to update the counter, therefore both will update the counter correctly given the code presented. (tested)
* counter = 0
* t1 update counter (counter => 1)
* t2 update counter (blocked)
* t1 commit (counter = 1)
* t2 unblocked (can now update counter) (counter => 2)
* t2 commit
---
Read Committed just means you can only read committed values, but it doesn't mean you have Repeatable Reads. Thus, if you use and depend on the counter variable, and intend to update it later, you're might be running the transactions at the wrong isolation level.
You can either use a repeatable read lock, or if you only sometimes will update the counter, you can do it yourself using an optimistic locking technique. e.g. a timestamp column with the counter table, or a conditional update.
```
DECLARE @CounterInitialValue INT
DECLARE @NewCounterValue INT
SELECT @CounterInitialValue = SELECT counter FROM MyTable WHERE MyID = 1234
-- do stuff with the counter value
UPDATE MyTable
SET counter = counter + 1
WHERE
MyID = 1234
AND
counter = @CounterInitialValue -- prevents the update if counter changed.
-- the value of counter must not change in this scenario.
-- so we rollback if the update affected no rows
IF( @@ROWCOUNT = 0 )
ROLLBACK
```
This [devx](http://www.devx.com/codemag/Article/21570) article is informative, although it talks about the features while they were still in beta, so it may not be completely accurate.
---
update: As Justice indicates, if t2 is a nested transaction in t1, the semantics are different. Again, both would update counter correctly (+2) because from t2's perspective inside t1, counter was already updated once. The nested t2 has no access to what counter was before t1 updated it.
* counter = 0
* t1 update counter (counter => 1)
* t2 update counter (nested transaction) (counter => 2)
* t2 commit
* t1 commit (counter = 2)
With a nested transaction, if t1 issues ROLLBACK after t1 COMMIT, counter returns to it's original value because it also undoes t2's commit.
|
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/MixingLanguagesInASingleAssemblyInVisualStudioSeamlesslyWithILMergeAndMSBuild.aspx) is a very good example about it.
|
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 [Assembly Linker (Al.exe)](http://msdn.microsoft.com/en-us/library/c405shex.aspx). There's even an msbuild task for it: [AL (Assembly Linker) Task](http://msdn.microsoft.com/en-us/library/cywecfx9.aspx).
A full overview is provided on MSDN: [How to: Build a Multifile Assembly](http://msdn.microsoft.com/en-us/library/226t7yxe.aspx)
|
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 "Option B"?
I tried `$("#list[value='2']").text();`, but it is not working.
|
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 possibly broken toolchain it might not follow the standard.
|
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 under low memory conditions....
So for everybody that still uses VC++ 6 and STL check this article for a Fix.
[Don't Let Memory Allocation Failures Crash Your Legacy STL Application](http://msdn.microsoft.com/pt-br/magazine/cc164087(en-us).aspx)
|
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 validating this is with XPath, and I have implemented this already, but I would also like something less verbose - I want to be able to use CSS Selectors, like I can with jQuery, but on the server - within CFML code - as opposed to on the client.
**Is there a CFML or Java library that allows me to use CSS Selectors against an XHTML string?**
|
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 Ruby methods from your Java code (using BSF, [JSR-222 Scripting APIs](http://wiki.jruby.org/wiki/Java_Integration), or [an internal API](http://wiki.jruby.org/wiki/Direct_JRuby_Embedding)).
Are you using Coldfusion 8? Coldfusion 8, being based on Java 6, supports JSR-222 Scripting APIs "javax.scripting".
Take a look at [this blog entry on embedding PHP within CFML](http://corfield.org/blog/index.cfm/do/blog.entry/entry/ColdFusion_8_running_PHP). You should be able to do **the same with Ruby**. There is ZIP file example code linked from this blog posting, and if you crack open the CFML, you'll see a good example of embedding Ruby within CFML.
Although it might take a bit of work to make all the pieces work together, but with a bit of investment, it should give you the robust parsing/CSS selector querying that you're looking for.
|
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.length;
alert(cellCount); // will return the number of cells in the row
```
|
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('td').length;
}
...
// total cells in row 1
totals[0];
// in row 2
totals[1];
// etc.
```
|
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 **ORM** too... The problem is that in all my research, **I do not find something that satisfies me completely in PHP**. On the other hand, at my job (mostly in .Net winform 2.0) I see many good IOC and other solutions possible, and, I think that .Net is more mature for developing software with best-practices.
I haven't found many good IOC for PHP. As for ORM, I have seen Propel, which looks nice, but haven't found a complete Framework too (Symfony documentation isn't up-to-date, contains lot of error; Zend looks too big I think...), etc.
Do you suggest that I simply try another framework and keep the website in PHP, or would it would be a good idea to switch to .Net?
## Reasons of this question
* The system works but has begun to slow down (since it has more users). The database is normalized too much... etc.
* The code isn't bad - business logic is separated of the HTML - but the problem is that controllers are inside the view so it's harder and harder to make some layout changes.
* No unit tests have been done, and it's very "stressful" to make change.
* There's no logging in the system, and it's hard to get a snapshot to see if everything is working properly.
## More information (added the 3 nov 2008)
* I know .Net 2.0 this is why my alternative is .Net and not RoR.
* I were suggesting an other language not for the speed issue but for the tool/framework available.
* It's slow because of the database normalisation, too many table that are great in theory but not in practice (we learn from our mistake!)
* It's an hobby, but I take it seriously cause I have over 25 000 users registered since the beginning (not all active).
## Current suggestion from people over here
I think I'll keep what I have done and try to do some refactoring slowly. I am surprise that most of the vote have been to keep the current system but well :P this might be the simpler for me for the short term.
---
Thx to **nickf** who has spell check all my text.
|
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 references at the edge of PHP 4's capabilities.
|
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 the "new perspective" of how things can be done. On the other hand it can be difficult to let go of the old code and methods. A complete rewrite is hard because at first you lose all the bug fixes, the little tweaks and tricks - back to square one. And usually you don't get the exact same result. But if you are going to build an (improved) version 2.0 anyway and want to stretch yourself ...go ahead, try something new. Even if you fail, at least you have something to blog about on your site :)
edit: It would also be possible to port only parts of the code or develop the new fetatures in .net - as long as can "bear" the two seperated codebases.
And you might also want to look into <http://www.codeplex.com/Phalanger>, a .net compiler for php. (Haven't tried that yet.)
|
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 snippet with the wider community.
```
DateTime timer = DateTime.Now;
Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
try
{
exampleFile = new FileInfo(Path.Combine(System.Environment.CurrentDirectory, "Large.xlsx"));
excelApplication.Workbooks.Open(exampleFile.FullName, false, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing);
Console.WriteLine(string.Format("Took {0} seconds to open file", (DateTime.Now - timer).Seconds.ToString()));
timer = DateTime.Now;
foreach(Workbook workbook in excelApplication.Workbooks)
{
foreach(Worksheet sheet in workbook.Sheets)
{
int i = 0, iRowMax, iColMax;
string data = String.Empty;
Object[,] rangeData = (System.Object[,]) sheet.UsedRange.Cells.get_Value(missing);
if (rangeData != null)
{
iRowMax = rangeData.GetUpperBound(0);
iColMax = rangeData.GetUpperBound(1);
for (int iRow = 1; iRow < iRowMax; iRow++)
{
for(int iCol = 1; iCol < iColMax; iCol++)
{
data = rangeData[iRow, iCol] != null ? rangeData[iRow, iCol].ToString() : string.Empty;
if (i % 100 == 0)
{
Console.WriteLine(String.Format("Processed {0} cells.", i));
}
i++;
}
}
}
}
workbook.Close(false, missing, missing);
}
Console.WriteLine(string.Format("Took {0} seconds to parse file", (DateTime.Now - timer).Seconds.ToString()));
}
finally
{
excelApplication.Workbooks.Close();
excelApplication.Quit();
}
```
**Edit**:
Worth stating that I want to use PIA and interop in order to access properties of excel workbooks that are not exposed by API's that work directly with the Excel file.
|
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 can't remember which one) on it.
This will yield an `object[,]`, that is, a two dimensional array, which can be easily enumerated and is quick to be read.
**EDIT**: I just read your actual code and realized that it actually does what I proposed. Shame on me for not reading the question properly before answering. In that case, you cannot make it much faster. Excel PIA Interop is slow. If you need a quicker solution you will have to either migrate jExcelApi from Java to C# (not a terribly hard thing to do) or use some commercial component. I suggest to avoid the OLEDB interface at all costs, in order to keep your sanity.
Unrelated, but helpful tip: You should use the ?? operator. It is really handy. Instead of
```
data = rangeData[iRow, iCol] != null ? rangeData[iRow, iCol].ToString() : string.Empty;
```
you could just write
```
data = Convert.ToString(rangeData[iRow, iCol]) ?? string.Empty;
```
In that case, even String.Empty is not necessary since [Convert.ToString(object)](http://msdn.microsoft.com/en-us/library/astxcyeh.aspx) converts `null` to an empty string anyway.
|
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 that totally relies on .vcproj and .sln files. These can be checked into source control unlike VS Options which have to be configured on each development PC separately. We handled the transition for most libraries by adding the Include directories to each Project's Property Pages > Configuration Properties > C/C++ > General > Additional Include Directories, and Library directories to Linker > General > Additional Library Directories.
Unfortunately, this approach doesn't work for STLPort. We get LNK2019 and LNK2001 errors during linking:
```
Error 1 error LNK2019: unresolved external symbol "public: virtual bool __thiscall MyClass::myFunction(class stlp_std::basic_istream<char,class stlp_std::char_traits<char> > &,class MyOtherClass &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > &)const " (?myFunction@MyClass@@UBE_NAAV?$basic_istream@DV?$char_traits@D@stlp_std@@@stlp_std@@AAVSbprobScenarioData@@AAV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@3@@Z) referenced in function _main MyLibrary.obj
Error 5 error LNK2001: unresolved external symbol "public: static void __cdecl MyClass::myFunction(class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,long,enum MyClass::MessageType,int,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &)" (?myFunction@MyClass@@SAXABV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@stlp_std@@000JW4MessageType@1@H0@Z) MyLibrary.lib
```
This happens while linking and executable project to dependencies which are library projects. Curiously, this does not happen while linking the library projects themselves. Any ideas?
|
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 is looking for. It will be a horrible mangled name.
Use a hex editor (IIRC, Visual Studio will do this) to look at the .lib file you're linking to.
Find the symbol that's almost the thing the linker is looking for, but not quite.
Given the differences in the symbols, try to figure out what command line switches will help.
Good luck -- for people who aren't used to this sort of problem, the solution can take days to figure out (!)
|
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 that will **make your search much much easier**.
For starters, understanding decorated names will help. Within all that garbage, you will recognise some things: The **name of your function**, **namespaces**, some **class types** you are using. All of those characters around them mean something to the compiler, but you don't need the compiler to tell you what they are.
> ## Enter undname.exe:
>
> ---
>
> *undname.exe <decoratedname>*
>
> * is a simple command line program that is in your VS bin directory.
> * takes the decorated name as it's first argument.
> * outputs a human readable format of the symbol.
Armed with that knowledge, you can now move on to finding a reasonable candidate for the mis-created symbol.
First off, you could edit your libraries in a hex editor, as suggested elsewhere. However, there is a much easier way to find the symbols.
> ## Enter dumpbin.exe:
>
> ---
>
> *dumpbin.exe <switches> <library name>*
>
> * is a simple command line program that is in your VS bin directory.
> * takes a set of switches and a library to apply them to.
> * outputs information from the library
The switch you will be interested in for your question is */linkermember*. There are many other switches that can get you very interesting information, but this one will list out all the symbols in the library.
At this point, a little commandline savvy will serve you well. Tools like *grep* can really shorten your work-cycle, but you can get by with redirecting to a file and using notepad or the like.
Since I don't have your code or library, I'll contrive an example from TinyXML.
Assuming your error message was this:
```
Error 1 error LNK2019: unresolved external symbol "public: unsigned char __cdecl TiXmlComment::Accept(bool,class TiXmlVisitor *) " (?Accept@TiXmlComment@@ZBE_NPAVTiXmlVisitor@@@Z) referenced in function _main MyLibrary.obj
```
Having determined this is a function in the TinyXML, I can start looking for the mismatched symbol. I'll start by dumping the linkermembers of the library. (Notice the switch is singular, this always gets me when I type it from memory!)
```
>dumpbin /linkermember tinyxml.lib
Microsoft (R) COFF/PE Dumper Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file tinyxml.lib
File Type: LIBRARY
Archive member name at 8: /
4992E7BC time/date Wed Feb 11 08:59:08 2009
uid
gid
0 mode
B402 size
correct header end
859 public symbols
16292 ??$_Allocate@D@std@@YAPADIPAD@Z
16292 ??$_Char_traits_cat@U?$char_traits@D@std@@@std@@YA?AU_Secure_char_traits_tag@0@XZ
16292 ??$copy_s@U?$char_traits@D@std@@@_Traits_helper@std@@YAPADPADIPBDI@Z
16292 ??$copy_s@U?$char_traits@D@std@@@_Traits_helper@std@@YAPADPADIPBDIU_Secure_char_traits_tag@1@@Z
16292 ??$move_s@U?$char_traits@D@std@@@_Traits_helper@std@@YAPADPADIPBDI@Z
16292 ??$move_s@U?$char_traits@D@std@@@_Traits_helper@std@@YAPADPADIPBDIU_Secure_char_traits_tag@1@@Z
16292 ??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z
16292 ??0?$_String_val@DV?$allocator@D@std@@@std@@IAE@V?$allocator@D@1@@Z
16292 ??0?$_String_val@DV?$allocator@D@std@@@std@@QAE@ABV01@@Z
```
This is obviously too much to read, but we don't have to, we know what we're looking for, so we'll just look for it.
```
>dumpbin /linkermember tinyxml.lib | grep Accept
529AE ?Accept@TiXmlComment@@UBE_NPAVTiXmlVisitor@@@Z
529AE ?Accept@TiXmlDeclaration@@UBE_NPAVTiXmlVisitor@@@Z
529AE ?Accept@TiXmlDocument@@UBE_NPAVTiXmlVisitor@@@Z
529AE ?Accept@TiXmlElement@@UBE_NPAVTiXmlVisitor@@@Z
529AE ?Accept@TiXmlText@@UBE_NPAVTiXmlVisitor@@@Z
529AE ?Accept@TiXmlUnknown@@UBE_NPAVTiXmlVisitor@@@Z
3 ?Accept@TiXmlComment@@UBE_NPAVTiXmlVisitor@@@Z
3 ?Accept@TiXmlDeclaration@@UBE_NPAVTiXmlVisitor@@@Z
3 ?Accept@TiXmlDocument@@UBE_NPAVTiXmlVisitor@@@Z
3 ?Accept@TiXmlElement@@UBE_NPAVTiXmlVisitor@@@Z
3 ?Accept@TiXmlText@@UBE_NPAVTiXmlVisitor@@@Z
3 ?Accept@TiXmlUnknown@@UBE_NPAVTiXmlVisitor@@@Z
```
That's much easier to read. Looking at our error, we're looking for the Accept Function of TiXmlComment. We could grep the output additionally for that name, if we had lots of matches (like looking at the size function in the stl!), but in this case, we can pick it out of the list. Here is where we turn to undname:
```
>undname ?Accept@TiXmlComment@@UBE_NPAVTiXmlVisitor@@@Z
Microsoft (R) C++ Name Undecorator
Copyright (C) Microsoft Corporation. All rights reserved.
Undecoration of :- "?Accept@TiXmlComment@@UBE_NPAVTiXmlVisitor@@@Z"
is :- "public: virtual bool __thiscall TiXmlComment::Accept(class TiXmlVisitor *)const "
```
So, in this example, our application is looking for a function which returns an **unsigned char**, but the library has a function returning a **bool**.
This is a contrived example, but it illustrates the technique to use to track down your issue. You are probably looking for a typedef type which is set differently based on your options.
The problem where I ran into this was with **time\_t**. In some libraries I was using, the **time\_t** used a 32-bit type as part of it's internal representation. This library was generated with an older compiler, where that was the default. In VS 2005, the **time\_t** uses a 64-bit type by default. I had to add the preprocessor define **\_USE\_32BIT\_TIME\_T** to get it to compile. I tracked this issue down precisely as I have described.
I hope this helps someone solve this issue!
|
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 type and so I can't return null there.
Ideally I would like the methods to 'look' similar; one solution could be to define them as
```
public Point CalculatePoint(... out Boolean boSuccess);
public List<Point> CalculateListOfPoints(... out Boolean boSuccess);
```
or alternatively to return a Point? for CalculatePoint, and return null to indicate failure. That would mean having to cast back to the non-nullable type though, which seems excessive.
Another route would be to return the Boolean boSuccess, have the result (Point or List) as an 'out' parameter, and call them TryToCalculatePoint or something...
What is best practice?
Edit: I do not want to use Exceptions for flow control! Failure is sometimes expected.
|
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 not to work for some entries).
|
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 that they will always provide good data will receive a suitably strong message (i.e. an exception) if they're ever wrong.
|
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 users' settings in them.
For example, userdb["bob"]["colour\_scheme"] would have the value "blue".
What is the best way to store it on file? Pickling the dictionary?
Are there better ways of doing what I am trying to do?
|
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 you'd have to use a language neutral text format. And even here you could get away with the pickle plus an export tool.
|
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 config file above, and then print it out:
```
import sys
from ConfigParser import *
c = ConfigParser()
c.add_section("bob")
c.set("bob", "colour_scheme", "blue")
c.set("bob", "british", str(True))
c.add_section("joe")
c.set("joe", "color_scheme", "that's 'color', silly!")
c.set("joe", "british", str(False))
c.write(sys.stdout) # this outputs the configuration to stdout
# you could put a file-handle here instead
for section in c.sections(): # this is how you read the options back in
print section
for option in c.options(section):
print "\t", option, "=", c.get(section, option)
print c.get("bob", "british") # To access the "british" attribute for bob directly
```
Note that ConfigParser only supports strings, so you'll have to convert as I have above for the Booleans. See [effbot](http://effbot.org/librarybook/configparser.htm) for a good run-down of the basics.
|
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.
Or in code:
```
struct Interval
{
public DateTime Date;
public long Duration;
public int State;
}
struct StateSummary
{
public int State;
public long TotalSeconds;
}
public Interval[] GetRandomIntervals(DateTime start, DateTime end, StateSummary[] sums, int totalEvents)
{
// insert your cool algorithm here
}
```
I'm working on this now, but in case someone beats me to a solution (or knows of an elegant pre-existing algorithm) I'm posting this on SO.
|
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;
}
public DateTime Date;
public long Duration;
public int State;
}
class StateSummary
{
public StateSummary(StateEnum state, long totalSeconds)
{
State = (int)state;
TotalSeconds = totalSeconds;
}
public int State;
public long TotalSeconds;
}
Interval[] GetRandomIntervals(DateTime start, DateTime end, StateSummary[] sums, int totalEvents)
{
Random r = new Random();
ArrayList intervals = new ArrayList();
for (int i=0; i < sums.Length; i++)
{
intervals.Add(new Interval(sums[i].State));
}
for (int i=0; i < totalEvents - sums.Length; i++)
{
intervals.Add(new Interval(sums[r.Next(0,sums.Length)].State));
}
Hashtable eventCounts = new Hashtable();
foreach (Interval interval in intervals)
{
if (eventCounts[interval.State] == null)
{
eventCounts[interval.State] = 1;
}
else
{
eventCounts[interval.State] = ((int)eventCounts[interval.State]) + 1;
}
}
foreach(StateSummary sum in sums)
{
long avgDuration = sum.TotalSeconds / (int)eventCounts[sum.State];
foreach (Interval interval in intervals)
{
if (interval.State == sum.State)
{
long offset = ((long)(r.NextDouble() * avgDuration)) - (avgDuration / 2);
interval.Duration = avgDuration + offset;
}
}
}
// cap the durations.
Hashtable eventTotals = new Hashtable();
foreach (Interval interval in intervals)
{
if (eventTotals[interval.State] == null)
{
eventTotals[interval.State] = interval.Duration;
}
else
{
eventTotals[interval.State] = ((long)eventTotals[interval.State]) + interval.Duration;
}
}
foreach(StateSummary sum in sums)
{
long diff = sum.TotalSeconds - (long)eventTotals[sum.State];
if (diff != 0)
{
long diffPerInterval = diff / (int)eventCounts[sum.State];
long mod = diff % (int)eventCounts[sum.State];
bool first = true;
foreach (Interval interval in intervals)
{
if (interval.State == sum.State)
{
interval.Duration += diffPerInterval;
if (first)
{
interval.Duration += mod;
first = false;
}
}
}
}
}
Shuffle(intervals);
DateTime d = start;
foreach (Interval interval in intervals)
{
interval.Date = d;
d = d.AddSeconds(interval.Duration);
}
return (Interval[])intervals.ToArray(typeof(Interval));
}
public static ICollection Shuffle(ICollection c)
{
Random rng = new Random();
object[] a = new object[c.Count];
c.CopyTo(a, 0);
byte[] b = new byte[a.Length];
rng.NextBytes(b);
Array.Sort(b, a);
return new ArrayList(a);
}
```
|
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://mikhailstadnik.com/ext/examples/nested-grid.htm), that is [Grid Plugin with Row Expander](http://dev.sencha.com/deploy/dev/examples/grid/grid-plugins.html) modified by Mikhail
+ [Ext.ux.maximgb.treegrid](http://www.max-bazhenov.com/dev/ux.maximgb.treegrid/index.php), another mod, by Max (the one proposed by eyelidlessness)
* [JQTreeTable](http://www.hanpau.com/index.php?page=jqtreetable), minimal, requires jQuery \*
* [Treetable](http://plugins.jquery.com/project/treeTable), plugin for jQuery \*
* [dojo-treetable](http://code.google.com/p/dojo-treetable/), based on Dojo \*
* [Maxdesign](http://www.maxdesign.com.au/articles/tree-table/), it's simply a good css \*
\* seems not sortable
Personally I'm trying **Treetable** and, after some configurations (rummaging in the examples in the source of the documentation page...), I'm enjoying its simplicity and clarity.
|
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 embedding Ruby in C++](http://aeditor.rubyforge.org/ruby_cplusplus/index.html), and while it's very useful, it's kinda old and I was wondering if there are any other resources on the subject (or open source implementations of similar engines).
|
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 google\_desc %} and bam!
I *think* it was [this](http://www.b-list.org) guy that made it, but im not quite sure.
Would anyone know where i could find this piece of awesomeness?
**Edit:** I was after an app or something to plug into my project. Not, an existing website/service.
**Edit 2:** insin got it. I was after [django-chunks](http://code.google.com/p/django-chunks/)
|
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 without knowing the actual name and without using the 'exec' statement?
|
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, it would still be necessary to run the CREATE SYNONYM code as dynamic SQL.
To run CREATE SYNONYM, the user must be granted the respective permission, or have ALTER SCHEMA permission. Be sure to read more about synonyms before you go that route, there are a few strings attached.
|
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 store the link between your logic and the name entered by the user?
|
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("192.168.2.1"); // the destination IP address
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
if (SendARP(BitConverter.ToInt32(dst.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen) != 0)
throw new InvalidOperationException("SendARP failed.");
string[] str = new string[(int)macAddrLen];
for (int i=0; i<macAddrLen; i++)
str[i] = macAddr[i].ToString("x2");
Console.WriteLine(string.Join(":", str));
```
|
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")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 len);
/// <summary>
/// Returns the MACAddress by a string.
/// </summary>
public static Int64 GetRemoteMAC(string remoteIP)
{
Int32 ldest = inet_addr(remoteIP);
try
{
Int64 macinfo = 0;
Int32 len = 6;
int res = SendARP(ldest, 0, ref macinfo, ref len);
return macinfo;
}
catch (Exception e)
{
return 0;
}
}
/// <summary>
/// Format a long/Int64 into string.
/// </summary>
public static string FormatMac(this Int64 mac, char separator)
{
if (mac <= 0)
return "00-00-00-00-00-00";
char[] oldmac = Convert.ToString(mac, 16).PadLeft(12, '0').ToCharArray();
System.Text.StringBuilder newMac = new System.Text.StringBuilder(17);
if (oldmac.Length < 12)
return "00-00-00-00-00-00";
newMac.Append(oldmac[10]);
newMac.Append(oldmac[11]);
newMac.Append(separator);
newMac.Append(oldmac[8]);
newMac.Append(oldmac[9]);
newMac.Append(separator);
newMac.Append(oldmac[6]);
newMac.Append(oldmac[7]);
newMac.Append(separator);
newMac.Append(oldmac[4]);
newMac.Append(oldmac[5]);
newMac.Append(separator);
newMac.Append(oldmac[2]);
newMac.Append(oldmac[3]);
newMac.Append(separator);
newMac.Append(oldmac[0]);
newMac.Append(oldmac[1]);
return newMac.ToString();
}
}
```
|
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="stylez.css" type="text/css" />
<!-- here? -->
</head>
<body>
<!-- here? -->
<p>All the page content ...</p>
<!-- or here? -->
</body>
</html>
```
Will there be any functional difference between each of the options?
|
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 are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.
|
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();">link</a>`
4. `<a href="#" onClick="return DoSomething();">link</a>`
I understand the idea of trying to put a valid URL instead of just JavaScript code, just in case the user doesn't have JavaScript enabled. But for the purpose of this discussion, I need to assume JavaScript is enabled (they can't login without it).
I personally like option 2 as it allows you to see what's going to be run–especially useful when debuging where there are parameters being passed to the function. I have used it quite a bit and haven't found browser issues.
I have read that people recommend 4, because it gives the user a real link to follow, but really, # isn't "real". It will go absolutely no where.
Is there one that isn't support or is really bad, when you know the user has JavaScript enabled?
Related question: *[Href for JavaScript links: “#” or “javascript:void(0)”?](https://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0)*.
|
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, there's no reason you can't have a simple HTML page that all your JavaScript links can point to for their `href` section in the event that someone happens to turn off JavaScript after logging in. I would highly encourage you to still allow this fallback mechanism. Something like this will adhere to "best practices" and accomplish your goal:
```
<a href="javascript_required.html" onclick="doSomething(); return false;">go</a>
```
|
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 selection not change.
I tried doing this with a valueChangeListener on the JTree, but currently then have to have the valueChanged method call "setSelectionRow" to the old selection if there is an error. So that I don't get a StackOverflow, I set a boolean "isError" to true before I do this so that I can ignore the new valueChanged event. Somehow I have the gut feeling this is not the best solution. ;-)
How would I go about it instead? Is there a good design pattern for situations like this?
|
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 versions) this solution won't work, because the FocusEvent appears not to be a low-level event. Hence it cannot be consumed. See Method AWTEvent.consume()
|
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 TreeSelectionListener() {
boolean treeSelectionListenerEnabled = true;
public void valueChanged(TreeSelectionEvent e) {
if (treeSelectionListenerEnabled) {
if (ok to change selection...) {
...
} else {
TreePath treePath = e.getOldLeadSelectionPath();
treeSelectionListenerEnabled = false;
try {
// prevent from leaving the last visited node
navTree.setSelectionPath(treePath);
} finally {
treeSelectionListenerEnabled = true;
}
}
}
}
});
```
always remember to remove all listeners you added, to prevent memory leaks.
here is another approach:
```
private class VetoableTreeSelectionModel extends DefaultTreeSelectionModel {
public void setSelectionPath(TreePath path){
if (allow selection change?) {
super.setSelectionPath(path);
}
}
}
{
navTree.setSelectionModel(new VetoableTreeSelectionModel());
}
```
|
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 specified applet is executed as the first order of business.
By `run()`, I assume you mean the method of Runnable. This is the method invoked when a new thread is started.
* main: program start
* init: applet start
* run: thread start
If Eclipse is running your `run()` method even though you have no `main()`, then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.
|
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` command page](http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/java.html):
> The **java** tool launches a Java application. It does this by starting
> a Java runtime environment, loading a specified class, and invoking that
> class's **main** method.
>
> The method must be declared public and static, it must not return any
> value, and it must accept a `String` array as a parameter. The method
> declaration must look like the following:
>
> ```
> public static void main(String args[])
> ```
For additional resources on how an Java application is executed, please refer to the following sources:
1. [Chapter 12: Execution](http://java.sun.com/docs/books/jls/third_edition/html/execution.html) from the [Java Language Specification, Third Edition](http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html).
2. [Chapter 5: Linking, Loading, Initializing](http://java.sun.com/docs/books/jvms/second_edition/html/ConstantPool.doc.html) from the [Java Virtual Machine Specifications, Second Edition](http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html).
3. [A Closer Look at the "Hello World" Application](http://java.sun.com/docs/books/tutorial/getStarted/application/index.html) from the [Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html).
---
The `run` method is the entry point for a new [`Thread`](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html) or an class implementing the [`Runnable`](http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html) interface. It is not called by the Java Virutal Machine when it is started up by the `java` command.
As a `Thread` or `Runnable` itself cannot be run directly by the Java Virtual Machine, so it must be invoked by the `Thread.start()` method. This can be accomplished by instantiating a `Thread` and calling its `start` method in the `main` method of the application:
```
public class MyRunnable implements Runnable
{
public void run()
{
System.out.println("Hello World!");
}
public static void main(String[] args)
{
new Thread(new MyRunnable()).start();
}
}
```
For more information and an example of how to start a subclass of `Thread` or a class implementing `Runnable`, see [Defining and Starting a Thread](http://java.sun.com/docs/books/tutorial/essential/concurrency/runthread.html) from the Java Tutorials.
---
The `init` method is the first method called in an [Applet](http://java.sun.com/javase/6/docs/api/java/applet/Applet.html) or [JApplet](http://java.sun.com/javase/6/docs/api/javax/swing/JApplet.html).
When an applet is loaded by the Java plugin of a browser or by an applet viewer, it will first call the `Applet.init` method. Any initializations that are required to use the applet should be executed here. After the `init` method is complete, the `start` method is called.
For more information about when the `init` method of an applet is called, please read about the lifecycle of an applet at The [Life Cycle of an Applet](https://java.sun.com/docs/books/tutorial/deployment/applet/lifeCycle.html) from the Java Tutorials.
See also: [How to Make Applets](http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html) from the Java Tutorial.
|
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 date it was extracted as a file header.
thanks.
|
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 it. It will create a folder in the same location as the VB file which contains the code from the package, and it will dump the SQL code that it finds. It assumes the output of the SQL goes into CSV files (see the `outExt` parameter) or comes from an "Execute SQL Task" task, and names the SQL queries after the output file or SQL task. If your package doesn't do anything else, this is an useful solution.
Feel free to clean this code up if you're so inclined.
```
# from __future__ import with_statement # Version 2.5 requires this.
import os, re
def dump_sql(infile, outExt=r'csv'):
"""Parse a DTS package saved as a .bas file, and dump the SQL code.
Pull out the SQL code and the filename for each task. This process
depends on the way that DTS saves packages as VB modules.
Keyword arguments:
infile - The .bas file defining a DTS package.
outExt - The extension (without a period) of the files exported by the
data pumps in the DTS package. These are used to rename the
extracted SQL scripts. If an extract file does not use this
extension, then the whole name of the extract file is used to
name the SQL script. (default: csv)
The function produces a folder in the same folder that contains the
.bas file. It's named like this: if the .bas file is "DTS package.bas",
then the directory will be named "DTS package_SQL". The SQL scripts are
stored in this folder.
"""
#Declare all of the RE's used in the script here.
basExtRE = re.compile(r'\.bas$', re.IGNORECASE)
outExtRE = re.compile(r'\.' + outExt + r'$', re.IGNORECASE)
startTaskRE = re.compile(r'Set oCustomTask(\d+) = oTask.CustomTask')
startSqlRE = re.compile(
r'oCustomTask(\d+)\.(?:Source)?SQLStatement = "(.*)"( & vbCrLf)?')
nextSqlRE = re.compile(
r'oCustomTask(\d+)\.(?:Source)?SQLStatement = oCustomTask\1\.'
r'(?:Source)?SQLStatement & "(.*)"( & vbCrLf)?')
filenameRE = re.compile(
r'oCustomTask(\d+)\.DestinationObjectName = "(.*)"')
descripRE = re.compile(r'oCustomTask(\d+)\.Description = "(.*)"')
invalidCharsRE = re.compile(r'[][+/*?<>,.;:"=\\|]')
#Read the file
with open(infile, 'r') as f:
#Produce the directory for the SQL scripts.
outfolder = '%s_SQL\\' % basExtRE.sub('', infile)
if not os.path.exists(outfolder):
os.makedirs(outfolder)
taskNum = -1
outfile = ''
sql = []
for line in f:
line = line.rstrip().lstrip()
if taskNum == -1:
#Seek the beginning of a task.
m = startTaskRE.match(line)
if m is not None:
taskNum = int(m.group(1))
elif line == '' and outfile != '':
#Save the SQL code to a file.
if sql:
if os.path.exists(outfile):
os.unlink(outfile)
with open(outfile, 'w') as fw:
fw.writelines(["%s" % sqlQ for sqlQ in sql])
print "%2d - %s" % (taskNum, outfile)
else:
print "%2d > No SQL (%s)" % (
taskNum, os.path.basename(outfile))
sql = []
outfile = ''
taskNum = -1
else:
#Acquire SQL code and filename
m = startSqlRE.match(line)
if m:
#Start assembling the SQL query.
tnum, sqlQ, lf = m.groups()
assert int(tnum) == taskNum
sql = [sqlQ.replace('""', '"')
+ ('\n' if lf is not None else '')]
continue
m = nextSqlRE.match(line)
if m:
#Continue assembling the SQL query
tnum, sqlQ, lf = m.groups()
assert int(tnum) == taskNum
sql.append(sqlQ.replace('""', '"')
+ ('\n' if lf is not None else ''))
continue
m = descripRE.match(line)
if m:
# Get a SQL output filename from the task's
# description. This always appears near the top of the
# task's definition.
tnum, outfile = m.groups()
assert int(tnum) == taskNum
outfile = invalidCharsRE.sub('_', outfile)
outfile = "%s%s.sql" % (outfolder, outfile)
continue
m = filenameRE.match(line)
if m:
# Get a SQL output filename from the task's output
# filename. This always appears near the bottom of the
# task's definition, so we overwrite the description if
# one was found earlier.
tnum, outfile = m.groups()
assert int(tnum) == taskNum
outfile = os.path.basename(outfile)
outfile = outExtRE.sub('', outfile)
outfile = "%s%s.sql" % (outfolder, outfile)
continue
print 'Done.'
```
|
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](http://msdn.microsoft.com/en-us/library/aa216414(SQL.80).aspx) and looking at what the VB file does to the object model.
|
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 7.0M2
|
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`
+ Owner: `root:admin`
* I copied `ZendDebugger.so` from the `5_2_x_comp` directory to `/Developer/Extras/PHP`
* I updated `/etc/php.ini` file, adding the following lines:
```
zend_extension=/Developer/Extras/PHP/ZendDebugger.so
zend_debugger.expose_remotely=always
zend_debugger.connector_port=10013
zend_debugger.allow_hosts=127.0.0.1
```
* I restarted Apache via the System Preferences "Sharing" panel
When I run `phpinfo()` within a PHP file, I get no mention of the Zend Debugger. When I run `php -m` from the command line, it shows the Zend Debugger is loaded. Both state that they're running the same version of PHP, and loading the same INI file.
Anyone have another suggestion for me to try?
|
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/phpbb2/viewtopic.php?t=2905)
2) Recompile Apache and PHP in 32-bit mode.
I haven't actually gotten around to doing either yet, but I think I am leaning to recompiling to avoid future problems.
|
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 you can quickly pop into 32-bit mode when needed.
|
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 helpful direction for which libraries are best suited to game servers where the actual server doesn't have any graphical display (or doesn't need to but could have). In all honesty I think the answer will be *any* and once I get the hang of sockets it'll become a breeze sending data back and forth... but it can't help to ask first.
I have very little experience in flash or as3 but like the idea of being able to access the game through a browser - learning flash is obvisouly going to be an obstical that I'll have to overcome but my main interest again is any tips on libraries, or sources, or tutorials that are good for sending/recieving data via sockets or whichever method works best.
I've read about the arguments between TCP/UDP so I don't want to start a war like that here; just general helpful advice please - I'm only looking for something simple to get me up and running :-p
As a side note, the reason I'm choosing C++ is because the players are actually robots with minature virtual-machines and everything will run on the server so as the player count rises so will the need to emulate each and every vm :-p
Update:
The game world is intended to be real-time, but the interaction of the player doesn't have to be. The basis of the game is that you program little robots that interact in a persistent world and have goals and challenges to meet on a daily/weekly basis to earn points.
I was thinking that buffering the display data would be possible as the player doesn't need real-time visual as they have no direct control of their robots. The server would buffer up 10 seconds or so of data for each connection and then ship it out in one go - this way while the data is being played back in the client the server is busy buffering some more.
The general interactions the player will have with the server will be uploading new code and getting statistics, there may also be other one off commands to move your robot around or reset it to a starting position. Any remote control is done through a communications channel and thus is delayed by the buffer. This could easily be explained by the fact that the persistent world is somewhere like Mars (the planet) and the signal takes a while to go back and forth.
I was planning on having a "lab" whereby you could set up the robots and test them in realtime on the client, this has nothing to do with the actual game world and thus shouldn't require any networking - although I don't fancy writing a VM in both languages :(
I'm completely comfortable in C++ and have some working prototypes of the persistent world in place already - I'm just a complete newbie when it comes to networking so figured it'd be best to get advice first.
|
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,szData,strlen(szData),0); use send(socket,szData,strlen(szData)+1,0); to send a string :)
|
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 not using. I'd like to just use plain SQL SELECT, INSERT and UPDATE statements, unless there's something better available (the MERGE statement isn't available in SQL Server 2005).
I guess my general idea is this:
```
If the row is found
update
else
insert
```
As for checking for a row's existence, how expensive is it to do a SELECT statement before calling an UPDATE or an INSERT? Or is it better to just try an UPDATE, check for the number of rows affected, and then do an INSERT if the rows affected is 0?
|
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 identifies the new rows
* run an insert with these elements
* drop/clear your (temporary) table
This will probably run faster, if you are inserting/updating large amounts of rows.
|
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 seems to be very intensive if the tables become large.
|
> 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.
Anyway, this is an algorithms question, which is not my specialty, but my naive approach would be as follows:
1: Can you exploit any properties of the data? Are all the rows in each table unique, and can you sort them both by the same criteria? If so, you can do this:
* Sort both tables by their ID (using some useful thing like a quicksort). If they're already sorted then you win big.
* Step through both tables at once, skipping over any gaps in ID's in either table. Matched ID's mean duplicated records.
This allows you to do it in (sort time \* 2 ) + one pass, so if my big-O-notation is correct, it'd be (whatever-sort-time) + O(m+n) which is pretty good.
(Revision: this is the approach that [ΤΖΩΤΖΙΟΥ describes](https://stackoverflow.com/questions/164144/c-how-to-compare-two-datatables-a-b-how-to-show-rows-which-are-in-b-but-not-in-a#164213) )
2: An alternative approach, which may be more or less efficient depending on how big your data is:
* Run through table 1, and for each row, stick it's ID (or computed hashcode, or some other unique ID for that row) into a dictionary (or hashtable if you prefer to call it that).
* Run through table 2, and for each row, see if the ID (or hashcode etc) is present in the dictionary. You're exploiting the fact that dictionaries have really fast - O(1) I think? lookup. This step will be really fast, but you'll have paid the price doing all those dictionary inserts.
I'd be really interested to see what people with better knowledge of algorithms than myself come up with for this one :-)
|
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().Select(row => (string)row["ID"]);
IEnumerable<string> idsInB = tableB.AsEnumerable().Select(row => (string)row["ID"]);
IEnumerable<string> bNotA = idsInB.Except(idsInA);
```
|
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 to write an algorithm to calculate the character offset, but I feel I must be missing something.
So, what's the easiest way to calculate the character offset of the start of an Internet Explorer TextRange?
|
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 caret movement, but for expanded selections and for getting the exact node that holds the range anchor you'll need something more complex:
```
// where paramter r is a range:
function getRangeOffsetIE( r ) {
var end = Math.abs( r.duplicate().moveEnd('character', -1000000) );
// find the anchor element's offset
var range = r.duplicate();
r.collapse( false );
var parentElm = range.parentElement();
var children = parentElm.getElementsByTagName('*');
for (var i = children.length - 1; i >= 0; i--) {
range.moveToElementText( children[i] );
if ( range.inRange(r) ) {
parentElm = children[i];
break;
}
}
range.moveToElementText( parentElm );
return end - Math.abs( range.moveStart('character', -1000000) );
}
```
This should return the correct caret text offset. Of course, if you know the target node already, or are able to provide a context, then you can skip the whole looping search mess.
|
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/Regular_expressions) for a great overview. Regular Expressions can seem overwhelming if you're just starting out, but once you get a handle on the basic syntax, they're incredibly useful and powerful.
|
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 of MyClass and test them.
My question: how can I link the object file of MyClass, created by building MyDll, to the MyDllUnitTest EXE? I don't want to build MyClass in MyDllUnitTest and I don't want to export the class.
I tried using the same *Intermediate Directory* for both projects (so object files are in the same directory) and using the References feature of VS2005 (right click project --> References --> Add New Reference...), but it didn't work - I still get a linking error (LNK2001).
**Edit:** I don't want to have the same source file in two projects - consider the face that I have many MyClass/MyClassTest, which means I have to duplicate each MyClass to a different project.
I know it is possible to use the same object file in two projects, I've seen it done before but forgot how.
**Edit:** I've decided to put the files in both projects, so they are compiled twice. It turns out the "Reference" feature works automatically - but only for static lib projects.
|
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 exporting classes in a dll is usually a bad idea), consider exporting a "factory" function from the dll. It would have a signature like:
```
extern "C" MyClass *CreateMyClass();
```
This function would create an object of MyClass and return a pointer to it. Your unit test can then do whatever it needs with the returned class object.
|
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 assemblies these types are "invisible". Magic!
Here is the MSDN reference of the attribute to use ...
<http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx>
|
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.