Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
When I use quick documentaion lookup (Ctrl+Q) on j2ee classes or annotations in IDEA I only get an empty javadoc. It only contains the basics like class name.
How do I add the javadoc to the libs IDEA provides itself?
|
You can attach javadoc to any library you have configure in your module or project. Just access the project structure windows `(File -> Project Structure)`, then select "modules" and select the module that has the dependency you want to configure.
Then select the "Dependencies" tab, select the dependency that's missing the javadoc and click "Edit". In the window that just showed up you see two buttons "Add" and "Specify Javadoc URL". If you have the javadoc in a jar file select the first one, if you want to point to a web site that contains the javadoc select the latest.
That's it.
|
If using maven:
"right click on your pom.xml" -> "Maven" -> then choose "Download Sources and Documentation"
To avoid this in the future: "Preferences" -> "Build, Execution, Deployment" -> "Build Tools" -> "Maven" -> "Importing" -> Check the Automatically download Sources and Documentation boxes.
Credit to Yacov Schondorf and Stephen Boesch from Intellij user forums.
|
Attaching additional javadoc in Intellij IDEA
|
[
"",
"java",
"intellij-idea",
"javadoc",
""
] |
There are so many Linux distributions to choose from! What is the "best" linux flavor for a web hosting environment running primarily:
Apache HTTP, Tomcat or JBoss, MySQL and Alfresco (not necessarily all in the same instance).
Are there any significant differences in terms of ease of administration and configuration, performance and stability for such applications, etc.?
What would you recommend?
Thanks!
Mike
|
They all use similar tools to administer things like webmin, and sshd.
What are you more familiar with. Red Hat based systems(fedora, mandriva) or Debian based systems(Ubuntu). This family divide will determine a few things. First rpm packaging vs deb packaging.
You also want to look at the level of activity of the project. Mandriva and Ubuntu are two examples of active distributions. That try to keep up with current releases of software.
Other than that most stuff performs with little difference.
|
You also might want to consider [OpenSolaris](http://opensolaris.org/), as it is from the same company which developed Java in the first place and I've heard rumours, that it supports threading better than Linux does and in Java threads are quite important.
Update: Since Oracle changed the distribution model of OpenSolaris to a more commercial one you might want to check out the open source fork [OpenIndiana](http://openindiana.org/) (thanks to sed for bringing this to my attention). Oracle seems to still be providing the non-open Solaris and does also own Java, so decide for yourself.
|
Which distro of Linux is best suited for Java web apps?
|
[
"",
"java",
"mysql",
"linux",
"hosting",
"alfresco",
""
] |
Since the release of Adobe AIR I am wondering why Java Web Start has not gained more attention in the past as to me it seems to be very similar, but web start is available for a much longer time.
Is it mainly because of bad marketing from Sun, or are there more technical concerns other than the need of having the right JVM installed? Do you have bad experiences using Web Start? If yes, which? What are you recommendations when using Web Start for distributing applications?
|
In my company we used Java Web Start to deploy Eclipse RCP applications. It was a pain to setup, but it works very well once in place. So the only recommendation I could make is to start small, to get the hang of it. Deploying one simple application first. Trying to deploy a complete product that is already made without experience with JWS gets complicated rather quickly.
Also, learning how to pass arguments to the JWS application was invaluable for debugging. Setting the Environment variable JAVAWS\_VM\_ARGS allows setting any arbitrary property to the Java Virtual machine. In my case:
-Xdebug -Xnoagent -Xrunjdwp:transport=dt\_socket,server=y,suspend=y,address=4144
Helpful when you need to check problems during start-up (suspend=y)
I think the main problem for the acceptance of Java Web Start is that it is relatively difficult to setup. Also, somehow there is this dissonance: When you have a desktop application, people expects a installer they can double click. When you have a web application, people expects they can use it right from the browser. Java Web Start is neither here not there...
It is widely used in intranets, though.
|
I work in the intranet of a Bank since 5 years, and my departament has developed and distributed a LOT of Java Web Start Applications which are used all arround the world, i think Java Web Start has the best of the Desktop applications (easy development, rich user interface, processing power in the client machine) and the Internet applications (easy deployment and upgrade).
I really like Java Web Start
|
Objections against Java Webstart?
|
[
"",
"java",
"java-web-start",
""
] |
Does someone have experience with storing key-value pairs in a database?
I've been using this type of table:
```
CREATE TABLE key_value_pairs (
itemid varchar(32) NOT NULL,
itemkey varchar(32) NOT NULL,
itemvalue varchar(32) NOT NULL,
CONSTRAINT ct_primarykey PRIMARY KEY(itemid,itemkey)
)
```
Then for example the following rows could exist:
```
itemid itemkey itemvalue
---------------- ------------- ------------
123 Colour Red
123 Size Medium
123 Fabric Cotton
```
The trouble with this scheme is the SQL syntax required to extract data is quite complex.
Would it be better to just create a series of key/value columns?
```
CREATE TABLE key_value_pairs (
itemid varchar(32) NOT NULL,
itemkey1 varchar(32) NOT NULL,
itemvalue1 varchar(32) NOT NULL,
itemkey2 varchar(32) NOT NULL,
itemvalue2 varchar(32) NOT NULL,
. . .etc . . .
)
```
This will be easier and faster to query but lacks the extensibility of the first approach.
Any advice?
|
Before you continue on your approach, I would humbly suggest you step back and consider if you really want to store this data in a "Key-Value Pair"table. I don't know your application but my experience has shown that every time I have done what you are doing, later on I wish I had created a color table, a fabric table and a size table.
Think about referential integrity constraints, if you take the key-value pair approach, the database can't tell you when you are trying to store a color id in a size field
Think about the performance benefits of joining on a table with 10 values versus a generic value that may have thousands of values across multiple domains. How useful is an index on Key Value really going to be?
Usually the reasoning behind doing what you are doing is because the domains need to be "user definable". If that is the case then even I am not going to push you towards creating tables on the fly (although that is a feasible approach).
However, if your reasoning is because you think it will be easier to manage than multiple tables, or because you are envisioning a maintenance user interface that is generic for all domains, then stop and think really hard before you continue.
|
In most cases that you would use the first method, it's because you haven't really sat down and thought out your model. "Well, we don't know what the keys will be yet". Generally, this is pretty poor design. It's going to be slower than actually having your keys as columns, which they should be.
I'd also question why your id is a varchar.
In the rare case that you really must implement a key/value table, the first solution is fine, although, I'd generally want to have the keys in a separate table so you aren't storing varchars as the keys in your key/value table.
eg,
```
CREATE TABLE valid_keys (
id NUMBER(10) NOT NULL,
description varchar(32) NOT NULL,
CONSTRAINT pk_valid_keys PRIMARY KEY(id)
);
CREATE TABLE item_values (
item_id NUMBER(10) NOT NULL,
key_id NUMBER(10) NOT NULL,
item_value VARCHAR2(32) NOT NULL,
CONSTRAINT pk_item_values PRIMARY KEY(item_id),
CONSTRAINT fk_item_values_iv FOREIGN KEY (key_id) REFERENCES valid_keys (id)
);
```
You can then even go nuts and add a "TYPE" to the keys, allowing some type checking.
|
Key value pairs in relational database
|
[
"",
"sql",
"database",
""
] |
For the following HTML:
```
<form name="myForm">
<label>One<input name="area" type="radio" value="S" /></label>
<label>Two<input name="area" type="radio" value="R" /></label>
<label>Three<input name="area" type="radio" value="O" /></label>
<label>Four<input name="area" type="radio" value="U" /></label>
</form>
```
Changing from the following JavaScript code:
```
$(function() {
var myForm = document.myForm;
var radios = myForm.area;
// Loop through radio buttons
for (var i=0; i<radios.length; i++) {
if (radios[i].value == "S") {
radios[i].checked = true; // Selected when form displays
radioClicks(); // Execute the function, initial setup
}
radios[i].onclick = radioClicks; // Assign to run when clicked
}
});
```
Thanks
EDIT: The response I selected answers the question I asked, however I like the answer that uses `bind()` because it also shows how to distinguish the group of radio buttons
|
```
$( function() {
$("input:radio")
.click(radioClicks)
.filter("[value='S']")
.attr("checked", "checked");
});
```
|
```
$(document).ready(function(){
$("input[name='area']").bind("click", radioClicks);
});
functionradioClicks() {
alert($(this).val());
}
```
I like to use `bind()` instead of directly wiring the event handler because you can pass additional data to the event hander (not shown here but the data is a third bind() argument) and because you can easily unbind it (and you can bind and unbind by group--see the jQuery docs).
<http://docs.jquery.com/Events/bind#typedatafn>
|
Using jQuery, what is the best way to set onClick event listeners for radio buttons?
|
[
"",
"javascript",
"jquery",
""
] |
I'm having a little problem and I don't see why, it's easy to go around it, but still I want to understand.
I have the following class :
```
public class AccountStatement : IAccountStatement
{
public IList<IAccountStatementCharge> StatementCharges { get; set; }
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
public AccountStatement(IPeriod period, int accountID)
{
StatementCharges = new List<IAccountStatementCharge>();
StartDate = new Date(period.PeriodStartDate);
EndDate = new Date(period.PeriodEndDate);
AccountID = accountID;
}
public void AddStatementCharge(IAccountStatementCharge charge)
{
StatementCharges.Add(charge);
}
```
}
(note startdate,enddate,accountID are automatic property to...)
If I use it this way :
```
var accountStatement = new AccountStatement{
StartDate = new Date(2007, 1, 1),
EndDate = new Date(2007, 1, 31),
StartingBalance = 125.05m
};
```
When I try to use the method "AddStatementCharge: I end up with a "null" StatementCharges list... In step-by-step I clearly see that my list get a value, but as soon as I quit de instantiation line, my list become "null"
|
This code:
```
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
```
is undoubtedly not what you wanted. That makes a second instance of AccountStatement and does nothing with it.
I think what you meant was this instead:
```
public AccountStatement() : this(new Period(new NullDate().DateTime, new NullDate().DateTime), 0)
{
}
```
|
Use
```
public AccountStatement() : this(new Period(new NullDate().DateTime,newNullDate().DateTime), 0) { }
```
insetad of
```
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
```
|
C# 3.0 - Object initializer
|
[
"",
"c#",
".net-3.5",
""
] |
In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar)
|
```
Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)
```
To run this on a column, replace GetDate() with your column name.
The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value.
|
```
SELECT DATEADD(mm, DATEDIFF(mm, 0, @date), 0)
```
|
Simplest way to create a date that is the first day of the month, given another date
|
[
"",
"sql",
"sql-server",
"datetime",
"date",
""
] |
I am using jProfiler to find memory leaks in a Java swing application. I have identified instances of a JFrame which keeps growing in count.
This frame is opened, and then closed.
Using jProfiler, and viewing the Paths to GC Root there is only one reference, 'JNI Global reference'.
What does this mean? Why is it hanging on to each instance of the frame?
|
Wikipedia has a good overview of [Java Native Interface](http://en.wikipedia.org/wiki/Java_Native_Interface), essentially it allows communication between Java and native operating system libraries writen in other languages.
JNI global references are prone to memory leaks, as they are not automatically garbage collected, and the programmer must explicitly free them. If you are not writing any JNI code yourself, it is possible that the library you are using has a memory leak.
**edit** [here](http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/refs.html) is a bit more info on local vs. global references, and why global references are used (and how they should be freed)
|
A JNI global reference is a reference from "native" code to a Java object managed by the Java garbage collector. Its purpose is to prevent collection of an object that is still in use by native code, but doesn't appear to have any live references in the Java code.
A JFrame is a `java.awt.Window`, and is associated with a "native" Window object. When you are completely finished with a particular JFrame instance, you should invoke its `dispose()` method to clean up.
I am not sure if any native code is creating a global reference to the JFrame, but it seems likely. If it does, this will prevent the JFrame from being garbage collected. If you are creating many Windows (or subclasses) and seeing that they are never collected, make sure that they are disposed.
|
What is 'JNI Global reference'
|
[
"",
"java",
"swing",
"jprofiler",
""
] |
To my amazement I just discovered that the C99 stdint.h is missing from MS Visual Studio 2003 upwards. I'm sure they have their reasons, but does anyone know where I can download a copy? Without this header I have no definitions for useful types such as uint32\_t, etc.
|
Turns out you can download a MS version of this header from:
<https://github.com/mattn/gntp-send/blob/master/include/msinttypes/stdint.h>
A portable one can be found here:
<http://www.azillionmonkeys.com/qed/pstdint.h>
Thanks to the [Software Rambling](http://stephendoyle.blogspot.com/2008/03/c-tr1-stdinth-still-missing-from-visual.html)s blog.
*NB:* The Public Domain version of the header, mentioned by [Michael Burr](https://stackoverflow.com/users/12711/michael-burr) in a comment, can be find as an archived copy [here](https://web.archive.org/web/20101104120614/http://snipplr.com/view/18199/stdinth/). An updated version can be found in [the Android source tree for libusb\_aah](https://android.googlesource.com/platform/external/libusb_aah/+/master/msvc/stdint.h).
|
Just define them yourself.
```
#ifdef _MSC_VER
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
```
|
C99 stdint.h header and MS Visual Studio
|
[
"",
"c++",
"c",
"visual-studio",
"c99",
""
] |
After I [messed up the description of my previous post](https://stackoverflow.com/questions/121922/automatic-casts) on this I have sat down and tried to convey my exact intent.
I have a class called P which performs some distinct purpose. I also have PW which perform some distinct purpose on P. PW has no member variables, just member functions.
From this description you would assume that the code would follow like this:
```
class P
{
public:
void a( );
};
class PW
{
public:
PW( const P& p ) : p( p ) { }
void b( );
P& p;
};
class C
{
public:
P GetP( ) const { return p; }
private:
P p;
};
// ...
PW& p = c.GetP( ); // valid
// ...
```
However that brings up a problem. I can't call the functions of P without indirection everywhere.
```
// ...
p->p->a( )
// ...
```
**What I would like to do is call p->a( ) and have it automatically determine that I would like to call the member function of P.**
Also having a member of PW called *a* doesn't really scale - what if I add (or remove) another function to P - this will need to be added (or removed) to PW.
|
You could try overriding operator\* and operator-> to return access to the embedded p.
Something like this might do the trick :
```
class P
{
public:
void a( ) { std::cout << "a" << std::endl; }
};
class PW
{
public:
PW(P& p) : p(p) { }
void b( ) { std::cout << "b" << std::endl; }
P & operator*() { return p; }
P * operator->() { return &p; }
private:
P & p;
};
class C
{
public:
P & getP() { return p; }
private:
P p;
};
int main()
{
C c;
PW pw(c.getP());
(*pw).a();
pw->a();
pw.b();
return EXIT_SUCCESS;
}
```
This code prints
```
a
a
b
```
However, this method may confuse the user since the semantic of operator\* and operator-> becomes a little messed up.
|
If you make P a superclass to PW, like you did in your previous question, you could call p->a() and it would direct to class P. It seems like you've already considered and rejected this though, judging from this question. If so, would you care to elaborate why this wont work for you?
|
Automatic Casts redux
|
[
"",
"c++",
"casting",
""
] |
I couldn't find any useful information on Microsoft's site, so here is the question: has the compiler in Visual C++ 2008 been improved significantly since the 2005 version? I'm especially looking for better optimization.
|
Straight from the horses mouth....
> <http://msdn.microsoft.com/en-us/library/bb384632.aspx>
|
[Somasegar](http://blogs.msdn.com/somasegar) has some notes in this [blog post](http://blogs.msdn.com/somasegar/archive/2007/09/27/vs-2008-performance-improvements.aspx).
Mainly about [incremental build improvements](http://blogs.msdn.com/vcblog/archive/2007/03/02/managed-incremental-build.aspx) and [multi core improvements](http://blogs.msdn.com/vcblog/archive/2007/03/12/multi-processor-builds-in-orcas.aspx).
|
Difference between Visual C++ 2008 and 2005
|
[
"",
"c++",
"visual-studio",
"visual-studio-2008",
"visual-studio-2005",
"compiler-construction",
""
] |
I am hosting [SpiderMonkey](http://developer.mozilla.org/En/SpiderMonkey/JSAPI_Reference) in a current project and would like to have template functions generate some of the simple property get/set methods, eg:
```
template <typename TClassImpl, int32 TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp)
{
if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL))
return ::JS_ValueToInt32(cx, *vp, &(pImpl->*mem));
return JS_FALSE;
}
```
Used:
```
::JSPropertySpec Vec2::s_JsProps[] = {
{"x", 1, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::x>, &JsWrap::WriteProp<Vec2, &Vec2::x>},
{"y", 2, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::y>, &JsWrap::WriteProp<Vec2, &Vec2::y>},
{0}
};
```
This works fine, however, if I add another member type:
```
template <typename TClassImpl, JSObject* TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp)
{
if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL))
return ::JS_ValueToObject(cx, *vp, &(pImpl->*mem));
return JS_FALSE;
}
```
Then Visual C++ 9 attempts to use the JSObject\* wrapper for int32 members!
```
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'specialization' : cannot convert from 'int32 JsGlobal::Vec2::* ' to 'JSObject *JsGlobal::Vec2::* const '
1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2973: 'JsWrap::ReadProp' : invalid template argument 'int32 JsGlobal::Vec2::* '
1> d:\projects\testing\jswnd\src\wrap_js.h(64) : see declaration of 'JsWrap::ReadProp'
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'JSPropertyOp'
1> None of the functions with this name in scope match the target type
```
Surprisingly, parening JSObject\* incurs a parse error! (unexpected '('). This is probably a VC++ error (can anyone test that "template void foo() {}" compiles in GCC?). Same error with "typedef JSObject\* PObject; ..., PObject TClassImpl::*mem>", void*, struct Undefined\*, and double. Since the function usage is fully instantiated: "&ReadProp", there should be no normal function overload semantics coming into play, it is a defined function at that point and gets priority over template functions. It seems the template ordering is failing here.
Vec2 is just:
```
class Vec2
{
public:
int32 x, y;
Vec2(JSContext* cx, JSObject* obj, uintN argc, jsval* argv);
static ::JSClass s_JsClass;
static ::JSPropertySpec s_JsProps[];
};
```
JSPropertySpec is described in JSAPI link in OP, taken from header:
```
typedef JSBool
(* JS_DLL_CALLBACK JSPropertyOp)(JSContext *cx, JSObject *obj, jsval id,
jsval *vp);
...
struct JSPropertySpec {
const char *name;
int8 tinyid;
uint8 flags;
JSPropertyOp getter;
JSPropertyOp setter;
};
```
|
Pretty sure VC++ has "issues" here. Comeau and g++ 4.2 are both happy with the following program:
```
struct X
{
int i;
void* p;
};
template<int X::*P>
void foo(X* t)
{
t->*P = 0;
}
template<void* X::*P>
void foo(X* t)
{
t->*P = 0;
}
int main()
{
X x;
foo<&X::i>(&x);
foo<&X::p>(&x);
}
```
VC++ 2008SP1, however, is having none of it.
I haven't the time to read through my standard to find out exactly what's what... but I think VC++ is in the wrong here.
|
Try changing the JSObject \* to another pointer type to see if that reproduces the error. Is JSObject defined at the point of use? Also, maybe JSObject\* needs to be in parens.
|
Are C++ non-type parameters to (function) templates ordered?
|
[
"",
"c++",
"templates",
"overloading",
""
] |
I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?
If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting [Unicode](http://en.wikipedia.org/wiki/Unicode) and different type sizes (and all browsers for that matter).
|
Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.
```
var fontSize = 12;
var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px"
console.log(height, width);
```
```
#Test
{
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap; /* Thanks to Herb Caudill comment */
}
```
```
<div id="Test">
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</div>
```
|
In **HTML 5**, you can just use the [Canvas.measureText method](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText) (further explanation [here](http://www.html5canvastutorials.com/tutorials/html5-canvas-text-metrics/)).
[Try this fiddle](http://jsfiddle.net/eNzjZ/34/):
```
/**
* Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
*
* @param {String} text The text to be rendered.
* @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
*
* @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
*/
function getTextWidth(text, font) {
// re-use canvas object for better performance
const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
const context = canvas.getContext("2d");
context.font = font;
const metrics = context.measureText(text);
return metrics.width;
}
function getCssStyle(element, prop) {
return window.getComputedStyle(element, null).getPropertyValue(prop);
}
function getCanvasFont(el = document.body) {
const fontWeight = getCssStyle(el, 'font-weight') || 'normal';
const fontSize = getCssStyle(el, 'font-size') || '16px';
const fontFamily = getCssStyle(el, 'font-family') || 'Times New Roman';
return `${fontWeight} ${fontSize} ${fontFamily}`;
}
console.log(getTextWidth("hello there!", "bold 12pt arial")); // close to 86
```
If you want to use the font-size of some specific element `myEl`, you can make use of the `getCanvasFont` utility function:
```
const fontSize = getTextWidth(text, getCanvasFont(myEl));
// do something with fontSize here...
```
Explanation: The `getCanvasFontSize` function takes some element's (by default: the `body`'s) font and converts it into a format compatible with the [Context.font property](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font). Of course any element must first be added to the DOM before usage, else it gives you bogus values.
## More Notes
There are several advantages to this approach, including:
* More concise and safer than the other (DOM-based) methods because it does not change global state, such as your DOM.
* Further customization is possible by [modifying more canvas text properties](http://diveintohtml5.info/canvas.html#text), such as `textAlign` and `textBaseline`.
NOTE: When you add the text to your DOM, remember to also take account of [padding, margin and border](http://api.jquery.com/outerwidth/).
NOTE 2: On some browsers, this method yields sub-pixel accuracy (result is a floating point number), on others it does not (result is only an int). You might want to run `Math.floor` (or `Math.ceil`) on the result, to avoid inconsistencies. Since the DOM-based method is never sub-pixel accurate, this method has even higher precision than the other methods here.
According to [this jsperf](http://jsperf.com/measure-text-width/4) (thanks to the contributors in comments), the *Canvas method* and the *DOM-based method* are about equally fast, if caching is added to the *DOM-based method* and you are not using Firefox. In Firefox, for some reason, this *Canvas method* is much much faster than the *DOM-based method* (as of September 2014).
## Performance
[This fiddle](http://jsfiddle.net/eNzjZ/70/) compares this Canvas method to a variation of [Bob Monteverde's DOM-based method](https://stackoverflow.com/a/5047712/2228771), so you can analyze and compare accuracy of the results.
|
Calculate text width with JavaScript
|
[
"",
"javascript",
"textbox",
""
] |
How do I lock compiled Java classes to prevent decompilation?
I know this must be very well discussed topic on the Internet, but I could not come to any conclusion after referring them.
Many people do suggest obfuscator, but they just do renaming of classes, methods, and fields with tough-to-remember character sequences but what about sensitive constant values?
For example, you have developed the encryption and decryption component based on a password based encryption technique. Now in this case, any average Java person can use [JAD](http://www.kpdus.com/jad.html) to decompile the class file and easily retrieve the password value (defined as constant) as well as [salt](http://en.wikipedia.org/wiki/Salt_%28cryptography%29) and in turn can decrypt the data by writing small independent program!
Or should such sensitive components be built in native code (for example, VC++) and call them via [JNI](http://en.wikipedia.org/wiki/Java_Native_Interface)?
|
Some of the more advanced Java bytecode obfuscators do much more than just class name mangling. [Zelix KlassMaster](http://www.zelix.com/), for example, can also scramble your code flow in a way that makes it really hard to follow and works as an excellent code optimizer...
Also many of the obfuscators are also able to scramble your string constants and remove unused code.
Another possible solution (not necessarily excluding the obfuscation) is to use [encrypted JAR files](http://www.componio.com/products/jinstaller/jinstaller_secure_edition/jarcryp.html) and a custom classloader that does the decryption (preferably using native runtime library).
Third (and possibly offering the strongest protection) is to use native ahead of time compilers like [GCC](http://en.wikipedia.org/wiki/GNU_Compiler_Collection) or [Excelsior JET](http://www.excelsior-usa.com/jet.html), for example, that compile your Java code directly to a platform specific native binary.
In any case You've got to remember that as the saying goes in Estonian "Locks are for animals". Meaning that every bit of code is available (loaded into memory) during the runtime and given enough skill, determination and motivation, people can and will decompile, unscramble and hack your code... Your job is simply to make the process as uncomfortable as you can and still keep the thing working...
|
As long as they have access to both the encrypted data and the software that decrypts it, there is basically no way you can make this completely secure. Ways this has been solved before is to use some form of external black box to handle encryption/decryption, like dongles, remote authentication servers, etc. But even then, given that the user has full access to their own system, this only makes things difficult, not impossible -unless you can tie your product directly to the functionality stored in the "black box", as, say, online gaming servers.
|
How to lock compiled Java classes to prevent decompilation?
|
[
"",
"java",
"jvm",
"decompiling",
""
] |
How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.
**EDIT**: [The Java Tutorials - Drag and Drop and Data Transfer](http://java.sun.com/docs/books/tutorial/uiswing/dnd/index.html).
|
I liked [Terai Atsuhiro san's DnDTabbedPane](http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html), but I wanted more from it. The original Terai implementation transfered tabs within the TabbedPane, but it would be nicer if I could drag from one TabbedPane to another.
Inspired by @[Tom](https://stackoverflow.com/questions/60269/how-to-implement-draggable-tab-using-java-swing#60306)'s effort, I decided to modify the code myself.
There are some details I added. For example, the ghost tab now slides along the tabbed pane instead of moving together with the mouse.
`setAcceptor(TabAcceptor a_acceptor)` should let the consumer code decide whether to let one tab transfer from one tabbed pane to another. The default acceptor always returns `true`.
```
/** Modified DnDTabbedPane.java
* http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html
* originally written by Terai Atsuhiro.
* so that tabs can be transfered from one pane to another.
* eed3si9n.
*/
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
public class DnDTabbedPane extends JTabbedPane {
public static final long serialVersionUID = 1L;
private static final int LINEWIDTH = 3;
private static final String NAME = "TabTransferData";
private final DataFlavor FLAVOR = new DataFlavor(
DataFlavor.javaJVMLocalObjectMimeType, NAME);
private static GhostGlassPane s_glassPane = new GhostGlassPane();
private boolean m_isDrawRect = false;
private final Rectangle2D m_lineRect = new Rectangle2D.Double();
private final Color m_lineColor = new Color(0, 100, 255);
private TabAcceptor m_acceptor = null;
public DnDTabbedPane() {
super();
final DragSourceListener dsl = new DragSourceListener() {
public void dragEnter(DragSourceDragEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}
public void dragExit(DragSourceEvent e) {
e.getDragSourceContext()
.setCursor(DragSource.DefaultMoveNoDrop);
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
s_glassPane.setPoint(new Point(-1000, -1000));
s_glassPane.repaint();
}
public void dragOver(DragSourceDragEvent e) {
//e.getLocation()
//This method returns a Point indicating the cursor location in screen coordinates at the moment
TabTransferData data = getTabTransferData(e);
if (data == null) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
/*
Point tabPt = e.getLocation();
SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
if (DnDTabbedPane.this.contains(tabPt)) {
int targetIdx = getTargetTabIndex(tabPt);
int sourceIndex = data.getTabIndex();
if (getTabAreaBound().contains(tabPt)
&& (targetIdx >= 0)
&& (targetIdx != sourceIndex)
&& (targetIdx != sourceIndex + 1)) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
return;
} // if
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
*/
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
}
public void dragDropEnd(DragSourceDropEvent e) {
m_isDrawRect = false;
m_lineRect.setRect(0, 0, 0, 0);
// m_dragTabIndex = -1;
if (hasGhost()) {
s_glassPane.setVisible(false);
s_glassPane.setImage(null);
}
}
public void dropActionChanged(DragSourceDragEvent e) {
}
};
final DragGestureListener dgl = new DragGestureListener() {
public void dragGestureRecognized(DragGestureEvent e) {
// System.out.println("dragGestureRecognized");
Point tabPt = e.getDragOrigin();
int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
if (dragTabIndex < 0) {
return;
} // if
initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex);
try {
e.startDrag(DragSource.DefaultMoveDrop,
new TabTransferable(DnDTabbedPane.this, dragTabIndex), dsl);
} catch (InvalidDnDOperationException idoe) {
idoe.printStackTrace();
}
}
};
//dropTarget =
new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,
new CDropTargetListener(), true);
new DragSource().createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE, dgl);
m_acceptor = new TabAcceptor() {
public boolean isDropAcceptable(DnDTabbedPane a_component, int a_index) {
return true;
}
};
}
public TabAcceptor getAcceptor() {
return m_acceptor;
}
public void setAcceptor(TabAcceptor a_value) {
m_acceptor = a_value;
}
private TabTransferData getTabTransferData(DropTargetDropEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DropTargetDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DragSourceDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getDragSourceContext()
.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
class TabTransferable implements Transferable {
private TabTransferData m_data = null;
public TabTransferable(DnDTabbedPane a_tabbedPane, int a_tabIndex) {
m_data = new TabTransferData(DnDTabbedPane.this, a_tabIndex);
}
public Object getTransferData(DataFlavor flavor) {
return m_data;
// return DnDTabbedPane.this;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] f = new DataFlavor[1];
f[0] = FLAVOR;
return f;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.getHumanPresentableName().equals(NAME);
}
}
class TabTransferData {
private DnDTabbedPane m_tabbedPane = null;
private int m_tabIndex = -1;
public TabTransferData() {
}
public TabTransferData(DnDTabbedPane a_tabbedPane, int a_tabIndex) {
m_tabbedPane = a_tabbedPane;
m_tabIndex = a_tabIndex;
}
public DnDTabbedPane getTabbedPane() {
return m_tabbedPane;
}
public void setTabbedPane(DnDTabbedPane pane) {
m_tabbedPane = pane;
}
public int getTabIndex() {
return m_tabIndex;
}
public void setTabIndex(int index) {
m_tabIndex = index;
}
}
private Point buildGhostLocation(Point a_location) {
Point retval = new Point(a_location);
switch (getTabPlacement()) {
case JTabbedPane.TOP: {
retval.y = 1;
retval.x -= s_glassPane.getGhostWidth() / 2;
} break;
case JTabbedPane.BOTTOM: {
retval.y = getHeight() - 1 - s_glassPane.getGhostHeight();
retval.x -= s_glassPane.getGhostWidth() / 2;
} break;
case JTabbedPane.LEFT: {
retval.x = 1;
retval.y -= s_glassPane.getGhostHeight() / 2;
} break;
case JTabbedPane.RIGHT: {
retval.x = getWidth() - 1 - s_glassPane.getGhostWidth();
retval.y -= s_glassPane.getGhostHeight() / 2;
} break;
} // switch
retval = SwingUtilities.convertPoint(DnDTabbedPane.this,
retval, s_glassPane);
return retval;
}
class CDropTargetListener implements DropTargetListener {
public void dragEnter(DropTargetDragEvent e) {
// System.out.println("DropTarget.dragEnter: " + DnDTabbedPane.this);
if (isDragAcceptable(e)) {
e.acceptDrag(e.getDropAction());
} else {
e.rejectDrag();
} // if
}
public void dragExit(DropTargetEvent e) {
// System.out.println("DropTarget.dragExit: " + DnDTabbedPane.this);
m_isDrawRect = false;
}
public void dropActionChanged(DropTargetDragEvent e) {
}
public void dragOver(final DropTargetDragEvent e) {
TabTransferData data = getTabTransferData(e);
if (getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM) {
initTargetLeftRightLine(getTargetTabIndex(e.getLocation()), data);
} else {
initTargetTopBottomLine(getTargetTabIndex(e.getLocation()), data);
} // if-else
repaint();
if (hasGhost()) {
s_glassPane.setPoint(buildGhostLocation(e.getLocation()));
s_glassPane.repaint();
}
}
public void drop(DropTargetDropEvent a_event) {
// System.out.println("DropTarget.drop: " + DnDTabbedPane.this);
if (isDropAcceptable(a_event)) {
convertTab(getTabTransferData(a_event),
getTargetTabIndex(a_event.getLocation()));
a_event.dropComplete(true);
} else {
a_event.dropComplete(false);
} // if-else
m_isDrawRect = false;
repaint();
}
public boolean isDragAcceptable(DropTargetDragEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
return false;
}
public boolean isDropAcceptable(DropTargetDropEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
return false;
}
}
private boolean m_hasGhost = true;
public void setPaintGhost(boolean flag) {
m_hasGhost = flag;
}
public boolean hasGhost() {
return m_hasGhost;
}
/**
* returns potential index for drop.
* @param a_point point given in the drop site component's coordinate
* @return returns potential index for drop.
*/
private int getTargetTabIndex(Point a_point) {
boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM;
// if the pane is empty, the target index is always zero.
if (getTabCount() == 0) {
return 0;
} // if
for (int i = 0; i < getTabCount(); i++) {
Rectangle r = getBoundsAt(i);
if (isTopOrBottom) {
r.setRect(r.x - r.width / 2, r.y, r.width, r.height);
} else {
r.setRect(r.x, r.y - r.height / 2, r.width, r.height);
} // if-else
if (r.contains(a_point)) {
return i;
} // if
} // for
Rectangle r = getBoundsAt(getTabCount() - 1);
if (isTopOrBottom) {
int x = r.x + r.width / 2;
r.setRect(x, r.y, getWidth() - x, r.height);
} else {
int y = r.y + r.height / 2;
r.setRect(r.x, y, r.width, getHeight() - y);
} // if-else
return r.contains(a_point) ? getTabCount() : -1;
}
private void convertTab(TabTransferData a_data, int a_targetIndex) {
DnDTabbedPane source = a_data.getTabbedPane();
int sourceIndex = a_data.getTabIndex();
if (sourceIndex < 0) {
return;
} // if
Component cmp = source.getComponentAt(sourceIndex);
String str = source.getTitleAt(sourceIndex);
if (this != source) {
source.remove(sourceIndex);
if (a_targetIndex == getTabCount()) {
addTab(str, cmp);
} else {
if (a_targetIndex < 0) {
a_targetIndex = 0;
} // if
insertTab(str, null, cmp, null, a_targetIndex);
} // if
setSelectedComponent(cmp);
// System.out.println("press="+sourceIndex+" next="+a_targetIndex);
return;
} // if
if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {
//System.out.println("press="+prev+" next="+next);
return;
} // if
if (a_targetIndex == getTabCount()) {
//System.out.println("last: press="+prev+" next="+next);
source.remove(sourceIndex);
addTab(str, cmp);
setSelectedIndex(getTabCount() - 1);
} else if (sourceIndex > a_targetIndex) {
//System.out.println(" >: press="+prev+" next="+next);
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex);
setSelectedIndex(a_targetIndex);
} else {
//System.out.println(" <: press="+prev+" next="+next);
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex - 1);
setSelectedIndex(a_targetIndex - 1);
}
}
private void initTargetLeftRightLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height);
m_isDrawRect = true;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
}
}
private void initTargetTopBottomLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
}
}
private void initGlassPane(Component c, Point tabPt, int a_tabIndex) {
//Point p = (Point) pt.clone();
getRootPane().setGlassPane(s_glassPane);
if (hasGhost()) {
Rectangle rect = getBoundsAt(a_tabIndex);
BufferedImage image = new BufferedImage(c.getWidth(),
c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
c.paint(g);
image = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
s_glassPane.setImage(image);
} // if
s_glassPane.setPoint(buildGhostLocation(tabPt));
s_glassPane.setVisible(true);
}
private Rectangle getTabAreaBound() {
Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);
return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (m_isDrawRect) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(m_lineColor);
g2.fill(m_lineRect);
} // if
}
public interface TabAcceptor {
boolean isDropAcceptable(DnDTabbedPane a_component, int a_index);
}
}
class GhostGlassPane extends JPanel {
public static final long serialVersionUID = 1L;
private final AlphaComposite m_composite;
private Point m_location = new Point(0, 0);
private BufferedImage m_draggingGhost = null;
public GhostGlassPane() {
setOpaque(false);
m_composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);
}
public void setImage(BufferedImage draggingGhost) {
m_draggingGhost = draggingGhost;
}
public void setPoint(Point a_location) {
m_location.x = a_location.x;
m_location.y = a_location.y;
}
public int getGhostWidth() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getWidth(this);
}
public int getGhostHeight() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getHeight(this);
}
public void paintComponent(Graphics g) {
if (m_draggingGhost == null) {
return;
} // if
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(m_composite);
g2.drawImage(m_draggingGhost, (int) m_location.getX(), (int) m_location.getY(), null);
}
}
```
|
Curses! Beaten to the punch by a Google search. Unfortunately it's true there is no easy way to create draggable tab panes (or any other components) in Swing. So whilst the example above is complete this one I've just written is a bit simpler. So it will hopefully demonstrate the more advanced techniques involved a bit clearer. The steps are:
1. Detect that a drag has occurred
2. Draw the dragged tab to an offscreen buffer
3. Track the mouse position whilst dragging occurs
4. Draw the tab in the buffer on top of the component.
The above example will give you what you want but if you want to really understand the techniques applied here it might be a better exercise to round off the edges of this example and add the extra features demonstrated above to it.
Or maybe I'm just disappointed because I spent time writing this solution when one already existed :p
```
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public class DraggableTabbedPane extends JTabbedPane {
private boolean dragging = false;
private Image tabImage = null;
private Point currentMouseLocation = null;
private int draggedTabIndex = 0;
public DraggableTabbedPane() {
super();
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if(!dragging) {
// Gets the tab index based on the mouse position
int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY());
if(tabNumber >= 0) {
draggedTabIndex = tabNumber;
Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber);
// Paint the tabbed pane to a buffer
Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics totalGraphics = totalImage.getGraphics();
totalGraphics.setClip(bounds);
// Don't be double buffered when painting to a static image.
setDoubleBuffered(false);
paintComponent(totalGraphics);
// Paint just the dragged tab to the buffer
tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = tabImage.getGraphics();
graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this);
dragging = true;
repaint();
}
} else {
currentMouseLocation = e.getPoint();
// Need to repaint
repaint();
}
super.mouseDragged(e);
}
});
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if(dragging) {
int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10);
if(tabNumber >= 0) {
Component comp = getComponentAt(draggedTabIndex);
String title = getTitleAt(draggedTabIndex);
removeTabAt(draggedTabIndex);
insertTab(title, null, comp, null, tabNumber);
}
}
dragging = false;
tabImage = null;
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Are we dragging?
if(dragging && currentMouseLocation != null && tabImage != null) {
// Draw the dragged tab
g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this);
}
}
public static void main(String[] args) {
JFrame test = new JFrame("Tab test");
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(400, 400);
DraggableTabbedPane tabs = new DraggableTabbedPane();
tabs.addTab("One", new JButton("One"));
tabs.addTab("Two", new JButton("Two"));
tabs.addTab("Three", new JButton("Three"));
tabs.addTab("Four", new JButton("Four"));
test.add(tabs);
test.setVisible(true);
}
}
```
|
How to implement draggable tab using Java Swing?
|
[
"",
"java",
"user-interface",
"swing",
"tabs",
""
] |
This is kind of hard to explain, I hope my English is sufficient:
I have a class "A" which should maintain a list of objects of class "B" (like a private List). A consumer of class "A" should be able to add items to the list. After the items are added to the list, the consumer should not be able to modify them again, left alone that he should not be able to temper with the list itself (add or remove items). But he should be able to enumerate the items in the list and get their values. Is there a pattern for it? How would you do that?
If the question is not clear enough, please let me know.
|
To prevent editing the list or its items you have to make them [immutable](http://en.wikipedia.org/wiki/Immutable_object), which means you have to return a new instance of an element on every request.
See Eric Lippert's excellent series of "Immutability in C#": <http://blogs.msdn.com/ericlippert/archive/tags/Immutability/C_2300_/default.aspx> (you have to scroll down a bit)
|
As many of these answers show, there are many ways to make the collection itself immutable.
It takes more effort to keep the members of the collection immutable. One possibility is to use a facade/proxy (sorry for the lack of brevity):
```
class B
{
public B(int data)
{
this.data = data;
}
public int data
{
get { return privateData; }
set { privateData = value; }
}
private int privateData;
}
class ProxyB
{
public ProxyB(B b)
{
actual = b;
}
public int data
{
get { return actual.data; }
}
private B actual;
}
class A : IEnumerable<ProxyB>
{
private List<B> bList = new List<B>();
class ProxyEnumerator : IEnumerator<ProxyB>
{
private IEnumerator<B> b_enum;
public ProxyEnumerator(IEnumerator<B> benum)
{
b_enum = benum;
}
public bool MoveNext()
{
return b_enum.MoveNext();
}
public ProxyB Current
{
get { return new ProxyB(b_enum.Current); }
}
Object IEnumerator.Current
{
get { return this.Current; }
}
public void Reset()
{
b_enum.Reset();
}
public void Dispose()
{
b_enum.Dispose();
}
}
public void AddB(B b) { bList.Add(b); }
public IEnumerator<ProxyB> GetEnumerator()
{
return new ProxyEnumerator(bList.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
```
The downside of this solution is that the caller will be iterating over a collection of ProxyB objects, rather than the B objects they added.
|
Controlling access to an internal collection in c# - Pattern required
|
[
"",
"c#",
"design-patterns",
"collections",
"data-access",
""
] |
What's the best way to shut down the computer from a C# program?
I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.
|
Taken from: [a Geekpedia post](http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html)
This method uses [WMI](http://en.wikipedia.org/wiki/Windows_Management_Instrumentation) to shutdown windows.
You'll need to add a reference to System.Management to your project to use this.
```
using System.Management;
void Shutdown()
{
ManagementBaseObject mboShutdown = null;
ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
mcWin32.Get();
// You can't shutdown without security privileges
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams =
mcWin32.GetMethodParameters("Win32Shutdown");
// Flag 1 means we want to shut down the system. Use "2" to reboot.
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown",
mboShutdownParams, null);
}
}
```
|
Works starting with windows XP, not available in win 2000 or lower:
This is the quickest way to do it:
```
Process.Start("shutdown","/s /t 0");
```
Otherwise use P/Invoke or WMI like others have said.
Edit: how to avoid creating a window
```
var psi = new ProcessStartInfo("shutdown","/s /t 0");
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);
```
|
How to shut down the computer from C#
|
[
"",
"c#",
".net",
"windows",
"shutdown",
""
] |
Java is one of my programming languages of choice. I always run into the problem though of distributing my application to end-users.
Giving a user a JAR is not always as user friendly as I would like and using Java WebStart requires that I maintain a web server.
What's the best way to distribute a Java application? What if the Java application needs to install artifacts to the user's computer? Are there any good Java installation/packaging systems out there?
|
There are a variety of solutions, depending on your distribution requirements.
1. Just use a jar. This assumes that the user has the the correct java version installed, otherwise the user will get "class-file format version" exceptions. This is fine for internal distribution inside a company.
2. Use launch4j and an installer like NSIS. This gives you a lot more control, although the user can still do stupid stuff like un-installing the java runtime. This is probably the most popular approach, and what I currently use.
3. Use Webstart. This also assumes that the user has the correct java version installed, but it's a lot easier to get going. My experience is that this is fine for tightly controlled intranet environments, but becomes a pain with larger deployments because it has some many weird failures. It may get better with the new plug-in technology in Java 1.7.
4. Use a native-code compiler like Excelsior JET and distribute as a executable, or wrap it up in an installer. Expensive, and it generally ties you to a slightly older version of java, and there is some pain with dynamic class-loading, but its very effective for large-scale deployment where you need to minimise your support hassles.
|
[advanced installer](http://www.advancedinstaller.com/) makes it easy to package java apps as windows executables, and it's quite flexible in the way you can set it up. I've found that for distributing java applications to windows clients, this is the easiest way to go.
|
What's the best way to distribute Java applications?
|
[
"",
"java",
"installation",
"jar",
"software-distribution",
""
] |
PHP stores its session information on the file system of the host of the server establishing that session. In a multiple-host PHP environment, where load is unintelligently distributed amongst each host, PHP session variables are not available to each request (unless by chance the request is assigned to the same host -- assume we have no control over the load balancer).
[This site, dubbed "The Hitchhikers Guide to PHP Load Balancing"](http://porteightyeight.com/archives/121-The-Hitchhikers-Guide-to-PHP-Load-Balancing.html) suggests overriding PHPs session handler and storing session information in the shared database.
What, in your humble opinion, is the *best* way to maintain session information in a multiple PHP host environment?
**UPDATE:** Thanks for the great feedback. For anyone looking for example code, we found a [useful tutorial on writing a Session Manager class for MySQL](http://www.devshed.com/c/a/PHP/Storing-PHP-Sessions-in-a-Database/) which I recommend checking out.
|
Database, or Database+Memcache. Generally speaking sessions should not be written to very often. Start with a database solution that only writes to the db when the session data has *changed*. Memcache should be added later as a performance enhancement. A db solution will be very fast because you are only ever looking up primary keys. Make sure the db has row locking, not table locking (myISAM). MemCache only is a bad idea... If it overflows, crashes, or is restarted, the users will be logged out.
|
Whatever you do, do not store it on the server itself (even if you're only using one server, or in a 1+1 failover scenario). It'll put you on a dead end.
I would say, use Database+Memcache for storage/retrieval, it'll keep you out of Zend's grasp (and believe me things do break down at some point with Zend). Since you will be able to easily partition by UserID or SessionID even going with MySQL will leave things quite scalable.
(Edit: additionally, going with DB+Memcache does not bind you to a comercial party, it does not bind you to PHP either -- something you might be happy for down the road)
|
What is the best way to handle sessions for a PHP site on multiple hosts?
|
[
"",
"php",
"mysql",
"session",
"load-balancing",
"memcached",
""
] |
Was this an oversight? Or is it to do with the JVM?
|
Java does indeed have pointers--pointers on which you cannot perform pointer arithmetic.
From the venerable [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.1):
> There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).
And [later](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3.1):
> An *object* is a *class instance* or an *array*.
>
> The reference values (often just *references*) are *pointers* to these objects, and a special null reference, which refers to no object.
(emphasis theirs)
So, to interpret, if you write:
```
Object myObj = new Object();
```
then `myObj` is a *reference type* which contains a *reference value* that is itself a *pointer* to the newly-created `Object`.
Thus if you set `myObj` to `null` you are setting the *reference value* (aka *pointer*) to `null`. Hence a NullPointerException is reasonably thrown when the variable is dereferenced.
Don't worry: this topic has been [heartily debated](http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/65bf7e9d6bffb1b9/) before.
|
In Java they use the nomenclature REFERENCE for referring to dynamically created objects. In previous languages, it is named POINTER. Just as the naming of METHODS in object oriented languages has taken over from former FUNCTION's and PROCEDURE's in earlier (object oriented as well as not object oriented) languages. There is no particular better or worse in this naming or new standard, it is just another way of naming the phenomenon of being able to create former dynamic objects, hanging in the air (heap space) and being referred to by a fixed object reference (or dynamic reference also hanging in the air). The authors of the new standard (use of METHODS and REFERENCES) particularly mentioned that the new standards were implemented to make it conformant with the upcoming planning systems - such as UML and UP, where the use of the Object oriented terminology prescribes use of ATTRIBUTES, METHODS and REFERENCES, and not VARIABLES, FUNCTIONS and POINTERS.
Now, you may think now, that it was merely a renaming, but that would be simplifying the description of the process and not be just to the long road which the languages have taken in the name of development. A method is different in nature from a procedure, in that it operates within a scope of a class, while the procedure in its nature operates on the global scope. Similarly an attribute is not just a new name for variable, as the attribute is a property of a class (and its instance - an object). Similarly the reference, which is the question behind this little writing here, is different in that it is typed, thus it does not have the typical property of pointers, being raw references to memory cells, thus again, a reference is a structured reference to memory based objects.
Now, inside of Java, that is - in the stomach of Java, there is an arbitration layer between the underlying C-code and the Java code (the Virtual Machine). In that arbitration layer, an abstraction occurs in that the underlying (bare metal) implementation of the references, as done by the Virtual machine, protects the references from referring bare metal (memory cells without structure). The raw truth is therefore, that the NullPointerException is truly a Null Pointer Exception, and not just a Null Reference Exception. However, that truth may be completely irrelevant for the programmer in the Java environment, as he/she will not at any point be in contact with the bare metal JVM.
|
Java: Why aren't NullPointerExceptions called NullReferenceExceptions?
|
[
"",
"java",
""
] |
I'm trying to teach Komodo to fire up [IDLE](http://en.wikipedia.org/wiki/IDLE_(Python)) when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.
I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.
How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.
|
There's a file called `idle.py` in your Python installation directory in `Lib\idlelib\idle.py`.
If you run that file with Python, then IDLE should start.
> c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py
|
In Python 3.2.2, I found `\Python32\Lib\idlelib\idle.bat` which was useful because it would let me open python files supplied as args in IDLE.
|
How to start IDLE (Python editor) without using the shortcut on Windows Vista?
|
[
"",
"python",
"python-idle",
"komodo",
"pywin",
""
] |
I've wanted this for fluent interfaces. See, for example [this](http://channel9.msdn.com/forums/Coffeehouse/257556-C-Extension-Properties/) Channel9 discussion. Would probably [require](http://ayende.com/Blog/archive/2007/12/02/Why-C-doesnt-have-extension-properties.aspx) also adding indexed properties.
What are your thoughts? Would the advantages outweigh the "language clutter"?
|
In my book the #1 most substantial reason for extension properties is implementing fluent interface patterns around unowned code. I built a wrapper around the NHibernate session to make it more intitutive to work with so I can do logic similar to
```
public bool IsInTransaction
{
get { return _session.Is().Not.Null && _session.Is().InTransaction; }
}
```
Which looks very stupid that Is must be a method as there is no way for me to insert the Is as a property unless I directly modify the source on the session object.
|
Since properties are just syntactic sugar for methods, I don't see why C# should have extension methods without extension properties.
|
Should extension properties be added to C# 4.0?
|
[
"",
"c#",
""
] |
Say I have the following methods:
```
def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
```
In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define `methodA` as follows, the second argument will be passed on as positional rather than named variable arguments.
```
def methodA(arg, **kwargs):
methodB("argvalue", kwargs)
```
How do I make sure that the \*\*kwargs in methodA gets passed as \*\*kwargs to methodB?
|
Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments.
```
methodB("argvalue", **kwargs)
```
|
As an aside: When using functions instead of methods, you could also use functools.partial:
```
import functools
def foo(arg, **kwargs):
...
bar = functools.partial(foo, "argvalue")
```
The last line will define a function "bar" that, when called, will call foo with the first argument set to "argvalue" and all other functions just passed on:
```
bar(5, myarg="value")
```
will call
```
foo("argvalue", 5, myarg="value")
```
Unfortunately that will not work with methods.
|
Passing on named variable arguments in python
|
[
"",
"python",
"variadic-functions",
""
] |
This has been a problem that I haven't been able to figure out for sometime. Preventing the second instance is trivial and has many methods, however, bringing back the already running process isn't. I would like to:
* Minimized: Undo the minimize and bring the running instance to the front.
* Behind other windows: Bring the application to the front.
The language I am using this in is VB.NET and C#.
|
I found this code to be useful. It does the detection and optional activation of an existing application:
<http://www.codeproject.com/KB/cs/cssingprocess.aspx>
|
If you're using .NET, this seems easier and more straightforward using build-in .NET functionality:
[The Weekly Source Code 31- Single Instance WinForms and Microsoft.VisualBasic.dll](http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx)
|
Return to an already open application when a user tries to open a new instance
|
[
"",
"c#",
".net",
"windows",
"vb.net",
""
] |
Writing some test scripts in IronPython, I want to verify whether a window is displayed or not. I have the pid of the main app's process, and want to get a list of window titles that are related to the pid.
I was trying to avoid using win32api calls, such as FindWindowEx, since (to my knowledge) you cannot access win32api directly from IronPython. Is there a way to do this using built-in .net classes? Most of the stuff I have come across recommends using win32api, such as below.
[.NET (C#): Getting child windows when you only have a process handle or PID?](https://stackoverflow.com/questions/79111/net-c-getting-child-windows-when-you-only-have-a-process-handle-or-pid)
UPDATE: I found a work-around to what I was trying to do. Answer below.
|
The article below shows how to access the win32api indirectly from IronPython. It uses CSharpCodeProvider CompileAssemblyFromSource method to compile an assembly in memory from the supplied C# source code string. IronPython can then import the assembly.
[Dynamically compiling C# from IronPython](http://www.voidspace.org.uk/ironpython/dynamically_compiling.shtml)
|
As of IronPython 2.6 the [ctypes](http://docs.python.org/library/ctypes) module is supported. This module provides C compatible data types, and allows calling functions in DLLs. Quick example:
```
import ctypes
buffer = ctypes.create_string_buffer(100)
ctypes.windll.kernel32.GetWindowsDirectoryA(buffer, len(buffer))
print buffer.value
```
|
How to use win32api from IronPython
|
[
"",
"c#",
"winapi",
"ironpython",
""
] |
(Java question)
If I reference a field in an inner class, does this cause a circular dependency between the enclosing class and the inner class?
How can I avoid this?
Here is an example:
```
public class Outer {
private Other o;
private Inner i;
public Outer() {
o = new Other();
i = new Inner() {
public void doSomething() {
o.foo();
}
};
}
}
```
|
**Static vs instance class:** If you declare the inner class as static then the instances of the inner class doesn't have any reference to the outer class. If it's not satic then your inner object efectivelly points to the outer object that created it (it has an implicit reference, in fact, if you use reflection over its constructors you'll see an extra parameter for receiving the outer instance).
**Inner instance points outer instance:** Circular reference is in case each instance points the other one. A lot of times you use inner classes for elegantly implementing some interface and accessing private fields while not implementing the interface with the outer class. It does mean inner instance points outer instance but doesn't mean the opposite. Not necesary a circular reference.
**Closing the circle:** Anyway there's nothing wrong with circular referencing in Java. Objects work nicely and when they're not more referenced they're garbage collected. It doesn't matter if they point each other.
|
The syntax you're using in the example is a little off there is no declaration of the class or interface Inner. But there isn't anything wrong with the concept of the example. In Java it will work fine.
I'm not sure what you're doing here, but you may want to consider a more simple design for maintainability etc.
It's a common pattern for anonymous event handlers to reference elements of their parent class, so no reason to avoid it if that's the case, that's how Java was designed instead of having function pointers.
|
How do you resolve a circular dependency with an inner class?
|
[
"",
"java",
"circular-dependency",
"anonymous-inner-class",
""
] |
In my database (SQL 2005) I have a field which holds a comment but in the comment I have an id and I would like to strip out just the id, and IF possible convert it to an int:
`activation successful of id 1010101`
The line above is the exact structure of the data in the db field.
And no I don't want to do this in the code of the application, I actually don't want to touch it, just in case you were wondering ;-)
|
This should do the trick:
```
SELECT SUBSTRING(column, PATINDEX('%[0-9]%', column), 999)
FROM table
```
Based on your sample data, this that there is only one occurence of an integer in the string and that it is at the end.
|
```
-- Test table, you will probably use some query
DECLARE @testTable TABLE(comment VARCHAR(255))
INSERT INTO @testTable(comment)
VALUES ('activation successful of id 1010101')
-- Use Charindex to find "id " then isolate the numeric part
-- Finally check to make sure the number is numeric before converting
SELECT CASE WHEN ISNUMERIC(JUSTNUMBER)=1 THEN CAST(JUSTNUMBER AS INTEGER) ELSE -1 END
FROM (
select right(comment, len(comment) - charindex('id ', comment)-2) as justnumber
from @testtable) TT
```
I would also add that this approach is more set based and hence more efficient for a bunch of data values. But it is super easy to do it just for one value as a variable. Instead of using the column comment you can use a variable like `@chvComment`.
|
SQL strip text and convert to integer
|
[
"",
"sql",
"text",
"strip",
""
] |
As many of us know (and many, many more don't), C++ is currently undergoing final drafting for the next revision of the International Standard, expected to be published in about 2 years. Drafts and papers are currently available from the [committee website](http://open-std.org/JTC1/SC22/WG21/). All sorts of new features are being added, the biggest being concepts and lambdas. There is a very comprehensive [Wikipedia article](http://en.wikipedia.org/wiki/C++0x) with many of the new features. GCC 4.3 and later implement [some C++0x features](http://gcc.gnu.org/projects/cxx0x.html).
As far as new features go, I really like type traits (and the appropriate concepts), but my definite leader is variadic templates. Until 0x, long template lists have involved Boost Preprocessor usually, and are very unpleasant to write. This makes things a lot easier and allows C++0x templates to be treated like a perfectly functional language using variadic templates. I've already written some very cool code with them already, and I can't wait to use them more often!
So what features are you most eagerly anticipating?
|
**auto** keyword for variable type inferencing
|
Lambdas and initializer lists.
Also, the changes to make it easier to eventually bring C++ into a garbage collected model, those seem pretty interesting. Perhaps C++1x will actually bring in garbage collection, but 0x/10 just set things up for the eventuality.
|
What's your favorite C++0x feature?
|
[
"",
"c++",
"c++11",
""
] |
Greetings all,
I'm trying to localize a .NET/C# project. I'm using string resource files and setting the "Localizable" property on all my forms to 'True'. The assembly culture is empty. The resx/resource files are successfully passed through Lingobit, resgen, and al.
When running the localized executables, *some* of my forms are not localized (ones in which I know the Localizable flag is set) while others are. There are even a few forms which are localized but a button or two isn't. I cannot tell any difference between the non-localized forms/controls with the localized ones.
Anyone have an idea what I might be missing? Thanks!
|
When you open the form in Visual Studio, if you change the Language property of the Form to the language you are localizing to, does the same problem exist there? Could it be possible that the non-localized forms/buttons still have the English text set even in the localized resources?
|
Yeah, I'd go with Andy on this and be suspicious of the contents of the resource files. We dabbled with localisation for a time, and encountered a number of issues, but this certainly wasn't one of them.
If that isn't it, then how are you testing your app? If you haven't tried this already I'd suggest firing up a set of VMs with foreign language versions of Windows installed (rather than just changing the language settings on your machine) and seeing if that makes any difference.
|
Why Aren't All My WinForm Controls and Forms Localizing?
|
[
"",
"c#",
".net",
"localization",
""
] |
I want to access the call stack at runtime in a Native C++ application. I am not using the IDE. How do I display the call stack?
Update: I have a function which is called from many points all over the application. It crashes on rare occasions. I was looking for a way to get name of the caller and log it.
|
I believe that [this](https://stackoverflow.com/questions/105659/how-can-one-grab-a-stack-trace-in-c#105741) page has the answer you are looking for. You said Visual C so I assume you mean windows.
|
Have a look at [StackWalk64](http://msdn.microsoft.com/en-us/library/ms680650(VS.85).aspx).
If you're used to doing this on .NET, then you're in for a nasty surprise.
|
Call Stack at Runtime
|
[
"",
"c++",
"debugging",
"visual-c++",
"stack-trace",
"callstack",
""
] |
My users would like to be able to hit `Ctrl`+`S` to save a form. Is there a good cross-browser way of capturing the `Ctrl`+`S` key combination and submit my form?
App is built on Drupal, so jQuery is available.
|
```
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
```
Key codes can differ between browsers, so you may need to check for more than just 115.
|
This works for me (using jquery) to overload `Ctrl`+`S`, `Ctrl`+`F` and `Ctrl`+`G`:
```
$(window).bind('keydown', function(event) {
if (event.ctrlKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 's':
event.preventDefault();
alert('ctrl-s');
break;
case 'f':
event.preventDefault();
alert('ctrl-f');
break;
case 'g':
event.preventDefault();
alert('ctrl-g');
break;
}
}
});
```
|
Best cross-browser method to capture CTRL+S with JQuery?
|
[
"",
"javascript",
"jquery",
""
] |
I have an application that has created a number of custom event log sources to help filter its output. How can I delete the custom sources from the machine WITHOUT writing any code as running a quick program using System.Diagnostics.EventLog.Delete is not possible.
I've tried using RegEdit to remove the custom sources from [HKEY\_LOCAL\_MACHINE\SYSTEM\ControlSetXXX\Services\Eventlog] however the application acts as if the logs still exist behind the scenes.
What else am I missing?
|
I also think you're in the right place... it's stored in the registry, under the name of the event log. I have a custom event log, under which are multiple event sources.
> HKLM\System\CurrentControlSet\Services\Eventlog\LOGNAME\LOGSOURCE1
> HKLM\System\CurrentControlSet\Services\Eventlog\LOGNAME\LOGSOURCE2
Those sources have an *EventMessageFile* key, which is *REG\_EXPAND\_SZ* and points to:
> C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll
I think if you delete the Key that is the log source, LOGSOURCE1 in my example, that should be all that's needed.
For what it's worth, I tried it through .NET and that's what it did. However, it does look like each custom event log also has a source of the same name. If you have a custom log, that could affect your ability to clear it. You'd have to delete the log outright, perhaps. Further, if your app has an installer, I can see that the application name also may be registered as a source in the application event log. One more place to clear.
|
What about using [Powershell](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.management/remove-eventlog)?
```
Remove-EventLog -LogName "Custom log name"
Remove-EventLog -Source "Custom source name"
```
|
Deleting Custom Event Log Source Without Using Code
|
[
"",
"c#",
"windows",
"event-log",
""
] |
So I was writing some code today that basically looks like this:
```
string returnString = s.Replace("!", " ")
.Replace("@", " ")
.Replace("#", " ")
.Replace("$", " ")
.Replace("%", " ")
.Replace("^", " ")
.Replace("*", " ")
.Replace("_", " ")
.Replace("+", " ")
.Replace("=", " ")
.Replace("\", " ")
```
Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the `Replace()` function?
|
You can use **Regex.Replace()**. All of the characters can be placed between square brackets, which matches any character between the square brackets. Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. The first parameter is the input string and the last parameter is the replacement string.
```
var returnString = Regex.Replace(s,@"[!@#\$%\^*_\+=\\]"," ");
```
|
FYI - if you need to modify this regex, you'll need to have an understanding of the regular expression language. It is quite simple, and as a developer you really owe it to yourself to add regular expressions to your toolbox - you don't need them every day, but being able to apply them appropriately where necessary when the need does arise will pay you back tenfold for the initial effort. Here is a link to a website with some top notch, easy to follow tutorials and reference material on regular expressions: [regular-expressions.info](http://www.regular-expressions.info/). Once you get a feel for regular expressions and want to use them in your software, you'll want to buy Regex Buddy. It is a cheap and extraordinary tool for learning and using regular expressions. I *very* rarely purchase development tools, but this one was worth every penny. It is here: [Regex Buddy](http://www.regexbuddy.com/)
|
Alternative to String.Replace
|
[
"",
"c#",
"regex",
"string",
"replace",
""
] |
Eg. can I write something like this code:
```
public void InactiveCustomers(IEnumerable<Guid> customerIDs)
{
//...
myAdoCommand.CommandText =
"UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)";
myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs;
//...
}
```
The only way I know is to Join my IEnumerable and then use string concatenation to build my SQL string.
|
Generally the way that you do this is to pass in a comma-separated list of values, and within your stored procedure, parse the list out and insert it into a temp table, which you can then use for joins. As of **Sql Server 2005**, this is standard practice for dealing with parameters that need to hold arrays.
Here's a good article on various ways to deal with this problem:
[Passing a list/array to an SQL Server stored procedure](http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm)
But for **Sql Server 2008**, we finally get to pass table variables into procedures, by first defining the table as a custom type.
There is a good description of this (and more 2008 features) in this article:
[Introduction to New T-SQL Programmability Features in SQL Server 2008](http://technet.microsoft.com/en-us/library/cc721270.aspx)
|
You can with [SQL 2008](http://blog.benhall.me.uk/2007/07/sql-server-2008-table-value-parameters.html). It hasn't been out very long, but it is available.
|
Is it possible to send a collection of ID's as a ADO.NET SQL parameter?
|
[
"",
".net",
"sql",
"ado.net",
""
] |
What is `std::pair` for, why would I use it, and what benefits does `boost::compressed_pair` bring?
|
[`std::pair`](http://en.cppreference.com/w/cpp/utility/pair) is a data type for grouping two values together as a single object. [`std::map`](http://en.cppreference.com/w/cpp/container/map) uses it for key, value pairs.
While you're learning [`pair`](http://en.cppreference.com/w/cpp/utility/pair), you might check out [`tuple`](http://en.cppreference.com/w/cpp/utility/tuple). It's like `pair` but for grouping an arbitrary number of values. `tuple` is part of TR1 and many compilers already include it with their Standard Library implementations.
Also, checkout Chapter 1, "Tuples," of the book *The C++ Standard Library Extensions: A Tutorial and Reference* by Pete Becker, ISBN-13: 9780321412997, for a thorough explanation.

|
`compressed_pair` uses some template trickery to save space. In C++, an object (small o) can not have the same address as a different object.
So even if you have
```
struct A { };
```
`A`'s size will not be 0, because then:
```
A a1;
A a2;
&a1 == &a2;
```
would hold, which is not allowed.
*But* many compilers will do what is called the "empty base class optimization":
```
struct A { };
struct B { int x; };
struct C : public A { int x; };
```
Here, it is fine for `B` and `C` to have the same size, even if `sizeof(A)` can't be zero.
So `boost::compressed_pair` takes advantage of this optimization and will, where possible, inherit from one or the other of the types in the pair if it is empty.
So a `std::pair` might look like (I've elided a good deal, ctors etc.):
```
template<typename FirstType, typename SecondType>
struct pair {
FirstType first;
SecondType second;
};
```
That means if either `FirstType` or `SecondType` is `A`, your `pair<A, int>` has to be bigger than `sizeof(int)`.
But if you use `compressed_pair`, its generated code will look akin to:
```
struct compressed_pair<A,int> : private A {
int second_;
A first() { return *this; }
int second() { return second_; }
};
```
And `compressed_pair<A,int>` will only be as big as sizeof(int).
|
What is std::pair?
|
[
"",
"c++",
"boost",
"stl",
"std-pair",
""
] |
A poorly-written back-end system we interface with is having trouble with handling the load we're producing. While they fix their load problems, we're trying to reduce any additional load we're generating, one of which is that the back-end system continues to try and service a form submission even if another submission has come from the same user.
One thing we've noticed is users double-clicking the form submission button. I need to de-bounce these clicks, and prevent a second form submission.
My approach (using Prototype) places an `onSubmit` on the form that calls the following function which hides the form submission button and displays a "loading..." `div`.
```
function disableSubmit(id1, id2) {
$(id1).style.display = 'none';
$(id2).style.display = 'inline';
}
```
The problem I've found with this approach is that if I use an animated gif in the "loading..." `div`, it loads fine but doesn't animate while the form is submitting.
Is there a better way to do this de-bouncing and continue to show animation on the page while waiting for the form result to (finally) load?
|
If you've got jQuery handy, attach a click() event that disables the button after the initial submission -
```
$('input[type="submit"]').click(function(event){
event.preventDefault();
this.click(null);
});
```
that sort of thing.
|
Using Prototype, you can use this code to watch if any form has been submitted and disable all submit buttons when it does:
```
document.observe( 'dom:loaded', function() { // when document is loaded
$$( 'form' ).each( function( form ) { // find all FORM elements in the document
form.observe( 'submit', function() { // when any form is submitted
$$( 'input[type="submit"]' ).invoke( 'disable' ); // disable all submit buttons
} );
} );
} );
```
This should help with users that double-click on submit buttons. However, it will still be possible to submit the form any other way (e.g. pressing Enter on text field). To prevent this, you have to start watching for any form submission after the first one and stop it:
```
document.observe( 'dom:loaded', function() {
$$( 'form' ).each( function( form ) {
form.observe( 'submit', function() {
$$( 'input[type="submit"]' ).invoke( 'disable' );
$$( 'form' ).observe( 'submit', function( evt ) { // once any form is submitted
evt.stop(); // prevent any other form submission
} );
} );
} );
} );
```
|
Debounce clicks when submitting a web form
|
[
"",
"javascript",
"html",
"prototypejs",
""
] |
SQL is not my forte, but I'm working on it - thank you for the replies.
I am working on a report that will return the completion percent of services for indiviudals in our contracts. There is a master table "Contracts," each individual Contract can have multiple services from the "services" table, each service has multiple standards for the "standards" table which records the percent complete for each standard.
I've gotten as far as calculating the total percent complete for each individual service for a specific Contract\_ServiceID, but how do I return all the services percentages for all the contracts? Something like this:
Contract Service Percent complete
---
abc Company service 1 98%
abc Company service 2 100%
xyz Company service 1 50%
Here's what I have so far:
```
SELECT
Contract_ServiceId,
(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete"
FROM dbo.Standard sta WITH (NOLOCK)
INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId
LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId
AND conSer.StandardReportId = standResp.StandardReportId
WHERE Contract_ServiceId = '[an id]'
GROUP BY Contract_ServiceID
```
This gets me too:
Contract\_serviceid Percent Complete
---
[an id] 100%
EDIT: Tables didn't show up in post.
|
I'm not sure if I understand the problem, if the result is ok for a service\_contract you canContract Service
```
SELECT con.ContractId,
con.Contract,
conSer.Contract_ServiceID,
conSer.Service,
(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete"
FROM dbo.Standard sta WITH (NOLOCK)
INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId
INNER JOIN dbo.Contract con ON con.ContractId = conSer.ContractId
LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId
AND conSer.StandardReportId = standResp.StandardReportId
GROUP BY con.ContractId, con.Contract, conSer.Contract_ServiceID, conSer.Service
```
make sure you have all the columns you select from the Contract table in the group by clause
|
You should be able to add in your select the company name and group by that and the service id and ditch the where clause...
Perhaps like this:
```
SELECT
Contract,
Contract_ServiceId,
(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete"
FROM dbo.Standard sta WITH (NOLOCK)
INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId
LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId
AND conSer.StandardReportId = standResp.StandardReportId
GROUP BY Contract, Contract_ServiceID
```
|
Nested SELECT Statement
|
[
"",
"sql",
"sql-server",
"t-sql",
""
] |
That's it. If you want to document a function or a class, you put a string just after the definition. For instance:
```
def foo():
"""This function does nothing."""
pass
```
But what about a module? How can I document what a *file.py* does?
|
For the packages, you can document it in `__init__.py`.
For the modules, you can add a docstring simply in the module file.
All the information is here: <http://www.python.org/dev/peps/pep-0257/>
|
Add your docstring as the [first statement in the module](http://www.python.org/dev/peps/pep-0257/).
```
"""
Your module's verbose yet thorough docstring.
"""
import foo
# ...
```
For packages, you can add your docstring to `__init__.py`.
|
How do I document a module in Python?
|
[
"",
"python",
"documentation",
"python-module",
""
] |
I would like to use client-side Javascript to perform a DNS lookup (hostname to IP address) as seen from the client's computer. Is that possible?
|
There's no notion of hosts or ip-addresses in the javascript standard library. So you'll have to access some external service to look up hostnames for you.
I recommend hosting a cgi-bin which looks up the ip-address of a hostname and access that via javascript.
|
**Edit**: This question gave me an itch, so I put up a JSONP webservice on Google App Engine that returns the clients ip address. Usage:
```
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"> </script>
```
Yay, no server proxies needed.
---
Pure JS can't. If you have a server script under the same domain that prints it out you could send a XMLHttpRequest to read it.
|
Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?
|
[
"",
"javascript",
"dns",
""
] |
I have an asp.net application that runs exclusively on IE7 (internal web site).
When a user needs to enter data, I pop up a child window with a form. When the form closes, it calls javascript:window.opener.location.reload(true) so that the new data will display on the main page.
The problem is that the browser complains that it must repost the page. Is there any way to turn this feature off?
|
It's because the page in window.opener comes from a POST Request
Maybe you can use
javascript:window.opener.location = window.opener.location; to do just a GET request if the data can be fetched without a POST.
|
No, but there is a solution. Its generally considered good design to use a 302 redirect immediately after someone posts data to a page. This prevents that popup from ever occuring. Allow me to elaborate.
1) The user fills in a form and submits data via POST.
2) The backend receives the data and acts upon it.
3) Instead of returning the content to the user, the backend issues a 302 redirect as soon as its done processing the page (possibly redirecting the user back to the exact same url, if need be)
4) The page that the user will see is the page you told their browser to redirect to. They will load up the redirected page with a standard GET request. If they try to refresh the page, it will not repost the data. Problem solved.
|
How to disable browser postback warning dialog
|
[
"",
"asp.net",
"javascript",
"internet-explorer-7",
""
] |
Basically, something similar to System.Xml.XmlWriter - A streaming XML Writer that doesn't incur much of a memory overhead. So that rules out xml.dom and xml.dom.minidom. Suggestions?
|
**xml.etree.cElementTree**, included in the default distribution of CPython since 2.5. Lightning fast for both reading and writing XML.
|
I think you'll find XMLGenerator from xml.sax.saxutils is the closest thing to what you want.
```
import time
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import AttributesNSImpl
LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR']
class xml_logger:
def __init__(self, output, encoding):
"""
Set up a logger object, which takes SAX events and outputs
an XML log file
"""
logger = XMLGenerator(output, encoding)
logger.startDocument()
attrs = AttributesNSImpl({}, {})
logger.startElementNS((None, u'log'), u'log', attrs)
self._logger = logger
self._output = output
self._encoding = encoding
return
def write_entry(self, level, msg):
"""
Write a log entry to the logger
level - the level of the entry
msg - the text of the entry. Must be a Unicode object
"""
#Note: in a real application, I would use ISO 8601 for the date
#asctime used here for simplicity
now = time.asctime(time.localtime())
attr_vals = {
(None, u'date'): now,
(None, u'level'): LOG_LEVELS[level],
}
attr_qnames = {
(None, u'date'): u'date',
(None, u'level'): u'level',
}
attrs = AttributesNSImpl(attr_vals, attr_qnames)
self._logger.startElementNS((None, u'entry'), u'entry', attrs)
self._logger.characters(msg)
self._logger.endElementNS((None, u'entry'), u'entry')
return
def close(self):
"""
Clean up the logger object
"""
self._logger.endElementNS((None, u'log'), u'log')
self._logger.endDocument()
return
if __name__ == "__main__":
#Test it out
import sys
xl = xml_logger(sys.stdout, 'utf-8')
xl.write_entry(2, u"Vanilla log entry")
xl.close()
```
You'll probably want to look at the rest of the article I got that from at <http://www.xml.com/pub/a/2003/03/12/py-xml.html>.
|
What's the easiest non-memory intensive way to output XML from Python?
|
[
"",
"python",
"xml",
"streaming",
""
] |
I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?
```
String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = new [UnknownClass]().format(unformattedXml);
```
Note: My input is a **String**. My output is a **String**.
(Basic) mock result:
```
<?xml version="1.0" encoding="UTF-8"?>
<root>
<tag>
<nested>hello</nested>
</tag>
</root>
```
|
Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. This has no dependencies outside of Java 6.
```
import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
/**
* Pretty-prints xml, supplied as a string.
* <p/>
* eg.
* <code>
* String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
* </code>
*/
public class XmlFormatter {
public String format(String xml) {
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
//May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.
return writer.writeToString(document);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String unformattedXml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
" xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
" xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
" <Query>\n" +
" <query:CategorySchemeWhere>\n" +
" \t\t\t\t\t <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
" </query:CategorySchemeWhere>\n" +
" </Query>\n\n\n\n\n" +
"</QueryMessage>";
System.out.println(new XmlFormatter().format(unformattedXml));
}
}
```
|
```
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
```
Note: Results may vary depending on the Java version. Search for workarounds specific to your platform.
|
How to pretty print XML from Java?
|
[
"",
"java",
"xml",
"pretty-print",
""
] |
Can anyone recommend a simple API that will allow me to use read a CSV input file, do some simple transformations, and then write it.
A quick google has found <http://flatpack.sourceforge.net/> which looks promising.
I just wanted to check what others are using before I couple myself to this API.
|
# Apache Commons CSV
Check out [*Apache Common CSV*](http://commons.apache.org/proper/commons-csv/).
This library reads and writes [several variations of CSV](http://commons.apache.org/proper/commons-csv/archives/1.6/apidocs/index.html), including the standard one [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180). Also reads/writes [Tab-delimited](https://en.wikipedia.org/wiki/Tab-separated_values) files.
* Excel
* InformixUnload
* InformixUnloadCsv
* MySQL
* Oracle
* PostgreSQLCsv
* PostgreSQLText
* RFC4180
* TDF
|
I've used [OpenCSV](http://opencsv.sourceforge.net/) in the past.
```
import au.com.bytecode.opencsv.CSVReader;
```
```
String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));
```
// if the first line is the header
String[] header = reader.readNext();
// iterate over reader.readNext until it returns null
String[] line = reader.readNext();
There were some other choices in the answers to [another question](https://stackoverflow.com/questions/123/csv-file-to-xml#53547).
|
CSV API for Java
|
[
"",
"java",
"csv",
""
] |
In my job we have to deploy an application on various environments. It's a standard WAR file which needs a bit of configuration, deployed on Tomcat 6.
Is there any way of creating a 'deployment package' with Tomcat so that you just extract it and it sets up Tomcat as well as your application? I'm not sure that creating a .zip file with the Tomcat folder would work! It certainly wouldn't install the service.
Suggestions welcome!
I should note that - at the moment - all apps are deployed on Windows servers.
Thanks,
Phill
|
We use [Ant Installer](http://antinstaller.sourceforge.net/) to deploy our application, app server and install it as a service. We embed [Java Service Wrapper](http://wrapper.tanukisoftware.org/doc/english/integrate.html) in the installer to install the Windows service.
|
It's commercial, but [install4j](http://www.ej-technologies.com/products/install4j/overview.html) will do this for you, including installing the service.
|
Packaging up Tomcat
|
[
"",
"java",
"web-applications",
"tomcat",
""
] |
varchar(255), varchar(256), nvarchar(255), nvarchar(256), nvarchar(max), etc?
256 seems like a nice, round, space-efficient number. But I've seen 255 used a lot. Why?
What's the difference between varchar and nvarchar?
|
VARCHAR(255). It won't use all 255 characters of storage, just the storage you need. It's 255 and not 256 because then you have space for 255 plus the null-terminator (or size byte).
The "N" is for Unicode. Use if you expect non-ASCII characters.
|
In MS SQL Server (7.0 and up), varchar data is represented internally with up to three values:
* The actual string of characters, which will be from 0 to something over 8000 bytes (it’s based on page size, the other columns stored for the row, and a few other factors)
* Two bytes used to indicate how long the data string is (which produces a value from 0 to 8000+)
* If the column is nullable, one bit in the row’s null bitmask (so the null status of up to eight nullable columns can be represented in one byte)
The important part is that two-byte data length indicator. If it was one byte, you could only properly record strings of length 0 to 255; with two bytes, you can record strings of length 0 to something over 64000+ (specifically, 2^16 -1). However, the SQL Server page length is 8k, which is where that 8000+ character limit comes from. (There's data overflow stuff in SQL 2005, but if your strings are going to be that long you should just go with varchar(max).)
So, no matter how long you declare your varchar datatype column to be (15, 127, 511), what you will actually be storing for each and every row is:
* 2 bytes to indicate how long the string is
* The actual string, i.e. the number of characters in that string
Which gets me to my point: a number of older systems used only 1 byte to store the string length, and that limited you to a maximum length of 255 characters, which isn’t all that long. With 2 bytes, you have no such arbitrary limit... and so I recommend picking a number that makes sense to the (presumed non-technically oriented) user. , I like 50, 100, 250, 500, even 1000. Given that base of 8000+ bytes of storage, 255 or 256 is just as efficient as 200 or 250, and *less* efficient when it comes time to explain things to the end users.
This applies to single byte data (i.e. ansii, SQL*\_*Latin1\*\_\*General\_CP1, et. al.). If you have to store data for multiple code pages or languages using different alphabets, you’ll need to work with the nvarchar data type (which I think works the same, two bytes for number of charactesr, but each actual character of data requires two bytes of storage). If you have strings likely to go over 8000, or over 4000 in nvarchar, you will need to use the [n]varchar(max) datatypes.
And if you want to know why it is so very important to take up space with extra bytes just to track how long the data is, check out <http://www.joelonsoftware.com/articles/fog0000000319.html>
Philip
|
How should I store short text strings into a SQL Server database?
|
[
"",
"sql",
"sql-server",
"database",
"database-design",
""
] |
I am running following `PHP` code to interact with a MS Access database.
```
$odbc_con = new COM("ADODB.Connection");
$constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";";
$odbc_con -> open($constr);
$rs_select = $odbc_con -> execute ("SELECT * FROM Main");
```
Using `($rs_select -> RecordCount)` gives -1 though the query is returning non-zero records.
(a) What can be the reason?
(b) Is there any way out?
I have also tried using `count($rs_select -> GetRows())`. This satisfies the need but looks inefficient as it will involve copying of all the records into an array first.
|
ADODB has its own rules for what recordcount is returned depending on the type of recordset you've defined. See:
[MS Knowledge Base article 194973](http://support.microsoft.com/kb/194973)
[W3C Schools article](http://www.w3schools.com/ADO/prop_rs_recordcount.asp)
In the example above, the PHP COM() object is used to instantiate ADODB, a COM interface for generic database access. According to the [PHP documentation](https://www.php.net/manual/en/class.com.php), the object reference produced is overloaded, so you can just use the same properties/methods that the native ADODB object would have. This means that you need to use the ADODB methods to set the recordset type to one that will give an accurate recordcount (if you must have it). The alternative, as others have mentioned, is to use a second query to get the COUNT() of the records returned by the SELECT statement. This is easier, but may be inappropriate in the particular environment.
I'm not an ADO guru, so can't provide you with the exact commands for setting your recordset type, but from the articles cited above, it is clear that you need a static or keyset cursor. It appears to me that the proper method of setting the CursorType is to use a parameter in the command that opens the recordset. [This W3C Schools article on the CursorType property](http://www.w3schools.com/ADO/prop_rs_cursortype.asp) gives the appropriate arguments for that command.
Hopefully, this information will help the original poster accomplish his task, one way or the other.
|
It is possible that ODBC doesn't know the recordcount yet. In that case it is possible to go to the last record and only then will recordcount reflect the true number of records. This will probably also not be very efficient since it will load all records from the query.
As Oli said, using `SELECT COUNT(*)` will give you the result. I think that using 2 queries would still be more efficient than using my first method.
|
PHP and MS Access: Number of Records returned by SELECT query
|
[
"",
"php",
"database",
"ms-access",
""
] |
I was asked to make some drools traning for my teammates. Just to show them how it can be used and how usefull it may be. To do this training I first have to learn Drools, and I figured that the best way to learn it will be small project centered around drools.
Any interesting ideas?
My idea for this project was to do some webMethods flow files validation (just some example validations). I'd do validation only - we have in-house parser of that file format.
But something that actually does some work would be nice.
|
Actually, we have a drools based project, you could try to mimic that. :-)
Suppose you have incoming SMS messages arriving on an HTTP based protocol. An HTTP request contains the Anumber (telephone number of the sender) the Bnumber (telephone number of the recipient) and the text of the message.
Your goal is to use drools to route the messages, based on their content, to the appropriate services. You should have a set of rules, each rule stating something like: if the Bnumber is 1792 and the message text contains the keyword "VIDEO" then the message should be directed to the video providing service.
Actually, we use this exact setup, a drools based router which picks up messages from HTTP servlet threads and puts them to JMS queues based on their contents.
Would it be interesting for you to work on this program? :-)
|
I'm gonna give you two real examples that my company is using right now. The company is one of the biggest e-commerce from Brazil.
1. Drools is used to apply price promotions and discount over products while users just navigates inside the product's catalog.
So, before rendering the response for the user browser, we have to apply promotions related to price, installment and freight.
2. And while checking out the products, there are may promotions that can be applied due to the customer address region, state, age, sex, product amount, product amount per category, combined promotions, holidays, and so on. The application of each promotion affects the entire list of product, that requires a new rules application until the checkout gets a stable state.
It was really challenging but working very well. Drools is used in other contexts inside this company too.
|
Drools project idea needed
|
[
"",
"java",
"drools",
"webmethods",
""
] |
I have a little problem with a Listview.
I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error]. There is a a narrow strip that doesn't paint. The width of that strip is approximately the same as a row header would be if I had a row header.
If you have a thought on what can be done to make the background draw I'd love to hear it.
Now just to try a new idea, I'm offering a ten vote bounty for the first solution that still has me using this awful construct of a mess of a pseudo grid view. [I love legacy code.]
**Edit:**
Here is a sample that exhibits the problem.
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ListView lv = new ListView();
lv.Dock = System.Windows.Forms.DockStyle.Fill;
lv.FullRowSelect = true;
lv.GridLines = true;
lv.HideSelection = false;
lv.Location = new System.Drawing.Point(0, 0);
lv.TabIndex = 0;
lv.View = System.Windows.Forms.View.Details;
lv.AllowColumnReorder = true;
this.Controls.Add(lv);
lv.MultiSelect = true;
ColumnHeader ch = new ColumnHeader();
ch.Name = "Foo";
ch.Text = "Foo";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch);
ColumnHeader ch2 = new ColumnHeader();
ch.Name = "Bar";
ch.Text = "Bar";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch2);
lv.BeginUpdate();
for (int i = 0; i < 3; i++)
{
ListViewItem lvi = new ListViewItem("1", "2");
lvi.BackColor = Color.Black;
lvi.ForeColor = Color.White;
lv.Items.Add(lvi);
}
lv.EndUpdate();
}
}
```
|
Ah! I see now :}
You want hacky? I present unto you the following:
```
...
lv.OwnerDraw = true;
lv.DrawItem += new DrawListViewItemEventHandler( lv_DrawItem );
...
void lv_DrawItem( object sender, DrawListViewItemEventArgs e )
{
Rectangle foo = e.Bounds;
foo.Offset( -10, 0 );
e.Graphics.FillRectangle( new SolidBrush( e.Item.BackColor ), foo );
e.DrawDefault = true;
}
```
For a more inventive - and no less hacky - approach, you could try utilising the background image of the ListView ;)
|
(Prior to the Edit...)
I've just tried setting the BackColor on a System.Windows.Forms.ListView, and the color is applied across the control just fine (with and without images).
Are you doing any Custom Painting at all?
|
Listview background drawing problem C# Winform
|
[
"",
"c#",
"winforms",
"listview",
""
] |
I am looking for a way to have some control over the shape of a simple MessageBox in Winforms. I would like to control where the passed in text wraps so that the dialog rect is narrower. Windows seems to want to make the dialog as wide as possible before wrapping the text. Is there an easy way to control the maximum width of the dialog without resorting to creating my own custom form?
|
You can embed newlines in the text to force it to wrap at a certain point. e.g.
```
"message text...\nmore text..."
```
update: I posted that thinking it was a win32 API question, but I think the principle should still apply. I assume WinForms eventually calls MessageBox().
|
There's really just two ways (sane ways)
1) Add line breaks to your string yourself to limit the lenghth of each line.
2) Make your own form and use it rather than messagebox.
|
Shape of a Winforms MessageBox
|
[
"",
"c#",
"winforms",
""
] |
When a PHP application makes a database connection it of course generally needs to pass a login and password. If I'm using a single, minimum-permission login for my application, then the PHP needs to know that login and password somewhere. What is the best way to secure that password? It seems like just writing it in the PHP code isn't a good idea.
|
Several people misread this as a question about how to **store** passwords in a database. That is wrong. It is about how to store the password that lets you get **to** the database.
The usual solution is to move the password out of source-code into a configuration file. Then leave administration and securing that configuration file up to your system administrators. That way developers do not need to know anything about the production passwords, and there is no record of the password in your source-control.
|
If you're hosting on someone else's server and don't have access outside your webroot, you can always put your password and/or database connection in a file and then lock the file using a .htaccess:
```
<files mypasswdfile>
order allow,deny
deny from all
</files>
```
|
How to secure database passwords in PHP?
|
[
"",
"php",
"database",
"security",
""
] |
What's the best practice for using a `switch` statement vs using an `if` statement for 30 `unsigned` enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical. I've abstracted the snippet so don't hate me for the naming conventions.
`switch` statement:
```
// numError is an error enumeration type, with 0 being the non-error case
// fire_special_event() is a stub method for the shared processing
switch (numError)
{
case ERROR_01 : // intentional fall-through
case ERROR_07 : // intentional fall-through
case ERROR_0A : // intentional fall-through
case ERROR_10 : // intentional fall-through
case ERROR_15 : // intentional fall-through
case ERROR_16 : // intentional fall-through
case ERROR_20 :
{
fire_special_event();
}
break;
default:
{
// error codes that require no additional action
}
break;
}
```
`if` statement:
```
if ((ERROR_01 == numError) ||
(ERROR_07 == numError) ||
(ERROR_0A == numError) ||
(ERROR_10 == numError) ||
(ERROR_15 == numError) ||
(ERROR_16 == numError) ||
(ERROR_20 == numError))
{
fire_special_event();
}
```
|
Use switch.
In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.
In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).
|
For the special case that you've provided in your example, the clearest code is probably:
```
if (RequiresSpecialEvent(numError))
fire_special_event();
```
Obviously this just moves the problem to a different area of the code, but now you have the opportunity to reuse this test. You also have more options for how to solve it. You could use std::set, for example:
```
bool RequiresSpecialEvent(int numError)
{
return specialSet.find(numError) != specialSet.end();
}
```
I'm not suggesting that this is the best implementation of RequiresSpecialEvent, just that it's an option. You can still use a switch or if-else chain, or a lookup table, or some bit-manipulation on the value, whatever. The more obscure your decision process becomes, the more value you'll derive from having it in an isolated function.
|
Advantage of switch over if-else statement
|
[
"",
"c++",
"if-statement",
"optimization",
"switch-statement",
""
] |
How can brackets be escaped in using `string.Format`?
For example:
```
String val = "1,2,3"
String.Format(" foo {{0}}", val);
```
This example doesn't throw an exception, but it outputs the string `foo {0}`.
Is there a way to escape the brackets?
|
For you to output `foo {1, 2, 3}` you have to do something like:
```
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
```
To output a `{` you use `{{` and to output a `}` you use `}}`.
**Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)**
**Escaping brackets: String interpolation $("")**. It is new feature in C# 6.0.
```
var inVal = "1, 2, 3";
var outVal = $" foo {{{inVal}}}";
// The output will be: foo {1, 2, 3}
```
|
Yes, to output `{` in `string.Format` you have to escape it like this: `{{`
So the following will output `"foo {1,2,3}"`.
```
String val = "1,2,3";
String.Format(" foo {{{0}}}", val);
```
*But* you have to know about a design bug in C# which is that by going on the above logic you would assume this below code will print {24.00}:
```
int i = 24;
string str = String.Format("{{{0:N}}}", i); // Gives '{N}' instead of {24.00}
```
But this prints {N}. This is because the way C# parses escape sequences and format characters. To get the desired value in the above case, you have to use this instead:
```
String.Format("{0}{1:N}{2}", "{", i, "}") // Evaluates to {24.00}
```
### Reference Articles
* [String.Format gotcha](https://learn.microsoft.com/en-us/archive/blogs/brada/string-format-gottach)
* [String Formatting FAQ](https://learn.microsoft.com/en-us/archive/blogs/brada/string-formatting-faq)
|
How to escape braces (curly brackets) in a format string in .NET
|
[
"",
"c#",
".net",
"string",
"parsing",
"formatting",
""
] |
Is there a way to debug or trace every JavaScript event in Internet Explorer 7?
I have a bug that prevents scrolling after text-selecting, and I have no idea which event or action creates the bug. I really want to see which events are being triggered when I move the mouse for example.
It's too much work to rewire the source and I kind of hoped there was something like a sniffer which shows me all the events that are triggered.
|
Borkdude said:
> You might want to try Visual Studio 2008 and its feature to debug JavaScript code.
I've been hacking around event handling multiple times, and in my opinion, although classical stepping debuggers are useful to track long code runs, they're not good in tracking events. Imagine listening to mouse move events and breaking into another application on each event... So in this case, I'd strongly advise logging.
> If the problem is not specific to Internet Explorer 7 but also occurs in Firefox, then another good way to debug JavaScript code is Firefox and the [Firebug](http://en.wikipedia.org/wiki/Firebug) add-on which has a JavaScript debugger.
And there's also [Firebug Lite](http://getfirebug.com/firebuglite) for Internet Explorer. I didn't have a chance to use it, but it exists. :-) The downside of it is that it doesn't a fully-fledged debugger, but it has a window.console object, which is exactly what you need.
|
Loop through all elements on the page which have an onXYZ function defined and then add the trace to them:
```
var allElements = document.all; // Is this right? Anyway, you get the idea.
for (var i in allElements) {
if (typeof allElements[i].onblur == "function") {
var oldFunc = allElements[i].onblur;
allElements[i].onblur = function() {
alert("onblur called");
oldFunc();
};
}
}
```
|
How to trace JavaScript events like onclick onblur?
|
[
"",
"javascript",
"debugging",
"events",
""
] |
> **Possible Duplicate:**
> [JavaScript: var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname)
What's the difference between:
```
function sum(x, y) {
return x+y;
}
// and
var sum = function (x, y) {
return x+y;
}
```
Why is one used over the other?
|
The first is known as a named function where the second is known as an anonymous function.
The key practical difference is in when you can use the sum function. For example:-
```
var z = sum(2, 3);
function sum(x, y) {
return x+y;
}
```
`z` is assigned 5 whereas this:-
```
var z = sum(2, 3);
var sum = function(x, y) {
return x+y;
}
```
Will fail since at the time the first line has executed the variable sum has not yet been assigned the function.
Named functions are parsed and assigned to their names before execution begins which is why a named function can be utilized in code that precedes its definition.
Variables assigned a function by code can clearly only be used as function once execution has proceeded past the assignment.
|
The first tends to be used for a few reasons:
1. The name "sum" shows up in the
stacktrace which makes debugging
easier in many browsers.
2. The name
"sum" can be used inside the
function body which makes it easier
to use for recursive functions.
3. function declarations are "hoisted"
in javascript, so in the first case,
the function is guaranteed to be
defined exactly once.
4. Semicolon insertion causes
```
var f = function (x) { return 4; }
(f)
```
to assign 4 to `f`.
There are a few caveats to keep in mind though.
Do not do
```
var sum = function sum(x, y) { ... };
```
on IE 6 since it will result in two function objects being created. Especially confusing if you do
```
var sum = function mySym(x, y) { ... };
```
According to the standard,
function sum(x, y) { ... }
cannot appear inside an if block or a loop body, so different interpreters will treat
```
if (0) {
function foo() { return 1; }
} else {
function foo() { return 2; }
}
return foo();
```
differently.
In this case, you should do
```
var foo;
if (0) {
foo = function () { return 1; }
} ...
```
|
The difference between the two functions? ("function x" vs "var x = function")
|
[
"",
"javascript",
""
] |
What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes).
I've already seen a [few](http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/) [ways](http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/) to do it, but can't decide on which one is the best.
|
The least painful and indeed Django-recommended way of doing this is through a `OneToOneField(User)` property.
> ## [Extending the existing User model](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model)
>
> …
>
> If you wish to store information related to `User`, you can use a [one-to-one relationship](https://docs.djangoproject.com/en/dev/ref/models/fields/#ref-onetoone) to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.
That said, extending `django.contrib.auth.models.User` and supplanting it also works...
> ## [Substituting a custom User model](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model)
>
> Some kinds of projects may have authentication requirements for which Django’s built-in `User` model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.
>
> *[Ed: **Two warnings and a notification follow**, mentioning that this is **pretty drastic**.]*
I would definitely stay away from changing the actual User class in your Django source tree and/or copying and altering the auth module.
|
**Note: this answer is deprecated. see other answers if you are using Django 1.7 or later.**
This is how I do it.
```
#in models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
#other fields here
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
#in settings.py
AUTH_PROFILE_MODULE = 'YOURAPP.UserProfile'
```
This will create a userprofile each time a user is saved if it is created.
You can then use
```
user.get_profile().whatever
```
Here is some more info from the docs
<http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users>
**Update:** Please note that `AUTH_PROFILE_MODULE` is deprecated since v1.5: <https://docs.djangoproject.com/en/1.5/ref/settings/#auth-profile-module>
|
What's the best way to extend the User model in Django?
|
[
"",
"python",
"django",
"django-models",
"django-authentication",
"django-users",
""
] |
I could swear I've seen the function (or method) that takes a list, like this `[3, 7, 19]` and makes it into iterable list of tuples, like so: `[(0,3), (1,7), (2,19)]` to use it instead of:
```
for i in range(len(name_of_list)):
name_of_list[i] = something
```
but I can't remember the name and googling "iterate list" gets nothing.
|
```
>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
... print i, val
...
0 3
1 4
2 5
3 6
>>>
```
|
Yep, that would be the [`enumerate`](http://docs.python.org/library/functions.html#enumerate) function! Or more to the point, you need to do:
```
list(enumerate([3,7,19]))
[(0, 3), (1, 7), (2, 19)]
```
|
Iterate a list with indexes
|
[
"",
"python",
"list",
""
] |
I am working on an application that is about 250,000 lines of code. I'm currently the only developer working on this application that was originally built in .NET 1.1. Pervasive throughout is a class that inherits from CollectionBase. All database collections inherit from this class. I am considering refactoring to inherit from the generic collection List instead. Needless to say, Martin Fowler's Refactoring book has no suggestions. Should I attempt this refactor? If so, what is the best way to tackle this refactor?
And yes, there are unit tests throughout, but no QA team.
|
250,000 Lines is alot to refactor, plus you should take into account several of the follow:
1. Do you have a QA department that will be able to QA the refactored code?
2. Do you have unit tests for the old code?
3. Is there a timeframe that is around the project, i.e. are you maintaining the code as users are finding bugs?
if you answered 1 and 2 no, I would first and foremost write unit tests for the existing code. Make them extensive and thorough. Once you have those in place, branch a version, and start refactoring. The unit tests should be able to help you refactor in the generics in correctly.
If 2 is yes, then just branch and start refactoring, relying on those unit tests.
A QA department would help a lot as well, since you can field them the new code to test.
And lastly, if clients/users are needing bugs fixed, fix them first.
|
Don't. Unless you have a really good business justification for putting your code base through this exercise. What is the cost savings or revenue generated by your refactor? If I were your manager I would probably advise against it. Sorry.
|
How to Refactor to Generics from Class that Inherits from CollectionBase?
|
[
"",
"c#",
"generics",
".net-3.5",
".net-2.0",
"refactoring",
""
] |
Lasty, I tried to implements an hybrid structure in Java, something that looks like:
```
public class MapOfSet<K, V extends HasKey<K>> implements Set<V>, Map<K, Set<V>>
```
Where HasKey is the following interface:
```
public interface HasKey<K> {
public K getKey();
}
```
Unfortunately, there are some conflicts between methos signature of the Set interface and the Map interface in Java. I've finally chosen to implements only the Set interface and to add the Map method without implementing this interface.
Do you see a nicer solution?
In response to the first comments, here is my goal:
> Have a set structure and be able to efficiently access to a subset of values of this set, corresponding to a given key value.
> At the beginning I instantiated a map and a set, but I tried to joined the two structures to optimize performances.
|
Perhaps you could add more information which operations do you really want. I guess you want to create a set which automatically groups their elements by a key, right? The question is which operations do you want to be able to have? How are elements added to the Set? Can elements be deleted by removing them from a grouped view? My proposal would be an interface like that:
```
public interface GroupedSet<K, V extends HasKey<K>> extends Set<V>{
Set<V> havingKey(K k);
}
```
If you want to be able to use the Set as map you can add another method
```
Map<K,Set<V>> asMap();
```
That avoids the use of multiple interface inheritance and the resulting problems.
|
What are you trying to accomplish? `Map` already exposes its keys as a `Set` via its [keySet()](<http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet())> method. If you want a reliable iteratior order, there's [LinkedHashMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html) and [TreeMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html).
UPDATE: If you want to ensure that a value has only been inserted once, you can extend one of the classes I mentioned above to create something like a `SingleEntryMap` and override the implementation of `put(K key, V value)` to do a uniqueness check and throw an Exception when the value has already been inserted.
UPDATE: Will something like this work? (I don't have my editor up, so this may not compile)
```
public final class KeyedSets<K, V> implements Map<K,Set<V>> {
private final Map<K, Set<V>> internalMap = new TreeMap<K, Set<V>>;
// delegate methods go here
public Set<V> getSortedSuperset() {
final Set<V> superset = new TreeSet<V>();
for (final Map.Entry<K, V> entry : internalMap.entrySet()) {
superset.addAll(entry.getValue());
}
return superset;
}
}
```
|
Implements several interfaces with conflict in signatures
|
[
"",
"java",
"collections",
""
] |
What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?
No legacy browser compatibility required, Safari, Opera and Firefox will do.
|
If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but **without jQuery**.
```
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
console.log("x: " + x + " y: " + y)
}
const canvas = document.querySelector('canvas')
canvas.addEventListener('mousedown', function(e) {
getCursorPosition(canvas, e)
})
```
|
**Update** (5/5/16): [patriques' answer](https://stackoverflow.com/a/18053642/1026023) should be used instead, as it's both simpler and more reliable.
---
Since the canvas isn't always styled relative to the entire page, the `canvas.offsetLeft/Top` doesn't always return what you need. It will return the number of pixels it is offset relative to its offsetParent element, which can be something like a `div` element containing the canvas with a `position: relative` style applied. To account for this you need to loop through the chain of `offsetParent`s, beginning with the canvas element itself. This code works perfectly for me, tested in Firefox and Safari but should work for all.
```
function relMouseCoords(event){
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = this;
do{
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
}
while(currentElement = currentElement.offsetParent)
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
return {x:canvasX, y:canvasY}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;
```
The last line makes things convenient for getting the mouse coordinates relative to a canvas element. All that's needed to get the useful coordinates is
```
coords = canvas.relMouseCoords(event);
canvasX = coords.x;
canvasY = coords.y;
```
|
How do I get the coordinates of a mouse click on a canvas element?
|
[
"",
"javascript",
"canvas",
""
] |
I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle.
|
From my "Geometry" class:
```
public struct Line
{
public static Line Empty;
private PointF p1;
private PointF p2;
public Line(PointF p1, PointF p2)
{
this.p1 = p1;
this.p2 = p2;
}
public PointF P1
{
get { return p1; }
set { p1 = value; }
}
public PointF P2
{
get { return p2; }
set { p2 = value; }
}
public float X1
{
get { return p1.X; }
set { p1.X = value; }
}
public float X2
{
get { return p2.X; }
set { p2.X = value; }
}
public float Y1
{
get { return p1.Y; }
set { p1.Y = value; }
}
public float Y2
{
get { return p2.Y; }
set { p2.Y = value; }
}
}
public struct Polygon: IEnumerable<PointF>
{
private PointF[] points;
public Polygon(PointF[] points)
{
this.points = points;
}
public PointF[] Points
{
get { return points; }
set { points = value; }
}
public int Length
{
get { return points.Length; }
}
public PointF this[int index]
{
get { return points[index]; }
set { points[index] = value; }
}
public static implicit operator PointF[](Polygon polygon)
{
return polygon.points;
}
public static implicit operator Polygon(PointF[] points)
{
return new Polygon(points);
}
IEnumerator<PointF> IEnumerable<PointF>.GetEnumerator()
{
return (IEnumerator<PointF>)points.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return points.GetEnumerator();
}
}
public enum Intersection
{
None,
Tangent,
Intersection,
Containment
}
public static class Geometry
{
public static Intersection IntersectionOf(Line line, Polygon polygon)
{
if (polygon.Length == 0)
{
return Intersection.None;
}
if (polygon.Length == 1)
{
return IntersectionOf(polygon[0], line);
}
bool tangent = false;
for (int index = 0; index < polygon.Length; index++)
{
int index2 = (index + 1)%polygon.Length;
Intersection intersection = IntersectionOf(line, new Line(polygon[index], polygon[index2]));
if (intersection == Intersection.Intersection)
{
return intersection;
}
if (intersection == Intersection.Tangent)
{
tangent = true;
}
}
return tangent ? Intersection.Tangent : IntersectionOf(line.P1, polygon);
}
public static Intersection IntersectionOf(PointF point, Polygon polygon)
{
switch (polygon.Length)
{
case 0:
return Intersection.None;
case 1:
if (polygon[0].X == point.X && polygon[0].Y == point.Y)
{
return Intersection.Tangent;
}
else
{
return Intersection.None;
}
case 2:
return IntersectionOf(point, new Line(polygon[0], polygon[1]));
}
int counter = 0;
int i;
PointF p1;
int n = polygon.Length;
p1 = polygon[0];
if (point == p1)
{
return Intersection.Tangent;
}
for (i = 1; i <= n; i++)
{
PointF p2 = polygon[i % n];
if (point == p2)
{
return Intersection.Tangent;
}
if (point.Y > Math.Min(p1.Y, p2.Y))
{
if (point.Y <= Math.Max(p1.Y, p2.Y))
{
if (point.X <= Math.Max(p1.X, p2.X))
{
if (p1.Y != p2.Y)
{
double xinters = (point.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X;
if (p1.X == p2.X || point.X <= xinters)
counter++;
}
}
}
}
p1 = p2;
}
return (counter % 2 == 1) ? Intersection.Containment : Intersection.None;
}
public static Intersection IntersectionOf(PointF point, Line line)
{
float bottomY = Math.Min(line.Y1, line.Y2);
float topY = Math.Max(line.Y1, line.Y2);
bool heightIsRight = point.Y >= bottomY &&
point.Y <= topY;
//Vertical line, slope is divideByZero error!
if (line.X1 == line.X2)
{
if (point.X == line.X1 && heightIsRight)
{
return Intersection.Tangent;
}
else
{
return Intersection.None;
}
}
float slope = (line.X2 - line.X1)/(line.Y2 - line.Y1);
bool onLine = (line.Y1 - point.Y) == (slope*(line.X1 - point.X));
if (onLine && heightIsRight)
{
return Intersection.Tangent;
}
else
{
return Intersection.None;
}
}
}
```
|
Do <http://mathworld.wolfram.com/Line-LineIntersection.html> for the line and each side of the rectangle.
Or: <http://mathworld.wolfram.com/Line-PlaneIntersection.html>
|
How to know if a line intersects a plane in C#?
|
[
"",
"c#",
"geometry",
"2d",
"computational-geometry",
""
] |
In my browsings amongst the Internet, I came across [this post](http://www.reddit.com/r/programming/comments/6y6lr/ask_proggit_which_is_more_useful_to_know_c_or_java/), which includes this
> "(Well written) C++ goes to great
> lengths to make stack automatic
> objects work "just like" primitives,
> as reflected in Stroustrup's advice to
> "do as the ints do". This requires a
> much greater adherence to the
> principles of Object Oriented
> development: your class isn't right
> until it "works like" an int,
> following the "Rule of Three" that
> guarantees it can (just like an int)
> be created, copied, and correctly
> destroyed as a stack automatic."
I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly?
Can someone give an example?
|
Stack objects are handled automatically by the compiler.
When the scope is left, it is deleted.
```
{
obj a;
} // a is destroyed here
```
When you do the same with a 'newed' object you get a memory leak :
```
{
obj* b = new obj;
}
```
b is not destroyed, so we lost the ability to reclaim the memory b owns. And maybe worse, the object cannot clean itself up.
In C the following is common :
```
{
FILE* pF = fopen( ... );
// ... do sth with pF
fclose( pF );
}
```
In C++ we write this :
```
{
std::fstream f( ... );
// do sth with f
} // here f gets auto magically destroyed and the destructor frees the file
```
When we forget to call fclose in the C sample the file is not closed and may not be used by other programs. (e.g. it cannot be deleted).
Another example, demonstrating the object string, which can be constructed, assigned to and which is destroyed on exiting the scope.
```
{
string v( "bob" );
string k;
v = k
// v now contains "bob"
} // v + k are destroyed here, and any memory used by v + k is freed
```
|
In addition to the other answers:
The C++ language actually has the `auto` keyword to explicitly declare the storage class of an object. Of course, it's completely needless because this is the implied storage class for local variables and cannot be used anywhere. The opposite of `auto` is `static` (both locally and globall).
The following two declarations are equivalent:
```
int main() {
int a;
auto int b;
}
```
Because the keyword is utterly useless, it will actually be recycled in the next C++ standard (“C++0x”) and gets a new meaning, namely, it lets the compiler infer the variable type from its initialization (like `var` in C#):
```
auto a = std::max(1.0, 4.0); // `a` now has type double.
```
|
C++ - What does "Stack automatic" mean?
|
[
"",
"c++",
"oop",
""
] |
Do any C++ GNU standalone classes exist which handle paths cross platform? My applications build on Windows and LInux. Our configuration files refer to another file in a seperate directory. I'd like to be able to read the path for the other configuration file into a class which would work on both Linux or Windows.
Which class would offer the smallest footprint to translate paths to use on either system? Thanks
|
Unless you're using absolute paths, there's no need to translate at all - Windows automatically converts forward slashes into backslashes, so if you use relative paths with forward slash path separators, you'll be golden. You should really avoid absolute paths if at all possible.
|
try [boost::filesystem](http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm)
|
Handling file paths cross platform
|
[
"",
"c++",
"windows",
"linux",
"cross-platform",
"gnu",
""
] |
Should simple JavaBeans that have only simple getters and setters be unit tested??
What about Beans with some logic in getters and setters?
|
You should not write tests which:
* Test the language or the IDE (i.e. automatically generated getters and setters)
* Add no value to your test harness and kill your enthusiasm for Unit Testing
The same applies for .NET objects which only have properties (sometimes called 'Info' objects).
In an ideal world you would have 100% test coverage, but in practice this is not going to happen. So spend the client's money where it will add the most benefit i.e. writing tests for classes with complex state and behaviour.
If your JavaBean becomes more interesting you can of course add a test case later. One of the common problems associated with Unit Testing / TDD is the mistaken belief that everything has to be perfect first time.
|
If it's not worth testing, it's not worth writing.
That doesn't always mean you should write tests. Sometimes it means you should delete code. Do you need these beans? Do they actually do anything important? If you need them, you should write tests. If not, delete the code and live a happier life knowing you have less to maintain.
|
Should domain objects and simple JavaBeans be unit tested?
|
[
"",
"java",
"unit-testing",
""
] |
When I iterate over the values or keys are they going to correlate? Will the second key map to the second value?
|
No, not necessarily. You should really use the entrySet().iterator() for this purpose. With this iterator, you will be walking through all Map.Entry objects in the Map and can access each key and associated value.
|
to use the entrySet that @Cuchullain mentioned:
```
Map<String, String> map = new HashMap<String, String>();
// populate hashmap
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// your code here
}
```
|
When using a HashMap are values and keys guaranteed to be in the same order when iterating?
|
[
"",
"java",
"collections",
"hashmap",
""
] |
In a `CakePHP 1.2` app, I'm using
```
<?php $session->flash();?>
```
to output messages like "Record edited". It's working great.
However, I want to add a link called "Dismiss" that will fade out the message. I know how to construct the link, but I don't know how to insert into the output of the flass message.
The flash message wraps itself in a `DIV tag`. I want to insert my dismiss code into that div, but I don't know how.
|
Figured this out:
Create a new layout in your layouts folder:
```
layouts/message.ctp
```
In that layout, include the call to output the content:
```
<?php echo $content_for_layout; ?>
```
Then when you set the flash message, specify the layout to use:
```
$this->Session->setFlash('Your record has been created! Wicked!','message');
```
|
You want to use the [setflash](http://api.cakephp.org/class_session_component.html) function. If you pass setflash an empty string for $default it will not wrap your message in a div and just store it as is. This way you can display any markup you want or as Justin posted you can use another view page for your message so you don't mix your view and controllers.
|
Add dismiss control to session-flash() output in CakePHP
|
[
"",
"php",
"cakephp",
"cakephp-1.2",
""
] |
How do you get a Media Type (MIME type) from a file using Java? So far I've tried JMimeMagic & Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly.
How would you probe the file to determine its actual type (not merely based on the extension)?
|
In Java 7 you can now just use [`Files.probeContentType(path)`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType%28java.nio.file.Path%29).
|
Unfortunately,
```
mimeType = file.toURL().openConnection().getContentType();
```
does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.
However, you have this:
```
mimeType= URLConnection.guessContentTypeFromName(file.getName());
```
and also the following, which has the advantage of going beyond mere use of file extension, and takes a peek at content
```
InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
//...close stream
```
However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).
|
How to get a file's Media Type (MIME type)?
|
[
"",
"java",
"mime",
""
] |
what is the best method for inter process communication in a multithreaded java app.
It should be performant (so no JMS please) easy to implement and reliable,so that
objects & data can be bound to one thread only?
Any ideas welcome!
|
Assuming the scenario 1 JVM, multiple threads then indeed java.util.concurrent is the place to look, specifically the various Queue implementations. However an abstraction on top of that may be nice and there [Jetlang](http://code.google.com/p/jetlang/) looks very interesting, lightweight Java message passing.
|
Could you clarify a bit? Do you mean IPC in a single JVM? (Multiple threads, yes, but at an OS-level only one process.) Or do you mean multiple JVMs? (And truly OS-level inter process communications.)
If it is the first, then maybe something out of **java.util.concurrent**, like [ConcurrentLinkedQueue](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html) would do the trick. (I pass message around inbetween my threads with classes from java.util.concurrent with success.)
If the later, then I'm going to just guess and suggest taking a look at **[RMI](http://java.sun.com/javase/technologies/core/basic/rmi/index.jsp)**, although I don' think it qualifies as fully reliable--you'd have to manage that a bit more 'hands on' like.
|
Best practice for Java IPC
|
[
"",
"java",
"multithreading",
""
] |
In Java, there is a practice of declaring every variable (local or class), parameter final if they really are.
Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.
What are your thoughts on this and what do you follow?
|
I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of `final` modifiers anywhere, but when you think about it...
Adding `final` to all things which *should not* change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing.
At first, it kind of looks awkward to see a lot of `final` keywords in your code, but pretty soon you'll stop noticing the word itself and will simply think, *that-thing-will-never-change-from-this-point-on* (you can take it from me ;-)
I think it's good practice. I am not using it all the time, but when I can and it makes sense to label something `final` I'll do it.
|
Obsess over:
* Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things that object reference refers to can still change and that affects the immutability.)
* Final static fields - Although I use enums now for many of the cases where I used to use static final fields.
Consider but use judiciously:
* Final classes - Framework/API design is the only case where I consider it.
* Final methods - Basically same as final classes. If you're using template method patterns like crazy and marking stuff final, you're probably relying too much on inheritance and not enough on delegation.
Ignore unless feeling anal:
* Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class.
|
Using the "final" modifier whenever applicable in Java
|
[
"",
"java",
"oop",
""
] |
I'm using Visual Studio 2008 and the built-in installation tools for a C# client application. How can I use this installer to install a font on the client machine (if it's not already there)?
|
In VS2005 (so I assume 2008 as well), right click on the File System on Target Machine, Add Special Folder -> Fonts Folder, then place your font file there.
|
For me, Timothy Carter had the answer mostly right:
"right click on the File System on Target Machine, Add Special Folder -> Fonts Folder, then place your font file there."
But that was not enough. The Fonts didn't actually get installed as system Fonts.
To install the fonts, I had to visit the Properties for each font file and change Register=vsdrfDoNoRegister to Register=vsdrfFont. After that the Setup file I generated would also install the font!
|
Installing a font on a client machine
|
[
"",
"c#",
"visual-studio-2008",
"installation",
"fonts",
""
] |
I am building a site that uses a simple AJAX Servlet to talk JMS (ActiveMQ) and when a message arrives from the topic to update the site.
I have Javascript that creates an XMLHttpRequest for data. The Servlet processes the Get Request and sends back JSON. However I have no idea how to connect my Servlet into my ActiveMQ Message Broker. It just sends back dummy data right now.
I am thinking the Servelt should implement the messagelistener. Then onMessage send data to the JavaScript page. But I'm not sure how to do this.
|
The problem with having a servlet implement MessageListener is that servlets are synchronous and MessageListeners are asynchronous. Instead you should create some other object to act as the MessageListener and update some state somewhere (possibly a database or a JMX MBean or a Stateful Session EJB) when messages come in. Then the servlet can query that state to see if there's data to report back to the client, and your web page can periodically ping the servlet to ask for fresh data.
|
As James Strachan says - <http://activemq.apache.org/ajax.html> is an ideal out-of-the-box solution for your problem.
If you still want to create such solution manually you can just create JMS connection in your Ajax servlet (connection per request). Consider using Spring JMS template for that reason ( <http://static.springsource.org/spring/docs/2.5.x/reference/jms.html> ). Then just receive the message in the Servlet doGet/doPost method. Consider low timeout value for receiving in that case. Such solution will work for the Queues and durable Topics.
For non-durable Topics consider external message listener. Spring `MessageListenerContainer` is an excellent tool for that purpose:
```
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer
<property name="connectionFactory" ref="jmsFactory"/>
<property name="destination" ref="myTopic" />
<property name="messageListener" ref="lastTenUpdatesCache" />
</bean>
```
Bean `lastTenUpdatesCache` will be a singleton bean implementing `MesssageListener`. This bean would be responsible for caching last ten messages (just putting it into a java.util list). It will be injected into your Ajax servlet so in your doGet/doPost method you can ask it about last 10 messages sent to the topic.
|
Write a Servlet that Talks to JMS (ActiveMQ) and OnMessage Update the Site
|
[
"",
"javascript",
"servlets",
"jms",
"activemq-classic",
""
] |
I'm writing a custom file selection component. In my UI, first the user clicks a button, which pops a `JFileChooser`; when it is closed, the absolute path of the selected file is written to a `JTextField`.
The problem is, absolute paths are usually long, which causes the text field to enlarge, making its container too wide.
I've tried this, but it didn't do anything, the text field is still too wide:
```
fileNameTextField.setMaximumSize(new java.awt.Dimension(450, 2147483647));
```
Currently, when it is empty, it is already 400px long, because of `GridBagConstraints` attached to it.
I'd like it to be like text fields in HTML pages, which have a fixed size and do not enlarge when the input is too long.
So, how do I set the max size for a `JTextField` ?
|
It may depend on the layout manager your text field is in. Some layout managers expand and some do not. Some expand only in some cases, others always.
I'm assuming you're doing
```
filedNameTextField = new JTextField(80); // 80 == columns
```
If so, for most reasonable layouts, the field should not change size (at least, it shouldn't grow). Often layout managers behave badly when put into `JScrollPane`s.
In my experience, trying to control the sizes via `setMaximumSize` and `setPreferredWidth` and so on are precarious at best. Swing decided on its own with the layout manager and there's little you can do about it.
All that being said, I have no had the problem you are experiencing, which leads me to believe that some judicious use of a layout manager will solve the problem.
|
I solved this by setting the maximum width on the container of the text field, using `setMaximumSize`.
According to davetron's answer, this is a fragile solution, because the layout manager might disregard that property. In my case, the container is the top-most, and in a first test it worked.
|
Java, Swing: how do I set the maximum width of a JTextField?
|
[
"",
"java",
"swing",
"jtextfield",
""
] |
We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" attribute of an iframe.
For example, the page at the URL <http://oursite/Page.aspx?a=1&b=2> would have JavaScript in it to read the "a" and "b" parameters. The JavaScript would then set the "src" attribute of an iframe based on those parameters. For example, "<iframe src="http://someothersite/Page.aspx?a=1&b=2" />"
We're currently doing this with server-side code that uses Microsoft's Anti Cross-Scripting library to check the parameters. However, a new requirement has come stating that we need to use JavaScript, and that it can't use any third-party JavaScript tools (such as jQuery or Prototype).
One way I know of is to replace any instances of "<", single quote, and double quote from the parameters before using them, but that doesn't seem secure enough to me.
One of the parameters is always a "P" followed by 9 integers.
The other parameter is always 15 alpha-numeric characters.
(Thanks Liam for suggesting I make that clear).
Does anybody have any suggestions for us?
Thank you very much for your time.
|
Upadte Sep 2022: Most JS runtimes now have a *URL* type which exposes query parameters via the [*searchParams*](https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams) property.
You need to supply a base URL even if you just want to get URL parameters from a relative URL, but it's better than rolling your own.
```
let searchParams/*: URLSearchParams*/ = new URL(
myUrl,
// Supply a base URL whose scheme allows
// query parameters in case `myUrl` is scheme or
// path relative.
'http://example.com/'
).searchParams;
console.log(searchParams.get('paramName')); // One value
console.log(searchParams.getAll('paramName'));
```
The difference between `.get` and `.getAll` is that the second returns an array which can be important if the same parameter name is mentioned multiple time as in `/path?foo=bar&foo=baz`.
---
Don't use escape and unescape, use decodeURIComponent.
E.g.
```
function queryParameters(query) {
var keyValuePairs = query.split(/[&?]/g);
var params = {};
for (var i = 0, n = keyValuePairs.length; i < n; ++i) {
var m = keyValuePairs[i].match(/^([^=]+)(?:=([\s\S]*))?/);
if (m) {
var key = decodeURIComponent(m[1]);
(params[key] || (params[key] = [])).push(decodeURIComponent(m[2]));
}
}
return params;
}
```
and pass in document.location.search.
As far as turning < into <, that is not sufficient to make sure that the content can be safely injected into HTML without allowing script to run. Make sure you escape the following <, >, &, and ".
It will not guarantee that the parameters were not spoofed. If you need to verify that one of your servers generated the URL, do a search on URL signing.
|
Using a whitelist-approach would be better I guess.
Avoid only stripping out "bad" things. Strip out anything except for what you think is "safe".
Also I'd strongly encourage to do a HTMLEncode the Parameters. There should be plenty of Javascript functions that can this.
|
Best way to safely read query string parameters?
|
[
"",
"javascript",
"security",
"parameters",
""
] |
What is the best way to reduce the size of the viewstate hidden field in JSF?
I have noticed that my view state is approximately 40k this goes down to the client and back to the server on every request and response espically coming to the server this is a significant slowdown for the user.
My Environment JSF 1.2, MyFaces, Tomcat, Tomahawk, RichFaces
|
Have you tried setting the state saving to server? This should only send an id to the client, and keep the full state on the server. Simply add the following to the file *web.xml* :
```
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
```
|
If you are using MyFaces you can try this setting to compress the viewstate before sending to the client.
```
<context-param>
<param-name>org.apache.myfaces.COMPRESS_STATE_IN_CLIENT</param-name>
<param-value>true</param-value>
</context-param> `
```
|
How to reduce javax.faces.ViewState in JSF
|
[
"",
"java",
"optimization",
"jsf",
"viewstate",
"bandwidth",
""
] |
Every time I try to run a small application that uses a Derby DB I get this error message:
> **Message: Database at /path/to/db/TheDB has an incompatible format with the current version of the software. The database was created by or upgraded by version 10.4.**
I've added the library from Netbeans, and still have the same problem.
I'm not sure what to do here.
|
The version included with Netbeans might be old (Derby 10.2 as of NB 6.0). If you added Derby via the project properties and added the "Library", then you probably had the old version.
You can update the library by going to Tool -> Libraries. Select "Java DB Driver". Delete the jar references and update them to point at your 10.4 version.
If you added the JAR file to the project properties AND had the library added, then NB may have grabbed the first/last JAR it found in the list...
|
Hmmm, all I have to do was to add the proper derby.jar **manually** to the project.
A simple copy command operation:
> cp /opt/Apache/derbyinstall/lib/**derby.jar** /path/to/project/**dist/lib/**
...did the job.
The problem was that: I did this operation *from* Netbeans, and *I don't know why*, Netbeans didn't update the jar file. Weird, but fixed. :)
|
How do I configure a project to use latest Derby DB version (10.4)?
|
[
"",
"java",
"netbeans",
"derby",
""
] |
In a recent conversation, I mentioned that I was using JavaScript for a web application. That comment prompted a response: "You should use Flex instead. It will cut your development time down and JavaScript is too hard to debug and maintain. You need to use the right tool for the right job." Now, I don't know too much about Flex, but I personally don't feel like JavaScript is too hard to debug or maintain, especially if you use a framework. JavaScript is also one of the most used languages right now, so it would seem a better choice in that regard too. However, his reply piqued my interest. Would Flex be a good choice for a distributable web app for which 3rd party developers could build add-ons? What are the advantages of using it vs. a JavaScript framework? What are some of the disadvantages?
|
I would push you towards standard web development technologies in most cases. Javascript is no longer a great challenge to debug or maintain with good libs like jQuery/Prototype to iron out some of the browser inconsistencies and tools like Firebug and the MS script debugger to help with debugging.
There are cases when Flash is a better option, but only in cases where you are doing complex animations. And, if you are willing to invest the effort, most animations can be achieved without resorting to flash. A [couple](http://www.hudsonstreetservices.com/) of [examples](http://www.hudsonstreetservices.com/hudsonstreet/services/index.asp)...
**Flash content is not as accessible as other content.**
This will not only affect people with out flash, but also search engine spiders. There may be some hacks to help get around this now, but I think that most flash content will never be indexed by google.
**Flash breaks the web UI.**
For example:
* If I click my mouse wheel on a link,
that link is opened in a background
tab. In a flash app there is no way
to simulate this behavior.
* If I select text in my browser and
right-click I get options provided
by the browser that include things
like "Search Google for this text".
In a flash app those options are no
longer there.
* If I right click on a link or an
image I get a different set of
options that are not available in a
flash app. This can be very
frustrating to a user who is not
"flash savvy".
|
I have recently started to develop Flex applications, and I personally find it a refreshing framework for the web.
You get a state-ful application that runs completely client side. You get no worries about cross-browser portability that you do with JavaScript, and you get some really neat things such as effects, graphing, and rich user interface components.
Flex also makes it easy to communicate to webservices and the XML parsing via ECMA is insanely powerful and simple.
I'm glad I have made the switch. As far as how popular it is...I'm not really sure, but I am fairly certain that the developer base is expanding rapidly.
The only real disadvantage I can think of is a flash player requirement, but I would say it is pretty safe to assume that most browser support flash player; even konquerer in Linux is supported; much more so then a silverlight runtime (which I NEVER plan on installing)
|
Why should I use Flex?
|
[
"",
"javascript",
"apache-flex",
""
] |
I'm working on a large c++ system that is has been in development for a few years now. As part of an effort to improve the quality of the existing code we engaged on a large long-term refactoring project.
Do you know a good tool that can help me write unit tests in C++? Maybe something similar to Junit or Nunit?
Can anyone give some good advice on the methodology of writing unit tests for modules that were written without unit testing in mind?
|
Applying unit tests to legacy code was the **very reason** [Working Effectively with Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052) was written. Michael Feathers is the author - as mentioned in other answers, he was involved in the creation of both [CppUnit](http://sourceforge.net/projects/cppunit) and [CppUnitLite](http://www.objectmentor.com/resources/downloads.html).

|
Google recently released their own library for unit testing C++ apps, called Google Test.
[Project on Google Code](http://code.google.com/p/googletest/)
|
Unit testing for C++ code - Tools and methodology
|
[
"",
"c++",
"unit-testing",
"refactoring",
""
] |
I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the file is already opened? Does this automatically make the second process get an exception if the file is open (which solves my problem) or do I have to explicitly open it in the first process with some sort of flag or argument?
### To clarify:
I have a Java app that lists a folder and opens each file in the listing for processing it. It processes each file after the other. The processing of each file consists of reading it and doing some calculations based on the contents and it takes about 2 minutes. I also have another Java app that does the same thing but instead writes on the file. What I want is to be able to run these apps at the same time so the scenario goes like this. ReadApp lists the folder and finds files A, B, C. It opens file A and starts the reading. WriteApp lists the folder and finds files A, B, C. It opens file A, sees that is is open (by an exception or whatever way) and goes to file B. ReadApp finishes file A and continues to B. It sees that it is open and continues to C. It is crucial that WriteApp doesn't write while ReadApp is reading the same file or vice versa. They are different processes.
|
FileChannel.lock is probably what you want.
```
try (
FileInputStream in = new FileInputStream(file);
java.nio.channels.FileLock lock = in.getChannel().lock();
Reader reader = new InputStreamReader(in, charset)
) {
...
}
```
(Disclaimer: Code not compiled and certainly not tested.)
Note the section entitled "platform dependencies" in the [API doc for FileLock](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/channels/FileLock.html#pdep).
|
Don't use the classes in the`java.io` package, instead use the `java.nio` package . The latter has a `FileLock` class. You can apply a lock to a `FileChannel`.
```
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();
/*
use channel.lock OR channel.tryLock();
*/
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
// Release the lock - if it is not null!
if( lock != null ) {
lock.release();
}
// Close the file
channel.close();
} catch (Exception e) {
}
```
|
How can I lock a file using java (if possible)
|
[
"",
"java",
"file-io",
""
] |
In Java, I use a class in which some fields can be `null`. For example:
```
class Foo {
String bar;
//....
}
```
I want to write a BarComparator for this class,
```
private static class BarComparator
implements Comparator<Foo> {
public int compare( final Foo o1, final Foo o2 )
{
// Implementation goes here
}
}
```
Is there a standard way to deal with the fact that any of `o1`, `o2`, `o1.bar`, `o2.bar` can be `null`, without writing lots of nested `if`...`else`?
Cheers!
|
I guess you could wrap the call to the field compareTo method with a small static method to sort nulls high or low:
```
static <T extends Comparable<T>> int cp(T a, T b) {
return
a==null ?
(b==null ? 0 : Integer.MIN_VALUE) :
(b==null ? Integer.MAX_VALUE : a.compareTo(b));
}
```
Simple usage (multiple fields is as you would normally):
```
public int compare( final Foo o1, final Foo o2 ) {
return cp(o1.field, o2.field);
}
```
|
Thanks for the replies! The generic method and the Google Comparators look interesting.
And I found that there's a [NullComparator](http://commons.apache.org/collections/api-release/org/apache/commons/collections/comparators/NullComparator.html) in the [Apache Commons Collections](http://commons.apache.org/collections/api-release/index.html) (which we're currently using):
```
private static class BarComparator
implements Comparator<Foo>
{
public int compare( final Foo o1, final Foo o2 )
{
// o1.bar & o2.bar nulleness is taken care of by the NullComparator.
// Easy to extend to more fields.
return NULL_COMPARATOR.compare(o1.bar, o2.bar);
}
private final static NullComparator NULL_COMPARATOR =
new NullComparator(false);
}
```
Note: I focused on the `bar` field here to keep it to the point.
|
What to do with null fields in compare()?
|
[
"",
"java",
"comparison",
"null",
""
] |
I have several log files of events (one event per line). The logs can possibly overlap. The logs are generated on separate client machines from possibly multiple time zones (but I assume I know the time zone). Each event has a timestamp that was normalized into a common time (by instantianting each log parsers calendar instance with the timezone appropriate to the log file and then using getTimeInMillis to get the UTC time). The logs are already sorted by timestamp. Multiple events can occur at the same time, but they are by no means equal events.
These files can be relatively large, as in, 500000 events or more in a single log, so reading the entire contents of the logs into a simple Event[] is not feasible.
What I am trying do is merge the events from each of the logs into a single log. It is kinda like a mergesort task, but each log is already sorted, I just need to bring them together. The second component is that the same event can be witnessed in each of the separate log files, and I want to "remove duplicate events" in the file output log.
Can this be done "in place", as in, sequentially working over some small buffers of each log file? I can't simply read in all the files into an Event[], sort the list, and then remove duplicates, but so far my limited programming capabilities only enable me to see this as the solution. Is there some more sophisticated approach that I can use to do this as I read events from each of the logs concurrently?
|
1. Read the first line from each of the log files
2. LOOP
a. Find the "earliest" line.
b. Insert the "earliest" line into the master log file
c. Read the next line from the file that contained the earliest line
You could check for duplicates between b and c, advancing the pointer for each of those files.
|
Sure - open every log file. Read in the first line for each into an array of 'current' lines. Then repeatedly pick the line with the lowest timestamp from the current array. Write it to the output, and read a new line from the appropriate source file to replace it.
Here's an example in Python, but it makes good pseudocode, too:
```
def merge_files(files, key_func):
# Populate the current array with the first line from each file
current = [file.readline() for file in files]
while len(current) > 0:
# Find and return the row with the lowest key according to key_func
min_idx = min(range(len(files)), key=lambda x: return key_func(current[x]))
yield current[min_idx]
new_line = files[min_idx].readline()
if not new_line:
# EOF, remove this file from consideration
del current[min_idx]
del files[min_idx]
else:
current[min_idx] = new_line
```
|
Algorithm for merging large files
|
[
"",
"java",
"sorting",
"file",
"merge",
""
] |
What are the potential pros and cons of each of these queries given different databases, configurations, etc? Is there ever a time when one would be more efficient than the other? Vice versa? Is there an even better way to do it? Can you explain why?
Query 1:
```
SELECT
*
FROM
table_a, table_b, table_c
WHERE
table_a.id = table_b.id AND
table_a.id = table_c.id AND
table_a.create_date > DATE('1998-01-01');
```
Query 2:
```
SELECT
*
FROM
table_a
INNER JOIN table_b ON
table_a.id = table_b.id
INNER JOIN table_c ON
table_a.id = table_c.id
WHERE
table_a.create_date > DATE('1998-01-01');
```
|
Same query, different revision of SQL spec. The query optimizer should come up with the same query plan for those.
|
Nope. I'm just sharing a large, overwhelmed database with some coworkers and am trying to come up with some ways to get more processor bang for our buck. I've been looking around online but haven't found a good explanation for some questions like this.
Sorry for sounding homework-y. I guess I spent too many years as a TA.
|
Comparing MySQL Cross and Inner Joins
|
[
"",
"mysql",
"sql",
""
] |
I am doing a project at the moment, and in the interest of code reuse, I went looking for a library that can perform some probabilistic accept/reject of an item:
i.e., there are three people (a, b c), and each of them have a probability P{i} of getting an item, where p{a} denotes the probability of a. These probabilities are calculated at run time, and cannot be hardcoded.
What I wanted to do is to generate one random number (for an item), and calculate who gets that item based on their probability of getting it. The alias method (<http://books.google.com/books?pg=PA133&dq=alias+method+walker&ei=D4ORR8ncFYuWtgOslpVE&sig=TjEThBUa4odbGJmjyF4daF1AKF4&id=ERSSDBDcYOIC&output=html>) outlined here explained how, but I wanted to see if there is a ready made implementation so I wouldn't have to write it up.
|
Would something like this do? Put all p{i}'s in the array, function will return an index to the person who gets the item. Executes in O(n).
```
public int selectPerson(float[] probabilies, Random r) {
float t = r.nextFloat();
float p = 0.0f;
for (int i = 0; i < probabilies.length; i++) {
p += probabilies[i];
if (t < p) {
return i;
}
}
// We should not end up here if probabilities are normalized properly (sum up to one)
return probabilies.length - 1;
}
```
EDIT: I haven't really tested this. My point was that the function you described is not very complicated (if I understood what you meant correctly, that is), and you shouldn't need to download a library to solve this.
|
Here is a Ruby implementation: <https://github.com/cantino/walker_method>
|
Opensource Implementation of the Alias Method
|
[
"",
"java",
"statistics",
"random",
"probability",
""
] |
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type:
Which is quicker and why?
```
switch(childNode.Name)
{
case "Bob":
break;
case "Jill":
break;
case "Marko":
break;
}
if(childNode is Bob)
{
}
elseif(childNode is Jill)
{
}
else if(childNode is Marko)
{
}
```
**Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements?
**Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
|
Greg's profile results are great for the exact scenario he covered, but interestingly, the relative costs of the different methods change dramatically when considering a number of different factors including the number of types being compared, and the relative frequency and any patterns in the underlying data.
The simple answer is that nobody can tell you what the performance difference is going to be in your specific scenario, you will need to measure the performance in different ways yourself in your own system to get an accurate answer.
The If/Else chain is an effective approach for a small number of type comparisons, or if you can reliably predict which few types are going to make up the majority of the ones that you see. The potential problem with the approach is that as the number of types increases, the number of comparisons that must be executed increases as well.
if I execute the following:
```
int value = 25124;
if(value == 0) ...
else if (value == 1) ...
else if (value == 2) ...
...
else if (value == 25124) ...
```
each of the previous if conditions must be evaluated before the correct block is entered. On the other hand
```
switch(value) {
case 0:...break;
case 1:...break;
case 2:...break;
...
case 25124:...break;
}
```
will perform one simple jump to the correct bit of code.
Where it gets more complicated in your example is that your other method uses a switch on strings rather than integers which gets a little more complicated. At a low level, strings can't be switched on in the same way that integer values can so the C# compiler does some magic to make this work for you.
If the switch statement is "small enough" (where the compiler does what it thinks is best automatically) switching on strings generates code that is the same as an if/else chain.
```
switch(someString) {
case "Foo": DoFoo(); break;
case "Bar": DoBar(); break;
default: DoOther; break;
}
```
is the same as:
```
if(someString == "Foo") {
DoFoo();
} else if(someString == "Bar") {
DoBar();
} else {
DoOther();
}
```
Once the list of items in the dictionary gets "big enough" the compiler will automatically create an internal dictionary that maps from the strings in the switch to an integer index and then a switch based on that index.
It looks something like this (Just imagine more entries than I am going to bother to type)
A static field is defined in a "hidden" location that is associated with the class containing the switch statement of type `Dictionary<string, int>` and given a mangled name
```
//Make sure the dictionary is loaded
if(theDictionary == null) {
//This is simplified for clarity, the actual implementation is more complex
// in order to ensure thread safety
theDictionary = new Dictionary<string,int>();
theDictionary["Foo"] = 0;
theDictionary["Bar"] = 1;
}
int switchIndex;
if(theDictionary.TryGetValue(someString, out switchIndex)) {
switch(switchIndex) {
case 0: DoFoo(); break;
case 1: DoBar(); break;
}
} else {
DoOther();
}
```
In some quick tests that I just ran, the If/Else method is about 3x as fast as the switch for 3 different types (where the types are randomly distributed). At 25 types the switch is faster by a small margin (16%) at 50 types the switch is more than twice as fast.
If you are going to be switching on a large number of types, I would suggest a 3rd method:
```
private delegate void NodeHandler(ChildNode node);
static Dictionary<RuntimeTypeHandle, NodeHandler> TypeHandleSwitcher = CreateSwitcher();
private static Dictionary<RuntimeTypeHandle, NodeHandler> CreateSwitcher()
{
var ret = new Dictionary<RuntimeTypeHandle, NodeHandler>();
ret[typeof(Bob).TypeHandle] = HandleBob;
ret[typeof(Jill).TypeHandle] = HandleJill;
ret[typeof(Marko).TypeHandle] = HandleMarko;
return ret;
}
void HandleChildNode(ChildNode node)
{
NodeHandler handler;
if (TaskHandleSwitcher.TryGetValue(Type.GetRuntimeType(node), out handler))
{
handler(node);
}
else
{
//Unexpected type...
}
}
```
This is similar to what Ted Elliot suggested, but the usage of runtime type handles instead of full type objects avoids the overhead of loading the type object through reflection.
Here are some quick timings on my machine:
```
Testing 3 iterations with 5,000,000 data elements (mode=Random) and 5 types
Method Time % of optimal
If/Else 179.67 100.00
TypeHandleDictionary 321.33 178.85
TypeDictionary 377.67 210.20
Switch 492.67 274.21
Testing 3 iterations with 5,000,000 data elements (mode=Random) and 10 types
Method Time % of optimal
If/Else 271.33 100.00
TypeHandleDictionary 312.00 114.99
TypeDictionary 374.33 137.96
Switch 490.33 180.71
Testing 3 iterations with 5,000,000 data elements (mode=Random) and 15 types
Method Time % of optimal
TypeHandleDictionary 312.00 100.00
If/Else 369.00 118.27
TypeDictionary 371.67 119.12
Switch 491.67 157.59
Testing 3 iterations with 5,000,000 data elements (mode=Random) and 20 types
Method Time % of optimal
TypeHandleDictionary 335.33 100.00
TypeDictionary 373.00 111.23
If/Else 462.67 137.97
Switch 490.33 146.22
Testing 3 iterations with 5,000,000 data elements (mode=Random) and 25 types
Method Time % of optimal
TypeHandleDictionary 319.33 100.00
TypeDictionary 371.00 116.18
Switch 483.00 151.25
If/Else 562.00 175.99
Testing 3 iterations with 5,000,000 data elements (mode=Random) and 50 types
Method Time % of optimal
TypeHandleDictionary 319.67 100.00
TypeDictionary 376.67 117.83
Switch 453.33 141.81
If/Else 1,032.67 323.04
```
On my machine at least, the type handle dictionary approach beats all of the others for anything over 15 different types when the distribution
of the types used as input to the method is random.
If on the other hand, the input is composed entirely of the type that is checked first in the if/else chain that method is *much* faster:
```
Testing 3 iterations with 5,000,000 data elements (mode=UniformFirst) and 50 types
Method Time % of optimal
If/Else 39.00 100.00
TypeHandleDictionary 317.33 813.68
TypeDictionary 396.00 1,015.38
Switch 403.00 1,033.33
```
Conversely, if the input is always the last thing in the if/else chain, it has the opposite effect:
```
Testing 3 iterations with 5,000,000 data elements (mode=UniformLast) and 50 types
Method Time % of optimal
TypeHandleDictionary 317.67 100.00
Switch 354.33 111.54
TypeDictionary 377.67 118.89
If/Else 1,907.67 600.52
```
If you can make some assumptions about your input, you might get the best performance from a hybrid approach where you perform if/else checks for the few types that are most common, and then fall back to a dictionary-driven approach if those fail.
|
Firstly, you're comparing apples and oranges. You'd first need to compare switch on type vs switch on string, and then if on type vs if on string, and then compare the winners.
Secondly, this is the kind of thing OO was designed for. In languages that support OO, switching on type (of any kind) is a code smell that points to poor design. The solution is to derive from a common base with an abstract or virtual method (or a similar construct, depending on your language)
eg.
```
class Node
{
public virtual void Action()
{
// Perform default action
}
}
class Bob : Node
{
public override void Action()
{
// Perform action for Bill
}
}
class Jill : Node
{
public override void Action()
{
// Perform action for Jill
}
}
```
Then, instead of doing the switch statement, you just call childNode.Action()
|
What is quicker, switch on string or elseif on type?
|
[
"",
"c#",
"performance",
""
] |
When I launch the "mvn install" command, maven sometimes tries to download dependencies that it has already downloaded. That's expected for SNAPSHOT but why does maven do that for other JARs?
I know I can avoid that behavior by "-o" flag but I just wonder what the cause is.
|
I'd look for dependencies that don't have a specified version number. Maven will periodically check to make sure that it has the most up-to-date version of these artifacts.
|
This is probably not what you're seeing, but in the past I've had to manually install artifacts into my local repository and if you forget to include the -Dgenerate.pom=true option there will be no pom in the repo for that artifact and Maven will go out to central (and any other remote repos you have configured) to try to download that pom on every build.
|
Why does maven 2 try to download dependencies that I already have?
|
[
"",
"java",
"maven-2",
""
] |
I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times.
```
ID uniqueidentifier not null,
ThingID int NOT NULL,
PriceDateTime datetime NOT NULL,
Price decimal(18,4) NOT NULL
```
I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries?
```
SELECT *
FROM Thing
WHERE ThingID IN (1,2,3,4,5,6)
AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime)
```
**UPDATE:** In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier.
|
I think the only solution with your table structure is to work with a subquery:
```
SELECT *
FROM Thing
WHERE ID IN (SELECT max(ID) FROM Thing
WHERE ThingID IN (1,2,3,4)
GROUP BY ThingID)
```
(Given the highest ID also means the newest price)
However I suggest you add a "IsCurrent" column that is 0 if it's not the latest price or 1 if it is the latest. This will add the possible risk of inconsistent data, but it will speed up the whole process a lot when the table gets bigger (if it is in an index). Then all you need to do is to...
```
SELECT *
FROM Thing
WHERE ThingID IN (1,2,3,4)
AND IsCurrent = 1
```
**UPDATE**
Okay, Markus updated the question to show that ID is a uniqueid, not an int. That makes writing the query even more complex.
```
SELECT T.*
FROM Thing T
JOIN (SELECT ThingID, max(PriceDateTime)
WHERE ThingID IN (1,2,3,4)
GROUP BY ThingID) X ON X.ThingID = T.ThingID
AND X.PriceDateTime = T.PriceDateTime
WHERE ThingID IN (1,2,3,4)
```
I'd really suggest using either a "IsCurrent" column or go with the other suggestion found in the answers and use "current price" table and a separate "price history" table (which would ultimately be the fastest, because it keeps the price table itself small).
(I know that the ThingID at the bottom is redundant. Just try if it is faster with or without that "WHERE". Not sure which version will be faster after the optimizer did its work.)
|
I would try something like the following subquery and forget about changing your data structures.
```
SELECT
*
FROM
Thing
WHERE
(ThingID, PriceDateTime) IN
(SELECT
ThingID,
max(PriceDateTime )
FROM
Thing
WHERE
ThingID IN (1,2,3,4)
GROUP BY
ThingID
)
```
**Edit** the above is ANSI SQL and i'm now guessing having more than one column in a subquery doesnt work for T SQL. Marius, I can't test the following but try;
```
SELECT
p.*
FROM
Thing p,
(SELECT ThingID, max(PriceDateTime ) FROM Thing WHERE ThingID IN (1,2,3,4) GROUP BY ThingID) m
WHERE
p.ThingId = m.ThingId
and p.PriceDateTime = m.PriceDateTime
```
another option might be to change the date to a string and concatenate with the id so you have only one column. This would be slightly nasty though.
|
SQL Query to get latest price
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
How would you write (in C/C++) a macro which tests if an integer type (given as a parameter) is signed or unsigned?
```
#define is_this_type_signed (my_type) ...
```
|
If what you want is a simple macro, this should do the trick:
```
#define is_type_signed(my_type) (((my_type)-1) < 0)
```
|
In C++, use `std::numeric_limits<type>::is_signed`.
```
#include <limits>
std::numeric_limits<int>::is_signed - returns true
std::numeric_limits<unsigned int>::is_signed - returns false
```
See <https://en.cppreference.com/w/cpp/types/numeric_limits/is_signed>.
|
Macro to test whether an integer type is signed or unsigned
|
[
"",
"c++",
"c",
""
] |
I are using EJB 3 on a fairly large J2EE project, by default with Netbeans sets the persistent provider for the entity beans to TopLink. There is the option to change the provider to one of the following or even add a new persistence library:
* Hibernate
* KODO
* OpenJPA
Which persistence provider do you prefer to use? What are the benefits of using the another provider?
While TopLink seems to be good, I can't find much good documentation on how to control caching etc. Any help would be much appreciated.
|
Theres only two JPA providers I'd consider using:
If you want to stick to standard JPA I'd use EclipseLink. Whereas Toplink Essentials is the reference implementation of JPA 1.0, EclipseLink basically inherited the TopLink Essentials code and will be the reference implementation of JPA 2.0 (and bundled with Glassfish V3 when it ships; expected around JavaOne in May 2009). TopLink Essentials was a somewhat crippled version of Oracle's commercial TopLink product but EclipseLink basically has all the features TopLink has.
The other choice is obviously Hibernate. Its widely used and mature but is not issue free from what I've seen. For example, last I looked Hibernate has issues with an entity having multiple one-to-many eager relationships. I don't know if Hibernate has an equivalent to EclipseLink's batch query hint, but its an incredibly useful feature to deal with this kind of problem.
Hibernate of course also supports standard JPA. The biggest advantage of Hibernate is that if you have question about how it works a google search is likely to find you an answer.
I honestly wouldn't consider anything other than the above two providers.
|
I would strongly recommend Hibernate for the following reasons:
* The most widely used and respected open source persistence layer in the Java world; huge active community and lots of use in high volume mission critical applications.
* You don't tie yourself to J2EE or a specific vendor at all should you wish to go a different route with the rest of your application, such as Spring, etc, as Hibernate will still play nice.
|
Which EJB 3 persisent provider should I use?
|
[
"",
"java",
"orm",
"jpa",
"jakarta-ee",
""
] |
I'm experiencing an issue on a test machine running Red Hat Linux (kernel version is 2.4.21-37.ELsmp) using Java 1.6 (1.6.0\_02 or 1.6.0\_04). The problem is, once a certain number of threads are created in a single thread group, the operating system is unwilling or unable to create any more.
This seems to be specific to Java creating threads, as the C thread-limit program was able to create about 1.5k threads. Additionally, this doesn't happen with a Java 1.4 JVM... it can create over 1.4k threads, though they are obviously being handled differently with respect to the OS.
In this case, the number of threads it's cutting off at is a mere 29 threads. This is testable with a simple Java program that just creates threads until it gets an error and then prints the number of threads it created. The error is a
```
java.lang.OutOfMemoryError: unable to create new native thread
```
This seems to be unaffected by things such as the number of threads in use by other processes or users or the total amount of memory the system is using at the time. JVM settings like Xms, Xmx, and Xss don't seem to change anything either (which is expected, considering the issue seems to be with native OS thread creation).
The output of "ulimit -a" is as follows:
```
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) 4
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
stack size (kbytes, -s) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 7168
virtual memory (kbytes, -v) unlimited
```
The user process limit does not seem to be the issue. Searching for information on what could be wrong has not turned up much, but [this post](http://blogs.oracle.com/gverma/2008/03/redhat_linux_kernels_and_proce_1.html) seems to indicate that at least some Red Hat kernels limit a process to 300 MB of memory allocated for stack, and at 10 MB per thread for stack, it seems like the issue could be there (though it seems strange and unlikely as well).
I've tried changing the stack size with "ulimit -s" to test this, but any value other than 10240 and the JVM does not start with an error of:
```
Error occurred during initialization of VM
Cannot create VM thread. Out of system resources.
```
I can generally get around Linux, but I really don't know much about system configuration, and I haven't been able to find anything specifically addressing this kind of situation. Any ideas on what system or JVM settings could be causing this would be appreciated.
**Edits**: Running the thread-limit program mentioned by [plinth](https://stackoverflow.com/questions/116640/low-single-process-thread-limit-in-red-hat-linux#116696), there was no failure until it tried to create the 1529th thread.
The issue also did not occur using a 1.4 JVM (does occur with 1.6.0\_02 and 1.6.0\_04 JVMs, can't test with a 1.5 JVM at the moment).
The code for the thread test I'm using is as follows:
```
public class ThreadTest {
public static void main(String[] pArgs) throws Exception {
try {
// keep spawning new threads forever
while (true) {
new TestThread().start();
}
}
// when out of memory error is reached, print out the number of
// successful threads spawned and exit
catch ( OutOfMemoryError e ) {
System.out.println(TestThread.CREATE_COUNT);
System.exit(-1);
}
}
static class TestThread extends Thread {
private static int CREATE_COUNT = 0;
public TestThread() {
CREATE_COUNT++;
}
// make the thread wait for eternity after being spawned
public void run() {
try {
sleep(Integer.MAX_VALUE);
}
// even if there is an interruption, dont do anything
catch (InterruptedException e) {
}
}
}
}
```
If you run this with a 1.4 JVM it will hang when it can't create any more threads and require a kill -9 (at least it did for me).
**More Edit:**
It turns out that the system that is having the problem is using the LinuxThreads threading model while another system that works fine is using the NPTL model.
|
Updating the kernel to a newer version (2.6.something) with NPTL threading fixed this.
|
Have you looked at [this resource](http://people.redhat.com/alikins/system_tuning.html#threads)?
It states that you should be able run thread-limit to find the maximum number of threads and can tweak it by compiling glibc.
|
Low Java single process thread limit in Red Hat Linux
|
[
"",
"java",
"linux",
"redhat",
""
] |
I would like to implement a data access object pattern in C++, but preferably without using multiple inheritance and/or boost (which my client does not like).
Do you have any suggestions?
|
OTL (otl.sourceforge.net) is an excellent C++ database library. It's a single include file so doesn't have all the complexity associated (rightly or wrongly!) with Boost.
In terms of the DAO itself, you have many options. The simplest that hides the database implementation is just to use C++ style interfaces and implement the data access layer in a particular implementation.
```
class MyDAO {
// Pure virtual functions to access the data itself
}
class MyDAOImpl : public MyDAO {
// Implementations to get the data from the database
}
```
|
A quick google search on data access object design patterns will return at least 10 results on the first page that will be useful. The most common of these is the abstract interface design as already shown by Jeff Foster. The only thing you may wish to add to this is a data access object factory to create your objects.
Most of the examples I could find with decent code are in Java, it's a common design pattern in Java, but they're still very relevant to C++ and you could use them quite easily.
[This is a good link](http://www.dofactory.com/patterns/PatternAbstract.aspx), it describes the abstract factory very well.
|
data access object pattern implementation
|
[
"",
"c++",
"design-patterns",
"oop",
""
] |
We want to maintain 3 webservices for the different steps of deployment, but how do we define in our application which service to use? Do we just maintain 3 web references and ifdef the uses of them somehow?
|
As others have mentioned you'll want to stash this information in a config file. In fact, I'd suggest using a different configuration file for each environment. This will address the inevitable problem of having multiple settings for each environment, e.g. you might have separate settings for the web service URL and web service port or have some extra settings to deal with https/security.
All that said, make sure you address these potential issues:
If the web service does anything particularly essential to the application you might want to marry the application to web services in each environment (i.e. have a version of your application in each environment). Certainly, any changes to the interface are easier when you do it this way.
Make sure it's obvious to someone which version of the web service you are speaking with.
|
Don't maintain the differences in code, but rather through a configuration file. That way they're all running the same code, just with different configuration values (ie. port to bind to, hostname to answer to, etc.)
|
How do you maintain separate webservices for dev/stage/production
|
[
"",
"c#",
".net",
"asp.net",
"web-services",
""
] |
During a long compilation with Visual Studio 2005 (version 8.0.50727.762), I sometimes get the following error in several files in some project:
```
fatal error C1033: cannot open program database 'v:\temp\apprtctest\win32\release\vc80.pdb'
```
(The file mentioned is either `vc80.pdb` or `vc80.idb` in the project's temp dir.)
The next build of the same project succeeds. There is no other Visual Studio open that might access the same files.
This is a serious problem because it makes nightly compilation impossible.
|
It is possible that an antivirus or a similar program is touching the pdb file on write - an antivirus is the most likely suspect in this scenario. I'm afraid that I can only give you some general pointers, based on my past experience in setting nightly builds in our shop. Some of these may sound trivial, but I'm including them for the sake of completion.
* First and foremost: make sure you start up with a clean slate. That is, force-delete the output directory of the build before you start your nightly.
* If you have an antivirus, antispyware or other such programs on your nightly machine, consider removing them. If that's not an option, add your obj folder to the exclusion list of the program.
* (optional) Consider using tools such as VCBuild or MSBuild as part of your nightly. I think it's better to use MSBuild if you're on a multicore machine. We use IncrediBuild for nightlies and MSBuild for releases, and never encountered the problem you describe.
If nothing else works, you can schedule a watchdog script a few hours after the build starts and check its status; if the build fails, the watchdog should restart it. This is an ugly hack, but it's better than nothing.
|
We've seen this a lot at my site too. [This explanation](http://graphics.ethz.ch/~peterkau/coding.php), from Peter Kaufmann, seems to be the most plausible based on our setup:
**When building a solution in Visual Studio 2005, you get errors like fatal error C1033: cannot open program database 'xxx\debug\vc80.pdb'. However, when running the build for a second time, it usually succeeds.**
Reason: It's possible that two projects in the solution are writing their outputs to the same directory (e.g. 'xxx\debug'). If the maximum number of parallel project builds setting in Tools - Options, Projects and Solutions - Bild and Run is set to a value greater than 1, this means that two compiler threads could be trying to access the same files simultaneously, resulting in a file sharing conflict.
Solution: Check your project's settings and make sure no two projects are using the same directory for output, target or any kind of intermediate files. Or set the maximum number of parallel project builds setting to 1 for a quick workaround. I experienced this very problem while using the VS project files that came with the CLAPACK library.
UPDATE: There is a chance that Tortoise SVN accesses 'vc80.pdb', even if the file is not under versioning control, which could also result in the error described above (thanks to Liana for reporting this). However, I cannot confirm this, as I couldn't reproduce the problem after making sure different output directories are used for all projects.
|
Compilation fails randomly: "cannot open program database"
|
[
"",
"c++",
"visual-studio",
"visual-studio-2005",
"compiler-errors",
"nightly-build",
""
] |
If I start a process via Java's [ProcessBuilder](http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html) class, I have full access to that process's standard in, standard out, and standard error streams as Java `InputStreams` and `OutputStreams`. However, I can't find a way to seamlessly connect those streams to `System.in`, `System.out`, and `System.err`.
It's possible to use `redirectErrorStream()` to get a single `InputStream` that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C `system()` call.
This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of [`isatty()`](http://www.opengroup.org/onlinepubs/009695399/functions/isatty.html) in the child process carries through the redirection.
|
You will need to copy the [Process](http://java.sun.com/javase/6/docs/api/java/lang/Process.html) out, err, and input streams to the System versions. The easiest way to do that is using the [IOUtils](http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html) class from the Commons IO package. The [copy method](http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html#copy%28java.io.InputStream,%20java.io.OutputStream%29) looks to be what you need. The copy method invocations will need to be in separate threads.
Here is the basic code:
```
// Assume you already have a processBuilder all configured and ready to go
final Process process = processBuilder.start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(process.getOutputStream(), System.out);
} } ).start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(process.getErrorStream(), System.err);
} } ).start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(System.in, process.getInputStream());
} } ).start();
```
|
A variation on John's answer that compiles and doesn't require you to use Commons IO:
```
private static void pipeOutput(Process process) {
pipe(process.getErrorStream(), System.err);
pipe(process.getInputStream(), System.out);
}
private static void pipe(final InputStream src, final PrintStream dest) {
new Thread(new Runnable() {
public void run() {
try {
byte[] buffer = new byte[1024];
for (int n = 0; n != -1; n = src.read(buffer)) {
dest.write(buffer, 0, n);
}
} catch (IOException e) { // just exit
}
}
}).start();
}
```
|
Starting a process with inherited stdin/stdout/stderr in Java 6
|
[
"",
"java",
"io",
"process",
"pipe",
""
] |
I'm fairly new to the world of versioning but would like to introduce Subversion into our small development team as we're finding that more and more we are working on the same projects/files. We primarily code in `PHP` on a `LAMP` environment (Red Hat Enterprise).
What I'm looking for are some starting points to get me up and running such as installation/configuration guides for Red Hat. I use Dreamweaver `CS3` (I see that Subversion functions will be introduced in `CS4`) so would be willing to look at other PHP IDEs with Subversion integration, do you have any preferences? I'm open to suggestions.
|
It depends on what version of RHEL you are running. Setting up Subversion in general is very easy you just have to install the binaries and run svnserve or adapt the Apache configuration.
1. Get it: <http://subversion.tigris.org/getting.html>
2. Install it
3. `svnadmin create --fs-type=fsfs`
After that you have a repository which you can serve via apache or svnserve. I can recommend Apache because it scales better, is easier to maintain and allows you to access the repository via DAV.
Example configurations are here: <http://svnbook.red-bean.com/en/1.0/ch06s04.html>
|
On a RHEL system, the easiest way to install subversion is by using yum:
yum install subversion
|
Setting up Subversion on a Red Hat system
|
[
"",
"php",
"svn",
"redhat",
""
] |
Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version?
|
I don´t know if it is correct usage, but I think you can force a reload of the css file using a query string:
```
<link href="mystyle.css?SOME_UNIQUE_TEXT" type="text/css" rel="stylesheet" />
```
I remember I used this method years ago to force a reload of a web-cam image, but time has probably moved on...
|
Without using js, you can just keep the css filename in a session variable. When a request is made to the Main Page, you simply compose the css link tag with the session variable name.
Being the ccs file name different, you force the broswer to download it without needing to check what was previusly loaded in the browser.
|
Force browser to use new CSS
|
[
"",
"c#",
"asp.net",
"css",
"master-pages",
""
] |
I administrate several Oracle Apps environment, and currently check profile options in lots of environments by loading up forms in each environment, and manually checking each variable, which requires a lot of time.
Is there a snippet of code which will list profile options and at what level and who they are applied to?
|
You'll want to query `APPLSYS.FND_PROFILE_OPTIONS` and `FND_PROFILE_OPTION_VALUES`.
For a comprehensive script that you can pick up the SQL from, look here:
<http://tipsnscripts.com/?p=16>
|
I hope this will help you get more granular information when you try to track down changes by users.
```
SELECT FP.LEVEL_ID "Level ID",
FPO.PROFILE_OPTION_NAME "PROFILE NAME",
FP.LEVEL_VALUE "LEVEL VALUE",
DECODE (FP.LEVEL_ID,
10001,
'SITE',
10002,
'APPLICATION',
10003,
'RESPONSIBILITY',
10004,
'USER')
"LEVEL",
DECODE (FP.LEVEL_ID,
10001,
'SITE',
10002,
APPLICATION_SHORT_NAME,
10003,
RESPONSIBILITY_NAME,
10004,
FL.USER_NAME)
LVALUE,
FPO.USER_PROFILE_OPTION_NAME "PROFILE DESCRIPTION",
FP.PROFILE_OPTION_VALUE "PROFILE VALUE",
FU.USER_NAME "USER NAME",
FU.LAST_UPDATE_DATE
FROM FND_PROFILE_OPTIONS_VL FPO,
FND_PROFILE_OPTION_VALUES FP,
FND_RESPONSIBILITY_TL,
FND_APPLICATION FA,
FND_USER FL,
FND_USER FU
WHERE FPO.APPLICATION_ID = FP.APPLICATION_ID
AND FPO.PROFILE_OPTION_ID = FP.PROFILE_OPTION_ID
AND FP.LEVEL_VALUE = FL.USER_ID(+)
AND FP.LEVEL_VALUE = RESPONSIBILITY_ID(+)
AND FP.LEVEL_VALUE = FA.APPLICATION_ID(+)
AND FU.USER_ID = FP.LAST_UPDATED_BY
AND FP.PROFILE_OPTION_VALUE IS NOT NULL
AND (UPPER (FP.Profile_Option_Value) LIKE UPPER ('%&1%')
OR UPPER (FP.Profile_Option_Value) LIKE UPPER ('%&2%'))
```
|
How do I list Oracle Apps profile options in PL/SQL?
|
[
"",
"c#",
"oracle",
"configuration",
""
] |
We are writing a complex rich desktop application and need to offer flexibility in reporting formats so we thought we would just expose our object model to a scripting langauge. Time was when that meant VBA (which is still an option), but the managed code derivative VSTA (I think) seems to have withered on the vine.
What is now the best choice for an embedded scripting language on Windows .NET?
|
I've used [CSScript](http://www.csscript.net/) with amazing results. It really cut down on having to do bindings and other low level stuff in my scriptable apps.
|
Personally, I'd use C# as the scripting language. The .NET framework (and Mono, thanks Matthew Scharley) actually includes the compilers for each of the .NET languages in the framework itself.
Basically, there's 2 parts to the implementation of this system.
1. Allow the user to compile the code
This is relatively easy, and can be done in only a few lines of code (though you might want to add an error dialog, which would probably be a couple dozen more lines of code, depending on how usable you want it to be).
2. Create and use classes contained within the compiled assembly
This is a little more difficult than the previous step (requires a tiny bit of reflection). Basically, you should just treat the compiled assembly as a "plug-in" for the program. There are quite a few tutorials on various ways you can create a plug-in system in C# (Google is your friend).
I've implemented a "quick" application to demonstrate how you can implement this system (includes 2 working scripts!). This is the complete code for the application, just create a new one and paste the code in the "program.cs" file.
At this point I must apologize for the large chunk of code I'm about to paste (I didn't intend for it to be so large, but got a little carried away with my commenting)
```
using System;
using System.Windows.Forms;
using System.Reflection;
using System.CodeDom.Compiler;
namespace ScriptingInterface
{
public interface IScriptType1
{
string RunScript(int value);
}
}
namespace ScriptingExample
{
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
// Lets compile some code (I'm lazy, so I'll just hardcode it all, i'm sure you can work out how to read from a file/text box instead
Assembly compiledScript = CompileCode(
"namespace SimpleScripts" +
"{" +
" public class MyScriptMul5 : ScriptingInterface.IScriptType1" +
" {" +
" public string RunScript(int value)" +
" {" +
" return this.ToString() + \" just ran! Result: \" + (value*5).ToString();" +
" }" +
" }" +
" public class MyScriptNegate : ScriptingInterface.IScriptType1" +
" {" +
" public string RunScript(int value)" +
" {" +
" return this.ToString() + \" just ran! Result: \" + (-value).ToString();" +
" }" +
" }" +
"}");
if (compiledScript != null)
{
RunScript(compiledScript);
}
}
static Assembly CompileCode(string code)
{
// Create a code provider
// This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones)
// come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that
// you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?)
Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();
// Setup our options
CompilerParameters options = new CompilerParameters();
options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net)
options.GenerateInMemory = true; // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile
// And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best!
// Add any references you want the users to be able to access, be warned that giving them access to some classes can allow
// harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows
// thus they can only do the things you want them to.
// (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it)
// Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another
// project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to
// the "script"
options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
// Compile our code
CompilerResults result;
result = csProvider.CompileAssemblyFromSource(options, code);
if (result.Errors.HasErrors)
{
// TODO: report back to the user that the script has errored
return null;
}
if (result.Errors.HasWarnings)
{
// TODO: tell the user about the warnings, might want to prompt them if they want to continue
// runnning the "script"
}
return result.CompiledAssembly;
}
static void RunScript(Assembly script)
{
// Now that we have a compiled script, lets run them
foreach (Type type in script.GetExportedTypes())
{
foreach (Type iface in type.GetInterfaces())
{
if (iface == typeof(ScriptingInterface.IScriptType1))
{
// yay, we found a script interface, lets create it and run it!
// Get the constructor for the current type
// you can also specify what creation parameter types you want to pass to it,
// so you could possibly pass in data it might need, or a class that it can use to query the host application
ConstructorInfo constructor = type.GetConstructor(System.Type.EmptyTypes);
if (constructor != null && constructor.IsPublic)
{
// lets be friendly and only do things legitimitely by only using valid constructors
// we specified that we wanted a constructor that doesn't take parameters, so don't pass parameters
ScriptingInterface.IScriptType1 scriptObject = constructor.Invoke(null) as ScriptingInterface.IScriptType1;
if (scriptObject != null)
{
//Lets run our script and display its results
MessageBox.Show(scriptObject.RunScript(50));
}
else
{
// hmmm, for some reason it didn't create the object
// this shouldn't happen, as we have been doing checks all along, but we should
// inform the user something bad has happened, and possibly request them to send
// you the script so you can debug this problem
}
}
else
{
// and even more friendly and explain that there was no valid constructor
// found and thats why this script object wasn't run
}
}
}
}
}
}
}
```
|
What is the best scripting language to embed in a C# desktop application?
|
[
"",
"c#",
"scripting",
""
] |
How do I read text from the (windows) clipboard with python?
|
You can use the module called [win32clipboard](http://timgolden.me.uk/pywin32-docs/win32clipboard.html), which is part of [pywin32](https://github.com/mhammond/pywin32).
Here is an example that first sets the clipboard data then gets it:
```
import win32clipboard
# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
win32clipboard.CloseClipboard()
# get clipboard data
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print data
```
An important reminder from the documentation:
> When the window has finished examining or changing the clipboard,
> close the clipboard by calling CloseClipboard. This enables other
> windows to access the clipboard. Do not place an object on the
> clipboard after calling CloseClipboard.
|
you can easily get this done through the built-in module [Tkinter](https://docs.python.org/2/library/tkinter.html) which is basically a GUI library. This code creates a blank widget to get the clipboard content from OS.
```
from tkinter import Tk # Python 3
#from Tkinter import Tk # for Python 2.x
Tk().clipboard_get()
```
|
How do I read text from the Windows clipboard in Python?
|
[
"",
"python",
"windows",
"interop",
"clipboard",
""
] |
What is the best python framework to create distributed applications? For example to build a P2P app.
|
You could checkout [pyprocessing](http://pyprocessing.berlios.de/) which will be included in the standard library as of 2.6. It allows you to run tasks on multiple processes using an API similar to threading.
|
I think you mean "Networked Apps"? Distributed means an app that can split its workload among multiple worker clients over the network.
You probably want.
[Twisted](http://twistedmatrix.com/trac/)
|
Distributed python
|
[
"",
"python",
"distributed",
""
] |
Is there a difference in performance (in oracle) between
```
Select * from Table1 T1
Inner Join Table2 T2 On T1.ID = T2.ID
```
And
```
Select * from Table1 T1, Table2 T2
Where T1.ID = T2.ID
```
?
|
No! The same execution plan, look at these two tables:
```
CREATE TABLE table1 (
id INT,
name VARCHAR(20)
);
CREATE TABLE table2 (
id INT,
name VARCHAR(20)
);
```
The execution plan for the query using the inner join:
```
-- with inner join
EXPLAIN PLAN FOR
SELECT * FROM table1 t1
INNER JOIN table2 t2 ON t1.id = t2.id;
SELECT *
FROM TABLE (DBMS_XPLAN.DISPLAY);
-- 0 select statement
-- 1 hash join (access("T1"."ID"="T2"."ID"))
-- 2 table access full table1
-- 3 table access full table2
```
And the execution plan for the query using a WHERE clause.
```
-- with where clause
EXPLAIN PLAN FOR
SELECT * FROM table1 t1, table2 t2
WHERE t1.id = t2.id;
SELECT *
FROM TABLE (DBMS_XPLAN.DISPLAY);
-- 0 select statement
-- 1 hash join (access("T1"."ID"="T2"."ID"))
-- 2 table access full table1
-- 3 table access full table2
```
|
If the query optimizer is doing its job right, there should be no difference between those queries. They are just two ways to specify the same desired result.
|
Inner join vs Where
|
[
"",
"sql",
"performance",
"oracle",
""
] |
I want to use javascript to insert some elements into the current page.
Such as this is the original document:
<p>Hello world!</p>
Now I want to insert an element in to the text so that it will become:
<p>Hello <span id=span1>new</span> world!</p>
I need the span tag because I want to handle it later.Show or hide.
But now problem comes out, if the original page has already defined a strange CSS style on all <span> tags, the "new" I just inserted will not appear to be the same as "Hello" and "world". How can I avoid this? I want the "new" be exactly the same as the "Hello" and "world".
|
Simply override any span styles. Set layout properties back to browser defaults and set formating to inherit from the parent:
```
span#yourSpan {
/* defaults */
position: static;
display: inline;
margin: 0;
padding: 0;
background: transparent;
border: none;
/* inherit from parent node */
font: inherit;
color: inherit;
text-decoration: inherit;
line-height: inherit;
letter-spacing: inherit;
text-transform: inherit;
white-space: inherit;
word-spacing: inherit;
}
```
This should be sufficient, although you may need to add !important if you are not using an id:
```
<span class="hello-node">hello</span>
span.hello-node {
/* defaults */
position: static !important;
display: inline !important;
...
}
```
|
Well, I don't know how married you are to using a <span> tag, but why not do this?
```
<p style="display: inline">Hello <p id="myIdValue" style="display: inline">new</p> World</p>
```
That way the inserted html retains the same styling as the outer, and you can still have a handle to it, etc. Granted, you will have to add the inline CSS style, but it would work.
|
How to insert a text-like element into document using javascript and CSS?
|
[
"",
"javascript",
"css",
""
] |
This may seem like a daft question, but i was wondering about how to use MVC frameworks on hosted servers.
I am playing about (albeit slowly) at home with the RoR on Ubuntu and understand that if i want to do a live site then i need hosting with Rails and Ruby.
However, what happens about the PHP frameworks. For example i have seen in the past all about the CakePHP but lately i have just come across the [Symfony project](http://www.symfony-project.org/tutorial/1_1/my-first-project) and was thinking that if i had a server stack set up i could develop at home, how would i go about deploying anything live.
How do i use php command line on live servers, and how would i go about installing the framework on another server.
This is all hyperthetical at the moment as i am just thinking about it, but it is a question that i have thought of in the past.
Regards
|
Not every framework needs things installed or configured via the command line or even the php.ini file. I believe CodeIgnitor is like this - you can just put the path to the base CI directory in the path and off you go. I'm sure there's documentation about how to use symfony on a hosting solution. In fact, [this document](http://www.symfony-project.org/book/1_1/03-Running-Symfony) explains how to use symfony on shared hosting.
|
Most MVC frameworks\* (Kohana, Zend Framework, for example) can be installed anywhere on the server. The front controller in the document root then specifies where it is, and loads it from there. So basically, you put the framework directory somewhere, and then have your front controller load it. ZF and Kohana in particular both have quickstart tutorials for getting this set up.
As for using the PHP command line... it's just the "php" command. Run "php -v" to see what version you have.
(\*MVC frameworks using the front controller pattern means that your web server's document tree really only contains one thing: the front controller file. For example, if you installed your framework at **/home/username/frameworks/Kohana\_2.2**, and your Apache docroot is **/home/username/document\_root**, then you'd have **index.php** in there, and all it would contain is something like this:
```
<?php
require_once("/home/username/frameworks/Kohana_2.2/system/core/Bootstrap.php");
```
(There'd be other configuration stuff, but there you go.))
|
MVC frameworks on hosted servers
|
[
"",
"php",
"model-view-controller",
"symfony1",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.