Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is it possible to get the top position of an element using javascript/jquery ?
The element is a table, if that matters. | If you want the position relative to the document then:
```
$("#myTable").offset().top;
```
but often you will want the position relative to the closest positioned parent:
```
$("#myTable").position().top;
``` | ```
$("#myTable").offset().top;
```
This will give you the computed offset (relative to document) of any object. | How to get the top position of an element? | [
"",
"javascript",
"jquery",
""
] |
Is there any way to override a class method with a lambda function?
For example with a class definition of
```
class MyClass {
public virtual void MyMethod(int x) {
throw new NotImplementedException();
}
}
```
Is there anyway to do:
```
MyClass myObj = new MyClass();
myObj.MyMethod = (x) => { Console.WriteLine(x); };
``` | No. However if you declare the method as a lambda in the first place, you can set it, though I would try to do that at initialization time.
```
class MyClass {
public MyClass(Action<int> myMethod)
{
this.MyMethod = myMethod ?? x => { };
}
public readonly Action<int> MyMethod;
}
```
This however cannot implement an interface that has a MyMethod declared, unless the interface specifies a lambda property.
F# has object expressions, which allow you to compose an object out of lambdas. I hope at some point this is part of c#. | Chris is right that methods cannot be used like variables. However, you could do something like this:
```
class MyClass {
public Action<int> MyAction = x => { throw new NotImplementedException() };
}
```
To allow the action to be overridden:
```
MyClass myObj = new MyClass();
myObj.MyAction = (x) => { Console.WriteLine(x); };
``` | Can a method be overriden with a lambda function | [
"",
"c#",
"lambda",
""
] |
This is the code:
```
struct comp
{
bool operator()(Reputation *one, Reputation *two)
{
if (one->Amount < 0 && two->Amount >= 0)
return false;
if (one->Amount >= 0 && two->Amount < 0)
return true;
if (one->Amount >= 0)
return one->Amount <= two->Amount;
else
return one->Amount >= two->Amount;
}
};
```
And this is the problem:
> Debug Assertion Failed!
> File: ..\VC\include\xtree
> Line: 638
>
> Expression: invalid operator<
After that, I can choose "Abort", "Retry" or "Ignore". If I choose ignore many more (identical ones) come up but it ends up working perfectly.
The problem seems to occur when I insert a Reputation with ->Amount == to one of the Reputation \*'s previously inserted, but I'm not sure about this last one.
Any help would be greatly appreciated
EDIT: The order I want them ordered in is first the positive ones in asc order, then the negative ones in desc order. Example: 1 5 10 11 11 20 50 -1 -5 -50 | You must define a relation that's **irreflexive**, just like `<` -- therefore, change the `<=` to `<` and the '>=' to '>' in the last couple of comparisons in your method. This is what VC++ is diagnosing.
Moreover, given a correctly coded, `<-`like operator, if two items a and b are such that a < b and b < a are both false, those items are considered equivalent and thus only one will be inserted in the set (it's not material whether the items could be distinguished by some other comparison: only the equivalence relationship implied by the comparator matters). | The items in the `std::set` must be unique! (and less-comparable) If you want to have multiple items with the same value (like the sample you provided) use `std::multiset`.
see: <http://www.cppreference.com/wiki/stl/set/start> and <http://www.cppreference.com/wiki/stl/multiset/start> | C++ std::set comparator | [
"",
"c++",
"set",
"comparator",
"stdset",
""
] |
I noticed some confusion initially with my question. I'm not asking about how to configure a logger nor how to use a logger properly, but rather how to capture all of the information that would have been logged at a lower logging level than what the current logging level is in the exception message.
I have been noticing two patterns in Java for logging information that may be useful to a developer when an exception occurs.
The following pattern seems very common. Basically, you just have your logger log information in-line as needed, so that when an exception occurs you have the log trace.
```
try {
String myValue = someObject.getValue();
logger.debug("Value: {}", myValue);
doSomething(myValue);
}
catch (BadThingsHappenException bthe) {
// consider this a RuntimeException wrapper class
throw new UnhandledException(bthe);
}
```
The drawback with the above approach is that if your users **require relatively quiet logs** and need a high level of reliability to the point where they just can't "try it again in debug mode", the exception message contains insufficient data by itself to be useful to the developer.
The next pattern is one that I have seen that tries to mitigate this problem but seems ugly:
```
String myValue = null;
try {
myValue = someObject.getValue();
doSomething(myValue);
}
catch (BadThingsHappenException bthe) {
String pattern = "An error occurred when setting value. [value={}]";
// note that the format method below doesn't barf on nulls
String detail = MessageFormatter.format(pattern, myValue);
// consider this a RuntimeException wrapper class
throw new UnhandledException(detail, bthe);
}
```
The above pattern seems to somewhat solve the problem, however, I'm not sure I like to declare so many variables outside the scope of the try block. Especially, when I have to deal with very complicated states.
The only other approach I have seen is using a Map to store key-value pairs that are then dumped into the exception message. I'm not sure I like that approach either since it seems to create code bloat.
Is there some Java voodoo out there that I am missing? How do you handle your exception state information? | We tend to create our most important application specific runtime exception classes with some special constructors, some constants and a ResourceBundle.
Example snippet:
```
public class MyException extends RuntimeException
{
private static final long serialVersionUID = 5224152764776895846L;
private static final ResourceBundle MESSAGES;
static
{
MESSAGES = ResourceBundle.getBundle("....MyExceptionMessages");
}
public static final String NO_CODE = "unknown";
public static final String PROBLEMCODEONE = "problemCodeOne";
public static final String PROBLEMCODETWO = "problemCodeTwo";
// ... some more self-descriptive problem code constants
private String errorCode = NO_CODE;
private Object[] parameters = null;
// Define some constructors
public MyException(String errorCode)
{
super();
this.errorCode = errorCode;
}
public MyException(String errorCode, Object[] parameters)
{
this.errorCode = errorCode;
this.parameters = parameters;
}
public MyException(String errorCode, Throwable cause)
{
super(cause);
this.errorCode = errorCode;
}
public MyException(String errorCode, Object[] parameters, Throwable cause)
{
super(cause);
this.errorCode = errorCode;
this.parameters = parameters;
}
@Override
public String getLocalizedMessage()
{
if (NO_CODE.equals(errorCode))
{
return super.getLocalizedMessage();
}
String msg = MESSAGES.getString(errorCode);
if(parameters == null)
{
return msg;
}
return MessageFormat.format(msg, parameters);
}
}
```
In the properties file we specify the exception descriptions, e.g.:
```
problemCodeOne=Simple exception message
problemCodeTwo=Parameterized exception message for {0} value
```
Using this approach
* We can use quite readable and understandable throw clauses (`throw new MyException(MyException.PROBLEMCODETWO, new Object[] {parameter}, bthe)`)
* The exception messages are "centralized", can easily maintained and "internationalized"
**EDIT:** change `getMessage` to `getLocalizedMessage` as Elijah suggested.
**EDIT2:** Forgot to mention: this approach does not support Locale changing "on-the-fly" but it is intentional (it can be implemented if you need it). | Another good logging API is SLF4J. It can be configured to also intercept log APIs for Log4J, Java Util Logging, and Jakarta Commons Logging. And it can also be configured to *use* various logging implementations, including Log4J, Logback, Java Util Logging, and one or two others. This gives it enormous flexibility. It was developed by the author of Log4J to be its successor.
Of relevance to this question, the SLF4J API has a mechanism to concatenate string valued expressions into a log message. The following calls are equivalent, but the second is about 30x faster to process if you're not outputting debug level messages, since the concatenation is avoided:
```
logger.debug("The new entry is " + entry + ".");
logger.debug("The new entry is {}.", entry);
```
There's a two argument version too:
```
logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);
```
And for more than two you can pass in an array of Object like this:
```
logger.debug("Value {} was inserted between {} and {}.",
new Object[] {newVal, below, above});
```
This is a nice terse format that eliminates clutter.
Example source is from the [SLF4J FAQ](http://www.slf4j.org/faq.html).
Edit: Here's a possible refactoring of your example:
```
try {
doSomething(someObject.getValue());
}
catch (BadThingsHappenException bthe) {
throw new UnhandledException(
MessageFormatter.format("An error occurred when setting value. [value={}]",
someObject.getValue()),
bthe);
}
```
Or if this pattern occurs more than a few places you could write a set of static methods that capture the commonality, something like:
```
try {
doSomething(someObject.getValue());
}
catch (BadThingsHappenException bthe) {
throwFormattedException(logger, bthe,
"An error occurred when setting value. [value={}]",
someObject.getValue()));
}
```
and of course the method would also put the formatted message out on the logger for you. | What is a good way to pass useful state information to an exception in Java? | [
"",
"java",
"exception",
"logging",
"error-handling",
""
] |
I have a console application (in C#) to read data from SQL server (Microsoft SQL 2005) and write data to SQL server. What I need right now is to add a trigger to a table to exec the console application when any row of data is changed.
Not sure what SP available on Microsoft SQL server (2005) to launch a console application? and how can I pass the result from app back? Will it be run as sync or asych manor? Is there any permission issue I have to configure? | Don't launch external processes from a trigger, you'll bring the server onto its knees. Doesn't matter if is [xp\_cmdshell](http://msdn.microsoft.com/en-us/library/ms175046.aspx) or CLR procedure. Instead use Service Broker and issue a SEND in your trigger to queue a message to a local service and rely on [activation](http://msdn.microsoft.com/en-us/library/ms171617.aspx) to do the external dependent processing, asynchronously and on a separate context. | The [xp\_cmdshell](http://msdn.microsoft.com/en-us/library/ms175046.aspx) stored procedure can be used to launch an external process but this is often disabled for security reasons.
As the console application is already written in C#, perhaps it could be re-written as an SQLCLR stored procedure? | Exec Console Application by using TSQL SP? | [
"",
"c#",
"sql-server-2005",
""
] |
I want to use [WebKit](http://webkit.org/ "WebKit website") as the layout/rendering engine, and I want to code it in Java. I am having troubles finding any useful info. I saw this question [here](https://stackoverflow.com/questions/598841/how-to-get-started-building-a-web-browser "Another question") which cleared things for me slightly, but I need more to get started.
I would like to know:
1. If I can use Java?
2. Where can I find documentation on how to work with and use WebKit? ( I am looking for something like the [Java API](http://java.sun.com/j2se/1.5.0/docs/api/ "Java API") )
3. Is there a WebKit build compiled for Linux? ( Specifically Ubuntu/Debian )
My plan thus far:
1. Learn to use/interact with WebKit and its components specifically JavascriptCore.
2. Create the UI, etc. in Java and create a basic browser. ( For now, I want to create a basic window that can display a webpage correctly. )
Sorry if this isn't very clear. I am still hatching ideas, and I am not really sure what I want to find or need in order to move forward.
Edit: I just came across this question [here](https://stackoverflow.com/questions/184373/what-is-the-best-html-rendering-engine-to-embed-in-an-application "Another question"). I want to do something like that; so I guess what I am wondering is how do I go about embedding an engine like this into an application that I make myself? I also forgot to mention that I am willing to do this in other languages. ( By this I mean C++ ) | 1: Yes, it's possible. A [google search](http://www.google.com/search?hl=en&q=webkit+java+browser&aq=0&oq=webkit+java+b&aqi=g1) for "WebKit Java Browser" brings up several projects.
2: The best I could find in terms of documentation is the documentation section in the [WebKit wiki](http://trac.webkit.org/wiki).
3: Here's a [guide](http://trac.webkit.org/wiki/BuildingQtOnLinux) to making a WebKit build on Linux using QT. | Hope for [JWebPane](http://weblogs.java.net/blog/ixmal/archive/2008/05/introducing_jwe.html) to be released and go from there | I want to make a web browser, but I'm not sure where to start? | [
"",
"java",
"browser",
"cross-platform",
"webkit",
""
] |
Why does C++ need and use pointers? I know they add power to the language but they make it a lot harder to understand for beginners. Languages like F#, Java, Ruby, Python, Lua, etc. get by just fine without them, and they're quite powerful. | All other languages you mention (and you forgot, at least, Java!!!), while each very useful and usable, don't let you get anywhere as close to the machine as C++ (and C) allow: simply put, all of those languages impose on you a higher level of abstraction... which may *mostly* be fine but **will** occasionally get in your way.
C++ is a bigger and more complicated language because it allows programming at really low levels of abstraction (very close to the machine) AND at pretty high levels (close to many of the languages you mention) within the same language, indeed within the same source files.
Beginners are well advised to stay FAR away from this amount of power and (inevitably) complication -- but not *every* programmer is a beginner, and not every bit of code needs (or, actually, can at all *stand*!-) being within an environment that has "let's protect the poor shmucks from themselves" as a major design goal!-) | Maybe C++ isn't for beginners.
Pointers have been around for a long time. They were in Pascal and C. When C++ came out, it would have lost out of the gate without pointers. | Why does C++ use pointers? | [
"",
"c++",
"pointers",
""
] |
I need to write a function that takes in some kind of input stream thing (e.g. an InputStream or a FileChannel) in order to read a large file in two passes: once to precompute some capacities, and second to do the "real" work. I do not want the whole file loaded into memory at once (unless it is small).
**Is there an appropriate Java class that provides this capability?** FileInputStream itself does not support mark()/reset(). BufferedInputStream does, I think, but I'm not clear whether it has to store the whole file to do this.
C is so simple, you just use fseek(), ftell(), and rewind(). :-( | I think the answers referencing a FileChannel are on the mark .
Here's a sample implementation of an input stream that encapsulates this functionality. It uses delegation, so it's not a true FileInputStream, but it is an InputStream, which is usually sufficient. One could similarly extend FileInputStream if that's a requirement.
Not tested, use at your own risk :)
```
public class MarkableFileInputStream extends FilterInputStream {
private FileChannel myFileChannel;
private long mark = -1;
public MarkableFileInputStream(FileInputStream fis) {
super(fis);
myFileChannel = fis.getChannel();
}
@Override
public boolean markSupported() {
return true;
}
@Override
public synchronized void mark(int readlimit) {
try {
mark = myFileChannel.position();
} catch (IOException ex) {
mark = -1;
}
}
@Override
public synchronized void reset() throws IOException {
if (mark == -1) {
throw new IOException("not marked");
}
myFileChannel.position(mark);
}
}
``` | `BufferedInputStream` supports `mark` by buffering the content in memory. It is best reserved for relatively small look-aheads of a predictable size.
Instead, `RandomAccessFile` can be used directly, or it could serve as the basis for a concrete `InputStream`, extended with a `rewind()` method.
Alternatively, a new `FileInputStream` can be opened for each pass. | java file input with rewind()/reset() capability | [
"",
"java",
"io",
"stream",
""
] |
Can JavaScript classes/objects have constructors? How are they created? | Using prototypes:
```
function Box(color) // Constructor
{
this.color = color;
}
Box.prototype.getColor = function()
{
return this.color;
};
```
Hiding "color" (somewhat resembles a private member variable):
```
function Box(col)
{
var color = col;
this.getColor = function()
{
return color;
};
}
```
Usage:
```
var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue
var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green
``` | Here's a template I sometimes use for OOP-similar behavior in JavaScript. As you can see, you can simulate private (both static and instance) members using closures. What `new MyClass()` will return is an object with only the properties assigned to the `this` object and in the `prototype` object of the "class."
```
var MyClass = (function () {
// private static
var nextId = 1;
// constructor
var cls = function () {
// private
var id = nextId++;
var name = 'Unknown';
// public (this instance only)
this.get_id = function () { return id; };
this.get_name = function () { return name; };
this.set_name = function (value) {
if (typeof value != 'string')
throw 'Name must be a string';
if (value.length < 2 || value.length > 20)
throw 'Name must be 2-20 characters long.';
name = value;
};
};
// public static
cls.get_nextId = function () {
return nextId;
};
// public (shared across instances)
cls.prototype = {
announce: function () {
alert('Hi there! My id is ' + this.get_id() + ' and my name is "' + this.get_name() + '"!\r\n' +
'The next fellow\'s id will be ' + MyClass.get_nextId() + '!');
}
};
return cls;
})();
```
I've been asked about inheritance using this pattern, so here goes:
```
// It's a good idea to have a utility class to wire up inheritance.
function inherit(cls, superCls) {
// We use an intermediary empty constructor to create an
// inheritance chain, because using the super class' constructor
// might have side effects.
var construct = function () {};
construct.prototype = superCls.prototype;
cls.prototype = new construct;
cls.prototype.constructor = cls;
cls.super = superCls;
}
var MyChildClass = (function () {
// constructor
var cls = function (surName) {
// Call super constructor on this instance (any arguments
// to the constructor would go after "this" in call(…)).
this.constructor.super.call(this);
// Shadowing instance properties is a little bit less
// intuitive, but can be done:
var getName = this.get_name;
// public (this instance only)
this.get_name = function () {
return getName.call(this) + ' ' + surName;
};
};
inherit(cls, MyClass); // <-- important!
return cls;
})();
```
And an example to use it all:
```
var bob = new MyClass();
bob.set_name('Bob');
bob.announce(); // id is 1, name shows as "Bob"
var john = new MyChildClass('Doe');
john.set_name('John');
john.announce(); // id is 2, name shows as "John Doe"
alert(john instanceof MyClass); // true
```
As you can see, the classes correctly interact with each other (they share the static id from `MyClass`, the `announce` method uses the correct `get_name` method, etc.)
One thing to note is the need to shadow instance properties. You can actually make the `inherit` function go through all instance properties (using `hasOwnProperty`) that are functions, and automagically add a `super_<method name>` property. This would let you call `this.super_get_name()` instead of storing it in a temporary value and calling it bound using `call`.
For methods on the prototype you don't need to worry about the above though, if you want to access the super class' prototype methods, you can just call `this.constructor.super.prototype.methodName`. If you want to make it less verbose you can of course add convenience properties. :) | Constructors in JavaScript objects | [
"",
"javascript",
"oop",
""
] |
I have a multi-module Maven project with a parent project `P` and three sub-modules `A`, `B`, and `C`. Both `B` and `C` are war projects and both depend on `A`.
I can type `mvn compile` in `P` and have all of the sub-modules properly compiled. The problem comes when I want to do operations for specific modules.
I'd like to be able to package a war for project `B`, but when I run the package command from `B`'s directory, it complains that it can't find the dependencies for `A`.
I understand from this question: [Maven and dependent modules](https://stackoverflow.com/questions/808516/maven-and-dependent-modules) that perhaps Maven isn't really designed for this type of dependency resolution, but that begs the question of how do I package `B`?
1. Do I have to run `mvn package` for the entire project hierarchy when I really just want `B`?
2. Do I have to install snapshots of A into my local repository every time I want to package `B`?
This second scenario isn't much fun when `A` is still under active development.
Any best practices here? | > Any best practices here?
Use the [Maven advanced reactor options](https://blog.sonatype.com/2009/10/maven-tips-and-tricks-advanced-reactor-options/), more specifically:
```
-pl, --projects
Build specified reactor projects instead of all projects
-am, --also-make
If project list is specified, also build projects required by the list
```
So just `cd` into the parent P directory and run:
```
mvn install -pl B -am
```
And this will build B and the modules required by B.
Note that you need to use a colon if you are referencing an `artifactId` which differs from the directory name:
```
mvn install -pl :B -am
```
As described here:
* [Define modules list which shall be build in Maven multiproject build](https://stackoverflow.com/questions/26429476/define-modules-list-which-shall-be-build-in-maven-multiproject-build/26439938#26439938) | Say Parent pom.xml contains 6 modules and you want to run **A**, **B** and **F**.
```
<modules>
<module>A</module>
<module>B</module>
<module>C</module>
<module>D</module>
<module>E</module>
<module>F</module>
</modules>
```
1- cd into parent project
```
mvn --projects A,B,F --also-make clean install
```
OR
```
mvn -pl A,B,F -am clean install
```
OR
```
mvn -pl A,B,F -amd clean install
```
**Note:** When you specify a project with the **-am** option, Maven will build all of the projects that the specified project depends upon (either directly or indirectly). Maven will examine the list of projects and walk down the dependency tree, finding all of the projects that it needs to build.
While the **-am** command makes all of the projects required by a particular project in a multi-module build, the **-amd** or **--also-make-dependents** option configures Maven to build a project and any project that depends on that project. When using **--also-make-dependents**, Maven will examine all of the projects in our reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else. | Maven Modules + Building a Single Specific Module | [
"",
"java",
"maven-2",
"build-process",
""
] |
Here's my question.
Right now I have a Linux server application (written using C++ - gcc) that communicates with a Windows C++ client application (Visual Studio 9, Qt 4.5.)
What is the *very* easiest way to add SSL support to both sides in order to secure the communication, without completely gutting the existing protocol?
It's a VOIP application that uses a combination of UDP and TCP to initially set up the connection and do port tunneling stuff, and then uses UDP for the streaming data.
I've had lots of problems in the past with creating the security certificates from scratch that were necessary to get this stuff working.
Existing working example code would be ideal.
Thank you! | [SSL is very complex](http://www.moserware.com/2009/06/first-few-milliseconds-of-https.html), so you're going to want to use a library.
There are several options, such as [Keyczar](http://www.keyczar.org/), [Botan](http://botan.randombit.net/news/), [cryptlib](http://www.cs.auckland.ac.nz/%7Epgut001/cryptlib/), etc. Each and every one of those libraries (or the libraries suggested by others, such as Boost.Asio or OpenSSL) will have sample code for this.
---
Answering your second question (how to integrate a library into existing code without causing too much pain): it's going to depend on your current code. If you already have simple functions that call the Winsock or socket methods to send/receive `int`s, `strings`, etc. then you just need to rewrite the guts of those functions. And, of course, change the code that sets up the socket to begin with.
On the other hand, if you're calling the Winsock/socket functions directly then you'll probably want to write functions that have similar semantics but send the data encrypted, and replace your Winsock calls with those functions.
However, you may want to consider switching to something like [Google Protocol Buffers](http://code.google.com/apis/protocolbuffers/) or [Apache Thrift](http://wiki.apache.org/thrift/) (a.k.a. Facebook Thrift). Google's Protocol Buffers documentation says, "Prior to protocol buffers, there was a format for requests and responses that used hand marshalling/unmarshalling of requests and responses, and that supported a number of versions of the protocol. This resulted in some very ugly code. ..."
You're currently in the hand marshalling/unmarshalling phase. It can work, and in fact a project I work on does use this method. But it is a lot nicer to leave that to a library; especially a library that has already given some thought to updating the software in the future.
If you go this route you'll set up your network connections with an SSL library, and then you'll push your Thrift/Protocol Buffer data over those connections. That's it. It does involve extensive refactoring, but you'll end up with less code to maintain. When we introduced Protocol Buffers into the codebase of that project I mentioned, we were able to get rid of about 300 lines of marshalling/demarshalling code. | I recommend to use [GnuTLS](http://www.gnu.org/software/gnutls/) on both the client and the server side, only for the TCP connection. Forget about the UDP data for now. The GnuTLS documentation has [example code](http://www.gnu.org/software/gnutls/manual/html_node/How-to-use-GnuTLS-in-applications.html) for writing both clients and servers. Please understand that at least the server side (typically the TCP responder) needs to have a certificate; the client side can work with anonymous identification (although there is even an example without server certificate, using only DH key exchange - which would allow man-in-the-middle attacks).
In general, it is likely that you will have to understand the principles of SSL, no matter what library you use. Library alternatives are OpenSSL (both Unix and Windows), and SChannel (only Windows). | Adding SSL support to existing TCP & UDP code? | [
"",
"c++",
"ssl",
"udp",
"tcp",
"ssl-certificate",
""
] |
Here's a question that I don't quite understand:
The command, `system("pause");` is taught to new programmers as a way to pause a program and wait for a keyboard input to continue. However, it seems to be frowned on by many veteran programmers as something that should not be done in varying degrees.
Some people say it is fine to use. Some say it is only to be used when you are locked in your room and no one is watching. Some say that they will personally come to your house and kill you if you use it.
I, myself am a new programmer with no formal programming training. I use it because I was taught to use it. What I don't understand is that if it is not something to be used, then why was I taught to use it? Or, on the flip side, is it really not that bad after all?
What are your thoughts on this subject? | It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his new program.
Bodging in `system("pause")` runs the Windows command-line "pause" command and waits for that to terminate before it continues execution of the program - the console window stays open so you can read the output.
A better idea would be to put a breakpoint at the end and debug it, but that again has problems. | It's slow. It's platform dependent. It's insecure.
First: What it does. Calling "system" is literally like typing a command into the windows command prompt. There is a ton of setup and teardown for your application to make such a call - and the overhead is simply ridiculous.
What if a program called "pause" was placed into the user's PATH? Just calling system("pause") only guarantees that a program called "pause" is executed (hope that you don't have your executable named "pause"!)
Simply write your own "Pause()" function that uses \_getch. OK, sure, \_getch is platform dependent as well (note: it's defined in "conio.h") - but it's much nicer than `system()` if you are developing on Windows and it has the same effect (though it is your responsibility to provide the text with cout or so).
Basically: why introduce so many potential problems when you can simply add two lines of code and one include and get a much more flexible mechanism? | system("pause"); - Why is it wrong? | [
"",
"c++",
""
] |
I am interating through classes in a Jar file and wish to find those which are not abstract. I can solve this by instantiating the classes and trapping InstantiationException but that has a performance hit as some classes have heavy startup. I can't find anything obviously like isAbstract() in the Class.java docs. | It'll have abstract as one of its modifiers when you call getModifiers() on the class object.
This [link](http://java.sun.com/docs/books/tutorial/reflect/class/classModifiers.html "link") should help.
```
Modifier.isAbstract( someClass.getModifiers() );
```
Also:
<http://java.sun.com/javase/6/docs/api/java/lang/reflect/Modifier.html>
<http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getModifiers()> | ```
Class myClass = myJar.load("classname");
bool test = Modifier.isAbstract(myClass.getModifiers());
``` | How can I determine whether a Java class is abstract by reflection | [
"",
"java",
"class",
"abstract",
""
] |
So I've got a column in a table that contains a string values (keywords populated from a 3rd party tool). I'm working on an automated tool to identify clusters of similar values that could probably be normalized to a single value. For example, "Firemen"/"Fireman", "Isotope"/"Asotope" or "Canine"/"Canines".
An approach that calculates the levenshtein distance seems ideal except for the fact that it involves too much string manipulation/comparison and would probably make poor use of SQL indexes.
I've considered incrementally grouping by the Left(X) characters of the column, which is a not-so-bad way to maximize index use, but this approach is really only effective at finding words with differences at the very end of the word.
Anyone got some good ideas for solving this problem efficiently in SQL?
Note: I realize this question is very similar to ([Finding how similar two strings are](https://stackoverflow.com/questions/577463/finding-how-similar-two-strings-are)), but the distinction here is the need to do this efficiently in SQL. | If you are using SQL Server, you might look into using the SOUNDEX() function as in:
```
...
where
SOUNDEX("searchterm") = SOUNDEX(searchvaluefield)
```
it is supposed to do Phonetic matching on the strings ...
Some odd examples ... so it seems you could catch plurals by always appending the plural text to both sides, since multiple 's's sound the same ... :-)
```
select soundex('Canine'), soundex('Canines')
go
----- -----
C550 C552
1 Row(s) affected
select soundex('Canine'), soundex('Caynyn')
go
----- -----
C550 C550
1 Row(s) affected
select soundex('Canines'), soundex('Caniness')
go
----- -----
C552 C552
1 Row(s) affected
``` | You don't mention what DB your using, but if it's T-SQL, you could use the [SOUNDEX](http://msdn.microsoft.com/en-us/library/ms187384.aspx) value and [difference](http://doc.ddart.net/mssql/sql70/de-dz_7.htm). | Performant techniques for finding similar values in SQL? | [
"",
"sql",
"pattern-matching",
""
] |
There seems to be a bug in a Wordpress PHP function that leaves whitespace in front of the title of the page generated by `<?php echo wp_title(''); ?>` I've been through the Wordpress docs and forums on that function without any luck.
I'm using it this way `<body id="<?php echo wp_title(''); ?>">` in order to generate an HTML body tag with the id of the page title.
So what I need to do is strip that white space, so that the body tag looks like this `<body id="mypage">` instead of this `<body id=" mypage">`
The extra white space kills the CSS I'm trying to use to highlight menu items of the active page. When I manually add a correct body tag without the white space, my CSS works.
So how would I strip the white space? Thanks, Mark
---
Part Two of the Epic
John, A hex dump was a good idea; it shows the white space as two "20" spaces. But all solutions that strip leading spaces and white space didn't.
And, `<?php ob_start(); $title = wp_title(''); ob_end_clean(); echo $title; ?>`
gives me `< body id ="">`
and `<?php ob_start(); $title = wp_title(''); echo $title; ?>`
gives me `< body id =" mypage">`
Puzzle. The root of the problem is that wp\_title has optional page title leading characters - that look like chevrons - that are supposed to be dropped when the option is false, and they are, but white space gets dumped in.
Is there a nuclear option?
---
Yup, tried them both before; they still return two leading spaces... arrgg | 1. Strip all whitespace from the left end of the title:
```
<?php echo ltrim(wp_title('')); ?>
```
2. Strip all whitespace from either end:
```
<?php echo trim(wp_title('')); ?>
```
3. Strip all spaces from the left end of the title:
```
<?php echo ltrim(wp_title(''), ' '); ?>
```
4. Remove the first space, even if it's not the first character:
```
<?php echo str_replace(' ', '', wp_title(''), 1); ?>
```
5. Strip only a single space (not newline, not tab) at the beginning:
```
<?php echo preg_replace('/^ /', '', wp_title('')); ?>
```
6. Strip the first character, whatever it is:
```
<?php echo substr(wp_title(''), 1); ?>
```
# Update
From the Wordpress [documentation on `wp_title`](http://codex.wordpress.org/Template_Tags/wp_title), it appears that `wp_title` displays the title itself unless you pass `false` for the second parameter, in which case it returns it. So try:
```
<?php echo trim(wp_title('', false)); ?>
``` | [`ltrim()`](http://www.php.net/ltrim) | Trim leading white space with PHP? | [
"",
"php",
"whitespace",
"trim",
""
] |
My first try of MVC. Am trying to implement a *simple* example. Inspiration from [here](https://stackoverflow.com/questions/1015813/what-goes-into-the-controller-in-mvc). Have I got this pattern (yet!)?
1. View: "Hey, controller, the user just told me he wants the first person"
2. Controller: "Hmm, having checked his credentials, he is allowed to do that... Hey, model, I want you to get me the first person"
3. Model: "First person... got it. Back to you, Controller."
4. Controller: "Here, I'll collect the new set of data. Back to you, view."
5. View: "Cool, I'll show the first person to the user now."
View:
```
namespace WinFormMVC
{
public partial class Form1 : Form
{
controller cont = new controller();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = cont.checkPermissionsAndGetFirstPerson();
}
}
}
```
Controller:
```
public class controller
{
public string checkPermissionsAndGetFirstPerson()
{
string returnValue = "";
if (checkPermissions())
{
model m = new model();
returnValue = m.getFirstPerson();
}
return returnValue;
}
public bool checkPermissions()
{
return true;
}
}
```
Model:
```
public class model
{
public string getFirstPerson()
{
return "Bill Smith";
}
}
``` | Hmm... I am not sure if I'd call this MVC... As with ASP.NET WebForm, this form is more like an MVP pattern.
As per my understanding, in MVC, controller is the one responsible for managing all resources and flow of the code. In your example, you basically creating a Windows Form first (the view) and then attach a controller to it which is more of a MVP sort of things.
In a classical MVC pattern, the Model, once instantiated, will be linked to the View and when the model changes, the view will get notified (possibly through Observer / PubSub pattern).
Button click, etc. from the View will be routed to the controller which will coordinate those sort of stuffs.
see: [this](http://dotnetslackers.com/articles/PrintArticle.aspx?ArticleId=305). | I would describe MVC more like this:
1. Request (MVC url routing, some event passed from previous UI etc)
2. Controller - check credentials, get data, return Model
3. Model - represents the data passed back from the Controller
4. View - render the Model returned by the Controller. Depending on the Model may display UI to initialise new Controller actions. May also pass Model back to next Controller action.
I think it can be a little confused because in many Model implementations (such as Linq) they provide data definition and access, but it's still the Controller that knows where to start (even if it's the Model that knows how to save its own changes).
So, your code should be something like:
```
//Controller:
public class PersonController
{
public PersonAction Detail(int personId)
{
Person returnValue;
//get person from DB and populate returnValue
return new PersonAction( returnValue );
}
}
//Model:
public class Person
{
public string FirstName {get; set;}
public string LastName {get; set;}
}
//View:
public partial class PersonDetailView : MVCForm<Person>
{
public Form1( Person model ):base(model) {
textBox1.Text = model.FirstName + " " + model.LastName;
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = model.FirstName + " " + model.LastName;
}
}
```
What this example is missing is the framework that makes this all possible - there are two significant parts to that:
1. Something that takes/parses parameters and based on that calls a controller's action method. For instance in Asp.net MVC this is the routing handlers - the call above would be the request url: ~/Person/Detail/personId
2. Something that takes the result from the action (`PersonAction` in the example above) and finds the correct view to display. In this example it would open a `PersonDetailView` form and pass the `Person` model to it.
There are lots of example frameworks for an MVC implementation for WinForms - one of them may be a good starting point. | MVC C# - Simplest Possible Implementation | [
"",
"c#",
"asp.net-mvc",
"design-patterns",
""
] |
So I have this page here:
<http://www.eminentmedia.com/development/powercity/>
As you can see when you mouse over the images the div slides up and down to show more information. Unfortunately I have 2 problems that i can't figure out and I've searched but haven't found quite the right answer through google and was hoping someone could point me in the direction of a tutorial.
The first problem is that when you mouse over an image it changes to color (loads a new image), but there's a short delay when the image is loading for the first time so the user sees white. Do I have to preload the images or something in order to fix that?
My second problem is that when you move your mouse over the 'additional content area' it goes crazy and starts going up and down a bunch of times. I just don't have any idea what would cause this but i hope one of you will!
All my code is directly in the source of that page if you would like to view the source.
Thanks in advance for your help! | Yes, you have to preload the images. Thankfully, this is simple:
```
var images_to_preload = ['myimage.jpg', 'myimage2.jpg', ...];
$.each(images_to_preload, function(i) {
$('<img/>').attr({src: images_to_preload[i]});
});
```
The other thing you have to understand is that when you use jQuery you have to truly embrace it or you will end up doing things the wrong way. For example, as soon as you find yourself repeating the same piece of code in different places, you are probably doing something wrong. Right now you have this all over the place:
```
<div id="service" onmouseover="javascript:mouseEnter(this.id);" onmouseout="javascript:mouseLeave(this.id);">
```
Get that out of your head. Now. Forever. Always. Inline javascript events are not proper, especially when you have a library like jQuery at your disposal. The proper way to do what you want is this:
```
$(function() {
$('div.box').hover(function() {
$(this).addClass('active');
$(this).find('div.slideup').slideDown('slow');
}, function() {
$(this).removeClass('active');
$(this).find('div.slideup').slideUp('slow');
});
});
```
(You have to give all the #industrial, #sustainable, etc elements a class of 'box' for the above to work)
These changes will also fix your sliding problem. | I can see your images (the ones that are changing) are set in the background of a div. Here is a jquery script that preloads every image found in a css file. I have had the same problem in the past and this script solves it. It is also very easy to use:
```
http://www.filamentgroup.com/lab/update_automatically_preload_images_from_css_with_jquery/
```
I will take a look at your other problem... | How to keep div focus when the mouse enters a child node | [
"",
"javascript",
"jquery",
""
] |
I'm confused with file moving under python.
Under windows commandline, if i have directory c:\a and a directory c:\b, i can do
```
move c:\a c:\b
```
which moves a to b result is directory structure c:\b\a
If I try this with os.rename or shutil.move:
```
os.rename("c:/a", "c:/b")
```
I get
```
WindowsError: [Error 17] Cannot create a file when that file already exists
```
If I move a single file under c:\a, it works.
In python how do i move a directory to another existing directory? | ```
os.rename("c:/a", "c:/b/a")
```
is equivalent to
```
move c:\a c:\b
```
under windows commandline | You can try using the [Shutil](http://docs.python.org/library/shutil.html#module-shutil) module. | Moving files under python | [
"",
"python",
"windows",
"move",
""
] |
I have a simple php script on my domain that sends me an email:
```
...
$toMail = "me@gmail.com"; //this works - I get the email at my gmail
$toMail = "me@mydomain.com"; //this doesn't - I get nothing
mail($toMail, $subject, $message, $header);
```
What setting to I change to fix this? | I've had this problem myself, when I was redesigning a site recently.
There was an issue with the way our system was set up, so that the system thought that because the email was coming from the same domain it was a spam email and as such blocked it.
Check with your system administrator that you are allowed to be sending the emails etc.
Either that, or you'll have to modify the headers to have look like it's being sent from an external address. Hope you get it sorted. | For the people using Google Apps for email, but having your host in other provider this are more detailed instructions for the people that is not very familiar with cPanel.
I could fix the problem of sending email from my domain using a PHP form, when sending the email to an account inside my domain.
i.e. `mydomain.example` Contact form sending email to `contact@mydomain.example`.
The above was not working even if my domain has the correct MX records for the domain using Google Apps.
As Mike noted (and others) above the problem was solved: Adding the MX records into the cPanel.
1. Enter into the cPanel
2. Go the the cPanel Mail section
3. Search for MX Entry Maintenance, sometimes there is no text above the icon.
4. Select the related domain
5. Change **Email** Routing to **Remote Mail Exchanger.**
6. Add all the Google MX records as they are in your domain configuration using the appropriate priority values.
You can check the records here and priorities
<https://support.google.com/a/answer/174125>
7. Double check that **Remote Mail Exchanger.** is selected.
With this setting I was able to send email using mail PHP function to an email account inside the same domain as my website.
Google App instructions talking about MX records
<https://support.google.com/a/answer/54717?hl=en> | can't send email to addresses at my own domain | [
"",
"php",
"email",
"dns",
""
] |
I have a JTable that I want to use to display some data (a `String` and a `Boolean` in each row). The data is maintained by my own class. Is there some way to bind the data model to the JTable, so that when I add to the model, the JTable is dynamically updated and when I remove something from the model, the row is removed from the JTable?
I have previously worked with Flex and Actionscript, and this is very easy to do there with data binding, so I'm just wondering how it's done in Java.
Thanks. | You will need to have your dataset implement the [`TableModel`](http://java.sun.com/javase/6/docs/api/javax/swing/table/TableModel.html) interface. if you do that then you can apply it to the JTable. If you extend [`AbstractTableModel`](http://java.sun.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html) you will inherit some event firing methods that your table will handle and will update the view. [see this tutorial](http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data). Note that the default implementation of `JTable` will renderer your data for you, and if a Boolean is found, it will show up as a check box. | While implementing TableModel is easy enough for simple cases, you might want to consider a true binding approach (my favorite is [Glazed Lists](http://www.publicobject.com/glazedlists/) - watch the 30 second video on how easy this is and you'll be won over). Beans Binding (now [Better Beans Binding](http://kenai.com/projects/betterbeansbinding/pages/Home)) also has an implementation of observable lists that might be useful (although I much prefer the Glazed Lists approach) | Working with data and a JTable? | [
"",
"java",
"data-binding",
"jtable",
""
] |
I'm after a simple stored procedure to drop tables. Here's my first attempt:
```
CREATE PROC bsp_susf_DeleteTable (@TableName char)
AS
IF EXISTS (SELECT name FROM sysobjects WHERE name = @TableName)
BEGIN
DROP TABLE @TableName
END
```
When I parse this in MS Query Analyser I get the following error:
```
Server: Msg 170, Level 15, State 1, Procedure bsp_susf_DeleteTable, Line 6
Line 6: Incorrect syntax near '@TableName'.
```
Which kind of makes sense because the normal SQL for a single table would be:
```
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'tbl_XYZ')
BEGIN
DROP TABLE tbl_XYZ
END
```
Note the first instance of tbl\_XYZ (in the WHERE clause) has single quotes around it, while the second instance in the DROP statement does not. If I use a variable (@TableName) then I don't get to make this distinction.
So can a stored procedure be created to do this? Or do I have to copy the IF EXISTS ... everywhere? | You should be able to use dynamic sql:
```
declare @sql varchar(max)
if exists (select name from sysobjects where name = @TableName)
BEGIN
set @sql = 'drop table ' + @TableName
exec(@sql)
END
```
Hope this helps.
Update: Yes, you could make @sql smaller, this was just a quick example. Also note other comments about SQL Injection Attacks | Personally I would be very wary of doing this. If you feel you need it for administrative purposes, please make sure the rights to execute this are extremely limited. Further, I would have the proc copy the table name and the date and the user executing it to a logging table. That way at least you will know who dropped the wrong table. You may want other protections as well. For instance you may want to specify certain tables that cannot be dropped ever using this proc.
Further this will not work on all tables in all cases. You cannot drop a table that has a foreign key associated with it.
Under no circumstances would I allow a user or anyone not the database admin to execute this proc. If you havea a system design where users can drop tables, there is most likely something drastically wrong with your design and it should be rethought.
Also, do not use this proc unless you have a really, really good backup schedule in place and experience restoring from backups. | How do I paramaterise a T-SQL stored procedure that drops a table? | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
Can I use PHP with Oledb connection?
As far as I know database connection as provided by PHP extension are all odbc. | You can use ActiveX Data Objects (Microsoft's OLEDB ActiveX layer) in PHP-Win without any third party extension as such:
```
$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
// Microsoft Access connection string.
$conn->Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\inetpub\wwwroot\php\mydb.mdb");
// SQL statement to build recordset.
$rs = $conn->Execute("SELECT myfield FROM mytable");
echo "<p>Below is a list of values in the MYDB.MDB database, MYABLE table, MYFIELD field.</p>";
// Display all the values in the records set
while (!$rs->EOF) {
$fv = $rs->Fields("myfield");
echo "Value: ".$fv->value."<br>\n";
$rs->MoveNext();
}
$rs->Close();
``` | Look at the [ADOdb Library for PHP](http://phplens.com/lens/adodb/docs-adodb.htm) extension. I've never used it, but it seems to be compatible with OLEDB providers. | PHP with Oledb | [
"",
"php",
"oledb",
""
] |
Does anyone with experience with these libraries have any comment on which one they preferred? Were there any performance differences or difficulties in using? | I've played around a little with both systems, nothing serious, just some simple hackish stuff, but I felt that there's a real difference in how you're supposed to use the libraries.
With boost::serialization, you write your own structs/classes first, and then add the archiving methods, but you're still left with some pretty "slim" classes, that can be used as data members, inherited, whatever.
With protocol buffers, the amount of code generated for even a simple structure is pretty substantial, and the structs and code that's generated is more meant for operating on, and that you use protocol buffers' functionality to transport data to and from your own internal structures. | I've been using Boost Serialization for a long time and just dug into protocol buffers, and I think they don't have the exact same purpose. BS (didn't see that coming) saves your C++ objects to a stream, whereas PB is an interchange format that you read to/from.
PB's datamodel is way simpler: you get all kinds of ints and floats, strings, arrays, basic structure and that's pretty much it. BS allows you to directly save all of your objects in one step.
That means with BS you get more data on the wire but you don't have to rebuild all of your objects structure, whereas protocol buffers is more compact but there is more work to be done after reading the archive. As the name says, one is for protocols (language-agnostic, space efficient data passing), the other is for serialization (no-brainer objects saving).
So what is more important to you: speed/space efficiency or clean code? | boost serialization vs google protocol buffers? | [
"",
"c++",
"performance",
"serialization",
"protocol-buffers",
"boost-serialization",
""
] |
Is an outer join only used for analysis by the developer? I'm having trouble finding a use case for why you would want to include data in two or more tables that is unrelated or does not "match" your select criteria. | An example use case would be to produce a report that shows ALL customers and their purchases. That is, show even customers who have not purchased anything. If you do an ordinary join of customers and purchases, the report would show only those customers with at least one purchase. | Here is a very good list of examples by none other than [Jeff Atwood - A Visual Explanation of SQL Joins](https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/) he shows a new representation visually of the SQL joins. | What is the purpose (or use case) for an outer join in SQL? | [
"",
"sql",
"join",
"outer-join",
""
] |
It seems that every time I want to perform a db query, I have to write the following:
```
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = dataSource.getConnection();
stmt = conn.prepareStatement(sql);
// ...set stmt params
rset = stmt.executeQuery();
while(rset.next()) {
// Do something interesting
}
} finally {
try { if (rset != null) rset.close(); } catch(SQLException e) { }
try { if (stmt != null) stmt.close(); } catch(SQLException e) { }
try { if (conn != null) conn.close(); } catch(SQLException e) { }
}
```
Is this really the best way to do this? Is there a way to at least reduce some of the clutter?
Edited: as some of the comments pointed out, this code wasn't long *enough*. | If you already have a DataSource you can use [Spring JdbcTemplate](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/ch13s02.html) for:
* greatly reduced boilerplate code
* have a good [sql exception hierarchy](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/ch12s02.html) to handle common database problems with specific runtime exceptions
* (later with further Spring usage) use declarative transaction management
If it seems too heavy for the moment you could implement some utility classes and methods for the 'boilerplate part'. Studying the source of JdbcTemplate should help in this case. | Yes, use the Sping JDBC Template classes (<http://static.springsource.org/spring/docs/2.0.x/reference/jdbc.html>).
Or if you don't use Spring copy the template pattern that they are using in your own code. | Remove boilerplate from db code | [
"",
"java",
"jdbc",
""
] |
I need to send some information on a VxWorks message queue. The information to be sent is decided at runtime and may be of different data types. I am using a structure for this -
```
struct structData
{
char m_chType; // variable to indicate the data type - long, float or string
long m_lData; // variable to hold long value
float m_fData; // variable to hold float value
string m_strData; // variable to hold string value
};
```
I am currently sending an array of structData over the message queue.
```
structData arrStruct[MAX_SIZE];
```
The problem here is that only one variable in the structure is useful at a time, the other two are useless. The message queue is therefore unneccessarily overloaded.
I can't use unions because the datatype and the value are required.
I tried using templates, but it doesn't solve the problem.I can only send an array of structures of one datatype at a time.
```
template <typename T>
struct structData
{
char m_chType;
T m_Data;
}
structData<int> arrStruct[MAX_SIZE];
```
Is there a standard way to hold such information? | There are many ways to handle different datatypes. Besides the union solution you can use a generic struct like :
```
typedef struct
{
char m_type;
void* m_data;
}
structData;
```
This way you know the type and you can cast the void\* pointer into the right type.
This is like the union solution a more C than C++ way of doing things.
The C++ way would be something using inheritance. You define a base "Data" class an use inheritance to specialize the data. You can use RTTI to check for type if needed.
But as you stated, you need to send your data over a VxWork queue. I'm no specialist but if those queues are OS realtime queue, all the previous solutions are not good ones. Your problem is that your data have variable length (in particular string) and you need to send them through a queue that probably ask for something like a fixed length datastruct and the actual length of this datastruct.
In my experience, the right way to handle this is to serialize the data into something like a buffer class/struct. This way you can optimize the size (you only serialize what you need) and you can send your buffer through your queue.
To serialize you can use something like 1 byte for type then data. To handle variable length data, you can use 1 to n bytes to encode data length, so you can deserialize the data.
For a string :
1 byte to code the type (0x01 = string, ...)
2 bytes to code the string length (if you need less than 65536 bytes)
n data bytes
So the string "Hello" will be serialized as :
```
0x00 0x00 0x07 0x65 0x48 0x6c 0x6c
```
You need a buffer class and a serializer/deserializer class. Then you do something like :
```
serialize data
send serialized data into queue
```
and on the other side
```
receive data
deserialize data
```
I hope it helps and that I have not misunderstood your problem. The serialization part is overkill if the VxWorks queues are not what I think ... | I don't see why you cannot use a union. This is the standard way:
```
struct structData
{
char m_chType; // variable to indicate the data type - long, float or string
union
{
long m_lData; // variable to hold long value
float m_fData; // variable to hold float value
char *m_strData; // variable to hold string value
}
};
```
Normally then, you switch on the data type, and then access on the field which is valid for that type.
Note that you cannot put a `string` into a union, because the `string` type is a non-POD type. I have changed it to use a pointer, which could be a C zero-terminated string. You must then consider the possibility of allocating and deleting the string data as necessary. | Handling different datatypes in a single structure | [
"",
"c++",
""
] |
I'm working on a page where I need to associate a list of objects with a row of a table, and I'm using jQuery.
jQuery.data seems to just associate a piece of data with a key, whereas I need more like
```
id=4,setting=2
id=3,setting=1
...
```
I don't know how long the list could be, and it could be empty.
Is there a sensible way of doing this? | You can store anything as jQuery data, so you could do this:
```
var myData = [ { id: 4, setting: 2 }, [ id:3, setting:1 ] };
$("#myitem").data("mydata", myData);
```
If you want to select something by id, you could do this:
```
var myData = {};
myData[4] = 2;
myData[3] = 1;
$("#myitem").data("mydata", myData);
```
Then you can access your settings like this:
```
var value = $("#myitem").data("mydata")[3]; // returns 1
``` | I haven't got a great amount of time to try it now, but instead of storing a simple string against the key, why not store an object against it?
To paraphrase the jquery docs...
```
$("div").data("blah", {id: 4,setting: 2});
var myBlah = $("div").data("blah");
var id = myBlah["id"];
var setting = myBlah["setting"];
```
Let me know how you get on. | Using jQuery.data to store a list of items | [
"",
"javascript",
"jquery",
"list",
""
] |
I have an application that writes to a folder on the C:\ drive. The program works fine on my computer, but on another laptop when running the .exe (The other laptop has no visual studio etc.), i get a filenotfoundexception and i cannot pinpoint the line of code where this happens from the error report.
Here is the code for creating the directory (assuming this is the issue)
```
try
{
WriteDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\SMS Notifier\");
if (!WriteDirectory.Exists)
WriteDirectory.Create();
}
catch (Exception e)
{
throw e;
}
```
Any ideas what the problem could be?
Should i check for write permission ?!
Help greatly appreciated! | My guess is that this isn't the real issue; neither [DirectoryInfo.Create](http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.create%28VS.71%29.aspx) nor
[Directory.CreateDirectory](http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory%28VS.71%29.aspx) throw a FileNotFoundException.
Best bet is to build the app for debug, then copy the file along with all it's .pdb files; hopefully this'll give you the methods and line numbers in your error message.
You might also consider adding a handler for any unhandled exception; the [AppDomain.UnhandledException](http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception%28VS.85%29.aspx) can be handled so that you can add your own event handler for any unhandled exception running anywhere in the app;
Add something like this to your Main function;
```
System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
```
And then write your own handler for the error;
```
static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
}
``` | If you deploy the .pdb files along with your .dlls, you will get line numbers in the exception messages!
Your `try..catch` block isn't doing anything useful, all it is doing is swallowing the stack trace so you cannot see what is going on! I'd suggest removing the `try..catch` block entirely.
`throw e;` causes the stack trace to be lost, use `throw;` to preserve it.
Also you should use `System.IO.Path.Combine()` to append the directory root and the sub-directory name, that way you don't have to worry about doing the `\`'s yourself and possibly making a mistake. | C# WriteDirectory Issue | [
"",
"c#",
"io",
""
] |
I'm looking for a function that calculates years from a date in format: 0000-00-00.
Found this function, but it wont work.
```
// Calculate the age from a given birth date
// Example: GetAge("1986-06-18");
function getAge($Birthdate)
{
// Explode the date into meaningful variables
list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);
// Find the differences
$YearDiff = date("Y") - $BirthYear;
$MonthDiff = date("m") - $BirthMonth;
$DayDiff = date("d") - $BirthDay;
// If the birthday has not occured this year
if ($DayDiff < 0 || $MonthDiff < 0)
$YearDiff--;
}
echo getAge('1990-04-04');
```
outputs nothing :/
i have error reporting on but i dont get any errors | Your code doesn't work because the function is not returning anything to print.
As far as algorithms go, how about this:
```
function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet
```
This is the same algorithm (just in PHP) as the accepted answer [in this question](https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c).
A shorter way of doing it:
```
function getAge($then) {
$then = date('Ymd', strtotime($then));
$diff = date('Ymd') - $then;
return substr($diff, 0, -4);
}
``` | An alternative way to do this is with PHP's [DateTime class](http://www.php.net/manual/en/book.datetime.php) which is new as of PHP 5.2:
```
$birthdate = new DateTime("1986-06-18");
$today = new DateTime();
$interval = $today->diff($birthdate);
echo $interval->format('%y years');
```
[See it in action](http://codepad.viper-7.com/RazGDg) | Calculate years from date | [
"",
"php",
"datetime",
""
] |
I have 2 collections, one of available features and one of user features. I would like to delete an item in the available features that contain the featurecode in the other collection but can't find the right syntax.
I've included my current code that doesn't compile (it's complaining that I can't use the "==" operator, my Linq knowledge is minimal)
Is Linq the best way to do this? Any help would be appreciated.
```
AvailableFeatureViewListClass availableFeatures = (AvailableFeatureViewListClass)uxAvailableList.ItemsSource;
UserFeatureListClass userFeatures = (UserFeatureListClass)uxUserFeatureList.ItemsSource;
foreach (UserFeatureClass feature in userFeatures)
{
availableFeatures.Remove(availableFeatures.First(FeatureCode => FeatureCode == feature.FeatureCode));
}
``` | Use `Except` method with a custom `Equals` or `IEqualityComparer` implementation for your type (the type of your collection item is not really obvious):
```
var features = availableFeatures.Except(userFeatures, new FeatureCodeComparer());
```
If the `availableFeatures` is just a collection of integers, you'd just do something like:
```
var features = availableFeatures.Except(userFeatures.Select(x => x.FeatureCode));
``` | Try something like this:
```
var features = (from af in availableFeatures select af.FeatureCode)
.Intersect(from uf in userFeatures select uf.FeatureCode);
``` | Comparing two collections of objects | [
"",
"c#",
"linq",
""
] |
Can you use two regex in preg\_replace to match and replace items in an array?
So for example:
Assume you have:
```
Array
(
[0] => mailto:9bc0d67a-0@acoregroup.com
[1] => mailto:347c6b@acoregroup.com
[2] => mailto:3b3cce0a-0@acoregroup.com
[3] => mailto:9b690cc@acoregroup.com
[4] => mailto:3b7f59c1-4bc@acoregroup.com
[5] => mailto:cc62c936-7d@acoregroup.com
[6] => mailto:5270f9@acoregroup.com
}
```
and you have two variables holding regex strings:
```
$reg = '/mailto:[\w-]+@([\w-]+\.)+[\w-]+/i';
$replace = '/[\w-]+@([\w-]+\.)+[\w-]+/i';
```
can I:
```
preg_replace($reg,$replace,$matches);
```
In order to replace "mailto:9bc0d67a-0@acoregroup.com" with "9bc0d67a-0@acoregroup.com" in each index of the array. | You could try this:
```
$newArray = preg_replace('/mailto:([\w-]+@([\w-]+\.)+[\w-]+)/i', '$1', $oldArray);
```
Haven't tested
See here: <http://php.net/manual/en/function.preg-replace.php> | ```
foreach($array as $ind => $value)
$array[$ind] = preg_replace('/mailto:([\w-]+@([\w-]+\.)+[\w-]+)/i', '$1', $value);
```
EDIT: gahooa's solution is probably better, because it moves the loop inside preg\_replace. | Replacing items in an array using two regular expressions | [
"",
"php",
"regex",
""
] |
I am writing a Java Applet. When run on Windows, I need to be able to get the clients OS version, e.g. Windows XP SP3 or Windows 2000 SP4.
I can currently use the following:
```
String os_name = System.getProperty( "os.name" );
String os_version = System.getProperty( "os.version" );
System.out.println( "Running on " + os_name + "(" + os_version + ")" );
```
And it will output something like "Running on Windows 2000 (5.0)" which is great but I need to be able to get the service pack version too.
Anybody know how I can get the underlying service pack version of a Windows machine from within a Java applet? (Without throwing an AccessControlException, or ideally without having to self sign the applet).
Many thanks in advance. | You can self-sign your java applet:
(stolen from: <http://www.captain.at/programming/java/>)
> Make the certificate:
>
> ```
> keytool -export -alias yourkey -file yourcert.crt
> ```
>
> Now we have to sign the applet:
>
> Just make a \*.bat file including this:
>
> ```
> javac yourapplet.java
> jar cvf yourapplet.jar yourapplet.class
> jarsigner yourapplet.jar yourkey
> ```
>
> The batch-file compiles the applet,
> makes a jar-archive and signs the
> jar-file.
>
> The HTML-code to display the applet:
>
> ```
> <applet code="yourapplet.class" archive="yourapplet.jar" width="600"
> ```
>
> height="500">
>
> Now we are done! The applet is signed
> and if the user accepts the
> certificate, the applet is allowed to
> access local files. If the user
> doesn't agree, you get a
> `java.security.AccessControlException`.
So, as long as you don't mind about this little dialog box... | i think you can get it using the 'sun.os.patch.level' property:
```
String os_sp = System.getProperty( "sun.os.patch.level" );
``` | Get Windows Service Pack Version from Java Applet? | [
"",
"windows",
"applet",
"java",
""
] |
I need to restart the program that im working on after an update has been downloaded except im running into some issues.
If i use CreateProcess nothing happens, if i use ShellExecute i get an 0xC0150002 error and if i use ShellExecute with the command "runas" it works fine. I can start the command prompt fine using CreateProcess and ShellExecute just not the same exe again and dont want to use runas as this will elevate the exe.
Any Ideas?
Windows 7, visual studio 2008 c++
[alt text http://lodle.net/shell\_error.jpg](http://lodle.net/shell_error.jpg)
CreateProcess:
```
char exePath[255];
GetModuleFileName(NULL, exePath, 255);
size_t exePathLen = strlen(exePath);
for (size_t x=exePathLen; x>0; x--)
{
if (exePath[x] == '\\')
break;
else
exePath[x] = '\0';
}
char name[255];
GetModuleFileName(NULL, name, 255);
PROCESS_INFORMATION ProcInfo = {0};
STARTUPINFO StartupInfo = {0};
BOOL res = CreateProcess(name, "-wait", NULL, NULL, false, 0, NULL, exePath, &StartupInfo, &ProcInfo );
```
ShellExecute:
```
char exePath[255];
GetModuleFileName(NULL, exePath, 255);
size_t exePathLen = strlen(exePath);
for (size_t x=exePathLen; x>0; x--)
{
if (exePath[x] == '\\')
break;
else
exePath[x] = '\0';
}
char name[255];
GetModuleFileName(NULL, name, 255);
INT_PTR r = (INT_PTR)ShellExecute(NULL, "runas", name, "-wait", exePath, SW_SHOW);
``` | Ok worked it all out in the end.
The first time my exe ran it used the default paths and as such loaded vld (a leak detector dll) from the default path. However in the exe i modified the dll path to be the bin folder ([app]\bin) when i restarted the exe using CreateProcess it picked up on a different vld dll (this was my mistake) that had incorrect side by side linkage and it was only after looking at event viewer that i worked it out.
Thanks for all your help. | CreateProcess() is an arcane beast. I remember unfondly my first frustrations with it. You should look at the [Microsoft CreateProcess Example](http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx) and the [CreateProcess Page](http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx). (those links likely have a short lifetime, Googling CreateProcess should work just as well).
I can see 3 problems in your code.
StartupInfo must have "cb" set to the structure size:
```
STARTUPINFO StartupInfo = {0};
StartupInfo.cb = sizeof(StartupInfo);
```
The second argument requires both the command and the arguments to form the command line. Your program will see "-wait" as argv[0] and ignore it or pay it no mind.
```
char command[512];
sprintf(command, "%s -wait", name);
BOOL res = CreateProcess(name, command, // and as you had before
```
You don't look at GetLastError() if CreateProcess() fails (by returning a zero). It may have helped you but I suspect it would just say "invalid argument" or somesuch. Hey, there's only 10 of them to check, don't be lazy :-)
Another bug I committed is not closing the hProcess and/or hThread handles return in PROCESS\_INFORMATION when I was done. I did do hProcess, but not hThread. | Trouble restarting exe | [
"",
"c++",
"windows",
""
] |
Is it possible to re-write (Apache Mod-Rewrite) a URL from this:
**`http://www.example.com/view.php?t=h5k6`** to this **`http://www.example.com/h5k6`**
The reason for this re-write is that the URL needs to be very short (a bit like a tiny URL service).
Would that new URL still hit my view.php page? Would it be able to still make use of the super global array GET (`$_GET`) to access the variable `t`? I still want my index.php page to map to this <http://www.example.com>.
I would also appreciate comments on effects this may have as I am a bit of a noob. :)
Thanks all | The terminology of [mod-rewrite](http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html) works the other way. Requests would come in like this `http://www.example.com/h5k6` and would be rewritten to `http://www.example.com/view.php?t=h5k6` internally. That way your PHP scripts can respond to the requests as if they were sent as GET parameters, but users see the URLs in a much friendlier way.
So you don't have to change any PHP scripts, and you can still access the parameter `t` from the GET array.
In your case, the rule would look like this:
```
RewriteRule ^/(.*) /view.php?t=$1
```
You might want to be more specific about what you accept (instead of just the catch-all `.*` expression). Also, you might want exceptions to this rule if you have other pages in this directory other than view.php. | Try one of these:
```
# /view.php?t=h5k6 externally to /h5k6
RewriteCond %{THE_REQUEST} ^GET\ /view\.php
RewriteCond %{QUERY_STRING} ^([^&]*&)*t=([^&]+)&?.*$
RewriteRule ^/view\.php$ /%2 [L,R=301]
# /h5k6 internally to /view.php?t=h5k6
RewriteRule ^/([0-9a-z]+)$ view.php?t=$1 [L]
``` | Can I re-write my URLs like this and is it a good idea? | [
"",
"php",
"apache",
"mod-rewrite",
""
] |
This is a really esoteric question, but I'm genuinely curious. I'm using usort for the first time today in years, and I'm particularly interested in what exactly is going on. Suppose I've got the following array:
```
$myArray = array(1, 9, 18, 12, 56);
```
I could sort this with usort:
```
usort($myArray, function($a, $b){
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
});
```
I'm not 100% clear about what is going on with the two parameters $a and $b. What are they, and what do they represent. I mean, I could assume that $a represents the current item in the array, but what exactly is this getting compared to? What is $b?
I could increase my array to include strings:
```
$myArray = array(
array("Apples", 10),
array("Oranges", 12),
array("Strawberries", 3)
);
```
And run the following:
```
usort($myArray, function($a, $b){
return strcmp($a[0], $b[0]);
});
```
And that would sort my child-arrays alphabetically based upon the [0] index value. But this doesn't offer any clarity about what $a and $b are. I only know that the match the pattern that I'm seeking.
Can somebody offer some clarity about what is actually taking place? | To sort anything you need a means to compare two items and figure out if one comes before the other. This is what you supply to usort. This function will be passed two items from your input array, and returns the order they should be in.
Once you have a means to compare two elements, you can use *sort-algorithm-of-your-choice*.
If you are unfamiliar, you might like to look at how a simple naive algorithm like [bubblesort](http://en.wikipedia.org/wiki/Bubble_sort) would use a comparison function.
Behind the scenes, PHP is using a [quicksort](http://en.wikipedia.org/wiki/Quicksort). | The exact definition of $a and $b will depend upon the algorithm used to sort the array. To sort anything you have to have a means to compare two elements, that's what the callback function is used for. Some sorting algorithms can start anywhere in the array, others can start only in a specific part of it so there's no *fixed* meaning in $a and $b other than they are two elements in the array that have to be compared according to the current algorithm.
This method can be used to shed light upon which algorithm PHP is using.
```
<?php
$myArray = array(1, 19, 18, 12, 56);
function compare($a, $b) {
echo "Comparing $a to $b\n";
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
}
usort($myArray,"compare");
print_r($myArray);
?>
```
Output
```
vinko@mithril:~$ php sort.php
Comparing 18 to 19
Comparing 56 to 18
Comparing 12 to 18
Comparing 1 to 18
Comparing 12 to 1
Comparing 56 to 19
Array
(
[0] => 1
[1] => 12
[2] => 18
[3] => 19
[4] => 56
)
```
From the output and looking at the source we can see the sort used is indeed a [quicksort](http://en.wikipedia.org/wiki/Quicksort) implementation, check for [Zend/zend\_qsort.c](http://www.google.com/codesearch/p?hl=en&sa=N&cd=1&ct=rc#6UjLvTvd8FQ/php-4.4.4/Zend/zend_qsort.c&q=zend_qsort.c) in the PHP source (the linked to version is a bit old, but hasn't changed much).
It picks the pivot in the middle of the array, in this case 18, then it needs to reorder the list so that all elements which are less (according to the comparison function in use) than the pivot come before the pivot and so that all elements greater than the pivot come after it, we can see it doing that when it compares everything to 18 at first.
Some further diagrammatic explanation.
```
Step 0: (1,19,18,12,56); //Pivot: 18,
Step 1: (1,12,18,19,56); //After the first reordering
Step 2a: (1,12); //Recursively do the same with the lesser, here
//pivot's 12, and that's what it compares next if
//you check the output.
Step 2b: (19,56); //and do the same with the greater
``` | PHP's USORT Callback Function Parameters | [
"",
"php",
"usort",
""
] |
How would you check if a String was a number before parsing it? | With [Apache Commons Lang](http://commons.apache.org/lang/) 3.5 and above: [`NumberUtils.isCreatable`](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/math/NumberUtils.html#isCreatable-java.lang.String-) or [`StringUtils.isNumeric`](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isNumeric-java.lang.CharSequence-).
With [Apache Commons Lang](http://commons.apache.org/lang/) 3.4 and below: [`NumberUtils.isNumber`](https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/math/NumberUtils.html#isNumber(java.lang.String)) or [`StringUtils.isNumeric`](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isNumeric-java.lang.CharSequence-).
You can also use [`StringUtils.isNumericSpace`](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isNumericSpace-java.lang.CharSequence-) which returns `true` for empty strings and ignores internal spaces in the string. Another way is to use [`NumberUtils.isParsable`](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-) which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.) | This is generally done with a simple user-defined function (i.e. Roll-your-own "isNumeric" function).
Something like:
```
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
```
However, if you're calling this function a lot, and you expect many of the checks to fail due to not being a number then performance of this mechanism will not be great, since you're relying upon exceptions being thrown for each failure, which is a fairly expensive operation.
An alternative approach may be to use a regular expression to check for validity of being a number:
```
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
```
Be careful with the above RegEx mechanism, though, as it will fail if you're using non-Arabic digits (i.e. numerals other than 0 through to 9). This is because the "\d" part of the RegEx will only match [0-9] and effectively isn't internationally numerically aware. (Thanks to OregonGhost for pointing this out!)
Or even another alternative is to use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string. If it is, we can assume the entire string is numeric:
```
public static boolean isNumeric(String str) {
ParsePosition pos = new ParsePosition(0);
NumberFormat.getInstance().parse(str, pos);
return str.length() == pos.getIndex();
}
``` | How to check if a String is numeric in Java | [
"",
"java",
"string",
"numeric",
""
] |
How to set blank default text on input field and clear it when element is active. | In modern browsers, you may set the `placeholder` attribute on a field to set its default text.
```
<input type="text" placeholder="Type some text" id="myField" />
```
However, in older browsers, you may use JavaScript to capture the focus and blur events:
```
var addEvent = function(elem, type, fn) { // Simple utility for cross-browser event handling
if (elem.addEventListener) elem.addEventListener(type, fn, false);
else if (elem.attachEvent) elem.attachEvent('on' + type, fn);
},
textField = document.getElementById('myField'),
placeholder = 'Type some text'; // The placeholder text
addEvent(textField, 'focus', function() {
if (this.value === placeholder) this.value = '';
});
addEvent(textField, 'blur', function() {
if (this.value === '') this.value = placeholder;
});
```
Demo: <http://jsbin.com/utecu> | Using the `onFocus` and `onBlur` events allows you to achieve this, I.e.:
```
onfocus="if(this.value=='EGTEXT')this.value=''"
```
and
```
onblur="if(this.value=='')this.value='EGTEXT'"
```
The full example is as follows:
```
<input name="example" type="text" id="example" size="50" value="EGTEXT" onfocus="if(this.value=='EGTEXT')this.value=''" onblur="if(this.value=='')this.value='EGTEXT'" />
``` | Default text on input | [
"",
"javascript",
"html",
"textinput",
""
] |
I'm building a concert calendar that's very heavy on javascript (using jQuery). I'm having trouble synchronizing various events throughout the app, and I'm looking for suggestions for how to do this.
An example of a simple use case:
1. User clicks a month
2. Calendar skips to that month
An example of a more complex use case:
1. User selects an artist
2. Calendar determines the date of that artist's first show
3. Calendar skips to that month
4. Calendar highlights that artist's show(s)
One occasional problem is that the new month isn't yet rendered by the time I try to highlight the artist's show(s). Thus, the show isn't highlighted even though these functions are called in order. Obviously, using setTimeout() is pretty hacky, and not guaranteed to work.
So first, a simple question -- would it ever be possible (even in Chrome) for the following function to run out of sequence?
```
function steps(){
stepOne(); //TAKES 30 SECONDS
stepTwo(); //TAKES < 1 SECOND
}
```
Second, a related simple question:
```
If placed at the end of a function, will a JS callback ALWAYS run after
everything else in the given function has finished running?
```
If so, I *could* nest each function as a callback of its previous function. But that would likely become unwieldy, once you consider all the different use cases.
Here's an approach I'm considering:
```
1) Allow each function an optional callback parameter. If it's present,
call it at the very end of the function.
2) During a UI refresh, create an array, and stack any functions to be
called within this array.
3) Once this "script" is completed, iterate through the array, calling
each function in the order it was added, using the next function
as the previous function's callback.
```
I imagine this would ensure that all the functions are called in order.
Another approach is to attach event listeners using
```
$(document).bind("listener.name", fnCallback);
```
And then calling
```
$(document).trigger("listener.name");
```
Whenever that event occurs.
However, I'm guessing this would be kind of unwieldy as well, considering different events might need to call different sets of functions depending on the use case. I could always call
```
$(document).unbind("listener.name");
```
before adding new events to it, but again -- I'm leaning toward creating sort of a master "script" as I suggested in the first approach.
Hopefully this isn't too vague -- any feedback? Any experience with complex UIs that had to synchronize various events?
Thanks very much,
Michael | Your approach #1 is the best way, and the most natural using jQuery. Most functions that act on the user interface and do something accept a callback function parameter, which gets called after the function has executed.
Where you are doing things not implemented in jQuery following the same pattern will make your code more readable. dominic's answer is a good terse example:
```
function steps(){
stepOne(stepTwo);
}
function stepOne(callback){
var AsyncDone = function() {
//any Synchronus Things here
callback();
}
someAsyncFunction( params, AsyncDone );
}
``` | The last approach, of using custom events, is the best approach in my humble opinion.
Design various components and events and let them interact with each other.
E.g. Let's say you have a Calendar object.
```
var calendar = function()
{
var pub = {};
pub.highlightRow = function(row) {};
pub.getRowByContent = function(content) { };
pub.selectMonth = function()
{
//your code to actually select month.
//Once all the necessary DOM work is done, fire the
//monthSelected event (namespacing the event so as to avoid the clash with other events).
$(document).trigger('calendar:monthSelected');
};
return pub;
}();
```
Now your artist search method may look like,
```
function searchArtist(artistName)
{
$(document).bind('calendar:monthSelected'), function()
{
calendar.highlightRow(calendar.getRowByContent(artistName));
}
);
calendar.selectMonth(getShowMonthByArtist(artistName));
}
``` | Javascript Event Synchronization | [
"",
"javascript",
"jquery",
"synchronization",
"events",
""
] |
Suppose I am designing a class that can handle any database technology to create a connection, execute command and retrieve data, etc.
If I need to create a generic database handling class for existing RDBMSs (like SQL Server, Oracle, FireBird, et.), which .net abstract-class/Interface should I use {DbConnection, DbCommand, DbParameter,...} or {IDbConnection, IDbCommand, IDbParameter,...}?
Should I use the code like
```
public bool CreateConnection(DatabaseTypeEnum type)
{
DbConnection conn ;
if(type==DatabaseTye.Oracle)
{
//....
}
}
public DbDataReader GetData()
{
DbCommand comm;
//...
}
```
or,
```
public bool CreateConnection(DatabaseTypeEnum type)
{
IDbConnection conn ;
if(type==DatabaseTye.Oracle)
{
//....
}
}
public IDbDataReader GetData()
{
IDbCommand comm;
//...
}
```
And, Why? | Ermm... totally different question :)
OK, neither...
You are going to violate Open Close Principle when you do that... The switch / if statement in that particular place is making me uncomfortable :).
I'd leave the actual creation to a Factory class and your code should not care if it is talking to a SQL Server or DB2 or Oracle or whatever.
Ideally, your code should only talk to IDbConnection, IDbCommand, etc. or the abstract base class (DbConnection, DbCommand, etc.). Sometimes I do find that you need to upcast to a specific provider tho (like SqlDataReader for using specific methods), but it is quite rare.
The Factory will encapsulate this switch / if statement to a single place so it's easily maintainable. You can further abstract the actual creation in a app.config. So in app.config you choose what type of DB backend you are supporting and the Factory will pick it up from there and create the necessary DB stuffs for you.
See: [this](http://msdn.microsoft.com/en-us/library/dd0w4a2z(VS.80).aspx). Read about Creating DbProviderFactory and Connection part... | Why don't you use generics?
You can define your class like this for example:
```
public class DBHelper<T, Y, W> where T: DbConnection, new() where Y : DbCommand, new()
{
private T conn_ = new T();
private Y comm_ = new Y();
}
```
That's what I do to and its really easy to maintain. | C# - A class for Generic database connection, command, reader | [
"",
"c#",
"ado.net",
""
] |
I'm trying to understand the `Repository Pattern`, while developing an ASP.NET MVC application (using .NET 3.5, ASP.NET MVC 1.0 and Entity Framework). I've gotten far enough to get the dependency injection and all working with one Controller and one Entity type, but now I've gotten as far as to implementing support for a relation between different types, and I'm stuck.
In all examples I've seen, the repository interface is called something like `IContactsRepository`, and contains (CRUD) methods that are concerned with `Contact` items only. I want to implement grouping of `Contacts`, so I have an entity type called `Group`, and an `IGroupRepository` interface for handling (CRUD) operations on groups.
* Where does a method belong that is concerned with more than one entity type (in this case for example the method `AddToGroup`, that adds a `Contact` to a `Group`)?
I made an attempt at a larger inheritance structure for repositories, where I created the following interfaces:
```
ITypedRepository<T>
{
IEnumerable<T> GetAll();
T Get(int id);
bool Add(T newObj);
bool Edit(T editedObj);
bool Delete(int id);
}
IContactsRepository : ITypedRepository<Contact> { }
IGroupsRepository : ITypedRepository<Group> {
bool AddToGroup(int contactId, int groupId);
}
IRepository : IContactsRepository, IGroupsRepository
```
I then tried to create a master repository that inherits `IRepository`, as follows:
```
public class EntitiesRepository : IRepository
{
IEnumerable<Contact> IRepository<Contact>.Get()
{
throw new NotImplementedException();
}
IEnumerable<Group> IRepository<Group>.Get()
{
throw new NotImplementedException();
}
// Etc. All methods were generated by hitting [Ctrl]+[.] with the cursor on
// the interface inheritance reference to IRepository and selecting
// "Explicitly implement IRepository"
}
```
As soon as I try to call one of the methods in the Repository from my Controller with this code
```
var contacts = _repository.Get();
```
I get a build error message about ambiguity between `Get<Contact>()` that was inherited via `IContactsRepository` and `Get<Group>()` that came via `IGroupsRepository`. I have understood that this is not allowed because the `IRepository` [inherits the same generic interface with different types](http://www.codeguru.com/csharp/sample_chapter/article.php/c11637__2/) (see example 5 in the linked article).
* Now, since I inherit via other interfaces, is there any chance I could "override the names" of these methods, for example like below?
```
IContactsRepository : ITypedRepository<Contact>
{
IEnumerable<Contact> GetContacts = ITypedRepository<Contact>.Get();
...
}
```
That way, I can access it from `IRepository.Getcontacts` without any ambiguity. Is it possible, or is there any workaround to this problem?
And a new question, for clarification:
* Is there anyway to specify in the call from the controller which of the `Get()` methods I want?
* What is the best way to tackle my initial problem - the need of a repository that handles a lot of things, instead of just one entity type?
**EDIT:** Added code example of `Repository` class and call from `Controller`. | I think you don't need all this complexity. When you add a contact to a group you are changing the group. I assume you have a collection of contacts on Group class. After adding a contact into a group, simply you need to save the group. So do you really need a AddContactToGroup method, just a Save method on Group repository interface would do the same job. Also you don't need a new method for every new relational property on Group.
For the implementation of the Save method itself, if you use NHibernate, only thing you need to do is to call relevant method. | You will probably have specialized methods on your IGroupRepository in addition to the CRUD methods:
```
IGroupRepository : ITypedRepository<Group>
{
bool AddContactToGroup(Group g, Contact C);
}
``` | "Rename" inherited methods in interface in C# | [
"",
"c#",
"design-patterns",
"interface",
"repository-pattern",
"multiple-inheritance",
""
] |
I compiled the following code as a shared library using `g++ -shared ...`:
```
class Foo {
public:
Foo() {}
virtual ~Foo() = 0;
virtual int Bar() = 0;
};
class TestFoo : public Foo {
public:
int Bar() { return 0; }
};
extern "C" {
Foo* foo;
void init() {
// Runtime error: undefined symbol: _ZN3FooD2Ev
foo = new TestFoo(); // causes error
}
void cleanup() { delete(foo); }
void bar() { foo->Bar(); }
}
```
The point is to expose the functionality of my classes (here just minimal toy classes as an example) as a simple `C` API with the three functions `init`, `cleanup`, and `bar`.
When I try to load the shared library (using `dyn.load` in `R`) I get an error:
```
unable to load shared library 'test.so':
test.so: undefined symbol: _ZN3FooD2Ev
```
So, it seems it cannot find the `Foo` constructor. What am I doing wrong and how can this be fixed?
*UPDATE*: Thanks, jbar! So it was the `Foo` *de*structor. Could I have known this from the cryptic symbol in the error message: `_ZN3FooD2Ev`? Does the `D` in `FooD` stand for destructor? | We can't declare pure virtual destructor. Even if a virtual destructor is declared as pure, it will have to implement an empty body (at least) for the destructor. | > UPDATE: So it was the Foo destructor. Could I have known this from the cryptic symbol in the error message: \_ZN3FooD2Ev? Does the D in FooD stand for destructor?
You can use the program c++filt.
So c++filt \_ZN3FooD2Ev returns "Foo::~Foo()". | Undefined symbol error for base class in C++ shared library | [
"",
"c++",
"compilation",
"linker-errors",
"shared-libraries",
"undefined-symbol",
""
] |
I want to write a long running process (linux daemon) that serves two purposes:
* responds to REST web requests
* executes jobs which can be scheduled
I originally had it working as a simple program that would run through runs and do the updates which I then cron’d, but now I have the added REST requirement, and would also like to change the frequency of some jobs, but not others (let’s say all jobs have different frequencies).
I have 0 experience writing long running processes, especially ones that do things on their own, rather than responding to requests.
My basic plan is to run the REST part in a separate thread/process, and figured I’d run the jobs part separately.
I’m wondering if there exists any patterns, specifically python, (I’ve looked and haven’t really found any examples of what I want to do) or if anyone has any suggestions on where to begin with transitioning my project to meet these new requirements.
I’ve seen a few projects that touch on scheduling, but I’m really looking for real world user experience / suggestions here. What works / doesn’t work for you? | * If the REST server and the scheduled jobs have nothing in common, do two separate implementations, the REST server and the jobs stuff, and run them as separate processes.
* As mentioned previously, look into existing schedulers for the jobs stuff. I don't know if [Twisted](http://twistedmatrix.com/trac/ "Twisted") would be an alternative, but you might want to check this platform.
* If, OTOH, the REST interface invokes the same functionality as the scheduled jobs do, you should try to look at them as two interfaces to the same functionality, e.g. like this:
+ Write the actual jobs as programs the REST server can fork and run.
+ Have a separate scheduler that handles the timing of the jobs.
+ If a job is due to run, let the scheduler issue a corresponding REST request to the local server.
This way the scheduler only handles job descriptions, but has no own knowledge how they are implemented.
* It's a common trait for long-running, high-availability processes to have an additional "supervisor" process that just checks the necessary demons are up and running, and restarts them as necessary. | One option is to simply choose a lightweight WSGI server from this list:
* <http://wsgi.org/wsgi/Servers>
and let it do the work of a long-running process that serves requests. (I would recommend [Spawning](http://pypi.python.org/pypi/Spawning/0.7).) Your code can concentrate on the REST API and handling requests through the well defined WSGI interface, and scheduling jobs.
There are at least a couple of scheduling libraries you could use, but I don't know much about them:
* <http://sourceforge.net/projects/pycron/>
* <http://code.google.com/p/scheduler-py/> | python long running daemon job processor | [
"",
"python",
"web-services",
"scheduling",
"long-running-processes",
""
] |
Oracle `START WITH ... CONNECT BY` clause is applied **before** applying `WHERE` condition in the same query. Thus, WHERE constraints won't help optimize `CONNECT BY`.
For example, the following query will likely perform full table scan (ignoring selectivity on `dept_id`):
```
SELECT * FROM employees
WHERE dept_id = 'SALE'
START WITH manager_id is null
CONNECT BY PRIOR employee_id = manager_id
```
I tried to improve performance in 2 ways:
query A:
```
SELECT * FROM employees
START WITH manager_id is null AND dept_id = 'SALE'
CONNECT BY PRIOR employee_id = manager_id
```
query B:
```
SELECT * FROM (
SELECT * FROM employees
WHERE dept_id = 'SALE'
)
START WITH manager_id is null
CONNECT BY PRIOR employee_id = manager_id
```
While both queries did much better than original, on Oracle 10g Release 2, query B did performed much better than A.
Did you have similar performance optimization to deal with with respect to `CONNECT BY` and `WHERE` clauses? How would you explain query B doing much better than query A? | Query A says start with managers in the Sales department and then get all their employees. Oracle doesn't "know" that **all** the employees returned be the query will be in the Sales department, so it can't use that information to reduce the set of data to work with before performing the CONNECT BY.
Query B **explicitly** reduces the set of data to be worked on to just those employees in Sales, which Oracle can then do before performing the CONNECT BY. | This should give the ultimate performance:
```
CREATE INDEX i_employees_employee_manager_dept ON employees (employee_id,manager_id,dept_id);
CREATE INDEX i_employees_manager_employee_dept ON employees (manager_id,employee_id,dept_id);
SELECT * FROM employees
START WITH manager_id is null AND dept_id = 'SALE'
CONNECT BY PRIOR employee_id = manager_id AND dept_id = 'SALE'
```
Note that you do need both index and both `AND` conditions for the optimization to work. | Optimizing Oracle CONNECT BY when used with WHERE clause | [
"",
"sql",
"performance",
"oracle",
"select",
"query-optimization",
""
] |
I have used valgrinds massif tool to monitor memory usage in the past.
Does anyone know how to capture memory use of php processes that are spawned on a linux lighttpd server?
I have found that Valgrind can not attach to a prerunning process (and I would not know the PID of the php process before hand anyway)
I only see lighttpd's memory usage, not the PHP processes that are spawned by lighttpd cgi module.
Thanks in advance. | PHP has it's own memory testing functions, I don't know if that's any use to you, but if you just want to log it you could use:
<http://php.net/manual/en/function.memory-get-peak-usage.php>
```
echo "Using ", memory_get_peak_usage(1), " bytes of ram.";
``` | Can't you use the 'ps' tool?
```
$ ps -F -C php-cgi
UID PID PPID C SZ RSS PSR STIME TTY TIME CMD
http 10794 10786 0 4073 228 0 Jun09 ? 00:00:00 /usr/bin/php-cgi
http 10795 10794 0 4073 28 0 Jun09 ? 00:00:00 /usr/bin/php-cgi
http 10796 10786 0 4073 228 0 Jun09 ? 00:00:00 /usr/bin/php-cgi
http 10797 10796 0 4613 3544 0 Jun09 ? 00:00:00 /usr/bin/php-cgi
...
```
RSS is the *Real-memory (resident set) size in kilobytes of the process.*
To sum it all up in bash (a bit rusty sorry)
```
#!/bin/bash
total=0
for i in `ps -C php-cgi -o rss=`
do
total=$(($total + $i))
done
echo "Memory usage: $total kb"
# Output: Memory usage: 4540 kb
```
One liner:
```
total=0; for i in `ps -C php-cgi -o rss=`; do total=$(($total+$i)); done; echo "Memory usage: $total kb";
```
I know the reliability of the memory part in *ps* is questioned but at least it gives you an idea of what the usage is like. | How can I monitor memory usage of php in linux? | [
"",
"php",
"memory",
"valgrind",
""
] |
I came across this term - Quine (also called self-reproducing programs). Just wanted to know more on it. How does one write a quine and are they used anywhere or they are just an exercise for fun?
I've started with Python, and I might try writing one in Python. Any suggestions? | Quines are useless in a practical sense, but they're a great exercise to help you learn more about a language.
Here's a very concise one in python:
```
a='a=%r;print a%%a';print a%a
``` | At a minimum, quines are programs which produce their own source as their output. They are a necessary step in constructing [Gödel's proof on incompleteness](http://en.wikipedia.org/wiki/G%C3%B6del%27s_incompleteness_theorems).
Whether this constitutes a practical use is something I offer no comment on. | What are quines? Any specific purpose to have them? | [
"",
"python",
"quine",
""
] |
I'm creating an FAQ page where the answer is toggled by clicking on the question. The question is `h3` and the answer is several `p`-elements. Like this:
```
<h3>The First Question</h3>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
<h3>The Second Question</h3>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
```
How can I toggle all `p`-elements belonging to a certain question? My JS toggles all following `p`-elements on the page:
```
$(document).ready(function(){
$("p").hide();
$("h3").click(function(){
$(this).nextAll("p").toggle();
});
});
```
I cannot use `div`'s or classes). | The best way to do this is using each and iterating until you get to the next element that should stop the iteration. Returning false during an each stops the iteration. Using filter allows you to check the type of the element in the iteration and respond appropriately.
```
$(function() {
$("p").hide();
$("h3").click(function() {
$(this).nextAll().each( function() {
if ($(this).filter('h3').length) {
return false;
}
$(this).filter('p').toggle();
});
});
});
``` | I would do it this way:
```
$(function() {
$("p").hide();
$("h3").click(function() {
$(this).nextAll().each(function() {
if ($(this).is('h3')) {
return false;
}
$(this).toggle();
});
});
});
```
Returning false from each() ends the chain.
I would also suggest, if possible, structuring your data better to handle this scenario. For example:
```
<h3 class="question">Why is there no soup for me?</h3>
<div class="answer">
<p>...</p>
<p>...</p>
<p>...</p>
</div>
```
and then the problem becomes trivial to solve:
```
$(function() {
$("div.answer").hide();
$("h3.question").click(function() {
$(this).next().toggle();
});
});
``` | jQuery nextAll -- Click on h-element toggles all p-elements until next h | [
"",
"javascript",
"jquery",
"toggle",
""
] |
Up until now we used Ant in my company. Whenever we wanted to send the application to the client we run a special Ant script that packaged all our source code with all jar libraries and Ant itself along with a simple batch file.
Then the client could put the files on a computer with no network access at all (and not even Ant) and run the batch file. As long as the computer had a valid JDK the batch script would compile all the code using the jars and create a WAR/EAR that would finally be deployed by the client on the application server.
Lately we migrated to Maven 2. But I haven't found a way to do the same thing. I have seen the Maven assembly plugin but this just creates source distributions or binary ones. Our scenario is actually a mix since it contains our source code but binary jars of the libraries we use (e.g. Spring, Hibernate)
So is it possible to create with Maven a self-contained assembly/release/package that one can run in a computer with no network access at all??? That means that all libraries should be contained inside.
Extra bonus if Maven itself is contained inside as well, but this is not a strict requirement. The final package should be easily compiled by just one command (easy for a system administrator to perform).
I was thinking of writing my own Maven plugin for this but I suspect that somebody has already encountered this. | You might try this approach:
* Use mvn ant:ant to create ant build
scripts from a maven project
* Make sure ant is a project dependency
* Use the assembly to build an ant
system
or plan b:
* Use mvn ant:ant to create ant build
scripts from a maven project
* Make sure ant is a project dependency
* Write a "bootstrap class" to call Ant and run the build
* Use [appassembler](http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/) to build a
scripted build and install environment
In plan b, you'd write scripts to set up a source tree someplace from the packaged source jars, and then use the appassembler build bat or sh scripts to call the bootstrap and build via ant. Your bootstrap can do anything you need to do before or after the build.
Hope this helps. | From your dev environment, if you include the following under build plugins
```
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
```
and invoke mvn assembly:assembly, you would get yourApp-version-with-dependencies.jar in the target folder. This is a self-sufficient jar, and with a Main-class MANIFEST.MF entry, anybody can double click and run the application. | Creating a self-contained source release with Maven | [
"",
"java",
"maven-2",
"migration",
"release",
"self-contained",
""
] |
In short, I am wondering if there is an auto\_ptr like type for arrays. I know I could roll my own, I'm just making sure that there isn't already something out there.
I know about vectors as well. however I don't think I can use them. I am using several of the Windows APIs/SDKs such as the Windows Media SDK, Direct Show API which in order to get back some structures to call a function which takes a pointer and a size twice. The first time passing NULL as the pointer to get back the size of the structure that I have to allocated in order to receive the data I am looking for. For example:
```
CComQIPtr<IWMMediaProps> pProps(m_pStreamConfig);
DWORD cbType = 0;
WM_MEDIA_TYPE *pType = NULL;
hr = pProps->GetMediaType(NULL, &cbType);
CHECK_HR(hr);
pType = (WM_MEDIA_TYPE*)new BYTE[cbType]; // Would like to use auto_ptr instread
hr = pProps->GetMediaType(pType, &cbType);
CHECK_HR(hr);
// ... do some stuff
delete[] pType;
```
Since cbType typically comes back bigger than sizeof(WM\_MEDIA\_TYPE) due to the fact is has a pointer to another structure in it, I can't just allocate WM\_MEDIA\_TYPE objects. Is there anything like this out there? | Use
```
std::vector<BYTE> buffer(cbType);
pType = (WM_MEDIA_TYPE*)&buffer[0];
```
or since **C++11**
```
std::vector<BYTE> buffer(cbType);
pType = (WM_MEDIA_TYPE*)buffer.data();
```
instead.
---
Additional:
If someone is asking if the [Vectors are guaranteed to be contiguous](http://herbsutter.wordpress.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/) the answer is **Yes** since C++ 03 standard. There is another [thread](https://stackoverflow.com/questions/849168/are-stdvector-elements-guaranteed-to-be-continguous) that already discussed it.
---
If **C++11** is supported by your compiler, unique\_ptr can be used for arrays.
```
unique_ptr<BYTE[]> buffer(new BYTE[cbType]);
pType = (WM_MEDIA_TYPE*)buffer.get();
``` | boost [`scoped_array`](http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/scoped_array.htm) or you can use boost [`scoped_ptr`](http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/scoped_ptr.htm) with a custom deleter | auto_ptr for arrays | [
"",
"c++",
"arrays",
"memory-management",
""
] |
I have the 'luck' of develop and enhance a legacy python web application for almost 2 years. The major contribution I consider I made is the introduction of the use of unit test, nosestest, pychecker and CI server. Yes, that's right, there are still project out there that has no single unit test (To be fair, it has a few doctest, but are broken).
Nonetheless, progress is slow, because literally the coverage is limited by how many unit tests you can afford to write.
From time to time embarrassing mistakes still occur, and it does not look good on management reports. (e.g. even pychecker cannot catch certain "missing attribute" situation, and the program just blows up in run time)
I just want to know if anyone has any suggestion about what additional thing I can do to improve the QA. The application uses WebWare 0.8.1, but I have expermentially ported it to cherrypy, so I can potentially take advantage of WSGI to conduct integration tests.
Mixed language development and/or hiring an additional tester are also options I am thinking.
Nothing is too wild, as long as it works. | Feather's [great book](https://rads.stackoverflow.com/amzn/click/com/0131177052) is the first resource I always recommend to anybody in your situation (wish I had it in hand before I faced it my first four times or so!-) -- not Python specific but a lot of VERY useful general-purpose pieces of advice.
Another technique I've been happy with is [fuzz testing](http://en.wikipedia.org/wiki/Fuzz_testing) -- low-effort, great returns in terms of catching sundry bugs and vulnerabilitues; check it out!
Last but not least, if you do have the headcount & budget to hire one more engineer, please do, but make sure he or she is a "software engineer in testing", NOT a warm body banging at the keyboard or mouse for manual "testing" -- somebody who's rarin' to write and integrate all sorts of *automated* testing approaches as opposed to spending their days endlessly repeating (if they're lucky) the same manual testing sequences!!!
I'm not sure what you think mixed language dev't will buy you in terms of QA. WSGI OTOH *will* give you nice bottlenecks/hooks to exploit in your forthcoming integration-test infrastructure -- it's good for that (AND for sundry other things too;-). | Automated testing seems to be as a very interesting approach. If you are developping a web app, you may be interested in WebDriver <http://code.google.com/p/webdriver/> | Looking for testing/QA idea for Python Web Application Project | [
"",
"python",
"testing",
"integration-testing",
""
] |
I wanted to develop one HTTP example on win32 platform, which is asynchronous.
I am new to win32 programming, what are the api and library win32 platform provides for HTTP send and receive request? I am using Windows XP with VS 2005.
If any example is available please provide a link to it. | You can use WinHTTP library. [Here](http://msdn.microsoft.com/en-us/library/aa383138%28VS.85%29.aspx) is an sample on Asynchronous completion. | [Window HTTP Services](http://msdn.microsoft.com/en-us/library/aa384273(VS.85).aspx) "provides developers with an HTTP client application programming interface (API) to send requests through the HTTP protocol to other HTTP servers."
[HTTP Server API](http://msdn.microsoft.com/en-us/library/aa364510(VS.85).aspx) "enables applications to communicate over HTTP without using Microsoft Internet Information Server (IIS)" | HTTP client example on win32 | [
"",
"c++",
"windows",
"http",
"asynchronous",
"windows-xp",
""
] |
The simple code block below can be served up in a static HTML page but results in a JavaScript error. How should you escape the embedded double quote in the `onClick` handler (i.e. "xyz)? Note that the HTML is generated dynamically by pulling data from a database, the data of which is snippets of other HTML code that could have either single or double quotes. It seems that adding a single backslash ahead of the double quote character doesn't do the trick.
```
<script type="text/javascript">
function parse(a, b, c) {
alert(c);
}
</script>
<a href="#x" onclick="parse('#', false, '<a href=\"xyz'); return false">Test</a>
``` | Did you try
**`"`** or **`\x22`**
instead of
```
\"
```
? | It needs to be HTML-escaped, not Javascript-escaped. Change `\"` to **`"`** | Escaping double quotes in JavaScript onClick event handler | [
"",
"javascript",
"html",
"escaping",
"dom-events",
""
] |
I'm trying to return a reference to an object, not pass it by value. This is due to not being able to pass a property by reference.
How can I get the code below to write 'new number plate' not 'old number plate'. After a bit of looking it seems like I cant. Just wanted to be sure first. Seems odd you cant.
Cheers
Steve
<http://hardcode.ro/archive/2008/03/18/c-return-reference-types.aspx>
[Link](https://web.archive.org/web/20200221092055/http://geekswithblogs.net:80/akraus1/archive/2006/02/10/69047.aspx)
```
public partial class Test2 : DefaultPage
{
protected void Page_Load(object sender, EventArgs e)
{
var car = new Car();
var numberPlate = car.GetNumberPlate();
numberPlate = "new number plate";
Response.Write(car.GetNumberPlate());
}
}
}
public class Car
{
private string _numberPlate;
public Car()
{
_numberPlate="old number plate";
}
public string NumberPlate
{
get { return _numberPlate; }
set { _numberPlate = value;}
}
public string GetNumberPlate()
{
return _numberPlate;
}
}
``` | You need to become clearer in your mind about the difference between objects and references. Your property *already* returns a reference to the string containing the current numberplate. It can't possibly return the object itself, because string is a reference type. (Even if you used a value type, the property would only be returning a *copy* of the data, so change to the variable's value still wouldn't affect the property.)
What you seem to want isn't a reference to the *object* but a reference to the *property*. There's no way of doing that in C# - and this is a good thing in my view, as it promotes readability. The kind of code you're trying to write in your example is much more complicated to understand, because assigning a value to a normal variable could do anything.
For more information, see my [article about value types and reference types](http://pobox.com/~skeet/csharp/references.html). | You're doing this a little backwards. If you want to change the value for that you need to actually change the property on the object.
```
car.NumberPlate = "old number plate";
Response.Write(car.GetNumberPlate());
```
If you're wanting to work with references you can use the *ref* keyword. This may not be what you're looking for though. | Returning a reference to an object | [
"",
"c#",
""
] |
I am using [Komodo Edit](https://github.com/Komodo/KomodoEdit), a code editor.
When I right click on projects and click "Show in Explorer", it will pop up a box just like Windows Explorer at the directory my project is. This is very convenient.
However, I noticed an insidious side effect. When you try to run a python file with this window that looks exactly like Windows Explorer, you will find out that it completely messes up sys.path in Python to use its own directory.
Is there any way to avoid this?
```
import sys
sys.path
C:\Windows\system32\python26.zip
C:\Program Files\ActiveState Komodo Edit 5\lib\python\DLLs
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\plat-win
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\lib-tk
C:\Python26
C:\Program Files\ActiveState Komodo Edit 5\lib\python
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\Pythonwin
``` | This is indeed a problem in Komodo. It actually stems from the Explorer window spawned by Komodo having the `PYTHONHOME` environment variable set to include Komodo's path, since the child process inherits the parent's environment. I noticed this by opening a Command Prompt window through an Explorer spawned by Komodo. If you look at the output from `set`, it contains (among other things) the following:
```
PYTHONHOME=C:\Program Files\ActiveState Komodo Edit 5\lib\python
_KOMODO_HOSTUSERDATADIR=C:\Users\Dev\AppData\Roaming\ActiveState\KomodoEdit\5.1\host-host\
_KOMODO_VERUSERDATADIR=C:\Users\Dev\AppData\Roaming\ActiveState\KomodoEdit\5.1\
_XRE_USERAPPDATADIR=C:\Users\Dev\AppData\Roaming\ActiveState\KomodoEdit\5.1\host-host\XRE
```
I reported this bug [here at the ActiveState bug tracker](http://bugs.activestate.com/show_bug.cgi?id=83693). | Oups! I've the same behavior on my Vista machine. I didn't see any settings for that feature and I think that this is a Komodo bug.
I though about a workaround: create a new command in the toolbox with "explorer %D" as command line. But it has the same problem :-(
Update: The workaround works if you put %D for StartIn. See the capture:
[alt text http://img10.imageshack.us/img10/2972/komodoshowinexplorer.jpg](http://img10.imageshack.us/img10/2972/komodoshowinexplorer.jpg) | Komodo Edit Changes Python sys.path If you "Show in Explorer" | [
"",
"python",
"path",
"module",
"komodo",
"komodoedit",
""
] |
I have been asked to write a java program on linux platform. According to system admin, the JRE on the linux system is GIJ, which is supposed to be compatible to JRE 1.4.2.
```
java version "1.4.2"
gij (GNU libgcj) version 4.1.2 20080704 (Red Hat 4.1.2-44)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
```
1. Is `gij` stable enough for commercial use?
2. Should I ask them to install [JRE 6.0](http://java.sun.com/javase/6/webnotes/install/jre/install-linux.html) from Sun?
3. What problems should I expect if I target `gij`?
Currently I am using WinXP, JDK 6.0, and Eclipse for software development. | gij is very ancient, and while I don't have references I doubt it's reliable enough to support commercial applications. That, and Java 1.4 is a chore to program in.
If your systems administrator is willing to install and support a newer version of Java, it'd probably be best to have them do it.
If the proprietary nature of the Sun JRE concerns you, you should look at [OpenJDK](http://openjdk.java.net/). Released under the GPL, it supplants the FSF's efforts with GCJ/GIJ . It's the default version of Java that comes with many open-source Linuxes, such as Debian, Ubuntu, and Fedora. Besides being free, it's also modern---OpenJRE 6 is fully compatible with Sun's JRE6. | `gij` does OK for Java 1.4 code, but if you're writing something from scratch, there's a good chance you want to use Java 5 and possibly Java 6 features. In particular, Java 5 offers generics, autoboxing/unboxing, and [a slew](http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html) of other helpful language and class library features. The Sun JRE is not onerous at all to install, so unless you're developing a very small app where the Java 5 language features wouldn't help much, or you have some other reason for wanting to stick with 1.4, I would just bite the bullet and install the newest JRE from [here](http://www.java.com/en/download/manual.jsp). | Is GIJ (GNU Interpreter for Java) stable enough for commercial use? | [
"",
"java",
"linux",
""
] |
We have been having some debate this week at my company as to how we should write our SQL scripts.
Background:
Our database is Oracle 10g (upgrading to 11 soon). Our DBA team uses SQLPlus in order to deploy our scripts to production.
Now, we had a deploy recently that failed because it had used both a semicolon and a forward slash (`/`). The semicolon was at the end of each statement and the slash was between statements.
```
alter table foo.bar drop constraint bar1;
/
alter table foo.can drop constraint can1;
/
```
There were some triggers being added later on in the script, some views created as well as some stored procedures. Having both the `;` and the `/` caused each statement to run twice causing errors (especially on the inserts, which needed to be unique).
In SQL Developer this does not happen, in TOAD this does not happen. If you run certain commands they will not work without the `/` in them.
In PL/SQL if you have a subprogram (DECLARE, BEGIN, END) the semicolon used will be considered as part of the subprogram, so you have to use the slash.
So my question is this: If your database is Oracle, what is the proper way to write your SQL script? Since you know that your DB is Oracle should you always use the `/`? | It's a matter of preference, but I prefer to see scripts that consistently use the slash - this way all "units" of work (creating a PL/SQL object, running a PL/SQL anonymous block, and executing a DML statement) can be picked out more easily by eye.
Also, if you eventually move to something like Ant for deployment it will simplify the definition of targets to have a consistent statement delimiter. | I know this is an old thread, but I just stumbled upon it and I feel this has not been explained completely.
There is a huge difference in SQL\*Plus between the meaning of a `/` and a `;` because they work differently.
The `;` ends a SQL statement, whereas the `/` executes whatever is in the current "buffer". So when you use a `;` **and** a `/` the statement is actually executed twice.
You can easily see that using a `/` after running a statement:
```
SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:37:20 2012
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options
SQL> drop table foo;
Table dropped.
SQL> /
drop table foo
*
ERROR at line 1:
ORA-00942: table or view does not exist
```
In this case one actually notices the error.
But assuming there is a SQL script like this:
```
drop table foo;
/
```
And this is run from within SQL\*Plus then this will be very confusing:
```
SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:38:05 2012
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options
SQL> @drop
Table dropped.
drop table foo
*
ERROR at line 1:
ORA-00942: table or view does not exist
```
The `/` is mainly required in order to run statements that have embedded `;` like `CREATE PROCEDURE`,`CREATE FUNCTION`,`CREATE PACKAGE` statements and for any `BEGIN...END` blocks. | When do I need to use a semicolon vs a slash in Oracle SQL? | [
"",
"sql",
"oracle",
"sqlplus",
""
] |
How do I keep a certain number of elements in an array?
```
function test($var)
{
if(is_array($_SESSION['myarray']) {
array_push($_SESSION['myarray'], $var);
}
}
test("hello");
```
I just want to keep 10 elements in array `$a`. So when I call `test($var)` it should push this value to array but keep the number to 10 by removing some elements from top of the array. | I would do this:
```
function test($var) {
if (is_array($_SESSION['myarray']) {
array_push($_SESSION['myarray'], $var);
if (count($_SESSION['myarray']) > 10) {
$_SESSION['myarray'] = array_slice($_SESSION['myarray'], -10);
}
}
}
```
If there a more than 10 values in the array after adding the new one, take just the last 10 values. | ```
while (count($_SESSION['myarray'] > 10)
{
array_shift($_SESSION['myarray']);
}
``` | how do I keep a certain number of elements in an array? | [
"",
"php",
"array-push",
""
] |
I have an application with an OpenGL window as a child window of the main window.
When I display a dialog box above the OpenGL window, it doesn't get drawn. It's like it's not getting `WM_PAINT` messages. If I can guess the title bar position of the dialog box, I can drag it and it's still responsive.
I realise this might be a vague question, but I was wondering if anyone else has seen this sort of behaviour before and knew of a solution?
I wondered if the Pixel Format Descriptor would make a difference - I had `PFD_DRAW_TO_WINDOW`, but changing to `PDF_DRAW_TO_BITMAP` didn't make any difference. I'm not sure what else I should be looking at? | Bugger. Should have given all the details. I was running Windows in a virtual machine on Mac OS X using Parallels. I upgrade from Parallels 3 to 4 and now everything is working fine. I suspect a Parallels video driver issue.
Thanks to all those who answered with suggestions. | Is your opengl window constantly rendering. It is possible that the 3D hardware is simply rendering into an overlay that is overdrawing your dialog box. If you position the dialog box so it overlaps your main window, can you see some of it?
Try to pause rendering into the main display to see if it effects the results.
You will also need to make sure that your window style ensures the results are clipped...
```
cs.style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN ;
```
You should check though all the items mentioned in this MSDN article, as it covers a lot of the basics for getting opengl rendering in a window correctly.
<http://msdn.microsoft.com/en-us/library/ms970745.aspx> | Windows not drawing above OpenGL windows | [
"",
"c++",
"windows",
"opengl",
""
] |
When you perform a left join in TSQL (MSSQL SERVER) is there any guarantee which row will return with your query if there are multiple rows on the right?
I'm trying to use this to exploit an ordering on the right table.
so
```
Select ColA, ColB, ColC
from T
Left Outer Join
(Select ColA, ColB, ColC
from T--CLARIFIED, this is a self join.
Order by TopColumn Desc) AS OrderedT(ColA, ColB, ColC)
On T.ColA = OrderedT.ColA
```
I would expect to retrieve all the ColA's in Table, and all the first row in the set of ColA results for my left join based on my ordering.
Is there any guarantee made on this by the language or server? | I believe you need this...
```
select T.ColA, T.ColB, T.ColC
from T
inner join
(select ColA, max(TopColumn) MaxTopColumn
from T
group by ColA) OrderedTable
on T.ColA = OrderedTable.ColA and T.TopColumn = OrderedTable.MaxTopColumn
```
Fairly common query for versioned tables, requires an inner join to a max query.
The table name "Table" doesn't help matters, I've renamed it T. | Not that simple. The LEFT JOIN returns all matching right-hand rows. So the question on guarantee here is not really relevant. You'd have to do something with a subquery to get the single row you need, using TOP 1 in the subquery. | TSQL Left Join with multiple right hand rows | [
"",
"sql",
"sql-server",
"t-sql",
"left-join",
""
] |
I have a question about the windows invariant culture.
**Succinctly, my question is:**
does there exist any pair of characters c1, and c2 such that:
lower(c1, invariant) =latin-general lower(c2, Invariant)
but
lower(c1, invaraint) !=invariant lower(c2, invariant)
**Background:**
I need to store an invariant lower case string (representing a file name) inside of SQL Server Compact, which does not support windows invariant collations.
Ideally I would like to do this without having to pull all of my comparison logic out of the database and into my app.
The idea I had for solving this was to store 2 versions of all file names: one that is used for displaying data to the customer, and another that is used for performing comparisons. The comparison column would be converted to lower case using the windows invariant locale before storing it in the database.
However, I don't really have any idea what kind of mappings the invariant culture does, other than the fact that its what windows uses for comparing file names.
I'm wondering if it is possible to get false positives (or false negatives) as a result of this scheme.
That is, can I produce characters (previously lower cased using the invariant culture) that compare equal to each other using the latin-general-1 case insensitive SQL server collation, but do not compare equal to each other under the invariant culture?
If this can happen, then my app may consider 2 files that Windows thinks are different as being the same. This could ultimately lead to data loss.
**NOTE:**
I am aware that it is possible to have case sensitive files on Windows. I don't need to support those scenarios, however. | By looking through the answers to this question:
[win32-file-name-comparison](https://stackoverflow.com/questions/410502/win32-file-name-comparison)
which I asked a while back.,
I found an indirect link the following page:
<http://msdn.microsoft.com/en-us/library/ms973919.aspx>
It suggests using an ordinal comparison after an invariant upper case as the best way to mimic what the file system does.
So I think if I use as "case sensitive, accent sensitive" collation in the database, and do a "upper" using the invariant local before storing the files I should be ok.
Does anyone know if there are any problems with that? | why don't you convert filenames to ASCII? In your situation can filenames contain non-ascii characters? | Windows Invariant Culture Puzzle | [
"",
"c#",
"sql-server",
"windows",
"filesystems",
"culture",
""
] |
I currently have a datasource from a client in the form of XML, this XML has content for all the pages that the website we're making will contain. Now after parsing and preparing all this content, does anyone know how we can then (using) PHP automate the creation of a drupal node (including all related fields for that node i.e. CCK fields, paths).
Ideally a function we can send all the content to and the nodes get created. Now i don't mind putting it straight into the db, but i'm not quite sure what db tables get updated (as the drupal setup has a gazillion tables).
I've searched through google and the drupal docs, but i can't really find something for this (Which i assumed would be a simple and often used function by web developers on drupal..)
Your input will be very much appreciated!
Thanks in advance,
Shadi | You can use Drupal's `node_save` function something like this:
```
require 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$node = new stdClass();
$node->title = "My imported node";
$node->body = "The body of my imported node.";
$node->type = 'story';
$node->created = time();
$node->changed = $node->created;
$node->status = 1;
$node->promote = 1;
$node->sticky = 0;
$node->format = 1;
$node->uid = 1;
node_save($node);
```
See this article on the Acquia site for more (including CCK fields, if you're using pathauto that should create paths on `node_save`): <http://acquia.com/blog/migrating-drupal-way-part-i-creating-node> | You should be able to use [node\_save()](http://api.drupal.org/api/function/node_save/6) for that purpose. I haven't tried with cck fields, but if you add the fields they should be saved through the hooks run. However, if you don't create the nodetype with fields through code, the function will be dependent on the setup you do in the admin interface. | Creating drupal pages (nodes) automatically from other (xml) content | [
"",
"php",
"xml",
"drupal",
""
] |
I have a compiled .NET assembly with a specific resource file embedded (named 'Script.xml'). I need to programmatically change it out for another.
Is this possible to do without recompiling from source?
Currently, I do a search for text I know is in the file and it works well. But I need to do it for another project where I don't know any of the contents of the resource file and I need to find another method.
```
FileStream exe = new FileStream(currentexe, FileMode.Open);
//find xml part of exefile
string find = "<?xml version=\"1.0\"?>";
string lastchars = new string(' ', find.Length);
while (exe.CanRead) {
lastchars = lastchars.Substring(1) + (char)exe.ReadByte();
if (lastchars == find) {
exe.Seek(-find.Length, SeekOrigin.Current);
break;
}
}
//output serialized script
int bytenum = 0;
foreach (byte c in xml) {
if (c == 0) break;
exe.WriteByte(c);
bytenum++;
}
//clean out extra data
while (bytenum++ < ScriptFileSize) {
exe.WriteByte(0x20);
}
exe.Close();
``` | You could use `Cecil` to open the assembly and insert a resource (I do). YMMV | Your current mechanism is very fragile - it won't work for signed assemblies (as the hash will change) or if you need to replace one resource with a larger one (as all the other offsets may move). It also has issues in terms of character encodings and the general mechanism to find the right point in the file anyway, but those are relatively unimportant given that I don't think the approach is appropriate to start with.
If you need replaceable resources, I'd put them in a different file altogether, which doesn't have the relatively delicate format of an assembly. | Programmatically embed resources in a .NET assembly | [
"",
"c#",
"compiler-construction",
"resources",
""
] |
I would like to have an explicit cast between from a string to an enum in c# in order to have this :
```
(MyEnum) Enum.Parse(typeof(MyEnum),stringValue)
```
I would like to deport this into an explicit cast operator, I did this but didn't work :
```
public static explicit operator (MyEnum)(value stringValue){
return (MyEnum) Enum.Parse(typeof(MyEnum),stringValue);
}
```
Do you know if it's possible in C# using .NET 3.5? | A cast is not possible. The issue is that a user-defined conversion must be enclosed in a struct or class declaration, and the conversion must be to or from the enclosing type. Thus,
```
public static explicit operator MyEnum(string value)
```
is impossible because neither `MyEnum` nor `string` can ever be the enclosing type.
The relevant section of the ECMA334 C# spec is 17.9.4:
A conversion operator converts from a source type, indicated by the parameter type of the conversion
operator, to a target type, indicated by the return type of the conversion operator. A class or struct is
permitted to declare a conversion from a source type S to a target type T only if all of the following are true,
where S0 and T0 are the types that result from removing the trailing ? modifiers, if any, from S and T:
S0 and T0 are different types.
**Either S0 or T0 is the class or struct type in which the operator declaration takes place**.
Neither S0 nor T0 is an interface-type.
Excluding user-defined conversions, a conversion does not exist from S to T or from T to S.
However, you can do an extension method on the string class.
```
public static class StringExtensions {
public static T ConvertToEnum<T>(this string value) {
Contract.Requires(typeof(T).IsEnum);
Contract.Requires(value != null);
Contract.Requires(Enum.IsDefined(typeof(T), value));
return (T)Enum.Parse(typeof(T), value);
}
}
``` | Is it necessary to use a cast operator? Another option would be to add an extension method off of string:
```
public static class StringEnumConversion
{
public static T Convert<T>(this string str)
{
return (T)Enum.Parse(typeof(T), str);
}
}
``` | C# explicit cast string to enum | [
"",
"c#",
".net-3.5",
"enums",
"casting",
""
] |
I'm creating a simple Swing application, then I realized that JToolBar doesn't provide much functionality. For example, I want to add multiple dragable toolbars onto one JFrame, but but I can only have one floatable JToolBar per JFrame if I use JToolbar.
I know that NetBeans is built with Swing, and the toolbars on NetBeans have more functionality then JToolBars. I haven't spent my time to take a peak at NetBeans source yet, but I"m wondering whether there's any other existing replacement for JToolBar out int the world. | You could try Kirill's Flamingo (Swing version of Microsoft's Ribbon style toolbar):
Project: <https://flamingo.dev.java.net/> | JIDE have a component called CommandBar, part of their Action set. I'm not sure if it meets your needs, but (like all JIDE's stuff) it's worth checking out.
<http://www.jidesoft.com/products/action.htm>
 | Is there a JToolBar replacement that offers more functionality? | [
"",
"java",
"user-interface",
"swing",
""
] |
> **Possible Duplicate:**
> [How many Python classes should I put in one file?](https://stackoverflow.com/questions/106896/how-many-python-classes-should-i-put-in-one-file)
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio between classes and files. By making it so that a single file contains a single class I find the code more navigable. As I introduce myself to Python I'm finding lots of examples where a single file contains multiple classes. Is that the recommended way of doing things in Python? If so, why?
Am I missing this convention in the [PEP8](http://www.python.org/dev/peps/pep-0008/)? | Here are some possible reasons:
1. Python is not exclusively class-based - the natural unit of code decomposition in Python is the module. Modules are just as likely to contain functions (which are first-class objects in Python) as classes. In Java, the unit of decomposition is the class. Hence, Python has one module=one file, and Java has one (public) class=one file.
2. Python is much more expressive than Java, and if you restrict yourself to one class per file (which Python does not prevent you from doing) you will end up with lots of very small files - more to keep track of with very little benefit.
An example of roughly equivalent functionality: Java's log4j => a couple of dozen files, ~8000 SLOC. Python logging => 3 files, ~ 2800 SLOC. | There's a mantra, "flat is better than nested," that generally discourages an overuse of hierarchy. I'm not sure there's any hard and fast rules as to when you want to create a new module -- for the most part, people just use their discretion to group logically related functionality (classes and functions that pertain to a particular problem domain).
Good [thread from the Python mailing list](http://mail.python.org/pipermail/python-list/2006-December/469439.html), and a quote by Fredrik Lundh:
> even more important is that in Python,
> you don't use classes for every-
> thing; if you need factories,
> singletons, multiple ways to create
> objects, polymorphic helpers, etc, you
> use plain functions, not classes or
> static methods.
>
> once you've gotten over the "it's all
> classes", use modules to organize
> things in a way that makes sense to
> the code that uses your components.
> make the import statements look good. | Are multiple classes in a single file recommended? | [
"",
"python",
"class",
""
] |
One of my users is having an issue when trying to open an Excel file through my C# app.
Everything works ok when I run it from my machine and it works for other users. I am no Excel interop expert so hopefully you guys can help me out.
Here is how it is set up:
I added a reference to my app to Microsoft.Office.Interop.Excel.dll, version 10.0.4504.0 (which I believe is Excel 2002). On my machine I have installed Excel 2007.
In my code I try to open a worksheet like so:
```
using Microsoft.Office.Interop
...
Microsoft.Office.Interop.Excel.ApplicationClass _excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = _excelApp.Workbooks.Open(workbookPath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", false, false, 0, true, false, false);
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(1);
```
I logged the users version as Excel 9.0 (which is 2000). The error that the user gets is:
```
Exception='System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)
```
It looks like the workbook cannot be opened. The file was confirmed to exist and was just loose on the user's PC at C:. I thought by using the PIA I wouldn't have to worry about Excel version issues. I know there are other users using Excel 2000, and it works on my development machine.
Any ideas? Maybe my calls to open the Excel file should be changed? The unfortunate thing is that I am unable to reproduce it. | > "I thought by using the PIA I wouldn't
> have to worry about Excel version
> issues. I know there are other users
> using Excel 2000, and it works on my
> dev machine."
Almost true, but not quite.
By developing against the PIA for Excel 2002, your program will be compatible for all versions of Excel 2002 (10.0) and above. The failing machine, however, is running with Excel 2000 (9.0), which is a version *below* the version that you have developed against.
There is no officially supported PIA below Excel 2002, so if you need your program to run on Excel 2000 (9.0) then you will have to create your own custom interop assembly. You can use TlbImp.exe to create an interop assembly for Excel 9.0, as explained in the article [Achieving Backward Compatibility with .NET Interop: Excel as Case Study](http://www.devcity.net/Articles/163/1/article.aspx).
If your assembly is strong-named, then you need to create a strong-named interop assembly. This can be done by providing the name of your .pfx or .snk file via the /keyfile switch, as demonstrated in the article [How to create a Primary Interop Assembly (PIA)](http://support.microsoft.com/kb/304295). That article is also making use of the /primary switch in order to create a "primary interop assembly". Making the interop assembly primary is not really needed in your case, but does not hurt. What the article omits, however, is the use of the /sysarray switch, which you should use.
Making a strong-named interop assembly does have some complexities to consider, however. For some more details, have a read of [Using TLBIMP.exe to create Strong Named Interop Assemblies](http://www.darinhiggins.com/2009/04/14/UsingTLBIMPexeToCreateStrongNamedInteropAssemblies.aspx). (Among other things, this article explains the need for the /sysarray switch.)
In short, making a custom interop assembly is very simple if your assembly is not strong named. It is more complicated if your assembly is strong-named and, therefore, you need to create a strong-named interop assembly. But hopefully these articles should get you going.
-- Mike | I'm using Microsoft.Office.Interop.Excel.dll:
Runtime version: v1.1.4322
Version: 12.0.0.0
Could try this:
```
private object mMissingValue = System.Reflection.Missing.Value;
private void CreateWorkbook(string fileName)
{
if (File.Exists(fileName))
{
// Create the new excel application reference
mExcelApplication = new Application();
// Open the file
Workbook excel_workbook = mExcelApplication.Workbooks.Open(templatePath,
mMissingValue, mMissingValue, mMissingValue, mMissingValue, mMissingValue,
mMissingValue, mMissingValue, mMissingValue, mMissingValue, mMissingValue,
mMissingValue, mMissingValue, mMissingValue, mMissingValue);
Worksheet sheet = (Worksheet)mExcelWorkbook.Worksheets[1];
}
}
``` | C# and Excel interop | [
"",
"c#",
"excel",
"interop",
""
] |
So the common (at least VS 2005 states) way to define exports/imports for a DLL is:
```
#ifdef MY_EXPORTS
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif
class MY_API MyClass {
...
};
```
This works great if I'm just building my code as a DLL. However, I want to have the option of using a static library OR a DLL. Now one obvious (but terrible) solution, is to copy all the code, removing the DLL 'MY\_API' defines. Now what would seem a much better approach is a command line switch to either define, or not define the DLL stuff. However in the case of a static library what should 'MY\_API' be?
```
#ifdef DLL_CONFIG
#ifdef MY_EXPORTS
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif
#else
#define MY_API // What goes here?
#endif
class MY_API MyClass {
...
};
```
Now assuming that this can be done will there be issues when a user of the library includes the header files (ie. will they have to define 'DLL\_CONFIG')? | Nothing.
Leave it as `#define MY_API` and all instances of MY\_API will simply vanish.
You can add new build configurations, such as Debug - DLL and Release - DLL that mimic the others except they `#define DLL_CONFIG`.
To clone a configuration, get to the configuration manager (like the drop down of the Debug/Release list box), then under 'Active solution configuration' select new. You can now name it "Debug - DLL" and set `Copy Settings` to `Debug` and now that's left to do is define `DLL_CONFIG`.
To do this, go to project properties->configuration properties->C/C++->Preprocessor, and type `DLL_CONFIG` in there. You will also see that's where things like `NDEBUG` and `WIN32` are defined.
Like [haffax said](https://stackoverflow.com/questions/1089828/same-header-file-for-both-dll-and-static-library/1089853#1089853), use project specific names. I would recommend something like:
```
#ifdef THEPROJECT_USE_DLL
#ifdef THEPROJECT_BUILDING_PROJECT
#define THEPROJECT_API __declspec(dllexport)
#else
#define THEPROJECT_API __declspec(dllimport)
#endif
#else
#define THEPROJECT_API
#endif
```
Now users of your DLL just `#define THEPROJECT_USE_DLL` if they are using the DLL version, just like your "- DLL" configurations have. | Just define MY\_API as empty. Like this:
```
#ifdef DLL_CONFIG
#ifdef MY_EXPORTS
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif
#else
#define MY_API
#endif
```
In case of static linking no declspec is necessary.
Users of your library will have to define `DLL_CONFIG` if they want to use it as a dll or not define it if they want to use it as a static library.
There won't be any issues as is. This kind of configuration is done in many libraries.
Edit: Of course you shouldn't use the names `MY_EXPORTS` and `DLL_CONFIG` as such. Use project specific prefixes for all of your macros, so that there are no name clashes. | Same Header File for both DLL and Static Library | [
"",
"c++",
"windows",
""
] |
I have a bunch of `console.log()` calls in my JavaScript.
Should I comment them out before I deploy to production?
I'd like to just leave them there, so I don't have to go to the trouble of re-adding the comments later on if I need to do any more debugging. Is this a bad idea? | It will cause Javascript errors, terminating the execution of the block of Javascript containing the error.
You could, however, define a dummy function that's a no-op when Firebug is not active:
```
if(typeof console === "undefined") {
console = { log: function() { } };
}
```
If you use any methods other than `log`, you would need to stub out those as well. | As others have already pointed it, leaving it in will cause errors in some browsers, but those errors can be worked around by putting in some stubs.
However, I would not only comment them out, but outright remove those lines. It just seems sloppy to do otherwise. Perhaps I'm being pedantic, but I don't think that "production" code should include "debug" code at all, even in commented form. If you leave comments in at all, those comments should describe what the code is doing, or the reasoning behind it--not blocks of disabled code. (Although, most comments should be removed automatically by your minification process. You are minimizing, right?)
Also, in several years of working with JavaScript, I can't recall ever coming back to a function and saying "Gee, I wish I'd left those console.logs in place here!" In general, when I am "done" with working on a function, and later have to come back to it, I'm coming back to fix some other problem. Whatever that new problem is, if the console.logs from a previous round of work could have been helpful, then I'd have spotted the problem the first time. In other words, if I come back to something, I'm not likely to need exactly the same debug information as I needed on previous occasions.
Just my two cents... Good luck!
---
# Update after 13 years
I've changed my mind, and now agree with the comments that have accumulated on this answer over the years.
Some log messages provide long-term value to an application, even a client-side JavaScript application, and should be left in.
Other log messages are low-value noise and should be removed, or else they will drown out the high-value messages. | Bad idea to leave "console.log()" calls in your production JavaScript code? | [
"",
"javascript",
"debugging",
"logging",
"production",
""
] |
I've come across an interesting problem in the following line of code:
```
<img style="background-image:url(Resources/bar.png); width: 300px; height: 50px;"/>
```
In Safari (at least), a gray border surrounds the 300x50px area. Adding style="border: none;" doesn't remove it. Any ideas?
Thanks.
Mike | So, you have an img element that doesn't have a src attribute, but it does have a background-image style applied.
I'd say that the gray border is the 'placeholder' for where the image would be, if you'd specified a src attribute.
If you don't want a 'foreground' image, then don't use an img tag - you've already stated that changing to a div solves the problem, why not go with that solution? | You can also add a blank image as a place holder:
```
img.src='data:image/png;base64,R0lGODlhFAAUAIAAAP///wAAACH5BAEAAAAALAAAAAAUABQAAAIRhI+py+0Po5y02ouz3rz7rxUAOw=='
```
This should do the trick! | How do I remove the gray border that surrounds background images? | [
"",
"javascript",
"html",
"css",
""
] |
I have a problem returning data back to the function I want it returned to. Code below:
```
function ioServer(request_data, callback)
{
$.ajax({
cache: false,
data: "request=" + request_data,
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown){},
success: function(response_data, textStatus){
callback(response_data);
},
timeout: 5000,
type: "POST",
url: "/portal/index.php/async"
});
}
function processRequest(command, item, properties)
{
var request = {};
request.command = command;
request.item = item;
request.properties = properties;
var toServer = JSON.stringify(request);
var id = ioServer(toServer, processResponse);
return id;
}
function processResponse(fromServer)
{
if (fromServer.response == 1)
{
return fromServer.id;
}
}
```
I invoke this piece of code by calling the processRequest function inside another function. Sending the request and retrieving the response works just fine. However, I need to return a value 'id' from the response back to the processRequest function, so it in turn can return that value to its caller. As far as I can follow, the return in processResponse returns to $.ajax, but I need it to return further back to processRequest.
BTW the if statement in processResponse refers to a value set by the server-side PHP script to tell whether the request was allowed (for instance if the user was not logged in, fromServer.response would be 0). It does not have anything to do with the success/error routines of the $.ajax object.
Many thanks for the help.
@Jani: Thanks for the response, but could you clarify a bit more? The function where 'id' is needed has the following code:
```
$(#tabs).tabs('add', '#tab-' + id, 'New tab');
```
Are you saying I should try to execute this piece of code in the processResponse function? Because that is not what I intented to do; these function are meant to be an all-purpose solution to maintain state server-side. That is why I avoided placing this piece of code there. | As Tony didn't provide any comments, let me add details about what he is suggesting.
As you have learned, the processRequest function completes as soon as $.ajax call is made because $.ajax method is asynchronous. So how would you notify the caller of processRequest that the task is done?
Simple, you ask that the caller of processRequest to supply a 'callback function'. The processRequest will call this function whenever it has received the ajax output. In tony's code, this is the last argument to the processRequest function.
So your calling code will now look like
```
function tabMethod() {
processRequest('command', 'item', 'properties',
function (id) {
if (id == null) {
alert('There is a problem!');
return;
}
$('#tabs').tabs('add', '#tab-' + id, 'New tab');
});
};
``` | I think maybe this is closer to what you are looking for...
```
function ioServer(request_data, callback)
{
$.ajax({
cache: false,
data: "request=" + request_data,
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown){},
success: function(response_data, textStatus){
processResponse(response_data, callback);
},
timeout: 5000,
type: "POST",
url: "/portal/index.php/async"
});
}
function processRequest(command, item, properties, callback)
{
var request = {};
request.command = command;
request.item = item;
request.properties = properties;
var toServer = JSON.stringify(request);
ioServer(toServer, callback);
}
//internal callback to handle response code
function processResponse(fromServer, callback)
{
if (fromServer.response == 1)
{
//call the callback with the id
callback(fromServer.id);
}
else
{
//You have to remember to call the callback no matter what
//or the caller won't know when it's complete
callback(null); //or some other "didn't get a valid response" value
}
}
``` | How does one return data to the original caller function in Javascript? | [
"",
"javascript",
"jquery",
"ajax",
"callback",
"return",
""
] |
I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
```
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
```
I can convert it to a decimal by using:
```
>>> from decimal import *
>>> d = Decimal(s)
>>> print d
23.45678
```
I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.
But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering. | How about this?
```
>>> s = '23.45678'
>>> int(float(s))
23
```
Or...
```
>>> int(Decimal(s))
23
```
Or...
```
>>> int(s.split('.')[0])
23
```
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on. | What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
```
s = '234.67'
i = int(round(float(s)))
```
Otherwise, just do:
```
s = '234.67'
i = int(float(s))
``` | Convert a string to integer with decimal in Python | [
"",
"python",
"string",
"integer",
"decimal",
""
] |
JSLint is giving me this error:
> Problem at line 11 character 33: Use the array literal notation [].
```
var myArray = new Array();
```
What is array literal notation and why does it want me to use it instead?
It shows here that `new Array();` should work fine... is there something I'm missing? | array literal notation is where you define a new array using just empty brackets. In your example:
```
var myArray = [];
```
It is the "new" way of defining arrays, and I suppose it is shorter/cleaner.
The examples below explain the difference between them:
```
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3], // e.length == 1, e[0] == 3
f = new Array(3); // f.length == 3, f[0] == undefined
```
> **Reference**: [What’s the difference between “Array()” and “[]” while declaring a JavaScript array?](https://stackoverflow.com/a/931875/177125) | See also: [What’s wrong with var x = new Array();](https://stackoverflow.com/questions/885156/whats-wrong-with-var-x-new-array)
Aside from the Crockford argument, I believe it is also due to the fact that other languages have similar data structures that happen to use the same syntax; for example, [Python has lists and dictionaries](http://docs.python.org/tutorial/datastructures.html); see the following examples:
```
// this is a Python list
a = [66.25, 333, 333, 1, 1234.5]
// this is a Python dictionary
tel = {'jack': 4098, 'sape': 4139}
```
Isn't it neat how Python is also grammatically correct Javascript? (yes, the ending semi-colons are missing, but those aren't required for Javascript, either)
Thus, by reusing common paradigms in programming, we save everyone from having to relearn something that shouldn't have to. | What is array literal notation in javascript and when should you use it? | [
"",
"javascript",
"arrays",
"jslint",
"literals",
""
] |
I'm having a problem. I would like to create Document object, and I would like to have a user property with **com.google.appengine.api.users.User** type (on GAE's docs site, they said we should use this object instead of email address or something else, because this object probably will be enchanced to be unique). But now the object can't be compiled by GWT, because I don't have the source for that object.
How can I resolve the problem?
I was searching for documents about DTOs, but I realized that maybe that's not the best pattern I should use.
What do you recommend?
Very thanks for your help!
Regards,
Bálint Kriván | to avoid DTOs for objects with com.google.appengine.api.users.User inside you can probably use the work from
<http://www.resmarksystems.com/code/>
He has build wrappers for the Core GAE data types (Key, Text, ShortBlob, Blob, Link, User). I've tested it with datastore.Text and it worked well. | There is a lot of debate about whether you should be able to reuse objects from the server on the client. However, the reuse rarely works out well in real applications so I generally recommend creating pure java objects that you copy your data into to send to the client. This allows you to tailor the data to what you need on the client and avoids pitfalls where you accidently send sensitive information over the wire.
So in this case, I would recommend that you create a separate object to send over the wire. BTW if you have the AppEngine SDK for Java (<http://code.google.com/appengine/downloads.html>), it includes a demo application that I did (sticky) that demonstrates this technique. | GWT + GAE/J, sending JDO objects through the wire, but how? | [
"",
"java",
"google-app-engine",
"gwt",
"gwt-rpc",
""
] |
This has happened before to me, but I can't remember how I fixed it.
I can't compile some programs here on a new Ubuntu install... Something is awry with my headers.
I have tried g++-4.1 and 4.3 to no avail.
```
g++ -g -frepo -DIZ_LINUX -I/usr/include/linux -I/usr/include -I/include -c qlisttest.cpp
/usr/include/libio.h:332: error: ‘size_t’ does not name a type
/usr/include/libio.h:336: error: ‘size_t’ was not declared in this scope
/usr/include/libio.h:364: error: ‘size_t’ has not been declared
/usr/include/libio.h:373: error: ‘size_t’ has not been declared
/usr/include/libio.h:493: error: ‘size_t’ does not name a type
/usr/include/stdio.h:294: error: ‘size_t’ has not been declared
...
```
the file...
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
...
@ubuntu:~/work/zpk/src$ cat /usr/include/linux/types.h | grep size_t
typedef __kernel_size_t size_t;
typedef __kernel_ssize_t ssize_t;
```
types.h is definitely in the path, and is getting picked up. I verified by changing the file name and get an error its missing...
Does anyone have any ideas...? I would really appreciate the help... | Start by removing -I/usr/include/linux and -I/usr/include. Adding system directories to include paths manually either has no effect, or breaks things. Also, remove -frepo for extra safety. | It's hard to say what the issue is without seeing your complete source. The best way to debug issues like this is to use g++'s "-E" parameter to produce pre-processor output, and then look at that to figure out what's going on in your includes. Here's what the g++ info page says about "-E":
> -E Stop after the preprocessing stage; do not run the compiler proper.
> The output is in the form of preprocessed source code, which is
> sent to the standard output.
Also, why not just include sys/types.h at the top of the file?
Addendum:
On my system, I've created a short file called foo.cc that contains only:
```
#include <time.h>
```
And then I've run:
> g++ -E /tmp/foo.cc > /tmp/foo.pp
Looking at this output in much detail is very important. For example, I learned that /usr/include/bits/types.h has a typedef for \_\_time\_t, and that /usr/include/types.h then uses that typedef to say "typedef \_\_time\_t time\_t". But, there are interesting other macros surrounding that definiton. Pay special attention to things like the macro "\_\_BEGIN\_NAMESPACE\_STD" in /usr/include/time.h, which on my system seems to be an empty define. But, I can imagine that some other systems may have a different value for this macro, forcing the definition of time\_t into some other namespace.
Read the Cpp info page, section "9 Preprocessor Output" that defines the format of the lines of the file. Of particular note is the section on:
> Source file name and line number information is conveyed by lines of the form
>
> # LINENUM FILENAME FLAGS
And then goes on to describe "FLAGS" which are of interest for this level of debugging. | size_t can not be found by g++-4.1 or others on Ubuntu 8.1 | [
"",
"c++",
"linux",
"header",
"size-t",
""
] |
I am currently working with a query in in MSSQL that looks like:
```
SELECT
...
FROM
(SELECT
...
)T1
JOIN
(SELECT
...
)T2
GROUP BY
...
```
The inner selects are relatively fast, but the outer select aggregates the inner selects and takes an incredibly long time to execute, often timing out. Removing the group by makes it run somewhat faster and changing the join to a LEFT OUTER JOIN speeds things up a bit as well.
Why would doing a group by on a select which aggregates two inner selects cause the query to run so slow? Why does an INNER JOIN run slower than a LEFT OUTER JOIN? What can I do to troubleshoot this further?
EDIT: What makes this even more perplexing is the two inner queries are date limited and the overall query only runs slow when looking at date ranges between the start of July and any other day in July, but if the date ranges are anytime before the the July 1 and Today then it runs fine. | The issue was with fragmented data. After the data was defragmented the query started running within reasonable time constraints. | Without some more detail of your query its impossible to offer any hints as to what may speed your query up. A possible guess is the two inner queries are blocking access to any indexes which might have been used to perform the join resulting in large scans but there are probably many other possible reasons.
To check where the time is used in the query check the execution plan, there is a detailed explanation here
<http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx>
The basic run down is run the query, and display the execution plan, then look for any large percentages - they are what is slowing your query down. | Aggregating two selects with a group by in SQL is really slow | [
"",
"sql",
"sql-server",
""
] |
I have a method which takes a directory path as a string. In the beginning of the method it checks if this path exists and if not it should throw an exception. I'm thinking it should maybe throw a `DirectoryNotFoundException` or something instead of a less specific `ArgumentException`.
I read the msdn documentation of that `DirectoryNotFoundException` and it says that
> `DirectoryNotFoundException` uses the `HRESULT COR_E_DIRECTORYNOTFOUND` which has the value `0x80070003`.
I don't know what that means exactly, and it looks a bit scary... should I still throw that exception, or should I stick to a regular `ArgumentException`? Or should I stick to the `ArgumentException` simply because it is an argument I am complaining about? Or?
```
public void MakeFunOf(string path)
{
if(!Directory.Exists(path))
throw new WhatException();
TellJokeAbout(path);
PointAndLaughAt(path);
}
``` | If you expect the developer to check for the existence of the directory before calling your method, use ArgumentException. If you want the developer to have the choice of handling the missing directory, use DirectoryNotFound exception.
In other words, "Is it a *bug* that the developer told me to access a directory that didn't exist?"
Personally, I'd use the DirectoryNotFound exception. | In my opinion you should check for the correctnes of the argument and throw an ArgumentException then after the check throw an DirectoryNotFoundException.
It is a big difference if no argument was given or only a wrong path was specified.
```
void CheckDir(string path)
{
if(String.IsNullOrEmpty(path))
{
throw new ArgumentException("Path not specified.");
}
if(!Directory.Exists(path))
{
throw new DirectoryNotFoundException();
}
}
``` | C#: Should I throw an ArgumentException or a DirectoryNotFoundException? | [
"",
"c#",
"exception",
""
] |
We have a sub-project 'commonUtils' that has many generic code-snippets used across the parent project.
One such interesting stuff i saw was :-
```
/*********************************************************************
If T is polymorphic, the compiler is required to evaluate the typeid
stuff at runtime, and answer will be true. If T is non-polymorphic,
the compiler is required to evaluate the typeid stuff at compile time,
whence answer will remain false
*********************************************************************/
template <class T>
bool isPolymorphic() {
bool answer=false;
typeid(answer=true,T());
return answer;
}
```
I believed the comment and thought that it is quite an interesting template though it is not
used across the project. I tried using it like this just for curiosity ...
```
class PolyBase {
public:
virtual ~PolyBase(){}
};
class NPolyBase {
public:
~NPolyBase(){}
};
if (isPolymorphic<PolyBase>())
std::cout<<"PolyBase = Polymorphic\n";
if (isPolymorphic<NPolyBase>())
std::cout<<"NPolyBase = Also Polymorphic\n";
```
But none of those ever returns true. MSVC 2005 gives no warnings but Comeau warns typeid expression has no effect. Section 5.2.8 in the C++ standard does not say anything like what the comment says i.e. typeid is is evaluated at compile time for non-polymorphic types and at runtime for polymorphic types.
1) So i guess the comment is misleading/plain-wrong or since the author of this code is quite a senior C++ programmer, am i missing something?
2) OTOH, I am wondering if we can test whether a class is polymorphic(has at least one virtual function) using some technique?
3) When would one want to know if a class is polymorphic? Wild guess; to get the start-address of a class by using `dynamic_cast<void*>(T)` (as `dynamic_cast` works only on polymorphic classes).
Awaiting your opinions.
Thanks in advance, | I cannot imagine any possible way how that typeid could be used to check that type is polymorphic. It cannot even be used to assert that it is, since typeid will work on any type.
Boost has an implementation [here](http://www.boost.org/doc/libs/1_39_0/boost/type_traits/is_polymorphic.hpp). As for why it might be necessary -- one case I know is the Boost.Serialization library. If you are saving non-polymorphic type, then you can just save it. If saving polymorphic one, you have to gets its dynamic type using typeid, and then invoke serialization method for that type (looking it up in some table).
**Update**: it appears I am actually wrong. Consider this variant:
```
template <class T>
bool isPolymorphic() {
bool answer=false;
T *t = new T();
typeid(answer=true,*t);
delete t;
return answer;
}
```
This actually does work as name suggests, exactly per comment in your original code snippet. The expression inside typeid is not evaluated if it "does not designate an lvalue of polymorphic class type" (std 3.2/2). So, in the case above, if T is not polymorphic, the typeid expression is not evaluated. If T is polymorphic, then \*t is indeed lvalue of polymorphic type, so entire expression has to be evaluated.
Now, your original example is still wrong :-). It used `T()`, not `*t`. And `T()` create **rvalue** (std 3.10/6). So, it still yields an expression that is not "lvalue of polymorphic class".
That's fairly interesting trick. On the other hand, its practical value is somewhat limited -- because while boost::is\_polymorphic gives you a compile-time constant, this one gives you a run-time value, so you cannot instantiate different code for polymorphic and non-polymorphic types. | Since C++11, this is now available in the `<type_traits>` header as `std::is_polymorphic`. It can be used like this:
```
struct PolyBase {
virtual ~PolyBase() {}
};
struct NPolyBase {
~NPolyBase() {}
};
if (std::is_polymorphic<PolyBase>::value)
std::cout << "PolyBase = Polymorphic\n";
if (std::is_polymorphic<NPolyBase>::value)
std::cout << "NPolyBase = Also Polymorphic\n";
```
This prints just "PolyBase = Polymorphic". | Test whether a class is polymorphic | [
"",
"c++",
"templates",
"polymorphism",
"typeid",
""
] |
I was going through the list of predefined Exceptions in PHP and I noticed the [DomainException](https://www.php.net/manual/en/class.domainexception.php). Anyone know what does DomainException mean? Does it mean failed data model validation? | There's a pretty hilarious discussion here about how no one seems to know what is means:
<http://bugs.php.net/bug.php?id=47097>
From the end of that link:
> Domain means data domain here. That is
> a `DomainException` shall be thrown
> whenever a value does not adhere to a
> defined valid data domain. Examples:
>
> * 0 is not in the domain for division.
> * Foo is not in the domain for weekdays.
>
> The first is different from out of
> range and alike, but you could use
> `InvalidParameter` in case it is
> actually a parameter to the function
> that performs the division. If it is a
> value calculated inside the function
> prior to executing the division and
> then a pre-conditon check throws
> instead of executing the division,
> then it becomes a `DomainException`. | The description of [`RangeException`](http://www.php.net/manual/en/class.rangeexception.php) is a bit more helpful:
> Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of [DomainException](http://www.php.net/manual/en/class.domainexception.php).
I think it is applicable to non-arithmetic too, e.g. see this [user comment](http://www.php.net/manual/en/class.domainexception.php#106241).
For example, if you expect a value to be in the set `{'jpeg', 'png', 'gif', 'bmp'}` and you receive something else like `'foo'`, it's a good candidate for a [DomainException](http://www.php.net/manual/en/class.domainexception.php) (logic) / [`RangeException`](http://www.php.net/manual/en/class.rangeexception.php) (runtime). I'm pretty sure you could think of many other use cases.
Also, I just found this useful article, which provide more thorough explanations than php.net: [How to use built-in SPL exception classes for better error handling](https://codeutopia.net/blog/2011/05/06/how-to-use-built-in-spl-exception-classes-for-better-error-handling/) | When would you throw a DomainException in PHP? | [
"",
"php",
"exception",
""
] |
```
<object width="438" height="280" id="pano" >
<param value="url_flash" name="movie" />
<param value="false" name="menu"/>
<param value="high" name="quality"/>
<param value="#FFFFFF" name="bgcolor"/>
<embed width="438" height="280" pluginpage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" name="pano" bgcolor="#FFFFFF" quality="high" menu="false" src="url_flash"/>
</object>
```
I have this flash code, what I want is that when I click some buttons to change with jquery `<embed src=''>` (for firefox) and the first `<param>` (for IE)
How I can do that?
This works for embed but how I can do for param in IE ?
```
$('.link a').click(function() {
var urlconst = 'changed_url';
$(".flash_photo embed").attr({
src: changed_url
});
```
I tried
```
$('#pano param:first').val(changed_url)
```
But that doesn't work. | Have you considered using jQuery SWFObject plugin?
<http://jquery.thewikies.com/swfobject/> | After searching for info, it seems you cannot dynamically change the param element's attributes dynamically. The simplest way will probably be to pull the element's HTML into a variable, feed that back into jQuery, and use CSS selectors on that. Then you could clear the object and replace it with the new code.
```
var url = (url here);
var code = $("#embedded").html();
var newcode = $("param:first", code).attr("src", url).html();
$("#embedded").html(newcode);
```
or something like that... ;) | object, param, jquery | [
"",
"javascript",
"jquery",
"html",
"flash",
""
] |
Here is what I am trying to do. I have a block of text and I would like to extract the first 50 words from the string without cutting off the words in the middle. That is why I would prefer words opposed to characters, then I could just use a left() function.
I know the str\_word\_count($var) function will return the number of words in a string, but how would I return only the first 50 words?
I'm going full immersion on PHP and I'm not familiar with many of the string functions, yet.
Thanks in advance,
Jason | I would recommend against using the number of words as a baseline. You could easily end up with *much* less or *much* more data than you intended to display.
One approach I've used in the past is to ask for a desired length, but make sure it does not truncate a word. Here's something that may work for you:
```
function function_that_shortens_text_but_doesnt_cutoff_words($text, $length)
{
if(strlen($text) > $length) {
$text = substr($text, 0, strpos($text, ' ', $length));
}
return $text;
}
```
That said, if you pass `1` as the second parameter to `str_word_count`, it will return an array containing all the words, and you can use array manipulation on that.
Also, you *could* although, it's somewhat hackey, explode the string on spaces, etc... But that introduces lots of room for error, such as things that are not words getting counted as words.
PS. If you need a Unicode safe version of the above function, and have either the `mbstring` or `iconv` extensions installed, simply replace all the string functions with their `mb_` or `iconv_` prefixed equivalents. | str\_word\_count takes an optional parameter that tells it what to return.
Returns an array of strings that are the words:
```
$words = str_word_count($var, 1);
```
Then you can slice things up with something like:
```
$len = min(50, count($words));
$first_fifty = array_slice($words, 0, $len);
``` | How do I get only a determined number of words from a string in php? | [
"",
"php",
"string",
"function",
""
] |
I'm a newbie to Java and I'm confused about something:
In the simple hello world program in Java, no object is created so how does the class work in the following example?
```
public class HelloWorld
{
public static void main (String args[])
{
System.out.println ("Hello World!");
}
}
``` | Any variable or method that is declared **static** can be used independently of a class instance.
**Experiment**
Try compiling this class:
```
public class HelloWorld {
public static int INT_VALUE = 42;
public static void main( String args[] ) {
System.out.println( "Hello, " + INT_VALUE );
}
}
```
This succeeds because the variable `INT_VALUE` is declared static (like the method `main`).
Try compiling this class along with the previous class:
```
public class HelloWorld2 {
public static void main( String args[] ) {
System.out.println( "Hello, " + HelloWorld.INT_VALUE );
}
}
```
This succeeds because the `INT_VALUE` variable is both **static** and **public**. Without going into too much detail, it is usually good to avoid making variables public.
Try compiling this class:
```
public class HelloWorld {
public int int_value = 42;
public static void main( String args[] ) {
System.out.println( "Hello, " + int_value );
}
}
```
This does not compile because there is no object instance from the class HelloWorld. For this program to compile (and run), it would have to be changed:
```
public class HelloWorld {
public int int_value = 42;
public HelloWorld() { }
public static void main( String args[] ) {
HelloWorld hw = new HelloWorld();
System.out.println( "Hello, " + hw.int_value );
}
}
``` | This doesn't create an instance of `HelloWorld` because `main` is a *static method*. Static methods (and static fields) are related to the *type* rather than to a particular *instance* of the type.
See the [Java Tutorial page on static/instance members](http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html) for more details, along with [this Stack Overflow question](https://stackoverflow.com/questions/913560/what-is-static) (amongst others). | How does Java's Hello World work without an object instance? | [
"",
"java",
""
] |
I'm trying to do some classic C development in Visual C++ 2008 that will modify the characters of a string like so:
```
void ModifyString(char *input)
{
// Change first character to 'a'
*input = 'a';
}
```
I'm getting a unhandled exception when I try to change a character. It seems like I could do this in Visual Studio 6 or using gcc, but maybe I'm just forgetting something. Does Visual Studio somehow pass char\* by value (managing memory). If so, how do I turn this off? | You're probably passing a string literal somewhere:
```
ModifyString("oops"); // ERROR!
```
C and C++ allow you to implicitly cast from string literals (which have type `const char[]`) to `char*`, but such usage is deprecated. String constants are allowed to be allocated in read-only memory (and they usually are), so if you attempt to modify them, you'll get an access violation (aka segmentation fault or bus error). If the compiler doesn't put string constants in read-only memory, the program will still work, but it is undefined behavior.
The correct way to do this is to copy the string into a writeable buffer:
```
// one way:
char mystring[] = "test";
ModifyString(mystring); // ok
// another way:
char mystring[64]; // make sure this is big enough!!
strcpy(mystring, "test");
ModifyString(mystring); // ok
``` | Is the input a string literal? That's probably the problem. Otherwise you'll need to post more code, as the pointer has somehow ended up pointing at a readonly location in memory. | Unhandled exception when dereferencing char pointer in Visual C++ 2008 | [
"",
"c++",
"visual-studio-2008",
"pointers",
"dereference",
""
] |
I'm using an Ant build script to collate my Eclipse-based application for distribution.
One step of the build is to check that the correct libraries are present in the build folders. I currently use the Ant command for this. Unfortunately, I have to amend the script each time I switch to a new Eclipse build (since the version numbers will have updated).
I don't need to check the version numbers, I just need to check that the file's there.
So, how do I check for:
```
org.eclipse.rcp_3.5.0.*
```
instead of:
```
org.eclipse.rcp_3.5.0.v20090519-9SA0FwxFv6x089WEf-TWh11
```
using Ant?
cheers,
Ian | You mean, something like (based on the [pathconvert task](http://ant.apache.org/manual/Tasks/pathconvert.html), after [this idea](http://marc.info/?l=ant-user&m=109647070406692&w=2)):
```
<target name="checkEclipseRcp">
<pathconvert property="foundRcp" setonempty="false" pathsep=" ">
<path>
<fileset dir="/folder/folder/eclipse"
includes="org.eclipse.rcp_3.5.0.*" />
</path>
</pathconvert>
</target>
<target name="process" depends="checkEclipseRcp" if="foundRcp">
<!-- do something -->
</target>
``` | A slightly shorter and more straightforward approach with [resourcecount](http://ant.apache.org/manual/Tasks/resourcecount.html) condition:
```
<target name="checkEclipseRcp">
<condition property="foundRcp">
<resourcecount when="greater" count="0">
<fileset file="/folder/folder/eclipse/org.eclipse.rcp_3.5.0.*"/>
</resourcecount>
</condition>
</target>
<target name="process" depends="checkEclipseRcp" if="foundRcp">
<!-- do something -->
</target>
``` | How to use wildcard in Ant's Available command | [
"",
"java",
"ant",
""
] |
I have been working with Exceptions lately. I think it makes sense to log uncaught Exceptions, because it greatly helps developers to take care of possible problems in the source by simply looking at Exception log. However, when an exception is dealt with, is there a need to log it any longer? Yes, to some extent. If you have "bad" developers who write code that has bugs, then by simply catching Exceptions will make the bugs go "away". For example:
```
try
{
fopen('/path/to/file','w');
}
catch (Exception $e)
{
// Display an error to user
}
```
The above code is PHP. The point is, this kind of code, imo, should not exist. Exceptions are meant to be exceptional and occur rarely, but with this code they occur more than rarely. For instance, the developer does not check if the file exists and he does not check if he has permissions to write to it. Instead, it should be:
```
try
{
if (file_exists('/path/to/file') && is_writable('/path/to/file'))
fopen('/path/to/file','w');
else
// Display an error to user about file not existing or not being writable
}
catch (Exception $e)
{
// Display an error to user about an unexpected error
}
```
This makes pretty much sense now. The exception is thrown and caught only if it is exceptional (e.g. server crash, power outage, whatever). But what if the developer uses Exceptions for everything and the omits checks - is there a way for me to log caught exceptions?
I don't want developers to put everything in try-catch blocks to "solve" issues. I want them to explicitly check whatever they should check - and leave exceptions for exceptional situations like hardware failure, server crash, etc. | I don't think that there's a magic method type approach if that's what you're looking for. But is it possible to wrap your entire app in a `try... catch...` structure? By definition, any exceptions that get to the outer-most `try... catch...` are uncaught... or am I missing the point ;-) | > Exceptions are meant to be exceptional and occur rarely, but with this code they occur more than rarely.
I think that's a misconception. The point of exceptions is to separate the ideal flow from the error-handling flow. | Logging Caught and Uncaught Exceptions? | [
"",
"php",
"exception",
"logging",
""
] |
Python 2.x has two ways to overload comparison operators, [`__cmp__`](http://docs.python.org/2.6/reference/datamodel.html#object.__cmp__) or the "rich comparison operators" such as [`__lt__`](http://docs.python.org/2.6/reference/datamodel.html#object.__lt__). **The rich comparison overloads are said to be preferred, but why is this so?**
Rich comparison operators are simpler to implement each, but you must implement several of them with nearly identical logic. However, if you can use the builtin `cmp` and tuple ordering, then `__cmp__` gets quite simple and fulfills all the comparisons:
```
class A(object):
def __init__(self, name, age, other):
self.name = name
self.age = age
self.other = other
def __cmp__(self, other):
assert isinstance(other, A) # assumption for this example
return cmp((self.name, self.age, self.other),
(other.name, other.age, other.other))
```
This simplicity seems to meet my needs much better than overloading all 6(!) of the rich comparisons. (However, you can get it down to "just" 4 if you rely on the "swapped argument"/reflected behavior, but that results in a net increase of complication, in my humble opinion.)
**Are there any unforeseen pitfalls I need to be made aware of if I only overload `__cmp__`?**
I understand the `<`, `<=`, `==`, etc. operators can be overloaded for other purposes, and can return any object they like. I am not asking about the merits of that approach, but only about differences when using these operators for comparisons in the same sense that they mean for numbers.
*Update:* As Christopher [pointed out](https://stackoverflow.com/questions/1061283/style-why-lt-instead-of-cmp/1061323#1061323), `cmp` is disappearing in 3.x. **Are there any alternatives that make implementing comparisons as easy as the above `__cmp__`?** | Yep, it's easy to implement everything in terms of e.g. `__lt__` with a mixin class (or a metaclass, or a class decorator if your taste runs that way).
For example:
```
class ComparableMixin:
def __eq__(self, other):
return not self<other and not other<self
def __ne__(self, other):
return self<other or other<self
def __gt__(self, other):
return other<self
def __ge__(self, other):
return not self<other
def __le__(self, other):
return not other<self
```
Now your class can define just `__lt__` and multiply inherit from ComparableMixin (after whatever other bases it needs, if any). A class decorator would be quite similar, just inserting similar functions as attributes of the new class it's decorating (the result might be microscopically faster at runtime, at equally minute cost in terms of memory).
Of course, if your class has some particularly fast way to implement (e.g.) `__eq__` and `__ne__`, it should define them directly so the mixin's versions are not use (for example, that is the case for `dict`) -- in fact `__ne__` might well be defined to facilitate that as:
```
def __ne__(self, other):
return not self == other
```
but in the code above I wanted to keep the pleasing symmetry of only using `<`;-).
As to why `__cmp__` had to go, since we *did* have `__lt__` and friends, why keep another, different way to do exactly the same thing around? It's just so much dead-weight in every Python runtime (Classic, Jython, IronPython, PyPy, ...). The code that **definitely** won't have bugs is the code that isn't there -- whence Python's principle that there ought to be ideally one obvious way to perform a task (C has the same principle in the "Spirit of C" section of the ISO standard, btw).
This doesn't mean we go out of our way to prohibit things (e.g., near-equivalence between mixins and class decorators for some uses), but it definitely **does** mean that we don't like to carry around code in the compilers and/or runtimes that redundantly exists just to support multiple equivalent approaches to perform exactly the same task.
Further edit: there's actually an even better way to provide comparison AND hashing for many classes, including that in the question -- a `__key__` method, as I mentioned on my comment to the question. Since I never got around to writing the PEP for it, you must currently implement it with a Mixin (&c) if you like it:
```
class KeyedMixin:
def __lt__(self, other):
return self.__key__() < other.__key__()
# and so on for other comparators, as above, plus:
def __hash__(self):
return hash(self.__key__())
```
It's a very common case for an instance's comparisons with other instances to boil down to comparing a tuple for each with a few fields -- and then, hashing should be implemented on exactly the same basis. The `__key__` special method addresses that need directly. | To simplify this case there's a class decorator in Python 2.7+/3.2+, [functools.total\_ordering](http://docs.python.org/library/functools.html#functools.total_ordering), that can be used to implement what Alex suggests. Example from the docs:
```
@total_ordering
class Student:
def __eq__(self, other):
return ((self.lastname.lower(), self.firstname.lower()) ==
(other.lastname.lower(), other.firstname.lower()))
def __lt__(self, other):
return ((self.lastname.lower(), self.firstname.lower()) <
(other.lastname.lower(), other.firstname.lower()))
``` | __lt__ instead of __cmp__ | [
"",
"python",
"operator-overloading",
""
] |
I have two desktop applications. After closing the first application, the first application will start the second application.
How do I start the second application after finishing first application?
My first application creates a separate desktop. | You can use .NET's Process Class to start a process as other people described. Then the question is when to call.
In most cases, using either `Form.Closing` or `Form.Closed` event seems to be an easy choice.
However, if someone else can handle the event and can set `CancelEventArgs.Cancel` to true, this may not be the right place to do this. Also, `Form.Closing` and `Form.Closed` events will not be raised when `Application.Exit()` is called. I am not sure whether either of events will be raised if any unhandled exceptions occur. (Also, you have to decide whether you want to launch the second application in case of `Application.Exit()` or any unhandled exception).
If you really want to make sure the second application (App2) launches after the first application (App1) exited, you can play a trick:
1. Create a separate application (App0)
2. App0 launches App1
3. App0 waits for App1 to exit with Process.WaitExit()
4. App0 launches App2 and exits itself
The sample console app attached below shows a very simple case: my sample app launches the notepad first. Then, when the notepad exits, it launches mspaint and exits itself.
If you want to hide the console, you can simply set the 'Output Type' property from 'Console Application' to 'Windows Application' under 'Application' tab of Project Property.
Sample code:
```
using System;
using System.Diagnostics;
namespace ProcessExitSample
{
class Program
{
static void Main(string[] args)
{
try
{
Process firstProc = new Process();
firstProc.StartInfo.FileName = "notepad.exe";
firstProc.EnableRaisingEvents = true;
firstProc.Start();
firstProc.WaitForExit();
//You may want to perform different actions depending on the exit code.
Console.WriteLine("First process exited: " + firstProc.ExitCode);
Process secondProc = new Process();
secondProc.StartInfo.FileName = "mspaint.exe";
secondProc.Start();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred!!!: " + ex.Message);
return;
}
}
}
}
``` | Use the [Process class](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx) when you are exiting your first application.
```
var p = new Process();
p.StartInfo.FileName = "notepad.exe"; // just for example, you can use yours.
p.Start();
``` | How do I launch application one from another in C#? | [
"",
"c#",
"desktop-application",
"launch",
""
] |
I'm trying to find a Java library to highlight code. I don't want to highlight Java code. I want a library that will easily allow me to highlight a macro language of my own, in a code editor of my own written in Java. | JSyntaxPane is decent. Advanced and decent IDEs use either Lexer/Parsers such as Antlr and Javacc or regular expressions. Implementing it correctly is not a trivial task.
As you mentioned "a macro language of my own", I suggest taking a look at [Lexer/Parser generators for Java](http://java-source.net/open-source/parser-generators) and maybe JEdit syntax package source code(google it, reached the maximum hyperlinks) for lexing strategies. | [GesHi](http://qbnz.com/highlighter/) is pretty good. There is a list of highlighters [here](http://www.webresourcesdepot.com/11-syntax-highlighters-to-beautify-code-presentation/).
UPDATE: missed that you wanted a java lib. Try [jedit syntax](http://syntax.jedit.org/) package. | Where can I find a Java library for code highlighting? | [
"",
"java",
""
] |
Hi i am trying to create the affine transform that will allow me to transform a triangle into another one. What i have are the coordinates for the 2 triangles. Can you help me?
Following the answer by Adam Rosenfield i came up with this code in case anyone is bored to solve the equation himself :
```
public static AffineTransform createTransform(ThreePointSystem source,
ThreePointSystem dest) {
double x11 = source.point1.getX();
double x12 = source.point1.getY();
double x21 = source.point2.getX();
double x22 = source.point2.getY();
double x31 = source.point3.getX();
double x32 = source.point3.getY();
double y11 = dest.point1.getX();
double y12 = dest.point1.getY();
double y21 = dest.point2.getX();
double y22 = dest.point2.getY();
double y31 = dest.point3.getX();
double y32 = dest.point3.getY();
double a1 = ((y11-y21)*(x12-x32)-(y11-y31)*(x12-x22))/
((x11-x21)*(x12-x32)-(x11-x31)*(x12-x22));
double a2 = ((y11-y21)*(x11-x31)-(y11-y31)*(x11-x21))/
((x12-x22)*(x11-x31)-(x12-x32)*(x11-x21));
double a3 = y11-a1*x11-a2*x12;
double a4 = ((y12-y22)*(x12-x32)-(y12-y32)*(x12-x22))/
((x11-x21)*(x12-x32)-(x11-x31)*(x12-x22));
double a5 = ((y12-y22)*(x11-x31)-(y12-y32)*(x11-x21))/
((x12-x22)*(x11-x31)-(x12-x32)*(x11-x21));
double a6 = y12-a4*x11-a5*x12;
return new AffineTransform(a1, a4, a2, a5, a3, a6);
}
``` | I'm going to assume you're talking about 2D here. An affine transformation matrix has 9 values in it:
```
| a1 a2 a3 |
A = | a4 a5 a6 |
| a7 a8 a9 |
```
There are 3 input vertices `x1`, `x2`, and `x3`, which when transformed should become `y1`, `y2`, `y3`. However, since we're working in homogeneous coordinates, applying `A` to `x1` doesn't necessarily give `y1` -- it gives a multiple of `y1`. So, we also have the unknown multipliers `k1`, `k2`, and `k3`, with the equations:
```
A*x1 = k1*y1
A*x2 = k2*y2
A*x3 = k3*y3
```
Each of those is a vector, so we really have 9 equations in 12 unknowns, so the solution is going to be underconstrained. If we require that `a7=0`, `a8=0`, and `a9=1`, then the solution will be unique (this choice is natural, since it means if the input point is (`x`, `y`, 1), then the output point will always have homogeneous coordinate 1, so the resulting transform is just a 2x2 transform plus a translation).
Hence, this reduces the equations to:
```
a1*x11 + a2*x12 + a3 = k1*y11
a4*x11 + a5*x12 + a6 = k1*y12
1 = k1
a1*x21 + a2*x22 + a3 = k2*y21
a4*x21 + a5*x22 + a6 = k2*y22
1 = k2
a1*x31 + a2*x32 + a3 = k3*y31
a4*x31 + a5*x32 + a6 = k3*y32
1 = k3
```
So, `k1` = `k2` = `k3` = 1. Plugging these in and converting to matrix form yields:
```
| x11 x12 1 0 0 0 | | a1 | | y11 |
| x21 x22 1 0 0 0 | | a2 | | y21 |
| x31 x32 1 0 0 0 | * | a3 | = | y31 |
| 0 0 0 x11 x12 1 | | a4 | | y12 |
| 0 0 0 x21 x22 1 | | a5 | | y22 |
| 0 0 0 x31 x32 1 | | a6 | | y32 |
```
Solving this 6x6 system of equations yields you your affine transformation matrix `A`. It will have a unique solution if and only if the 3 points of your source triangle are not collinear. | Hey, guys, Without Loss of Generality, make the two triangles have the origin as one vertex (you can tack on the affine shift later), so they're defined by the points **0, a, b, c, d** then multiply your points **x** by the matrix NM
where
M = inverse(**a b**) <--- this is 2x2 matrix with the points **a** and **b** as its columns
and
N = (**c d**)
That should do it. | Transform a triangle to another triangle | [
"",
"java",
"math",
"affinetransform",
""
] |
Let's say I have a very simple PrototypeJS class that looks like this:
```
var Foo = Class.create({
initialize: function() {
this.bar = 'bar';
},
dostuff: function() {
$$('.enabled').each( function(elem) {
alert(this.bar); //FAIL
});
}
});
```
This fails because the function being passed to **.each()** doesn't have any idea what *this* refers to.
How can I access the **bar** attribute of the Class from inside that function? | You can use [Prototype's bind function](http://www.prototypejs.org/api/function/bind), which 'locks [the function's] execution scope to an object'.
```
var Foo = Class.create({
initialize: function() {
this.bar = 'bar';
},
dostuff: function() {
$$('.enabled').each( function(elem) {
alert(this.bar);
}.bind(this)); // Set the execution scope to Foo
}
});
``` | Try:
```
dostuff: function() {
var that = this;
$$('.enabled').each( function(elem) {
alert(that.bar); //FTW
});
}
```
Or, pass a context to `each()`:
```
dostuff: function() {
$$('.enabled').each( function(elem) {
alert(this.bar); //FTW
}, this); // Context
}
``` | Giving a function within a class method of a PrototypeJS Class access to class members | [
"",
"javascript",
"oop",
"prototypejs",
""
] |
I have been using the CodeIgniter system for a while now - but [it has](http://codeigniter.com/forums/viewthread/120042/#594699) it's [short comings](http://codeigniter.com/forums/viewthread/100098/). I am grateful for what it taught me, but now I need a library for a new non-codeigniter project and so I am looking around for ideas on which libraries have things right and which don't. I will probably have to take pieces from several libraries to get everything I need.
I just took a look a the [Kohana PHP session](http://docs.kohanaphp.com/libraries/session) library and I like how it returns to the native PHP way of using the $\_SESSION superglobal instead of forcing a change to $this->session for data access.
At any rate, I wanted to know if there were other good session libraries out there I might be messing. There is a lot that must be handled in a session besides just CRUD functionally.
* Support for NON-cookie based session passing (i.e. Facebook or Flash uploaders)
* "Flash data" that only lasts for the next page load and then is auto-removed.
* Works with $\_SESSION or $this->session so that programmers don't have to change existing code.
* Supports setting a new session id (i.e. session\_id('new id')) in case you want to change the id mid-way through the page.
* Saves all data at the end of the page request instead of each time data is added or removed (saves extra DB queries).
* Supports using files, cookies, or Database for storage. (or memcached would be nice)
* Attempts to deny access in case of a session hijack. (IP, useragent, or [fingerprint](http://codeigniter.com/wiki/EckoSession/))
I just spent some time going over the logic for the CodeIgniter and Kohana session libraries and I came up with the following on how each starts and ends sessions for the page.
```
/**************
** Kohana Sessions
**************/
If not native file storage {
session_set_save_handler to the storage type (DB, cache, cookie...)
}
set the session_name() so php knows what cookie value to check
start session
/****** Saving ******/
session_write_close() which calls the given handler
/**************
** CI Sessions
**************/
Try to read_session() -> {
session = Get cookie (if using cookies will also contain data)
if(database) {
session .= pull data from database
}
checks if valid...
$this->userdata = session data
} else {
create a new one
}
/****** Saving ******/
session data is serialized either way
if(cookie) {
save cookie with serialized data and params like "last_activity"
}
if(database) {
save serialized data in db and session in cookie
}
``` | Did you have a look at [`Zend_Session`](http://framework.zend.com/manual/current/en/index.html#zend-session)?
* you can pass the session identifier via URL using PHP settings
* you can expire certain session variables by time or by hops (requests)
* migration into other apps won't be that easy and I think it's not very good when you mess with `$_SESSION` when you use `Zend_Session`
* `Zend_Session` has an adpater based-approach for saving session data. A [save-handler](http://framework.zend.com/manual/current/en/modules/zend.session.save-handler.html) for DBs is included, but its architecture allows for custom handlers to be passed in.
* `Zend_Session` supports validators to check the validity of a session. Here too we have an open architecture that allows you to pass in custom objects for validation.
* you can lock a session, aka make it read-only
* you can prevent the instantiation of multiple instances of the same session namespace
* plus there is a lot more to discover with `Zend_Session` such as regenerating session ids, issue remember-me-cookies, revoke remember-me-cookies and so on. | You can use this in CI: [EchoSession](http://codeigniter.com/wiki/EckoSession). | Best library for PHP Sessions | [
"",
"php",
"codeigniter",
"session",
"kohana",
""
] |
I have a problem of upgrading python from 2.4 to 2.6:
I have CentOS 5 (Full). It has python 2.4 living in /usr/lib/python2.4/ . Additional modules are living in /usr/lib/python2.4/site-packages/ . I've built python 2.6 from sources at /usr/local/lib/python2.6/ . I've set default python to python2.6 . Now old modules for 2.4 are out of pythonpath and are "lost". In particular, yum is broken ("no module named yum").
So what is the right way to migrate/install modules to python2.6? | They are not broken, they are simply not installed. The solution to that is to install them under 2.6. But first we should see if you really should do that...
Yes, Python will when installed replace the python command to the version installed (unless you run it with --alt-install). You don't exactly state what your problem is, so I'm going to guess. Your problem is that many local commands using Python now fail, because they get executed with Python 2.6, and not with Python 2.4. Is that correct?
If that is so, then simply delete /usr/local/bin/python, and make sure /usr/bin/python is a symbolic link to /usr/bin/python2.4. Then you would have to type python2.6 to run python2,6, but that's OK. That's the best way to do it. Then you only need to install the packages **you** need in 2.6.
But if my guess is wrong, and you really need to install all those packages under 2.6, then don't worry too much. First of all, install setuptools. It includes an easy\_install script, and you can then install modules with
```
easy_install <modulename>
```
It will download the module from pypi.python.org and install it. And it will also install any module that is a dependency. easy\_install can install any module that is using distutils as an installer, and not many don't. This will make installing 90% of those modules a breeze.
If the module has a C-component, it will compile it, and then you need the library headers too, and that will be more work, and all you can do there is install them the standard CentOS way.
You shouldn't use symbolic links between versions, because libraries are generally for a particular version. For 2.4 and 2.6 I think the .pyc files are compatible (but I'm not 100% sure), so that may work, but any module who uses C *will* break. And other versions of Python will have incompatible .pyc files as well. And I'm sure that if you do that, most Python people are not going to help you if you do it. ;-)
In general, I try too keep the system python "clean", I.e. I don't install anything there that isn't installed with the packaging tools. Instead I use virtualenv or buildout to let every application have their own python path where it's dependencies live. So every single project I have basically has it's own set of libraries. It gets easier that way. | Some Python libs may be still not accessible as with Python 2.6 `site-packages` is changed to `dist-packages`.
The only way in that case is to do move all stuff generated in site-packages (e.g. by `make install`) to dist-packages and create a sym-link. | Transition from Python2.4 to Python2.6 on CentOS, module migration problem | [
"",
"python",
"linux",
"upgrade",
"centos",
"python-2.6",
""
] |
I have backed myself into a a bit of a corner. Here is a simplified version of what I have (in C#):
```
class OuterClass
{
private class BadClass
{
private int Data;
public BadClass()
{
Data = 0;
...
}
}
T Build<T>(Object Input)
{
T x = new T();
...
return x;
}
void SomeMethod()
{
BadClass a = Build<BadClass>(anObject);
...
}
...
}
```
The problem I have is that I now must change the initial value of Data depending on the instance of OuterClass that is creating the BadClass instance. Normally I would simply use a BadClass constructor that takes a parameter:
```
public BadClass(int Data)
{
this.Data = Data;
...
}
```
But I use BadClass in several generic types so I must have a parameterless BadClass constructor. Too bad I can't do something like this:
```
Build<BadClass(5)>(anObject);
```
So, how do I give a constructor run-time information when I can't pass parameters into the constructor?
Is it possible to create a runtime instance of a BadClass type, give it the information it needs, and then use that in my generic types?
**EDIT:** I used List as an example generic type but that didn't fully express the depth of my dilemma...
I can create a test in Build to call an init function if I am working with a BadClass, but that is very hacky. I am hoping to find a slightly less ugly way to go about it. | If you need to have multiple BadClass types that are variations of generics, you can do so by changing your inheritance tree:
```
class OuterClass {
private class BadClassBase {
// whatever BadClass does
}
private class BadClass : BadClassBase {
public BadClass(T item) {
...
}
}
}
```
Not sure if this is what you're going for but you can then create your List<BadClassBase>. | When you create the `List<BadClass>`, you are not creating any BadClass instances. Go ahead and create a that way, but when you create a BadClass instance to add to it, that's when you call your parameterized constructor:
```
List<BadClass> a = new List<BadClass>();
a.Add(new BadClass(1));
a.Add(new BadClass(2));
```
By the way, having the construction of a BadClass instance depend on which OuterClass is creating it is a bit of a code smell. What you you trying to accomplish? | Passing information to a constructor without using a parameter in C# | [
"",
"c#",
"generics",
"constructor",
""
] |
I want to use the ClassLoader to load a properties file for the Properties class. I've simplified the below code to remove error handling for the purposes of this discussion:
```
loader = this.getClass().getClassLoader();
in = loader.getResourceAsStream("theta.properties");
result = new Properties();
result.load(in);
```
In the same directory as this class I have the file "theta.properties" but the InputStream is always null. Am I putting the file in the wrong place? I'm using eclipse and its set to build the class files to the source folder - so that shouldn't be the problem.
I can't find anything in the JavaDoc to get the ClassLoader to tell me what classpath is being searched. | By using `getClass().getClassloader()` you look for "theta.properties" from the root path directory. Just use `getClass().getResourceAsStream()` to get a resource relative to that class. | If the file is in the same directory as the class, you have to prefix the class's package as a directory.
So if your package is:
```
package com.foo.bar;
```
Then your code is:
```
.getResourceAsStream("com/foo/bar/theta.properties");
``` | How do I use the Java ClassLoader to load a file fromthe classpath? | [
"",
"java",
"properties",
"classloader",
""
] |
I know its possible to use a wakelock to hold the screen, cpu, ect on but how can I programmatically change the "**Screen Timeout**" setting on an Android phone. | The [Settings.System](http://developer.android.com/reference/android/provider/Settings.System.html) provider offers a [SCREEN\_OFF\_TIMEOUT](http://developer.android.com/reference/android/provider/Settings.System.html#SCREEN_OFF_TIMEOUT) setting that might be what you are looking for. | ```
public class HelloWorld extends Activity
{
private static final int DELAY = 3000;
int defTimeOut = 0;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/hello_world.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.hello_world);
defTimeOut = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, DELAY);
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, DELAY);
}
@Override
protected void onDestroy()
{
super.onDestroy();
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut);
}
}
```
And also dont forget to add this permission in manifest:
```
android:name="android.permission.WRITE_SETTINGS"
``` | Android Screen Timeout | [
"",
"java",
"android",
"android-1.5-cupcake",
""
] |
how do start/stop services using net stop command in c#
for example
```
Dim pstart As New ProcessStartInfo
Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
Dim p As New Process
pstart.FileName = path + "\cmd.exe"
pstart.UseShellExecute = False
pstart.CreateNoWindow = True
pstart.WorkingDirectory = path
pstart.FileName = "cmd.exe"
pstart.Arguments = " net start mysql"
p.StartInfo = pstart
p.Start()
```
i have used process class but no result | Instead of using a crude method like Process.Start, you can use the [ServiceController](http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller(VS.80).aspx) class to start/stop a particular service on a local/remote machine.
```
using System.ServiceProcess;
ServiceController controller = new ServiceController();
controller.MachineName = ".";
controller.ServiceName = "mysql";
// Start the service
controller.Start();
// Stop the service
controller.Stop();
``` | You might want to take a look at the [System.ServiceProcess.ServiceController](http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx) class, which provides a managed interface to Windows' Services.
In this case:
```
var mysql = new System.ServiceProcess.ServiceController("mysql");
if (mysql .Status == ServiceControllerStatus.Stopped) {
mysql.Start();
}
``` | how do start/stop services using net stop command in c# | [
"",
"c#",
"process",
""
] |
So, I have this array. It needs to be accessed outside the scope of this function. I have been slapping a pointer to it into a pair which gets put into a deque. But once I'm outside the scope, the local stack is gone, the array is invalid, and I've just got a useless pointer, right?
So I've trying to put this array onto the scope-transcending heap, where it will remain until I delete it at a later time. But I'm having issues getting this working. Right now g++ is coughing up errors about invalid conversion from 'int' to 'int\*'.
```
void randomFunction(int x, int y, int width, int height)
{
int **blah[4] = {x, y, width, height};
std::pair <foobar*, int* > tempPair (foobar1, blah);
randomDeque.push_front(tempPair);
}
```
I've also tried initializing it like this:
```
int *blah[4] = new int[4];
```
...and it says that the array must be initialized with a brace-enclosed initializer.
I'm really not used to working with pointers. What am I doing wrong? | The whole concept looks strange to me. If you declare array on the stack, it will not exist outside the scope of your function. If you allocate it using 'new' - make sure you 'delete' it sometime, otherwise it's **memory leak**!
The correct code with 'new' is:
```
int *blah = new int[4];
...
// don't forget to:
delete [] blah;
``` | There are two problems. First, indeed, you are confused about pointers/arrays:
```
int a[4]; // this is an array of 4 integers, a is the name of the array
int *a[4]; // This is an array of 4 *pointers* to int
```
So your declaration:
```
int **blah[4];
```
Define an array of 4 pointers to pointers array. Maybe you are confused by the following fact (I know I was when I learned C). If you *declare* a variable:
```
int *a;
```
This is a declaration of a pointer to an integer. But if you have a variable a which is a pointer, you get the thing it points to (an integer here) by using \*a:
```
*a = 1; // a is a pointer (i.e. an address), *a is the value pointed to by a.
```
So \* in declaration is used to declare pointer, but \* in statements is used to deference value.
But your second problem has nothing to do with pointer per-se. It is about ressource-management (memory being one, but file, locks being others). Anything allocated on the stack does not exist anymore when it is out of scope. In pure C, you only really have one solution: allocating on the heap with malloc, and making sure to free afterwards. So you would do something like:
```
// foo is a struct
foo *init_foo()
{
foo* tmp;
tmp = malloc(sizeof(*tmp));
// initialize tmp
return tmp;
}
```
And then, you will clean it with another function:
```
foo *a;
a = init_foo();
// do stuff
clean_foo(a);
```
Example: the FILE\* handle and fopen/fclose (in addition to allocating stuff, there are some things related to the OS to handle the file). Another solution is to use alloca, which is not standard C, but is supported by many toolchains.
In C++, you can use smart pointers, which use for example reference counting to do resources management. I am less familiar with C++, and I am sure people will jump in on that part. The idea with reference counting is that it still gives some of the advantages of auto pointers (you don't have to call delete by yourself, which is extremely error-prone for non trivial projects), but without being purely scope-based. One reference counting-based smart pointer is shared\_ptr in boost. | Scope, arrays, and the heap | [
"",
"c++",
"pointers",
"scope",
""
] |
I have written some code for playing a `.wav` through my application. Now I want to play a mp3 file through.
I have .NET framework 1.1 | if you have .NET framework 1.1. only, probably your best approach is to use a P/Invoke wrapper for mciSendCommand
```
[DllImport("winmm.dll")]
private static extern long mciSendString(
string strCommand, StringBuilder returnString,
int returnBufferLength, IntPtr callback);
void PlayFile(string mp3FileName)
{
string deviceType = "MPEGVideo";
string fileName = mp3FileName;
string alias = "MyMp3File";
string playCommand = string.Format("open \"{0}\" type {1} alias {2}",
fileName, deviceType, alias);
mciSendString(playCommand, null, 0, IntPtr.Zero);
playCommand = string.Format("play {0} from 0", alias);
mciSendString(playCommand, null, 0, IntPtr.Zero);
// send these when you are finished
// playCommand = "stop MyMp3File";
// playCommand = "close MyMp3File";
}
``` | You can try [NAudio](http://naudio.codeplex.com/). Otherwise you may consider to use a native library using Interop. | play mp3 audiofile | [
"",
"c#",
".net",
"audio",
"mp3",
""
] |
Suppose I have a JEditorPane in a JPanel. I want to be able to execute a callback each time the user enters/pastes text in the JEditorPane component. What type of listener should I create? | One way of doing this is to create a custom Document and override the insertString method. For example:
```
class CustomDocument extends PlainDocument {
@Override
public void insertString(int offset, String string, AttributeSet attributeSet)
throws BadLocationException {
// Do something here
super.insertString(offset, string, attributeSet);
}
}
```
This allows you to find out what is inserted and veto it if you wish (by not calling super.insertString). You can apply this document using this:
```
editorPane.setDocument(new CustomDocument());
``` | You can use a DocumentListener to be notified of any changes to the Document.
Since I can't yet leave comments, I would just like to say that it is better to use listeners when possible than it is to override a class, like the example given above that overrides the PlainDocument.
The listener approach will work on a JTextField, JTextArea, JEditorPane or JTextPane. By default an editor pane uses a HTMLDocument and a JTextPane uses a StyledDocument. So you are losing functionality by forcing the component to use a PlainDocument.
If your concern is about editing the text before it is added to the Document, then you should be using a [DocumentFilter](http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter) | What JEditorPane event should I create a listener for? | [
"",
"java",
"swing",
"events",
"jeditorpane",
""
] |
I have a property within a class, that I need to iterate through all the possible distinct IDs from a relationship.
I am within a User, which belongs to a Company. Companies, have many solutions and each solution has many "SolutionPortals". What I want, is a list of all distinct "PortalIds" from the "SolutionPortals" (SolutionPortal.PortalID) that are in the DB.
I can't for the life of me get this as a single list. I keep getting:
```
var solutionIds = from s in this.Company.Solutions.Select(s=>s.SolutionPortals)
select s.Select(sp=> sp.PortalID);
```
Of course this makes sense, since there is a list of Solutions, with a List of SolutionPortals, but I need to select JUST the IDS out into their own list.
```
IEnumerable<IEnumerable<int>> // <-- Don't want this
IEnumerable<int> // <-- I want this
```
Any help would be EXTREMELY appreciated.
Thanks/ | [`SelectMany`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx) is the key here:
```
var solutionIds = this.Company
.Solutions
.SelectMany(s=>s.SolutionPortals)
.Select(sp => sp.PortalId)
.Distinct();
``` | You probably need something like this:
```
var listOfIds = listOfSolutionPortals.SelectMany(sps => sps.Solutions)
.Select(sp => sp.PortalId);
``` | LinqToSql - Getting a list of distinct IDs from a nested list | [
"",
"c#",
"linq-to-sql",
""
] |
I'm running a .NET remoting application built using .NET 2.0. It is a console app, although I removed the [STAThread] on Main.
The TCP channel I'm using uses a ThreadPool in the background.
I've been reported that when running on a dual core box, under heay load, the application never uses more than 50% of the CPU (although I've seen it at 70% or more on a quad core).
Is there any restriction in terms of multi-core for remoting apps or ThreadPools?
Is it needed to change something in order to make a multithreaded app run on several cores?
Thanks | There shouldn't be.
There are several reasons why you could be seeing this behavior:
1. Your threads are IO bound.
In that case you won't see a lot of parallelism, because everything will be waiting on the disk. A single disk is inherently sequential.
2. Your lock granularity is too small
Your app may be spending most of it's time obtaining locks, rather than executing your app logic. This can slow things down considerably.
3. Your lock granularity is too big
If your locking is not granular enough, your other threads may spend a lot of time waiting.
4. You have a lot of lock contention
Your threads might all be trying to lock the same resources at the same time, making them inherently sequential.
5. You may not be partitioning your threads correctly.
You may be running the wrong things on multiple threads. For example, if you are using one thread per connection, you may not be taking advantage of available parallelism within the task you are running on that thread. Try splitting those tasks up into chunks that can run in parallel.
6. Your process may not have a lot of available parallelism
You might just be doing stuff that can't really be done in parallel.
I would try and investigate each one to see what the cause is. | Multithreaded applications will use all of your cores.
I suspect your behavior is due to this statement:
> The TCP channel I'm using uses a ThreadPool in the background.
TCP, as well as most socket/file/etc code, tends to use very little CPU. It's spending most of its time waiting, so the CPU usage of your program will probably never spike. Try using the threadpool with heavy computations, and you'll see your processor spike to near 100% CPU usage. | Are multithreaded apps bound to a single core? | [
"",
"c#",
"performance",
"multithreading",
""
] |
I've read in a few places now that the maximum instance size for a struct should be 16 bytes.
But I cannot see where that number (16) comes from.
Browsing around the net, I've found some who suggest that it's an approximate number for good performance but Microsoft talk like it is a hard upper limit. (e.g. [MSDN](http://msdn.microsoft.com/en-us/library/ms229017.aspx) )
Does anyone have a definitive answer about why it is 16 bytes? | It is just a performance rule of thumb.
The point is that because value types are passed by value, the entire size of the struct has to be copied if it is passed to a function, whereas for a reference type, only the reference (4 bytes) has to be copied. A struct might save a bit of time though because you remove a layer of indirection, so even if it is larger than these 4 bytes, it might still be more efficient than passing a reference around. But at some point, it becomes so big that the cost of copying becomes noticeable. And a common rule of thumb is that this typically happens around 16 bytes. 16 is chosen because it's a nice round number, a power of two, and the alternatives are either 8 (which is too small, and would make structs almost useless), or 32 (at which point the cost of copying the struct is already problematic if you're using structs for performance reasons)
But ultimately, this is performance advice. It answers the question of "which would be most efficient to use? A struct or a class?". But it doesn't answer the question of "which best maps to my problem domain".
Structs and classes behave differently. If you need a struct's behavior, then I would say to make it a struct, no matter the size. At least until you run into performance problems, profile your code, and find that your struct is a problem.
your link even says that it is just a matter of performance:
> If one or more of these conditions are
> not met, create a reference type
> instead of a structure. Failure to
> adhere to this guideline can
> negatively impact performance. | If a structure is not larger than 16 bytes, it can be copied with a few simple processor instructions. If it's larger, a loop is used to copy the structure.
As long as the structure is not larger than 16 bytes, the processor has to do about the same work when copying the structure as when copying a reference. If the structure is larger, you lose the performance benefit of having a structure, and you should generally make it a class instead. | Why should a .NET struct be less than 16 bytes? | [
"",
"c#",
".net",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.