Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm currently working on a tile-based game in Java2D, and I was thinking of adding some cheap eye candy.
For example, implementing a simple particle system (maybe something like [this](http://www.jhlabs.com/java/particles.html)) for explosions and/or smoke.
Do you have any suggestion for relatively easy to program effects that wouldn't require drawing a lot (or at all) of new art?
Tutorials and code samples for said effects would also be most welcome!
-Ido.
PS - if absolutely necessary I could switch to something like LWJGL/JOGL or even Slick - but I rather stay with Java2D. | Implementing blurs and other image filtering effects are fairly simple to perform.
For example, to perform a blur on a [`BufferedImage`](http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html), one can use the [`ConvolveOp`](http://java.sun.com/javase/6/docs/api/java/awt/image/ConvolveOp.html) with a convolution matrix specified in a [`Kernel`](http://java.sun.com/javase/6/docs/api/java/awt/image/Kernel.html):
```
BufferedImageOp op = new ConvolveOp(new Kernel(3, 3,
new float[] {
1/9f, 1/9f, 1/9f,
1/9f, 1/9f, 1/9f,
1/9f, 1/9f, 1/9f
}
));
BufferedImage resultImg = op.filter(originalImg, resultImage);
```
Not quite sure when a blur effect is needed, but it may come in handy some time. But I'd say it's a low-hanging fruit for its ease of implementation.
Here's some information on [convolution matrices](http://docs.gimp.org/2.6/en/plug-in-convmatrix.html). It can be used to implement effects such as sharpen, emboss, edge enhance as well. | Performing a pixelation effect is a low-hanging fruit operation on a [`BufferedImage`](http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html).
This can be performed in two steps:
1. Determine the color of the one block of the pixelation.
2. Fill in the block of pixelation on the image.
Step 1: Determine the color:
```
public static Color determineColor(BufferedImage img, int x, int y, int w, int h) {
int cx = x + (int)(w / 2);
int cy = y + (int)(h / 2);
return new Color(img.getRGB(cx, cy), true);
}
```
In the `determineColor` method, the pixel color from the center of the `BufferedImage` is determined, and is passed back to the caller.
Step 2: Fill in the pixelation block with determined color:
```
BufferedImage sourceImg = ...; // Source Image.
BufferedImage destimg = ...; // Destination Image.
Graphics g = destImg.createGraphics();
int blockSize = 8;
for (int i = 0; i < sourceImg.getWidth(); i += blockSize) {
for (int j = 0; j < sourceImg.getHeight(); j += blockSize) {
Color c = determineColor(sourceImg, i, j, blockSize, blockSize);
g.setColor(c);
g.fillRect(i, j, blockSize, blockSize);
}
}
g.dispose();
```
Although there is quite a bit of code, this effect is intellectually a low-hanging fruit -- there isn't much complex that is going on. It is basically finding the center color of a block, and filling a box with that color. This is a fairly naive implementation, so there may be better ways to do it.
The following is a before and after comparison of performing the above pixelation effect:
[](https://i.stack.imgur.com/2NGvC.png) [](https://i.stack.imgur.com/bxVN2.png) | Low-hanging graphics programming fruits? | [
"",
"java",
"graphics",
"java-2d",
""
] |
I'm computing the ordinate y of a point on a line at a given abscissa x. The line is defined by its two end points coordinates (x0,y0)(x1,y1). End points coordinates are floats and the computation must be done in float precision for use in GPU.
The maths, and thus the naive implementation, are trivial.
Let t = (x - x0)/(x1 - x0), then y = (1 - t) \* y0 + t \* y1 = y0 + t \* (y1 - y0).
The problem is when x1 - x0 is small. The result will introduce cancellation error. When combined with the one of x - x0, in the division I expect a significant error in t.
The question is if there exist another way to determine y with a better accuracy ?
i.e. should I compute (x - x0)\*(y1 - y0) first, and divide by (x1 - x0) after ?
The difference y1 - y0 will always be big. | To a large degree, your underlying problem is fundamental. When (x1-x0) is small, it means there are only a few bits in the mantissa of x1 and x0 which differ. And by extension, there are only a limted number of floats between x0 and x1. E.g. if only the lower 4 bits of the mantissa differ, there are at most 14 values between them.
In your best algorithm, the `t` term represents these lower bits. And to continue or example, if x0 and x1 differ by 4 bits, then t can take on only 16 values either. The calculation of these possible values is fairly robust. Whether you're calculating 3E0/14E0 or 3E-12/14E-12, the result is going to be close to the mathematical value of 3/14.
Your formula has the additional advantage of having y0 <= y <= y1, since 0 <= t <= 1
(I'm assuming that you know enough about float representations, and therefore "(x1-x0) is small" really means "small, relative to the values of x1 and x0 themselves". A difference of 1E-1 is small when x0=1E3 but large if x0=1E-6 ) | You may have a look at Qt's "QLine" (if I remember it right) sources; they have implemented an intersection determination algorithm taken from one the "Graphics Gems" books (the reference must be in the code comments, the book was on EDonkey a couple of years ago), which, in turn, has some guarantees on applicability for a given screen resolution when calculations are performed with given bit-width (they use fixed-point arithmetics if I'm not wrong). | Most accurate line intersection ordinate computation with floats? | [
"",
"c++",
"c",
"optimization",
"math",
"numerical",
""
] |
I want to pass 2 arrays to a function in Java and have them sorted in the calling function. How do i use a function to accomplish that?
I could have the function return an object with 2 arrays, but is there a non object-oriented solution to this?
EDIT : I this particular situation I cant use the inbuilt Array.sort function in Java. Lets say the 2 arrays are height and weight. They are of the same length, and the same index correspond to the same person's height and weight on both arrays. I want to sort the height array in ascending order, while sorting the weight array corresponding to the height array. So using the sort function would mess up the relations between the 2 arrays. | When you pass an array to a function, it's not copied. Just the reference of it is copied and passed to the function which will point to the same location. You just need to sort the arrays in-place.
EDIT: To solve the actual sorting problem, you can use any sorting algorithm to sort `height` array. The only difference is that when you're swapping two elements in `height` sorting process, you should also swap the corresponding elements in `weight` array. | ```
public void sort2(Object o1[], Object o2[])
{
Arrays.sort(o1);
Arrays.sort(o2);
}
```
Slightly more sophisticated:
```
public <T> void sort2(T o1[], T o2[], Comparator<? super T> c)
{
Arrays.sort(o1, c);
Arrays.sort(o2, c);
}
```
EDIT: Generally, when you use parallel arrays, that means you are not using objects properly. To follow your example, you should have a Comparable Person class with height and weight properties. Of course, like Mehrdad said, you can manually implement a parallel array sorting algorithm, but it's really not ideal. | Sorting arrays in Java | [
"",
"java",
"arrays",
"sorting",
""
] |
I've got a data source that provides a list of objects and their properties (a CSV file, but that doesn't matter). Each time my program runs, it needs to pull a new copy of the list of objects, compare it to the list of objects (and their properties) stored in the database, and update the database as needed.
Dealing with new objects is easy - the data source gives each object a sequential ID number, check the top ID number in the new information against the database, and you're done. I'm looking for suggestions for the other cases - when some of an object's properties have changed, or when an object has been deleted.
A naive solution would be to pull all the objects from the database and get the complement of the intersection of the two sets (old and new) and then examine those results, but that seems like it wouldn't be very efficient if the sets get large. Any ideas? | The standard approach for huge piles of data amounts to this.
We'll assume that list\_1 is the "master" (without duplicates) and list\_2 is the "updates" which may have duplicates.
```
iter_1 = iter( sorted(list_1) ) # Essentially SELECT...ORDER BY
iter_2 = iter( sorted(list_2) )
eof_1 = False
eof_2 = False
try:
item_1 = iter_1.next()
except StopIteration:
eof_1= True
try:
item_2 = iter_2.next()
except StopIteration:
eof_2= True
while not eof_1 and not eof_2:
if item_1 == item_2:
# do your update to create the new master list.
try:
item_2 = iter_2.next()
except StopIteration:
eof_2= True
elif item_1 < item_2:
try:
item_1 = iter_1.next()
except StopIteration:
eof_1= True
elif item_2 < item_1:
# Do your insert to create the new master list.
try:
item_2 = iter_2.next()
except StopIteration:
eof_2= True
assert eof_1 or eof_2
if eof_1:
# item_2 and the rest of list_2 are inserts.
elif eof_2:
pass
else:
raise Error("What!?!?")
```
Yes, it involves a potential sort. If list\_1 is kept in sorted order when you write it back to the file system, that saves considerable time. If list\_2 can be accumulated in a structure that keeps it sorted, then that saves considerable time.
Sorry about the wordiness, but you need to know which iterator raised the `StopIteration`, so you can't (trivially) wrap the whole while loop in a big-old-try block. | Is there no way to maintain a "last time modified" field? That's what it sounds like you're really looking for: an incremental backup, based on last time backup was run, compared to last time an object was changed/deleted(/added). | Algorithm for updating a list from a list | [
"",
"python",
"google-app-engine",
"set",
""
] |
How can I handle `StackOverflowError` in Java? | I'm not sure what you mean with "handle".
You can certainly catch that error:
```
public class Example {
public static void endless() {
endless();
}
public static void main(String args[]) {
try {
endless();
} catch(StackOverflowError t) {
// more general: catch(Error t)
// anything: catch(Throwable t)
System.out.println("Caught "+t);
t.printStackTrace();
}
System.out.println("After the error...");
}
}
```
but that is most likely a bad idea, unless you know exactly what you are doing. | You probably have some infinite recursion going on.
I.e. a method that calls itself over and over
```
public void sillyMethod()
{
sillyMethod();
}
```
One to handle this is to fix your code so that the recursion terminates instead of continuing forever. | How can I handle StackOverflowError in Java? | [
"",
"java",
"exception",
"jakarta-ee",
"stack-overflow",
""
] |
Is there a best practice for where configuration files should be stored in a Java project. The file type is a Java properties file in this case, but I do use other file types in other projects.
Would the recommendation vary from stand alone application(.jar) to web app(.war)? | You'll find that many open-source projects follow the [directory structure used by Maven](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html). In this setup your application source code is kept in src/main/java, application resources, including properties files, in src/main/resources, and other config files in src/main/config. Files related to unit tests use a similar directory structure; src/test/java and src/test/resources.
Personally I tend to use this layout because of its widespread use. I also keep an "etc" directory beneath the project root to house files that aren't directly related to the application. For example, I keep configuration files for PMD and Checkstyle in etc. | In general a common practice is to have a `resources` directory for configuration files which is copied into the build artifact by the build process. Maven uses this in its [default project structure](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html). Within the `resources` directory, you might also have a `META-INF` directory and/or a `WEB-INF` directory in an application packaged as a war. | What is the best practice for the location of Java application configuration files? | [
"",
"java",
"configuration",
"properties",
"project-structure",
""
] |
I have an `Array<string>`. I have to take all elements from `i` to `j`. How can I make this using an extension method? | Try the following.
```
public static IEnumerable<T> GetRange<T>(this IEnumerable<T> enumerable, int start, int end) {
return enumerable.Skip(start).Take(end-start);
}
```
Then you can do
```
Array<string> arr = GetSomeArray();
var res = arr.GetRange(i,j);
``` | ```
var result = myStringArray.Skip(i).Take(j-i);
``` | Take a sequence of elements from an array from i to j using C# and extension method | [
"",
"c#",
".net",
"linq",
"arrays",
"extension-methods",
""
] |
Just wondering if there is a way to clone a NamingEnumeration in Java? My program searches an LDAP server for people and it can take a few seconds to complete. To get the number of results I am using the following:
```
NamingEnumeration results = null;
NamingEnumeration results2 = null;
results = ctx.search("", "("+searchAt+"=" +searchVal +")", controls);
results2 = result;
int i = 0;
while(results2.hasMore())
{
results2.next();
i++;
}
```
But since results2 is just a reference to result when i go through displaying the results results.hasMore() will always return false.
is there a way to clone 'results' without having to re-preform the search and assign it to 'results2'?
Thanks, -Pete | Use Collections.list(results) to put the results in a list and then use List.size to get the count, and iterate over the list. | There is no guarantee that if you redo the search you'll get the same answer back.
The simple solution is to copy the results into a `List` (`ArrayList` to be specific). | Clone Java NamingEnumeration? | [
"",
"java",
"variables",
"clone",
""
] |
When a page is iframed or included as part of a frameset, it can use Javascript to check so. (i think usually by
```
if (self != top) top.location.href = self.location.href;
```
). Can the page always "jump back out" like that when Javascript is enabled? Is there a way to not let it jump back out? (suppose my page is iframing that page).
(in another scenario, i think if we use window.open() to open the page in a new windoe, then the page almost always cannot refuse... unless they check the referrer and actually refuse to serve the page even if it is a new, standalone window). | As far as I know, there is only one way - a Microsoft proprietary extension to HTML that allows an iframe start tag to specify that the page should be loaded with reduced security privileges - which usually blocks JS from running in it.
Happily other browsers do not support this feature. | Perhaps you can check out the window.location.href property. If it matches, then let your page load. Else, stop! | can a page always refused to be iframed or be part of a frameset if javascript is enabled? | [
"",
"javascript",
"iframe",
"frameset",
""
] |
In my shop we currently develop what I would consider small to medium sized projects. We have been investigating the Enterprise Library and how it may be able to help us in development. I have particularly been looking at the Logging block and comparing it with Log4Net. It seems to me that the Enterprise Library blocks would be an extremely over-engineered solution for something like simple application logging.
That being said. Are you using the Enterprise Library and on what size projects? What are your thoughts on the Enterprise Library as a whole?
Thanks | It's my opinion that the enterprise library is over engineered for most things. No, we don't use it, but most of our projects are short term high volume web sites of a promotional nature. | +1 for over-engineered. We use log4net instead of the logging or exception handling blocks. We use the native .NET System.Security namespace instead of entlib encryption blocks. Some of the tracing tools are nice, but we don't have anything in production that uses them. | Are you using the Microsoft Enterprise Library? | [
"",
"c#",
".net",
"asp.net",
"vb.net",
"enterprise-library",
""
] |
I want to split a polynomial like:
```
2x^7+x^2+3x-9
```
Into each one of its terms (2x^7, x^2, 3x, 9)
I've thought about using String.split(), but how can I make it take more than one paramether? | [`split`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)) takes a [regular expression](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#sum), so you can do:
```
String[] terms = myString.split("[-+]");
```
and it will split when it encounters either + or -.
**Edit:** Note that as Michael Borgwardt said, when you split like this you cannot tell which operator (+ or -) was the delimiter. If that's important for your use, you should use a [`StringTokenizer`](http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html) as he suggested. (If you're trying to write a math expression parser, neither of these will be of much help, though.) | This sounds like a perfect application for the [StringTokenizer](http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html) class:
```
StringTokenizer st = new StringTokenizer("2x^7+x^2+3x-9", "+-", true);
```
Will return the tokens ("2x^7", "+", "x^2", "+", "3x", "-", "9") - you do need the signs to have the full information about the polynomial. If not, leave off the laster constructor parameter. | How can I split a given String using either + or -? | [
"",
"java",
"string",
""
] |
I was reading here and there about llvm that can be used to ease the pain of cross platform compilations in c++ , i was trying to read the documents but i didn't understand how can i
use it in real life development problems can someone please explain me in simple words how can i use it ? | The key concept of LLVM is a low-level "intermediate" representation (IR) of your program.
This IR is at about the level of assembler code, but it contains more information to facilitate optimization.
The power of LLVM comes from its ability to defer compilation of this intermediate representation to a specific target machine until just before the code needs to run. A just-in-time (JIT) compilation approach can be used for an application to produce the code it needs just before it needs it.
In many cases, you have more information at the time the program is running that you do back at head office, so the program can be much optimized.
To get started, you could compile a C++ program to a single intermediate representation, then compile it to multiple platforms from that IR.
You can also try the Kaleidoscope demo, which walks you through creating a new language without having to actually write a compiler, just write the IR.
In performance-critical applications, the application can essentially write its own code that it needs to run, just before it needs to run it. | Why don't you go to the [LLVM](http://llvm.org/) website and check out all the documentation there. They explain in great detail what LLVM is and how to use it. For example they have a [Getting Started](http://llvm.org/docs/GettingStarted.html) page. | LLVM what is it and how can i use it to cross platform compilations | [
"",
"c++",
"cross-platform",
"llvm",
""
] |
Long version...
A co-worker asserted today after seeing my use of `while (1)` in a Perl script that `for (;;)` is faster. I argued that they should be the same hoping that the interpreter would optimize out any differences. I set up a script that would run 1,000,000,000 for loop iterations and the same number of while loops and record the time between. I could find no appreciable difference. My co-worker said that a professor had told him that the `while (1)` was doing a comparison `1 == 1` and the `for (;;)` was not. We repeated the same test with the 100x the number of iterations with C++ and the difference was negligible. It was however a graphic example of how much faster compiled code can be vs. a scripting language.
Short version...
Is there any reason to prefer a `while (1)` over a `for (;;)` if you need an infinite loop to break out of?
**Note:** If it's not clear from the question. This was purely a fun academic discussion between a couple of friends. I am aware this is not a super important concept that all programmers should agonize over. Thanks for all the great answers I (and I'm sure others) have learned a few things from this discussion.
**Update:** The aforementioned co-worker weighed in with a response below.
Quoted here in case it gets buried.
> It came from an AMD assembly programmer. He stated that C programmers
> (the poeple) don't realize that their code has inefficiencies. He said
> today though, gcc compilers are very good, and put people like him out
> of business. He said for example, and told me about the `while 1` vs
> `for(;;)`. I use it now out of habit but gcc and especially interpreters
> will do the same operation (a processor jump) for both these days,
> since they are optimized. | In perl, they result in the same opcodes:
```
$ perl -MO=Concise -e 'for(;;) { print "foo\n" }'
a <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 2 -e:1) v ->3
9 <2> leaveloop vK/2 ->a
3 <{> enterloop(next->8 last->9 redo->4) v ->4
- <@> lineseq vK ->9
4 <;> nextstate(main 1 -e:1) v ->5
7 <@> print vK ->8
5 <0> pushmark s ->6
6 <$> const[PV "foo\n"] s ->7
8 <0> unstack v ->4
-e syntax OK
$ perl -MO=Concise -e 'while(1) { print "foo\n" }'
a <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 2 -e:1) v ->3
9 <2> leaveloop vK/2 ->a
3 <{> enterloop(next->8 last->9 redo->4) v ->4
- <@> lineseq vK ->9
4 <;> nextstate(main 1 -e:1) v ->5
7 <@> print vK ->8
5 <0> pushmark s ->6
6 <$> const[PV "foo\n"] s ->7
8 <0> unstack v ->4
-e syntax OK
```
Likewise in GCC:
```
#include <stdio.h>
void t_while() {
while(1)
printf("foo\n");
}
void t_for() {
for(;;)
printf("foo\n");
}
.file "test.c"
.section .rodata
.LC0:
.string "foo"
.text
.globl t_while
.type t_while, @function
t_while:
.LFB2:
pushq %rbp
.LCFI0:
movq %rsp, %rbp
.LCFI1:
.L2:
movl $.LC0, %edi
call puts
jmp .L2
.LFE2:
.size t_while, .-t_while
.globl t_for
.type t_for, @function
t_for:
.LFB3:
pushq %rbp
.LCFI2:
movq %rsp, %rbp
.LCFI3:
.L5:
movl $.LC0, %edi
call puts
jmp .L5
.LFE3:
.size t_for, .-t_for
.section .eh_frame,"a",@progbits
.Lframe1:
.long .LECIE1-.LSCIE1
.LSCIE1:
.long 0x0
.byte 0x1
.string "zR"
.uleb128 0x1
.sleb128 -8
.byte 0x10
.uleb128 0x1
.byte 0x3
.byte 0xc
.uleb128 0x7
.uleb128 0x8
.byte 0x90
.uleb128 0x1
.align 8
.LECIE1:
.LSFDE1:
.long .LEFDE1-.LASFDE1
.LASFDE1:
.long .LASFDE1-.Lframe1
.long .LFB2
.long .LFE2-.LFB2
.uleb128 0x0
.byte 0x4
.long .LCFI0-.LFB2
.byte 0xe
.uleb128 0x10
.byte 0x86
.uleb128 0x2
.byte 0x4
.long .LCFI1-.LCFI0
.byte 0xd
.uleb128 0x6
.align 8
.LEFDE1:
.LSFDE3:
.long .LEFDE3-.LASFDE3
.LASFDE3:
.long .LASFDE3-.Lframe1
.long .LFB3
.long .LFE3-.LFB3
.uleb128 0x0
.byte 0x4
.long .LCFI2-.LFB3
.byte 0xe
.uleb128 0x10
.byte 0x86
.uleb128 0x2
.byte 0x4
.long .LCFI3-.LCFI2
.byte 0xd
.uleb128 0x6
.align 8
.LEFDE3:
.ident "GCC: (Ubuntu 4.3.3-5ubuntu4) 4.3.3"
.section .note.GNU-stack,"",@progbits
```
So I guess the answer is, they're the same in many compilers. Of course, for some other compilers this may not necessarily be the case, but chances are the code inside of the loop is going to be a few thousand times more expensive than the loop itself anyway, so who cares? | There's not much reason to prefer one over the other. I do think that `while(1)` and particularly `while(true)` are more readable than `for(;;)`, but that's just my preference. | while (1) Vs. for (;;) Is there a speed difference? | [
"",
"c++",
"perl",
"optimization",
"performance",
""
] |
I'm looking for a visual studio plugin with the following functionality:
On building the project or executing the tool, the plugin looks for all **`*.js`** and **`*.css`** files in your project and compresses/minimizes them into **`*.min.js`** and **`*.min.css`** files.
Executing the tool on project build would enable you to keep the references to \*.min.js in your pages while changes to the \*.js files would be instantly written to the \*.min.js files.
Is there such thing available?
If not what's the closest thing to automize tasks like that?
Extra question:
How about auto combining files? | Check out these two links:
[An MS build script for YUI compressor](http://www.coderjournal.com/2008/05/how-to-create-a-yui-compressor-msbuild-task/)
[YUI compressor for VS](http://blog.lavablast.com/post/2009/05/YUI-Compressor-for-Visual-Studio.aspx) | You probably be better off doing it with [NAnt](http://nant.sourceforge.net/) and coding it to run the [compression](http://codeclimber.net.nz/archive/2007/08/22/How-to-use-YUI-JS-Compressor-inside-a-NAnt-build.aspx). Automated process is always better than a manual one. | Is there a javascript/css compressor plugin for visual studio? | [
"",
"javascript",
"visual-studio",
"compression",
"obfuscation",
"minimize",
""
] |
I am running php 5.3, and have bumped into a problem I've not encountered before. I have an upload form (yes, enctype is set to multipart/form-data), that posts stuff to a php page.
The php installation has uploads enabled, and upload\_max\_filesize is set to .5GB.
Uploading pictures (I've tried up to 50 at a time) works fine. Uploading .zip files, however, does not. Uploading a .zip will render most global input arrays ($\_POST,$\_GET,$\_FILES, and $\_REQUEST) completely empty. A network sniff shows POST data beeing sent, as well as the zip beeing uploaded.
Apache logs show nothing out of the ordinary, and no errors are encountered. The arrays are just empty. Has anyone encountered this? | I don't have a clue what the exact problem could be, but I'd suggest trying out a few modifications on the files:
* can you upload a .jpg file that you've renamed to .zip?
* can you upload a .zip file that you've renamed to .jpg?
* try uploading a smaller .zip file, just to make sure it does actually get transfered.
* try uploading a .jpg with a bigger filesize
Hopefully this will give a pointer about where the problem lies.
For what it is worth, I doubt that the problem is in PHP. | I had recently encountered this same issue in php7.0.
When I tried to upload 0.7G zip- $\_POST,$\_REQUEST and $\_FILES were all empty but increasing **upload\_max\_filesize** and **post\_max\_size** values to correct limit in php.ini and **restarting php7.0-fpm** fixed it.
Hope this helps someone!!! | $_FILES array empty in php when uploading .zip, while .jpg works fine | [
"",
"php",
"upload",
"zip",
""
] |
Parent Div Click Function gets called when Child Div Click is clicked.
How to overcome this issue
I am using ASP.Net with C#
```
<div onclick="callme();">
<a href='#' onclick="Callme2();">Hi</a>
</div>
```
When I click on anchor tag the div elements onclick also gets executed. How to overcome this ? | That, of course, depends on the browser.
In newer browsers, call
```
event.stopPropagation();
```
on the event object.
In older IE, set
```
window.event.cancelBubble = true
```
Read abot the details at [Quirks mode](http://www.quirksmode.org/js/events_order.html "Quirksmode"). | This is due to event bubbling.
```
<div onclick="callme();">
<a href='#' onclick="return Callme2();">Hi</a>
</div>
```
make sure `Callme2()` returns `false` to stop the event from bubbling up. | Parent Div Click Function gets called when Child Div Click is clicked | [
"",
"javascript",
"html",
""
] |
I am using a hidden field 'Isjsenabled' to detect whether Client's Javascript is enabled or disabled. If Javascript is enabled, Javascript function will be fired and it will set hidden field's value to 1.
I want to check the hidden value from server side Page\_load. But the problem is Javascript gets fired after Page load.
Do you have any suggestion ?
Html Part
```
<script type="text/javascript">
$(function() {
$("#<%= Isjsenabled.ClientID %>").val(1);
});
</script>
<input id="Isjsenabled" runat="server" value ="0" type="hidden" />
```
Code Behind Part
```
protected void Page_Load(object sender, EventArgs e) {
HtmlInputHidden hdn = this.FindControl("Isjsenabled") as HtmlInputHidden;
if (hdn != null)
if (hdn.Value != null && hdn.Value == "0")
Helper.SetCookie("IJE", "0");
else
Helper.SetCookie("IJE", "1");
}
``` | Without thinking too hard about the direction you're trying to go in, there is a little used tag that is supported by all browsers called NOSCRIPT.
```
<noscript>
<img src="http://myserver/notify_no_script.aspx" style="display:none">
</noscript>
```
As you can see, the idea is to make the browser request an image but only if javascript is disabled. This page could set a session variable stating that the current client has no script capability that would be available to all code in the current session.
Or, you could follow your current methodology:
```
<noscript>
<input type="hidden" name="noscript" value="1">
</noscript>
<script><!--
document.writeline('<input type="hidden" name="noscript" value="0">');
//--></script>
```
Hope this helps,
-Oisin | you should draw your script or noscript header as a page onto itself that then redirects (either through a meta tag or through a script location.href) to the next place you want to go based on if javascript is turned on. It'll take 2 steps, but it'll get you the result you're looking for. You can pass the information you need back to yourself in the query of the redirect. | How can I execute Javascript function before Page load? | [
"",
".net",
"asp.net",
"javascript",
"browser",
""
] |
I'm using the YUI Rich Text editor on my site. I'm loading it using the load javascript from Google. When I try to create a link (or any other action that creates an "settings" box, the title bar is missing, see [picture here](http://img150.imageshack.us/i/missing.png/). You can see how it supposed to look over [here](http://developer.yahoo.com/yui/examples/editor/code_editor.html) at Yahoos site for YUI.
I'm using this code in the `<head>`-tag:
```
<!--Include YUI Loader: -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/yui/2.7.0/build/yuiloader/yuiloader-min.js"></script>
<!--Use YUI Loader to bring in your other dependencies: -->
<script type="text/javascript">
// Instantiate and configure YUI Loader:
(function() {
var loader = new YAHOO.util.YUILoader({
base: "http://ajax.googleapis.com/ajax/libs/yui/2.7.0/build/",
require: ["editor"],
loadOptional: true,
combine: false,
filter: "MIN",
allowRollup: true,
onSuccess: function() {
var Editor = new YAHOO.widget.Editor('content', {
height: '300px',
width: '802px',
dompath: true, //Turns on the bar at the bottom
animate: true //Animates the opening, closing and moving of Editor windows
});
Editor.render();
}
});
// Load the files using the insert() method.
loader.insert();
})();
</script>
```
And in my webpage:
```
<div class="sIFR-ignore yui-skin-sam">
<textarea name="content" id="content" cols="50" rows="10">
</textarea>
</div>
``` | I got some help from David Glass, one of the developers of YUI RTE. The error I had make was actually an CSS thing, some where in my CSS-files it was a line that read "h3 {visibility: hidden;}" which made this error. Any how, thanks for your help! | Try forcing your own title for the editor:
```
var Editor = new YAHOO.widget.Editor('content', {
height: '300px',
width: '802px',
dompath: true, //Turns on the bar at the bottom
animate: true //Animates the opening, closing and moving of Editor windows
});
Editor._defaultToolbar.titlebar="<b>Use my title</b>";
Editor.render();
``` | title bar is missing in YUI | [
"",
"javascript",
"yui",
"yui-editor",
""
] |
I have a socket that is receiving HTTP requests.
So I have a raw http request in byte[] form from my socket.
I have to study this request - BUT
Instead of reinventing the wheel - can I *'cast'* this byte array into a System.Net.HttpWebRequest or something similar?
----- UPDATE ---------
So anyway I couldn't find the answer. By digging a little further though I think it could be done by calling functions in:
**HttpApi.dll** *I think that the HttpWebRequest uses this dll (winxpsp2)*
the interesting structure is the [HTTP\_REQUEST](http://msdn.microsoft.com/en-us/library/aa364545(VS.85).aspx)
```
C++
typedef struct _HTTP_REQUEST {
ULONG Flags;
HTTP_CONNECTION_ID ConnectionId;
HTTP_REQUEST_ID RequestId;
HTTP_URL_CONTEXT UrlContext;
HTTP_VERSION Version;
HTTP_VERB Verb;
USHORT UnknownVerbLength;
USHORT RawUrlLength;
PCSTR pUnknownVerb;
PCSTR pRawUrl;
HTTP_COOKED_URL CookedUrl;
HTTP_TRANSPORT_ADDRESS Address;
HTTP_REQUEST_HEADERS Headers;
ULONGLONG BytesReceived;
USHORT EntityChunkCount;
PHTTP_DATA_CHUNK pEntityChunks;
HTTP_RAW_CONNECTION_ID RawConnectionId;
PHTTP_SSL_INFO pSslInfo;
}HTTP_REQUEST_V1, *PHTTP_REQUEST_V1;
```
I have only just started C# so delving into ??COM?? programming is over my head.
AND looking through the ducumentation, I cant see an 'entry' (by which I mean a simple send bytes-> receieve HTTP\_REQUEST).
Anyhoo! if anyone wants to point me in the direction of some nice WINDOWS KERNEL MODE HTTP SERVERS INCLUDING SSL then feel free it would be a great read and something to consider for the future. | just replace Socket by using **HttpListener**. It parses the HTTP request for you, easily.
Here is an example:
```
HttpListener listener = new HttpListener();
// prefix URL at which the listener will listen
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Listening...");
while (true)
{
// the GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// process the request
// if you want to process request from multiple clients
// concurrently, use ThreadPool to run code following from here
Console.WriteLine("Client IP " + request.UserHostAddress);
// in request.InputStream you have the data client sent
// use context.Response to respond to client
}
``` | Have you considered using the [HttpListener](http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx) class instead of a socket to receive your incoming HTTP requests? It will yield [HttpListenerRequest](http://msdn.microsoft.com/en-us/library/system.net.httplistenerrequest.aspx) objects instead of raw data. I've found these classes useful for simulating a web server. | How Create a .NET HttpWebRequest class from a Socket's received byte[]'s | [
"",
"c#",
".net",
"sockets",
"httpwebrequest",
""
] |
I'm trying to set up the GWT framework. I'm following the quick start at: <http://code.google.com/eclipse/docs/getting_started.html>. OS is Ubuntu 8.04. I create a new application and start/debug the application, and after a few seconds JVM crashes. Any ideas? Generated log is:
```
#
# An unexpected error has been detected by Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x0625665c, pid=19531, tid=2421361552
#
# Java VM: Java HotSpot(TM) Server VM (10.0-b23 mixed mode linux-x86)
# Problematic frame:
# V [libjvm.so+0x25665c]
#
# If you would like to submit a bug report, please visit:
# http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
--------------- T H R E A D ---------------
Current thread (0x080ff000): JavaThread "CompilerThread1" daemon [_thread_in_native, id=19544, stack(0x904b0000,0x90531000)]
siginfo:si_signo=SIGSEGV: si_errno=0, si_code=1 (SEGV_MAPERR), si_addr=0x00000000
Registers:
EAX=0x00000000, EBX=0x8a13e9ac, ECX=0x08929020, EDX=0xffffffff
ESP=0x9052ed80, EBP=0x9052edd8, ESI=0x8a13e978, EDI=0x00000000
EIP=0x0625665c, CR2=0x00000000, EFLAGS=0x00210202
Top of Stack: (sp=0x9052ed80)
0x9052ed80: 08929020 00000000 00000331 00000331
0x9052ed90: 9052eea0 8a7b2e64 00000000 9052eee0
0x9052eda0: 066a0bf0 ffffffff 0000000e 080966a8
0x9052edb0: 00000001 08929020 00000002 8a7b2e60
0x9052edc0: 00000011 9052f22c 01000312 000006fa
0x9052edd0: 9052eea0 9052f1c0 9052ef08 06255bb5
0x9052ede0: 9052f1c0 00000001 9052fb10 9052fb10
0x9052edf0: 0000010d 0000010d 9052ee38 9052f22c
Instructions: (pc=0x0625665c)
0x0625664c: 5d dc 8b 03 53 8d 5e 34 ff 50 40 89 c7 8b 56 34
0x0625665c: 8b 00 21 c2 89 56 34 8b 47 04 8b 4b 04 21 c1 8b
Stack: [0x904b0000,0x90531000], sp=0x9052ed80, free space=507k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V [libjvm.so+0x25665c]
V [libjvm.so+0x255bb5]
V [libjvm.so+0x2a2acd]
V [libjvm.so+0x29f950]
V [libjvm.so+0x2471e9]
V [libjvm.so+0x2a6e3a]
V [libjvm.so+0x2a6846]
V [libjvm.so+0x5b61ed]
V [libjvm.so+0x4fe289]
C [libpthread.so.0+0x54fb]
Current CompileTask:
C2:636 org.eclipse.jdt.internal.compiler.lookup.ParameterizedMethodBinding.<init>(Lorg/eclipse/jdt/internal/compiler/lookup/ParameterizedTypeBinding;Lorg/eclipse/jdt/internal/compiler/lookup/MethodBinding;)V (596 bytes)
--------------- P R O C E S S ---------------
Java Threads: ( => current thread )
0x08770400 JavaThread "btpool0-1" [_thread_blocked, id=19557, stack(0x8d206000,0x8d257000)]
0x8e707400 JavaThread "Timer-1" [_thread_blocked, id=19552, stack(0x8ea79000,0x8eaca000)]
0x08539400 JavaThread "btpool0-0 - Acceptor0 SelectChannelConnector@0.0.0.0:8080" [_thread_in_native, id=19551, stack(0x8f0ab000,0x8f0fc000)]
0x082a3400 JavaThread "Timer-0" daemon [_thread_blocked, id=19548, stack(0x8f05a000,0x8f0ab000)]
0x08100800 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=19545, stack(0x9045f000,0x904b0000)]
=>0x080ff000 JavaThread "CompilerThread1" daemon [_thread_in_native, id=19544, stack(0x904b0000,0x90531000)]
0x080fc800 JavaThread "CompilerThread0" daemon [_thread_in_native, id=19543, stack(0x90531000,0x905b2000)]
0x080fb800 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=19542, stack(0x905b2000,0x90603000)]
0x080dfc00 JavaThread "Finalizer" daemon [_thread_blocked, id=19541, stack(0x90649000,0x9069a000)]
0x080de800 JavaThread "Reference Handler" daemon [_thread_blocked, id=19540, stack(0x9069a000,0x906eb000)]
0x0805b800 JavaThread "main" [_thread_in_vm, id=19532, stack(0xb7da7000,0xb7df8000)]
Other Threads:
0x080db800 VMThread [stack: 0x906eb000,0x9076c000] [id=19539]
0x08102000 WatcherThread [stack: 0x903de000,0x9045f000] [id=19546]
VM state:not at safepoint (normal execution)
VM Mutex/Monitor currently owned by a thread: ([mutex/lock_event])
[0x08059558/0x08059580] VMOperationQueue_lock - owner thread: 0x0805b800
[0x08059998/0x080599b0] Heap_lock - owner thread: 0x0805b800
Heap
PSYoungGen total 38848K, used 21504K [0xb1370000, 0xb4c50000, 0xb4c50000)
eden space 19456K, 100% used [0xb1370000,0xb2670000,0xb2670000)
from space 19392K, 10% used [0xb2670000,0xb2870000,0xb3960000)
to space 19392K, 0% used [0xb3960000,0xb3960000,0xb4c50000)
PSOldGen total 96576K, used 69074K [0x94c50000, 0x9aaa0000, 0xb1370000)
object space 96576K, 71% used [0x94c50000,0x98fc4878,0x9aaa0000)
PSPermGen total 26624K, used 15975K [0x90c50000, 0x92650000, 0x94c50000)
object space 26624K, 60% used [0x90c50000,0x91be9e88,0x92650000)
Dynamic libraries:
06000000-0665d000 r-xp 00000000 08:03 1005378 /usr/lib/jvm/java-6-sun-1.6.0.07/jre/lib/i386/server/libjvm.so
0665d000-066a1000 rwxp 0065c000 08:03 1005378 /usr/lib/jvm/java-6-sun-1.6.0.07/jre/lib/i386/server/libjvm.so
066a1000-06ac3000 rwxp 066a1000 00:00 0
08048000-08052000 r-xp 00000000 08:03 1005321 /usr/lib/jvm/java-6-sun-1.6.0.07/jre/bin/java
08052000-08053000 rwxp 00009000 08:03 1005321 /usr/lib/jvm/java-6-sun-1.6.0.07/jre/bin/java
08053000-09d32000 rwxp 08053000 00:00 0 [heap]
89300000-893ec000 rwxp 89300000 00:00 0
893ec000-89400000 ---p 893ec000 00:00 0
89500000-89600000 rwxp 89500000 00:00 0
89700000-897ff000 rwxp 89700000 00:00 0
897ff000-89800000 ---p 897ff000 00:00 0
89900000-899f0000 rwxp 89900000 00:00 0
899f0000-89a00000 ---p 899f0000 00:00 0
89a00000-89af9000 rwxp 89a00000 00:00 0
89af9000-89b00000 ---p 89af9000 00:00 0
89b00000-89bee000 rwxp 89b00000 00:00 0
89bee000-89c00000 ---p 89bee000 00:00 0
8a000000-8a0f9000 rwxp 8a000000 00:00 0
8a0f9000-8a100000 ---p 8a0f9000 00:00 0
8a100000-8a1ed000 rwxp 8a100000 00:00 0
8a1ed000-8a200000 ---p 8a1ed000 00:00 0
8a200000-8a2f9000 rwxp 8a200000 00:00 0
8a2f9000-8a300000 ---p 8a2f9000 00:00 0
8a300000-8a3f9000 rwxp 8a300000 00:00 0
8a3f9000-8a400000 ---p 8a3f9000 00:00 0
8a400000-8a4f9000 rwxp 8a400000 00:00 0
8a4f9000-8a500000 ---p 8a4f9000 00:00 0
8a500000-8a5f9000 rwxp 8a500000 00:00 0
8a5f9000-8a600000 ---p 8a5f9000 00:00 0
8a600000-8a6f9000 rwxp 8a600000 00:00 0
8a6f9000-8a700000 ---p 8a6f9000 00:00 0
8a700000-8a7f9000 rwxp 8a700000 00:00 0
8a7f9000-8a800000 ---p 8a7f9000 00:00 0
8a900000-8a9e1000 rwxp 8a900000 00:00 0
8a9e1000-8aa00000 ---p 8a9e1000 00:00 0
8aabb000-8ab00000 r-xp 00000000 08:03 954857 /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Bold.ttf
8ab00000-8ac00000 rwxp 8ab00000 00:00 0
8ac3c000-8ac87000 r-xp 00000000 08:03 954858 /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf
8ac87000-8ac88000 ---p 8ac87000 00:00 0
8ac88000-8b488000 rwxp 8ac88000 00:00 0
8b488000-8b4bc000 r-xp 00000000 08:03 52538 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libmork.so
8b4bc000-8b4be000 rwxp 00034000 08:03 52538 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libmork.so
8b4be000-8b4c3000 r-xp 00000000 08:03 52577 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libxpcom_compat_c.so
8b4c3000-8b4c4000 rwxp 00005000 08:03 52577 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libxpcom_compat_c.so
8b4c4000-8b4c5000 ---p 8b4c4000 00:00 0
8b4c5000-8bcc5000 rwxp 8b4c5000 00:00 0
8bcc5000-8bcc6000 ---p 8bcc5000 00:00 0
8bcc6000-8c4c6000 rwxp 8bcc6000 00:00 0
8c4c6000-8c4c7000 ---p 8c4c6000 00:00 0
8c4c7000-8ccc7000 rwxp 8c4c7000 00:00 0
8ccc7000-8ccca000 r-xp 00000000 08:03 620228 /lib/libgpg-error.so.0.3.0
8ccca000-8cccb000 rwxp 00002000 08:03 620228 /lib/libgpg-error.so.0.3.0
8cccb000-8cd16000 r-xp 00000000 08:03 620226 /lib/libgcrypt.so.11.2.3
8cd16000-8cd18000 rwxp 0004a000 08:03 620226 /lib/libgcrypt.so.11.2.3
8cd18000-8cd27000 r-xp 00000000 08:03 818392 /usr/lib/libtasn1.so.3.0.12
8cd27000-8cd28000 rwxp 0000e000 08:03 818392 /usr/lib/libtasn1.so.3.0.12
8cd28000-8cde7000 r-xp 00000000 08:03 817682 /usr/lib/libasound.so.2.0.0
8cde7000-8cdeb000 rwxp 000be000 08:03 817682 /usr/lib/libasound.so.2.0.0
8cdeb000-8cdef000 r-xp 00000000 08:03 817594 /usr/lib/libORBitCosNaming-2.so.0.1.0
8cdef000-8cdf0000 rwxp 00003000 08:03 817594 /usr/lib/libORBitCosNaming-2.so.0.1.0
8cdf0000-8cdf2000 r-xp 00000000 08:03 637494 /lib/tls/i686/cmov/libutil-2.7.so
8cdf2000-8cdf4000 rwxp 00001000 08:03 637494 /lib/tls/i686/cmov/libutil-2.7.so
8cdf4000-8ce02000 r-xp 00000000 08:03 816254 /usr/lib/libavahi-client.so.3.2.4
8ce02000-8ce03000 rwxp 0000e000 08:03 816254 /usr/lib/libavahi-client.so.3.2.4
8ce03000-8ce0d000 r-xp 00000000 08:03 817895 /usr/lib/libavahi-common.so.3.5.0
8ce0d000-8ce0e000 rwxp 00009000 08:03 817895 /usr/lib/libavahi-common.so.3.5.0
8ce0e000-8ce7f000 r-xp 00000000 08:03 816405 /usr/lib/libgnutls.so.13.9.1
8ce7f000-8ce84000 rwxp 00071000 08:03 816405 /usr/lib/libgnutls.so.13.9.1
8ce84000-8ceb8000 r-xp 00000000 08:03 820345 /usr/lib/libdbus-1.so.3.4.0
8ceb8000-8ceba000 rwxp 00033000 08:03 820345 /usr/lib/libdbus-1.so.3.4.0
8ceba000-8ced4000 r-xp 00000000 08:03 817785 /usr/lib/libdbus-glib-1.so.2.1.0
8ced4000-8ced5000 rwxp 0001a000 08:03 817785 /usr/lib/libdbus-glib-1.so.2.1.0
8ced5000-8cfef000 r-xp 00000000 08:03 818875 /usr/lib/libxml2.so.2.6.31
8cfef000-8cff4000 rwxp 00119000 08:03 818875 /usr/lib/libxml2.so.2.6.31
8cff4000-8cff5000 rwxp 8cff4000 00:00 0
8cff5000-8cffc000 r-xp 00000000 08:03 620275 /lib/libpopt.so.0.0.0
8cffc000-8cffd000 rwxp 00006000 08:03 620275 /lib/libpopt.so.0.0.0
8cffd000-8d01f000 r-xp 00000000 08:03 817692 /usr/lib/libaudiofile.so.0.0.2
8d01f000-8d022000 rwxp 00021000 08:03 817692 /usr/lib/libaudiofile.so.0.0.2
8d022000-8d034000 r-xp 00000000 08:03 817715 /usr/lib/libbonobo-activation.so.4.0.0
8d034000-8d036000 rwxp 00012000 08:03 817715 /usr/lib/libbonobo-activation.so.4.0.0
8d036000-8d087000 r-xp 00000000 08:03 817713 /usr/lib/libbonobo-2.so.0.0.0
8d087000-8d091000 rwxp 00050000 08:03 817713 /usr/lib/libbonobo-2.so.0.0.0
8d091000-8d0e7000 r-xp 00000000 08:03 817975 /usr/lib/libgnomevfs-2.so.0.2200.0
8d0e7000-8d0ea000 rwxp 00056000 08:03 817975 /usr/lib/libgnomevfs-2.so.0.2200.0
8d0ea000-8d0fe000 r-xp 00000000 08:03 817945 /usr/lib/libgnome-2.so.0.2200.0
8d0fe000-8d0ff000 rwxp 00013000 08:03 817945 /usr/lib/libgnome-2.so.0.2200.0
8d0ff000-8d1ba000 r-xp 00000000 08:03 52567 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libuconv.so
8d1ba000-8d1c0000 rwxp 000bb000 08:03 52567 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libuconv.so
8d1c0000-8d1ca000 rwxp 8d1c0000 00:00 0
8d1cf000-8d1e4000 r-xp 00000000 08:03 52560 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libprofile.so
8d1e4000-8d1e5000 rwxp 00015000 08:03 52560 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libprofile.so
8d1e5000-8d1ff000 r-xp 00000000 08:03 52741 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libxpcom_compat.so
8d1ff000-8d200000 rwxp 0001a000 08:03 52741 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libxpcom_compat.so
8d200000-8d205000 r-xp 00000000 08:03 52565 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libtxmgr.so
8d205000-8d206000 rwxp 00004000 08:03 52565 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libtxmgr.so
8d206000-8d209000 ---p 8d206000 00:00 0
8d209000-8d257000 rwxp 8d209000 00:00 0
8d257000-8d25e000 r-xp 00000000 08:03 52555 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libp3p.so
8d25e000-8d25f000 rwxp 00006000 08:03 52555 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libp3p.so
8d25f000-8d269000 r-xp 00000000 08:03 52514 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libcookie.so
8d269000-8d26a000 rwxp 00009000 08:03 52514 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libcookie.so
8d26a000-8d26f000 r-xp 00000000 08:03 52743 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/plugins/libnullplugin.so
8d26f000-8d270000 rwxp 00004000 08:03 52743 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/plugins/libnullplugin.so
8d270000-8d299000 r-xp 00000000 08:03 52522 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libgkplugin.so
8d299000-8d29b000 rwxp 00028000 08:03 52522 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libgkplugin.so
8d29b000-8d2b3000 r-xp 00000000 08:03 52554 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/liboji.so
8d2b3000-8d2b4000 rwxp 00017000 08:03 52554 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/liboji.so
8d2b4000-8d2cd000 r-xp 00000000 08:03 52725 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libjsj.so
8d2cd000-8d2cf000 rwxp 00018000 08:03 52725 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libjsj.so
8d2cf000-8d2d6000 r-xp 00000000 08:03 52556 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libpipboot.so
8d2d6000-8d2d7000 rwxp 00007000 08:03 52556 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libpipboot.so
8d2d7000-8d34a000 r-xp 00000000 08:03 52508 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libappcomps.so
8d34a000-8d34d000 rwxp 00073000 08:03 52508 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libappcomps.so
8d34d000-8d399000 r-xp 00000000 08:03 52515 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libdocshell.so
8d399000-8d39c000 rwxp 0004c000 08:03 52515 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libdocshell.so
8d39c000-8d3cd000 r-xp 00000000 08:03 52519 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libgfx_gtk.so
8d3cd000-8d3cf000 rwxp 00031000 08:03 52519 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libgfx_gtk.so
8d3d2000-8d3d4000 r-xp 00000000 08:03 817804 /usr/lib/libavahi-glib.so.1.0.1
8d3d4000-8d3d5000 rwxp 00001000 08:03 817804 /usr/lib/libavahi-glib.so.1.0.1
8d3d5000-8d3de000 r-xp 00000000 08:03 817834 /usr/lib/libesd.so.0.2.38
8d3de000-8d3df000 rwxp 00008000 08:03 817834 /usr/lib/libesd.so.0.2.38
8d3e2000-8d3ed000 r-xp 00000000 08:03 52531 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libjar50.so
8d3ed000-8d3ee000 rwxp 0000a000 08:03 52531 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libjar50.so
8d3ee000-8d447000 r-xp 00000000 08:03 52523 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libhtmlpars.so
8d447000-8d44c000 rwxp 00058000 08:03 52523 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libhtmlpars.so
8d44c000-8d463000 r-xp 00000000 08:03 52512 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libchrome.so
8d463000-8d464000 rwxp 00017000 08:03 52512 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libchrome.so
8d464000-8d475000 r-xp 00000000 08:03 52573 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libwebbrwsr.so
8d475000-8d476000 rwxp 00011000 08:03 52573 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libwebbrwsr.so
8d476000-8d4be000 r-xp 00000000 08:03 817590 /usr/lib/libORBit-2.so.0.1.0
8d4be000-8d4c8000 rwxp 00047000 08:03 817590 /usr/lib/libORBit-2.so.0.1.0
8d4c8000-8d4f5000 r-xp 00000000 08:03 817879 /usr/lib/libgconf-2.so.4.1.5
8d4f5000-8d4f8000 rwxp 0002d000 08:03 817879 /usr/lib/libgconf-2.so.4.1.5
8d4f8000-8d520000 r-xp 00000000 08:03 52575 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libwidget_gtk2.so
8d520000-8d523000 rwxp 00028000 08:03 52575 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libwidget_gtk2.so
8d523000-8d538000 r-xp 00000000 08:03 817574 /usr/lib/libICE.so.6.3.0
8d538000-8d539000 rwxp 00014000 08:03 817574 /usr/lib/libICE.so.6.3.0
8d539000-8d53b000 rwxp 8d539000 00:00 0
8d53b000-8d588000 r-xp 00000000 08:03 817651 /usr/lib/libXt.so.6.0.0
8d588000-8d58c000 rwxp 0004c000 08:03 817651 /usr/lib/libXt.so.6.0.0
8d58d000-8d59a000 r-xp 00000000 08:03 52382 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/libgwt-ll.so
8d59a000-8d59b000 rwxp 0000d000 08:03 52382 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/libgwt-ll.so
8d59b000-8d5c4000 r-xp 00000000 08:03 52561 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/librdf.so
8d5c4000-8d5c6000 rwxp 00028000 08:03 52561 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/librdf.so
8d5c6000-8d5f3000 r-xp 00000000 08:03 52525 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libimglib2.so
8d5f3000-8d5f4000 rwxp 0002d000 08:03 52525 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libimglib2.so
8d5f4000-8d62c000 r-xp 00000000 08:03 52524 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libi18n.so
8d62c000-8d62f000 rwxp 00037000 08:03 52524 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libi18n.so
8d62f000-8d630000 ---p 8d62f000 00:00 0
8d630000-8de30000 rwxp 8d630000 00:00 0
8de30000-8de74000 r-xp 00000000 08:03 52578 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libxpconnect.so
8de74000-8de77000 rwxp 00043000 08:03 52578 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libxpconnect.so
8de77000-8de78000 rwxp 8de77000 00:00 0
8de78000-8e2f4000 r-xp 00000000 08:03 52521 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libgklayout.so
8e2f4000-8e32f000 rwxp 0047c000 08:03 52521 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libgklayout.so
8e32f000-8e335000 rwxp 8e32f000 00:00 0
8e335000-8e3fa000 r-xp 00000000 08:03 52548 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libnecko.so
8e3fa000-8e400000 rwxp 000c4000 08:03 52548 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libnecko.so
8e400000-8e500000 rwxp 8e400000 00:00 0
8e501000-8e514000 r-xp 00000000 08:03 52532 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libjsd.so
8e514000-8e515000 rwxp 00013000 08:03 52532 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libjsd.so
8e515000-8e52a000 r-xp 00000000 08:03 52511 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libcaps.so
8e52a000-8e52b000 rwxp 00014000 08:03 52511 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libcaps.so
8e52b000-8e53c000 r-xp 00000000 08:03 817631 /usr/lib/libXft.so.2.1.2
8e53c000-8e53d000 rwxp 00010000 08:03 817631 /usr/lib/libXft.so.2.1.2
8e53d000-8e547000 r-xp 00000000 08:03 816836 /usr/lib/libpangox-1.0.so.0.2002.3
8e547000-8e548000 rwxp 00009000 08:03 816836 /usr/lib/libpangox-1.0.so.0.2002.3
8e548000-8e54e000 r-xp 00000000 08:03 816837 /usr/lib/libpangoxft-1.0.so.0.2002.3
8e54e000-8e54f000 rwxp 00005000 08:03 816837 /usr/lib/libpangoxft-1.0.so.0.2002.3
8e551000-8e558000 r-xp 00000000 08:03 817598 /usr/lib/libSM.so.6.0.0
8e558000-8e559000 rwxp 00006000 08:03 817598 /usr/lib/libSM.so.6.0.0
8e559000-8e55d000 r-xp 00000000 08:03 52724 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libgtkxtbin.so
8e55d000-8e55e000 rwxp 00003000 08:03 52724 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libgtkxtbin.so
8e55e000-8e56a000 r-xp 00000000 08:03 52728 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libmozz.so
8e56a000-8e56c000 rwxp 0000b000 08:03 52728 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libmozz.so
8e56c000-8e57d000 r-xp 00000000 08:03 52559 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libpref.so
8e57d000-8e57e000 rwxp 00011000 08:03 52559 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libpref.so
8e57e000-8e5fc000 r-xp 00000000 08:03 52727 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libmozjs.so
8e5fc000-8e600000 rwxp 0007e000 08:03 52727 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libmozjs.so
8e600000-8e6df000 rwxp 8e600000 00:00 0
8e6df000-8e700000 ---p 8e6df000 00:00 0
8e700000-8e800000 rwxp 8e700000 00:00 0
8e800000-8e8f9000 rwxp 8e800000 00:00 0
8e8f9000-8e900000 ---p 8e8f9000 00:00 0
8e900000-8e9f8000 rwxp 8e900000 00:00 0
8e9f8000-8ea00000 ---p 8e9f8000 00:00 0
8ea00000-8ea05000 r-xp 00000000 08:03 52563 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libsystem-pref.so
8ea05000-8ea06000 rwxp 00005000 08:03 52563 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libsystem-pref.so
8ea06000-8ea15000 r-xp 00000000 08:03 52566 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libtypeaheadfind.so
8ea15000-8ea16000 rwxp 0000e000 08:03 52566 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libtypeaheadfind.so
8ea16000-8ea41000 r-xp 00000000 08:03 52517 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libembedcomponents.so
8ea41000-8ea43000 rwxp 0002a000 08:03 52517 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/components/libembedcomponents.so
8ea43000-8ea64000 r-xp 00000000 08:03 52722 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libgkgfx.so
8ea64000-8ea65000 rwxp 00021000 08:03 52722 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/mozilla-1.7.12/libgkgfx.so
8ea65000-8ea78000 r-xp 00000000 08:03 52385 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/libswt-mozilla-gtk-3235.so
8ea78000-8ea79000 rwxp 00012000 08:03 52385 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/libswt-mozilla-gtk-3235.so
8ea79000-8ea7c000 ---p 8ea79000 00:00 0
8ea7c000-8eaca000 rwxp 8ea7c000 00:00 0
8eaca000-8eb00000 r-xs 005cc000 08:03 25815 /home/toni/development/general_ws/HelloWorld/war/WEB-INF/lib/appengine-api-1.0-sdk-1.2.1.jar
8eb00000-8ebff000 rwxp 8eb00000 00:00 0
8ebff000-8ec00000 ---p 8ebff000 00:00 0
8ec00000-8ed00000 rwxp 8ec00000 00:00 0
8ed00000-8edfa000 rwxp 8ed00000 00:00 0
8edfa000-8ee00000 ---p 8edfa000 00:00 0
8ee01000-8ee03000 r-xp 00000000 08:03 820803 /usr/lib/gconv/UTF-16.so
8ee03000-8ee05000 rwxp 00001000 08:03 820803 /usr/lib/gconv/UTF-16.so
8ee05000-8ee0a000 r-xp 00000000 08:03 52387 /home/toni/development/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.linux_1.6.4.v200904062334/gwt-linux-1.6.4/libswt-mozilla17-profile-gtk-3235.so
8ee0a000-8ee0b0
``` | I had the same exception, I just installed the latest VM release and now the compilation complete successfully :) | [This document](http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/felog.html) on diagnosing JVM dumps may be of use. However, before you get to that:
1. can you recreate this reliably, or is it intermittent ? A one-off ?
2. are you using the latest VM release | GWT application/eclipse plugin crashes JVM | [
"",
"java",
"eclipse",
"gwt",
""
] |
I would like to use the jquery slideUp effect when the user navigates away from the page just to make the page look cool as it closes.
I assume that I should use the onunload event but how can I delay the page closing long enough for the effect to run to completion.
One of the options that came to mind is effectively hijacking the page closing function, storing it in some variable and then executing it once I had run my effect but I have no idea how I would do that.
Any suggestions or alternative ideas are more than welcome | As far as I know, the only way to stop a user from leaving a page is the onbeforeunload event, which **isn't** cancelable. Instead, you return a string from that method, the browser prompts the user with a Yes/No dialog, life goes on. [276660](https://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own) has more info about this.
I don't think you're going to have much luck with this one. | what you're looking for is the onbeforeunload event.
just a warning though... it should be ***really*** quick... or your visitors are probably going to hate it no matter how cool it looks
as to preventing the page from navigating away before the animation is done, that's a bigger problem... any animation is going to rely on setTimeout/setInterval and the page won't wait for those to complete before leaving. | Jquery Effect Onunload | [
"",
"javascript",
"jquery",
"effect",
"onunload",
""
] |
Currently, I add a pound sterling (£) sign to the Java source and compile the resulting Swing component shows as the square (unsupported character) symbol.
I suspect it's an encoding problem, the Java source file is encoded as cp1252 (Eclipse seems to default to this). What's the correct way of resolving this? | Use the \u00A3 notation. Further examples [here](http://www.herongyang.com/JDK/Encoding-Conversion-Unicode-Signs-in-Different-Encodings.html) for the unicodes Unicode code points for other symbols. | I believe you can change the source code's encoding from Eclipse (or from any decent editor). Set it to UTF-8. Then everything should behave smoothly, because Java Strings are Unicode.
I would strongly encourage using proper encoding in the source, instead of this \uXXX notation. The reason being, how on earth do you infer form the code what for instance \u00A3 means? It's much clearer to just put the correct character there. | How do I show the pound sterling (£) sign in Java Swing? | [
"",
"java",
"swing",
"encoding",
"character",
""
] |
I managed to get a set of images loaded using Python.
I'd like my script to take this series of images (in whatever format I need them), and create a video from them. The big limit in all this is that I am looking for something easy and simple to install. Ideally, using the standard OS X installation procedure:
* download .dmg
* click
* move into the application folder
I do not want to expend a lot of effort to install the video editing program. Just something simple that works.
---
### Questions
1. What format should I aim for? I need my video to be playable on Linux, Mac, and Windows systems. The images are graphs, so we are speaking of discreet images, not photographs. It should be pretty easy to compress it. There will be about 1000 images, so this will be a short movie.
2. What tools should I use to produce the actual video? I need to either do it directly from Python using a library designed for this purpose, or by scripting command-line tools called from Python. | If you're not averse to using the command-line, there's the `convert` command from the ImageMagick package. It's available for Mac, Linux, Windows. See <http://www.imagemagick.org/script/index.php>.
It supports a huge number of image formats and you can output your movie as an mpeg file:
```
convert -quality 100 *.png outvideo.mpeg
```
or as animated gifs for uploading to webpages:
```
convert -set delay 3 -loop 0 -scale 50% *.png animation.gif
```
More options for the `convert` command available here: [ImageMagick v6 Examples -
Animation Basics](http://www.imagemagick.org/Usage/anim_basics/) | You may use OpenCV. And it can be installed on Mac. Also, it has a [python interface](http://opencv.willowgarage.com/wiki/PythonInterface).
I have slightly modified a program taken from [here](http://morphm.ensmp.fr/wiki/morphee-admin/How_to_use_Morph-M_with_OpenCV_), but don't know if it compiles, and can't check it.
```
import opencv
from opencv.cv import *
from opencv.highgui import *
isColor = 1
fps = 25 # or 30, frames per second
frameW = 256 # images width
frameH = 256 # images height
writer = cvCreateVideoWriter("video.avi",-1,
fps,cvSize(frameW,frameH),isColor)
#-----------------------------
#Writing the video file:
#-----------------------------
nFrames = 70; #number of frames
for i in range(nFrames):
img = cvLoadImage("image_number_%d.png"%i) #specify filename and the extension
# add the frame to the video
cvWriteFrame(writer,img)
cvReleaseVideoWriter(writer) #
``` | How can I script the creation of a movie from a set of images? | [
"",
"python",
"macos",
"video",
""
] |
Are there any JavaScript libraries or Toolkits that allow me to bind the JSON data to html controls on the client?
So essentially I should be able specify the object property to which a html control should be bound. Hence when the form receives the JSON data, the controls are updated, and when the controls are updated, the data should be updated to JSON object. | [Ext](http://extjs.com/) has an excellent implementation of what you describe, and it's similarity to the old Delphi and .NET methods of binding data to controls is a little spooky (though without the GUI to see the binding it's not quite as pretty)
<http://extjs.com/deploy/dev/docs/>
Look up JSONStore. Beware, there is a learning curve here of a couple weeks to really start on the path.
Another option is [Perservere](http://www.persvr.org/), which is part of the DOJO toolkit. I'm not sure if it's exactly what you are looking for as I've never used it, but it appears to be robust and does a lot of things you would expect a persistent client side dataset to do. | Itemscript describes a JSON schema language for data and applications. <http://itemscript.org>
The project provides a reference implementation of Itemscript JAM (JSON application markup), a declarative markup language that's described in an Itemscript schema.
The Item Lens is an Itemscript JAM animator. The Itemscript project goal is to provide a standard lightweight language for binding data and widgets. The reference implementation is based on GWT.
The project will be providing a way to share Itemscripts, but is at this point taking comments on the Itemscript Schema language and developing Itemscript JAMs for common application patterns. | JavaScript libraries / toolkits that support binding JSON data to HTML controls? | [
"",
"javascript",
"html",
"json",
"data-binding",
""
] |
What is the vb.net or c# equivalent of the following javascript?
```
this.browserTime.value = Math.floor((new Date()).getTime() / 1000);
```
I'm using httpwebrequest to login in to a site.
PostData header recorded from the browser looks like:
```
goto=¤tSlave=235acbdcd297c9211eef670c6dfbd64d&browserTime=1245052940&username=username&password=password&go=Sign+In
```
and the javascript on the page that gets the browsertime value is:
this.browserTime.value = Math.floor((new Date()).getTime() / 1000);
thanks | number of seconds since 1970?
```
static readonly DateTime epoch = new DateTime(1970, 1, 1);
...
int seconds = (int)Math.Floor((DateTime.Now - epoch).TotalSeconds);
``` | Translation:
```
new Date() => DateTime.Now
.getTime() => .Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds
Math.floor() => Math.Floor()
```
so in VB:
```
seconds As Double = Math.Floor( _
DateTime.Now.Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds / 1000
);
```
and in C#:
```
double seconds = Math.Floor(
DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds / 1000
);
```
or simply getting the seconds instead of getting milliseconds and dividing, in VB:
```
seconds As Double = Math.Floor(
DateTime.Now.Subtract(New DateTime(1970, 1, 1)).TotalSeconds
);
```
and C#:
```
double seconds = Math.Floor(
DateTime.Now.Subtract(New DateTime(1970, 1, 1)).TotalSeconds
);
``` | .net equivalent of Javascript function | [
"",
".net",
"javascript",
""
] |
I recently inherited a warehouse which uses views to summarise data, my question is this:
Are views good practise, or the best approach?
I was intending to use cubes to aggregate multi dimensional queries.
Sorry if this is asking a basic question, I'm not experienced with warehouse and analyis services
Thanks | Analysis Services and Views have the fundamental difference that they will be used by different reporting or analytic tools.
If you have SQL-based reports (e.g. through Reporting Services or Crystal Reports) the views may be useful for these. Views can also be materialised (these are called indexed views on SQL Server). In this case they are persisted to the disk, and can be used to reduce I/O needed to do a query against the view. A query against a non-materialized view will still hit the underlying tables.
Often, views are used for security or simplicity purposes (i.e. to encapsulate business logic or computations in something that is simple to query). For security, they can restrict access to sensitive data by filtering (restricting the rows available) or masking off sensitive fields from the underlying table.
Analysis Services uses different query and reporting tools, and does pre-compute and store aggregate data. The interface to the server is different to SQL Server, so reporting or query tools for a cube (e.g. ProClarity) are different to the tools for reporting off a database (although some systems do have the ability to query from either). | Cubes are a much better approach to summarize data and perform multidimensional analysis on it.
The problem with views is twofold: bad performance (all those joins and group bys), and inability to dice and slice the data by the user.
In my projects I use "dumb" views as a another layer between the datawarehouse and the cubes (ie, my dimensions and measure groups are based on views), because It allows me a greater degree of flexibility. | Using views in a datawarehouse | [
"",
"sql",
"sql-server",
"database",
"database-design",
""
] |
I have a search feature on my site that's POST based. Now, however, I want to be able to provide links that search for certain keywords, but this isn't of course possible because the form doesn't handle GET requests. Is there a way around this? | Set the form's method to GET
```
<form action="/search" method="GET">
```
This will work if your search app on the server permits searching via get. Just of note, you should be using GET for search anyway. POST is to make modifications and post data. You're "getting" search results, so use GET. | use the super global
```
$_REQUEST
``` | Sending GET requests to POST based script? | [
"",
"php",
"forms",
""
] |
My PHP web application has an API that can recieve reasonably large files (up to 32 MB) which are base64 encoded. The goal is to write these files somewhere on my filesystem. Decoded of course. What would be the least resource intensive way of doing this?
**Edit:** Recieving the files through an API means that I have a 32MB string in my PHP app, not a 32 MB source file somewhere on disk. I need to get that string decoded an onto the filesystem.
Using PHP's own base64\_decode() isn't cutting it because it uses a *lot* of memory so I keep running into PHP's memory limit (I know, I could raise that limit but I don't feel good about allowing PHP to use 256MB or so per process).
Any other options? Could I do it manually? Or write the file to disk encoded and call some external command? Any thought? | Even though this has an accepted answer, I have a different suggestion.
If you are pulling the data from an API, you should not store the entire payload in a variable. Using curl or other HTTP fetchers you can automatically store your data in a file.
Assuming you are fetching the data through a simple GET url:
```
$url = 'http://www.example.com/myfile.base64';
$target = 'localfile.data';
$rhandle = fopen($url,'r');
stream_filter_append($rhandle, 'convert.base64-decode');
$whandle = fopen($target,'w');
stream_copy_to_stream($rhandle,$whandle);
fclose($rhandle);
fclose($whandle);
```
Benefits:
* Should be faster (less copying of huge variables)
* Very little memory overhead
If you must grab the data from a temporary variable, I can suggest this approach:
```
$data = 'your base64 data';
$target = 'localfile.data';
$whandle = fopen($target,'w');
stream_filter_append($whandle, 'convert.base64-decode',STREAM_FILTER_WRITE);
fwrite($whandle,$data);
fclose($whandle);
``` | Decode the data in smaller chunks. Four characters of Base64 data equal three bytes of “Base256” data.
So you could group each 1024 characters and decode them to 768 octets of binary data:
```
$chunkSize = 1024;
$src = fopen('base64.data', 'rb');
$dst = fopen('binary.data', 'wb');
while (!feof($src)) {
fwrite($dst, base64_decode(fread($src, $chunkSize)));
}
fclose($dst);
fclose($src);
``` | How to base64-decode large files in PHP | [
"",
"php",
"memory",
"base64",
""
] |
I'm writing a .NET assembly in C++/CLI to be used in our C#-based application. I'd like the application to see some of the C++ methods as extension methods. Is there some attribute I can apply to the declaration to specify that a method should be seen as an extension method from C#? | Make it a static method in a non-nested, non-generic static class, with the [`Extension`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx) attribute applied to both the class and the method.
The tricky bit here *may* be the concept of a static class - that may not exist in C++/CLI... I'm not sure. It's possible that the C# compiler doesn't really care whether or not the class is static when *detecting* an extension method, only when declaring one. It's certainly worth a try without it. | I had the same problem and here is a little example of an extension method in C++/CLI:
```
using namespace System;
namespace CPPLib
{
[System::Runtime::CompilerServices::Extension]
public ref class StringExtensions abstract sealed
{
public:
[System::Runtime::CompilerServices::Extension]
static bool MyIsNullOrEmpty(String^ s)
{
return String::IsNullOrEmpty(s);
}
};
}
```
This extension method can be used just like any other in C#:
```
using CPPLib;
namespace CShartClient
{
class Program
{
static void Main( string[] args )
{
string a = null;
Console.WriteLine( a.MyIsNullOrEmpty() ? "Null Or Empty" : "Not empty" );
a = "Test";
Console.WriteLine( a.MyIsNullOrEmpty() ? "Null Or Empty" : "Not empty" );
Console.ReadKey();
}
}
}
```
Unfortunately it seems C++ does not provide us with the "syntactic sugar" like in C#. At least I did not find it. | How do I declare a method in C++/CLI that will be seen as an extension method in C#? | [
"",
"c#",
"c++-cli",
"extension-methods",
""
] |
Does someone know/have experience in showing Java web application generated UI in Sharepoint? We have a Java web application and are evaluating the possibilities to embed Java-generated web UI into Sharepoint. I don't think Sharepoint supports Java portlets, but it might support consuming [WSRP](http://en.wikipedia.org/wiki/Web_Services_for_Remote_Portlets)? | As previously mentioned, the SharePoint team released the WSRP toolkit a few months back. [More details available here](http://blogs.msdn.com/sharepoint/archive/2008/12/05/announcing-the-wsrp-toolkit-for-sharepoint.aspx).
If that doesn't work out for you (I've never tried it so have no experience to share) depending on the UI requirements you can always use the simple route of the Page Viewer Web Part.
This essentially creates a mini-browser (I believe it uses an iFrame) within a SharePoint page. If you're portlet is simply a data entry/display method it may work out for you and it's definitely less work. | WSRP consumer support is out of the box in SharePoint Enterprise. You can find a WSRP WebPart on your site if you've activated the Enterprise feature.
The WSRP toolkit allow SharePoint to produce WSRP compatible webpart. | How to show Java portlets in Sharepoint | [
"",
"java",
"sharepoint",
"web-applications",
"portlet",
"wsrp",
""
] |
I'd like to know your thoughts about test/mocking frameworks that are widely used and have a good level of compatibility between Java and .NET. I mean, I want to learn those tools to use in a .NET project, but I still wanna be able to apply that knowledge in Java projects.
* I know there're many questions about test/mocking frameworks to those platforms especifically here in SO, but I've not found one question comparing those frameworks regarding its similarities in those two platforms. | The N/J-series of frameworks ([**NUnit**](http://nunit.org)/**[JUnit](http://www.junit.org)**, [**NMock**](http://www.nmock.org)/[**JMock**](http://www.jmock.org/), etc.) are typically parallel ports of each other or are based on the same starting principles. Those will definitely let you transfer at least some of your knowledge between them. | I would suggest that you take a look at [Moq](http://moq.me/) for mocking in .NET. It is conceptually very similar to Mockito on the Java side. | Test and Mock framework for Java and .NET | [
"",
"java",
".net",
"tdd",
"mocking",
"testing",
""
] |
How do you put a strongly typed object in ASP.NET MVC into the master page?
Do you have a `ViewModelBase` class that contains master page information and inherit from it for every view model, or is there a better approach? | Alex,
I think what you are asking is, "Where is my master page controller?"
Have a look at the following link. It explains how to create an "Application Controller," an abstract class that can be inherited by your other controllers, so that you only have to write the code once that pushes your needed master page data into the view.
Passing Data to View Master Pages:
<http://www.asp.net/learn/MVC/tutorial-13-cs.aspx>
Also, have a look at the following link, which explains how to implement Partial Views and Subcontrollers in ASP.NET MVC:
Partial Requests in ASP.NET MVC
<http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/> | That is exactly the approach that I use. Have a MasterViewData base class containing information that might be common to all pages and is used to render the master page (logged in user when not using built-in auth, page-level messages). All my other view data classes derive from it.
I also do what Robert mentions: I have a base controller class that overrides the View method, which actually handles putting some of the master page information into the viewdata classes.
I'm curious if there are other options, but this approach has definitely worked well for me. | How do I put data in a Masterpage? | [
"",
"c#",
"asp.net-mvc",
"master-pages",
""
] |
I'd like to split my views in Grails into 2 files a .gsp file and a .js file so that I get a cleaner Javascript separation from my views. So here's an example:
```
views/index.gsp
views/index.js
views/home/index.jsp
views/home/index.js
```
But when I simply add the index.js script reference like this:
```
<script src="index.js" type="text/javascript"></script>
```
all I get is a 404.
Does anyone knows how to deal with this?
A great benefit would be to have the ability to use view data inside the index.js file to produce the desired content.
Matthias. | Actually, it should be perfectly possible to serve a JS file (or any other file type) as a GSP from your `grails-app/views/` directory. The only thing you have to do, is define a suitable URL mapping for those GSPs, e.g.:
```
"/javascript/home/index"(view:'/home/index.js')
```
With this URL mapping, you can put your JS code into `grails-app/views/home/index.js.gsp` (note the trailing .gsp) and you can use any grails tags in your JS source. To ensure that your JS is delivered with the correct content type, you may want to place
```
<%@ page contentType="text/javascript"%>
```
at the beginning of your GSP.
Unfortunately, the `createLink` tag doesn't support link rewriting to views, but it should be easy to write your own tag to create those links.
Anyways, keep in mind that this won't have a very positive impact on your app's performance. It's usually better to have static JS files (and also serve them as static resources) while passing dynamic stuff as parameters to JS functions for example. This will also keep you from some headaches wrt. caching etc. | **Update 2:**
Grails offer the possibility of hooking into the build lifecycle using [custom events](http://grails.org/doc/1.0.x/guide/4.%20The%20Command%20Line.html).
An event handler can be written which synchronises all JavaScript files under `grails-app/views` with the target folder of `web-app/js`.
Place the custom code in `$PROJECT/scripts/Events.groovy`. The `PackagingEnd` is a good target for the invocation, since it happens right after `web.xml` is generated.
```
eventPackagingEnd = { ->
// for each js file under grails-app/views move to web-app/js
}
```
---
**Update**
If you'd like the JavaScript files simply 'meshed' together, you can do that using symlinks, e.g.:
```
grails-app/views/view1/index.js -> webapp/js/view1/index.js
```
As far as I know, there is no way of forcing grails to directly serve content which is outside of web-app.
Alternatively, you can inline your JavaScript, but that can have performance implications.
---
JavaScript files belong under `web-app/js`.
Then you can reference them using `<g:javascript src="index.js" />`. | Grails: Javascript files in views folder | [
"",
"javascript",
"grails",
"gsp",
""
] |
I have the Vehicles class and mapping file for it and i want to get all rows from vehicles table ordered by ID desc (I also need the same for my other tables).
I got the following code:
```
session = HibernateUtil.getSessionFactory().getCurrentSession();
tx = session.beginTransaction();
q = session.createQuery("from Vehicles order by ID DESC");
for (Iterator it=q.iterate(); it.hasNext();){
//some logic
}
```
But my set isn't ordered by ID and each time it has a different order like RAND() or something. I was wondering what is the easiest way to keep the functionality and just to add order by clause because I have the same syntax on many places... | Try after "q = session.createQuery(...);" part:
```
List results = q.list()
//loop through results
```
There is probably something wrong elsewhere, because "sort by id desc" part is correct. Check your database/mapping files if you have correct data types and if indexes are set properly. | I'm assuming your vehicles class looks like this? I'm using JPA here because thats what I know...
```
class Vehicles {
@Id
@Column(name="vehicles_id")
private int id;
// other stuff here
}
```
I don't expect your session.createQuery to be different from mine so wouldn't something like this work?
```
Query q = session.createQuery("select v from Vehicles v order by v.id desc");
```
Also you could use criteria if you wanted yeah?
```
class Main {
List<Vehicles> cars;
}
Criteria main = session.createCriteria(Main.class);
Criteria secondary = main.createCriteria("cars");
secondary.addOrder(Order.asc("id"));
``` | Hibernate ordering | [
"",
"java",
"hibernate",
""
] |
I have some IronPython code which makes use of XmlTextWriter which allows me to write code like
```
self.writer = System.Xml.XmlTextWriter(filename, None)
self.writer.Formatting = Formatting.Indented
self.writer.WriteStartElement(name)
self.writer.WriteString(str(text))
self.writer.WriteEndElement()
...
self.writer.Close()
```
I would like to make my code portable across Python implementations (CPython, IronPython and Jython). Is there a streaming Python XML writer I can use for this without needing to use either print statements, or to construct a whole DOM tree before writing it out to file? | I wrote a module named loxun to do just that: <http://pypi.python.org/pypi/loxun/>. It runs with CPython 2.5 and Jython 2.5, but I never tried it with IronPython.
Example usage:
```
with open("...", "wb") as out:
xml = XmlWriter(out)
xml.addNamespace("xhtml", "http://www.w3.org/1999/xhtml")
xml.startTag("xhtml:html")
xml.startTag("xhtml:body")
xml.text("Hello world!")
xml.tag("xhtml:img", {"src": "smile.png", "alt": ":-)"})
xml.endTag()
xml.endTag()
xml.close()
```
And the result:
```
<?xml version="1.0" encoding="utf-8"?>
<xhtml:html xlmns:xhtml="http://www.w3.org/1999/xhtml">
<xhtml:body>
Hello world!
<xhtml:img alt=":-)" src="smile.png" />
</xhtml:body>
</xhtml:html>
```
Among other features, it detects missalligned tags while you write, uses a streaming API with a small memory footprint, supports Unicode and allows to disable pretty printing. | I've never used the .NET implementation you're talking about, but it sounds like the closest you're going to get is Python's [SAX parser](http://docs.python.org/library/xml.sax.html) (specifically, the [XMLGenerator class](http://docs.python.org/library/xml.sax.utils.html#xml.sax.saxutils.XMLGenerator) -- some sample code [here](http://www.xml.com/pub/a/2003/03/12/py-xml.html)). | Writing XML from Python : Python equivalent of .NET XmlTextWriter? | [
"",
"python",
"xml",
"ironpython",
"jython",
""
] |
When I create a .exe, I can right click it and go to properties->details. Then I get a list like:
> ```
> File Description |
> Type | Application
> File Version |
> Product Name |
> Product Version |
> Copyright |
> Size | 18.0 KB
> Date Modified | 6/16/2009 8:23 PM
> Language |
> ```
How do I change these properties? (And on a side note, is there a way to change the icon?) | If you are using C/Win32 you can add something like this to your project encapsulated in a \*.rc (resource) file:
```
VS_VERSION_INFO VERSIONINFO
FILEVERSION 0,0,0,2
PRODUCTVERSION 0,0,0,2
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x1L
FILESUBTYPE 0x0L
{
BLOCK "StringFileInfo"
{
BLOCK "040904b0"
{
VALUE "Comments", "comment\0"
VALUE "CompanyName", "comment\0"
VALUE "FileDescription", "base file\0"
VALUE "FileVersion", "0.0.0.2 TP\0"
VALUE "InternalName", "testTP\0"
VALUE "LegalCopyright", "none\0"
VALUE "OriginalFilename", "test.exe\0"
VALUE "ProductName", "test\0"
VALUE "ProductVersion", "0.0.0.2 TP\0"
}
}
BLOCK "VarFileInfo"
{
VALUE "Translation", 0x409, 1200
}
}
``` | If you want to change the FileDescription or any other version resource string on a compiled executable, [rcedit](https://github.com/atom/rcedit) (a small open-source tool) does it pretty easily:
```
$ rcedit MyApp.exe --set-version-string FileDescription "My Awesome App"
``` | How to change an executable's properties? (Windows) | [
"",
"c++",
"windows",
"properties",
"exe",
"executable",
""
] |
Two questions:
1. How is the value returned from `setInterval` and `setTimeout` (the ones used to clear the timers) calculated?
2. Is it possible for both the functions to return the same value during runtime?
For example:
`var a = setInterval(fn1, 1000);`
`var b = setTimeout(fn2, 1000);`
Is it possible for `a` and `b` to have the same value?
The first one is more of a for-my-knowledge question, but the second one is more important. | [Returns a value which can be used to cancel the timer.](http://msdn.microsoft.com/en-us/library/ms536749(VS.85).aspx) So, it would seem unlikely that they return the same value (unless they are reusing values and one of the timers has already been cancelled)
[Mozilla states it's DOM level 0, but not part of the specification.](https://developer.mozilla.org/En/Window.setInterval) (look at the bottom of the page)
I've got an even better reference:
[Nabble](http://www.nabble.com/Timers-td23406399.html) says:
> SetTimeout and setInterval are from
> the original Javascript specification,
> pre-ECMA. That specification is not
> officially standardized anywhere, but
> it is supported by all web browsers
> and most implementations of the
> Javascript language. (Including
> ActionScript.)
>
> The pre-ECMA specs are often known as
> the "DOM-0" APIs. Since they have
> never been standardized before, it
> makes sense for HTML5 to finally spec
> the non-deprecated APIs in an attempt
> to provide a consistent environment
> across browsers. Especially when
> recent events have proven that there
> are companies who like to implement
> the letter of the standard, but not
> the spirit.
Read the original spec [here](http://docs.sun.com/source/816-6408-10/), or from [Sun](http://docs.sun.com/source/816-6408-10/window.htm#1203758) (who was an early endorser of JavaScript). | Tested this under Opera 9, Safari 3, Firefox 3 and IE 7.
All returned integer values, starting at 1 and then incrementing by 1 for each call to `setTimeOut()` and `setInterval()`. However, I noticed that the browsers started the counters and handled them differently:
* IE started with a (seemingly) random 6-digit number, but subsequent calls to either function incremented this number. After closing and reopening IE I found that the starting number appeared to be randomly generated, as it was nowhere near the count from the previous session.
* Opera maintained a counter for each tab - closing a tab and opening a new one started the counter from 1 in the new tab.
* In Safari, the count was global - opening a new tab and calling the functions in different tabs seemed to increment a global reference counter.
* In Firefox, the counter appeared to start at 2, and incremented on each subsequent call to either function. Like Opera, each tab had its own counter value, but they appeared to all start at 2.
Notice though, that in all the scenarios, no two identifiers (at least in the same tab) are the same. | setInterval/setTimeout return value | [
"",
"javascript",
"settimeout",
"setinterval",
""
] |
Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):
```
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
```
From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.
My main question is, how do I implement it in the right way? | In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
[Can any one provide me a sample of Singleton in c++?](https://stackoverflow.com/a/271104/364696)
Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and [thread-safe](https://stackoverflow.com/a/449823/52074).
```
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
```
See this article about when to use a singleton: (not often)
[Singleton: How should it be used](https://stackoverflow.com/questions/86582/singleton-how-should-it-be-used)
See this two article about initialization order and how to cope:
[Static variables initialisation order](https://stackoverflow.com/questions/211237/c-static-variables-initialisation-order/211307#211307)
[Finding C++ static initialization order problems](https://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems/335746#335746)
See this article describing lifetimes:
[What is the lifetime of a static variable in a C++ function?](https://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function)
See this article that discusses some threading implications to singletons:
[Singleton instance declared as static variable of GetInstance method, is it thread-safe?](https://stackoverflow.com/questions/449436/singleton-instance-declared-as-static-variable-of-getinstance-method/449823#449823)
See this article that explains why double checked locking will not work on C++:
[What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about/367690#367690)
[Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I](http://www.drdobbs.com/cpp/c-and-the-perils-of-double-checked-locki/184405726) | You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.
I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):
```
class Singleton
{
private:
Singleton();
public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};
```
It has no dynamic memory allocation. | How do you implement the Singleton design pattern? | [
"",
"c++",
"design-patterns",
"singleton",
""
] |
When we serialize objects, static members are not serialized, but if we need to do so, is there any way out? | The first question is why you need to serialize the static members?
Static members are associated with the class, not the instances, so it does not make sense to include them when serializing an instance.
The first solution is to make those members not static. Or, if those members are the same in the original class and the target class (same class, but possibly different runtime environments), don't serialize them at all.
I have a few thoughts on how one could send across static members, but I first need to see the use case, as in all cases that means updating the target class, and I haven't found a good reason to do so. | Folks, static doesn't mean IMMUTABLE. For instance, I may want to serialize the whole state of the computation (yes, including static fields -- counters, etc) to resume later, after JVM and/or host computer restarted.
The right answer to that, as already said, is to use Externalizable, not Serializable, interface. Then you have a complete control on what and how you externalize. | How to serialize static data members of a Java class? | [
"",
"java",
"serialization",
"static-members",
""
] |
I have a table in SQL Server 2005 which has approx 4 billion rows in it. I need to delete approximately 2 billion of these rows. If I try and do it in a single transaction, the transaction log fills up and it fails. I don't have any extra space to make the transaction log bigger. I assume the best way forward is to batch up the delete statements (in batches of ~ 10,000?).
I can probably do this using a cursor, but is the a standard/easy/clever way of doing this?
P.S. This table does not have an identity column as a PK. The PK is made up of an integer foreign key and a date. | You can 'nibble' the delete's which also means that you don't cause a massive load on the database. If your t-log backups run every 10 mins, then you should be ok to run this once or twice over the same interval. You can schedule it as a SQL Agent job
try something like this:
```
DECLARE @count int
SET @count = 10000
DELETE FROM table1
WHERE table1id IN (
SELECT TOP (@count) tableid
FROM table1
WHERE x='y'
)
``` | What distinguishes the rows you want to delete from those you want to keep? Will this work for you:
```
while exists (select 1 from your_table where <your_condition>)
delete top(10000) from your_table
where <your_condition>
``` | SQL Batched Delete | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-administration",
""
] |
I am trying to parse this date with `SimpleDateFormat` and it is not working:
```
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Formaterclass {
public static void main(String[] args) throws ParseException{
String strDate = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dateStr = formatter.parse(strDate);
String formattedDate = formatter.format(dateStr);
System.out.println("yyyy-MM-dd date is ==>"+formattedDate);
Date date1 = formatter.parse(formattedDate);
formatter = new SimpleDateFormat("dd-MMM-yyyy");
formattedDate = formatter.format(date1);
System.out.println("dd-MMM-yyyy date is ==>"+formattedDate);
}
}
```
If I try this code with strDate=`"2008-10-14"`, I have a positive answer. What's the problem? How can I parse this format?
PS. I got this date from a `jDatePicker` and there is no instruction on how modify the date format I get when the user chooses a date. | You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.
To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):
```
SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
```
Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.
```
String input = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);
...
```
JavaDoc: <http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html> | The problem is that you have a date formatted like this:
```
Thu Jun 18 20:56:02 EDT 2009
```
But are using a `SimpleDateFormat` that is:
```
yyyy-MM-dd
```
The two formats don't agree. You need to construct a [`SimpleDateFormat`](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html) that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a `SimpleDateFormat` like this:
```
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009
```
Check the JavaDoc page I linked to and see how the characters are used. | How to parse a date? | [
"",
"java",
"date",
"simpledateformat",
""
] |
this must be such a common scenario that there's been a lot written about it already, hopefully even a really good pattern. I have a domain model in which a custom container contains entities. For example (properties and interfaces excluded for brevity):
```
class Entity
{
public int Id;
public EntityContainer ParentContainer;
}
class EntityContainer
{
public int Id;
public IList<Entity> Entities = new List<Entity>();
public void AddEntity(Entity entity)
{
entity.ParentContainer = this;
Entities.Add(entity);
}
}
class Main
{
public Main()
{
Entity entity1 = new Entity();
Entity entity2 = new Entity();
EntityContainer entityContainer = new EntityContainer();
entityContainer.AddEntity(entity1);
entityContainer.AddEntity(entity2);
// Can now traverse graph easily, e.g.
Console.WriteLine("entity1's parent container ID = " + entity1.ParentContainer.Id);
Console.WriteLine("Container contains at least this entity ID: " + entityContainer.Entities[0].Id);
}
}
```
I can now easily traverse my object graph both ways, but have created a circular reference. Would you create a third type to divorce the dependencies?
Thanks in advance | There's nothing wrong with circular references, per se, and they are used extensively in the .NET Framework, e.g. XmlNode.OwnerDocument, Control.Parent.
If you need to traverse up the tree, then a back reference is fine to use.
In COM, circular references are tricky because if you were the set the container and all its children to nothing, then objects will not be cleaned up properly as the children still hold references to the parent. However the .NET garbage collection has no problem with this the way it is implemented. | Does the container need to know about the *type* of the contents? If not, generics can avoid this - i.e. `Container<T>`, where you *happen* to use `Container<Entity>`. Other than that; pushing the necessary details into an interface (or base-class) in an assembly that both can reference is a common approach.
Personally, I'd try to simply avoid the need for the child to know about the parent.
Also; note that if you *do* go down the abstraction (interface etc) route; this can have a big implication if you are using (for example) xml serialization.
---
(edit re comments)
OK; first: what problem is the circular reference (within an assembly) causing; if none, leave it alone. If there is a problem, then you'll need an extra type; presumably some interfaces to represent the concrete types - i.e. where `Entity : IEntity`, and `EntityContainer` only knows about `IEntity` (or vv with `IEntityContainer`, or both), | Avoid circular reference in domain model | [
"",
"c#",
".net",
"design-patterns",
"domain-driven-design",
""
] |
I'm dealing with some legacy code that stores its data in a proprietary string format and I'm trying to create a regex to make parsing this format much easier.
What I'm having trouble with is the format contains groups that can be repeated many times sporadically. For example typically the data will look liks this (A)(B)(B)(B), but sometimes it can have multiple (A)'s like this (A)(B)(B)(B)(A)(B)(B), or even (A)(A)(B)(B)(B). The number of repetitions of (B) can vary too, as few as none or as many as well, lots.
What's happening is my current regex works fine when the data looks like (A)(B)(B)... but it breaks when there is another (A) later on in the string. The first (A) gets caught, but all remaining (A)'s don't.
So basically right now I have a regex that has a group for parsing (A)'s and a group for parsing (B)'s and these groups work fine independently, but I can't figure out how to combine these with the correct repetition syntax between them so that dispersed matches get found, instead of only the first one and the rest being ignored.
Am I just missing something or do I have to break my regex up into two separate ones and parse out (A)'s and (B)'s separately? (I'm using C#/.Net) | If you have a working pattern that matches `(A)` and another that matches `(B)`, then the expression to match any number of either is
```
(?:(A)|(B))*
```
There's no need to get fancy if that's all you need. This expression matches either `(A)` or `(B)` any number of times, but leaves the capturing of the groups to the `A` and `B` level. | It would help to see your current regexp.
To match any sequence of A's or B's use the following
```
(A*B*)*
```
That any number of groups of of A's followed by any number of B's
This will match the empty string, to ensure there is at least some data :
```
(A|B)(A*B*)*
```
Or is data always starts with an A (as in all your examples)
```
A(A*B*)*
``` | Matching multiple sporadic groups in a regex | [
"",
"c#",
"regex",
""
] |
I have a query that looks like this:
```
SELECT *
FROM employees e
LEFT JOIN
(
SELECT *
FROM timereports
WHERE date = '2009-05-04'
) t
ON e.id = t.employee_id
```
As you can see, my `LEFT JOIN` second table parameter is generated by a a subquery.
Does the db evaluate this subquery only once, or multiple times?
thanks.
matti | This depends on the `RDBMS`.
In most of them, a `HASH OUTER JOIN` will be employed, in which case the subquery will be evaluated once.
`MySQL`, on the other hand, isn't capable of making `HASH JOIN`'s, that's why it will most probably push the predicate into the subquery and will issue this query:
```
SELECT *
FROM timereports t
WHERE t.employee_id = e.id
AND date = '2009-05-04'
```
in a nested loop. If you have an index on `timereports (employee_id, date)`, this will also be efficient. | If you are using SQL Server, you can take a look at the [Execution Plan](http://msdn.microsoft.com/en-us/library/ms181055.aspx) of the query. The SQL Server query optimizer will optimize the query so that it takes the least time in execution. Best time will be based on some conditions viz. indexing and the like. | Are LEFT JOIN subquery table arguments evaluated more than once? | [
"",
"sql",
"mysql",
""
] |
In my application, I have a task which is running on a background thread. I need a notification in the background thread when ever a MessageBox or any modal dialog is displayed in the UI thread.
Though I can do it manually by calling some function before displaying the MessageBox, but it will be great if I dont have to.
For e.g.:
```
backgroundThread.MessageShown(); // I do not want to call this explicitly every time!
MessageBox.Show("Task halted!");
```
I am guessing there might me some message which can be hooked on to. Even in the main GUI thread, is there any message/event that get fired just before a modal dialog is shown?
Okay, here is the requirement. I have some tasks which are done on the UI thread, and I have to show progress on a separate dialog, which is been shown on a worker thread. I understand that it should be the tasks which must be done on worker thread, but the current scenario cannot be changed for the time being.
Every thing is working fine, except for one glitch - if a message box is shown in the UI thread, it gets hidden below the progress dialog. So the user never gets to know that UI is waiting for an input. I need a way to get notified that a modal dialog box has been shown and I should hide the progress dialog.
Right now, I have to hide it explicitly just before every call to MessageBox.
I hope that explains. | Set up a [CBT Hook](http://msdn.microsoft.com/en-us/library/ms644977(VS.85).aspx). Then you'll get notification of all created, activated, deactivated and destroyed windows. Then use GetWindowClass to check if the hWnd created/activated is in fact a MessageBox. | create your own messagebox that fires an event when calling Show? | How to know when a Message Box has been shown for a form? | [
"",
"c#",
"forms",
""
] |
I need to integrate with a legacy .NET Web Service that uses WSE 2.0 for WS-Security and DIME. The catch is I need to do this from a Java application.
I'm expecting that Axis2 works fine with the WS-Security because folks around here have done it before. It's the DIME that I'm concerned about. I see a reference to DIME at <http://ws.apache.org/axis/java/client-side-axis.html>, but I'm wondering if anyone has actually done this with Axis and a WSE 2.0 Web Service. | I can't tell you anything for sure from own expierence. And about every 2nd page on the "web" seems to state something different to this question.
So taking all together the following is all possible
1. Dime Support was dropped from 1.x to 2.x
2. Some kind of support in 2.x is there, possibly flaky
3. Support is there
4. No support at all is there
5. One of the provided links gives enough insight/code sample to get something useful going
Links to "Does Axis 2.0 support Dime"?
[No. You have to switch back to 1.4](http://www.mail-archive.com/axis-user@ws.apache.org/msg33083.html)
[No some guy](http://osdir.com/ml/axis-user-ws.apache.org/2009-05/msg00259.html)
[large attachments in dime format](http://mail-archives.apache.org/mod_mbox/ws-axis-user/200701.mbox/%3cBAY133-DAV468A5BA91D05A54768084AEB90@phx.gbl%3e) -> btw the same guy which 2009 states he never has heard of Dime since 2002
[Axis 1.x to Axis 2.1 port Dime](http://www.mail-archive.com/axis-user@ws.apache.org/msg21674.html) -> againThe same guy 2006 posting something which looks like a port
[Creating Apache Axis Java proxy classes that use DIME](http://livedocs.adobe.com/livecycle/8.2/programLC/programmer/help/wwhelp/wwhimpl/common/html/wwhelp.htm?context=sdkHelp&file=001510.html) From some Adobe Docu site
[J2EE Web Service Development with Attachments Using Axis](http://roseindia.net/webservices/web-services-development.shtml) -> The only real tutorial I found until now. But uses Axis 1.2.1
[AttachmentProblems](http://wiki.apache.org/ws/FrontPage/Axis/AttachmentProblems) -> An Axis Wiki page stating problems with Dime attachment files > 1 MB | My investigation and experiments on this topic a year ago showed that Axis 2 doesn't supports DIME attachments despite the fact that there were some unclear notes in documentation and defines in the code. Now documentation is cleared up and there are no any notes on DIME support. But Axis 1.4 works with DIME attachments OK. Downgrade you Axis library to 1.4 if you can't force your partners to upgrade their service to support MTOM/XOP. | Java client calling WSE 2.0 with DIME attachment | [
"",
"java",
".net",
"web-services",
"axis",
"ws-security",
""
] |
Suppose I have a Javascript object which is initialized
```
var letters = {q:0, t:0, o:0, b:0, y:0, n:0, u:0, m:0, p:0,
w:0, a:0, d:0, k:0, v:0, c:0, z:0, l:0, j:0,
i:0, e:0, g:0, s:0, x:0, r:0, h:0, f:0};
```
and then I want to iterate over the keys of this objects
```
for(var letter in letters) {
// code goes here
}
```
In both Firefox 3 and Internet Explorer 8 the objects are iterated over in the order in which they are listed in the object declaration (q, t, o, b, y, etc).
Can I rely on this? Assume that I don't modify my object in any way before the iteration. Is it part of the ECMAScript standard? Does anyone know which browsers iterate in the declared order? | No, it cannot be relied upon, at least [not in Firefox](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for...in):
> A for...in loop iterates over the properties of an object in an arbitrary order. | The order is not guaranteed. See this SO question for more information: [Iterate over a Javascript associative array in sorted order](https://stackoverflow.com/questions/890807/iterate-over-a-javascript-associative-array-in-sorted-order). | Iteration order of for..in loops in Javascript | [
"",
"javascript",
""
] |
First, a caveat. The main script is **not run in a webpage**. I will be running the .js file in Windows using Windows Script Host.
**The problem:**
I would like to create a javascript "library" containing a number of objects, each with a number of functions. I expect this library will get rather large with time and would like to keep it in a separate javascript file (let's call it **Library.js**). I would like to access the objects from **Library.js** from another script (let's call this one **User.js**).
In essence, I am looking for something similar to the C/C++ "include" paradigm.
**Is there anyway to implement this in javascript? (Remember, this is not web-based)** | [This page right here](http://msdn.microsoft.com/en-us/library/15x4407c(VS.85).aspx) is the closest I could find. It talks about .wsf files which let you combine multiple scripts (that may be written in different languages) in one file.
For your question it should be something like:
**user.wsf**
```
<job id="IncludeExample">
<script language="JScript" src="library.js"/>
<script language="JScript">
<![CDATA[
// use your library functions here
]]>
</script>
</job>
```
There may be better ways, but I'm not a WSH expert. | I know this is an old question and it has been answered and accepted.
I know about .WSF files and how they work; they serve the purpose.
However, I've also found it handy to do the "inclusion" from within a pure .js file that runs in WSH. Here's my solution for that.
```
function includeFile (filename) {
var fso = new ActiveXObject ("Scripting.FileSystemObject");
var fileStream = fso.openTextFile (filename);
var fileData = fileStream.readAll();
fileStream.Close();
eval(fileData);
}
```
With that utility function defined, I can do this from within a javascript module:
```
includeFile("externalFile1.js");
includeFile("externalFile2.js");
includeFile("etc.js");
```
...and then I can invoke any of the functions or tickle any of the variables defined in those modules.
A similar technique works with .vbs files:
[How do I include a common file in VBScript (similar to C #include)?](https://stackoverflow.com/questions/316166/how-do-i-include-a-common-file-in-vbscript-similar-to-c-include/316169#316169) | How can I create a javascript library in a separate file and "include" it in another? | [
"",
"javascript",
"include",
"wsh",
"windows-scripting",
""
] |
I recently had a techical test for a job interview where I did a Response.Write(). I was told that this was "old fashioned" and that there are better ways of doing this now. The interviewer wouldn't elaborate, so I'm keen to know what he was referring to. Anyone have any ideas? | Response.Write is great, if *everything* on the page is sent by it. I use it when I have to use ASPX to serve non-HTML files that I generate on the fly.
Response.Write doesn't make any sense at all if you are using non-empty ASPX pages. | In the aspx - inline server script tags:
```
<%= SomeProperty.Name %>
```
In the code - that depends on the circumstances but there's usually a better alternative such as a HtmlTextWriter, a ScriptManager (for registering your scripts), a literal control, a placeholder or something else. | Response.Write outdated? | [
"",
"c#",
"asp.net",
""
] |
Is C# compiler open source? | At Build 2014, Microsoft announce that their next generation of compilers codenamed "Roslyn" would be made open source and be available on [Github](https://github.com/dotnet/roslyn).
The legacy C# compiler from Microsoft is not open source, although it is freely available through [Visual Studio Express](http://www.microsoft.com/Express/) or the .NET Framework SDK. However there are freely available, open source, C# compilers out there. Check out [Mono](http://www.mono-project.com/Main_Page) | [SSCLI](http://code.msdn.microsoft.com/ssclimsbuild), otherwise known as Rotor, is a shared source version of the CLI + build tools from Microsoft. Also [Blue](http://blogs.msdn.com/jmstall/archive/2005/02/06/368192.aspx) (as answered by SnapConfig.com) is also a C# compiler written in C# | Is C# compiler open source? | [
"",
"c#",
".net",
"open-source",
"compiler-construction",
""
] |
I'm not sure if the question title is the best one but it was the best one I could come up with...
I have this .NET (C#) applications which starts up with Windows and remains opened until the computer is turned off. The app stays on the tray and I open it by clicking the tray icon and close it the same way.
The app is not slow at first, it works normally, no problems there. But after long periods of inactivity of itself, it gets very slow when showing it again for the first time in a long period. Know what I mean.
For instance, I could not use/open (click the tray icon) for a few days and between those days I opened and closed and used lots of other apps, heavy apps too and I probably hibernated and resumed the computer a few times and when I needed to open my app again, it was slow. After a few minutes of using it, it goes back to normal and works fine.
I believe this has something to with memory management and the system probably frees up most of my app's memory so other programs can use it more efficiently. And maybe .NET memory management as something to do with it...
Whatever the reason, is there anything I can do to optimize my app regarding that issue? | This is almost certainly due to memory being paged out to disk.
When you cease using your application and other applications or tasks start exerting memory pressure, pages of memory from your app can be written out to disk. When you try to use your application again, all this data must then be read in causing the stalls that you see.
Unfortunately, there is no good solution - if you run as administrator or have the SeLockMemoryPrivilege, you can lock parts of your application into physical memory. You can try "touching" pages periodically to keep them in physical memory. Unfortunately, both these options will cause your application to interact badly with other applications on the system - your memory is getting paged out because the physical memory is needed for something else. You can attempt to lower your overall memory footprint, but you will still run into this issue in some cases. There are options for tweaking your working set size, but the OS is free to ignore those, and will in many cases. | You can use the [.NET memory profiler](http://memprofiler.com/) to get a good idea of what your application is doing with memory over time. You can check if anything is building up where you don't expect it to (collections, lists, etc.) and causing your memory footprint to grow. | .NET Application very slow after long period of inactivity | [
"",
"c#",
".net",
"performance",
""
] |
I'd like to edit an object like the one below. I'd like the UsersSelectedList populated with one or more Users from the UsersGrossList.
Using the standard edit-views in mvc, I get only strings and booleans (not shown below) mapped.
Many of the examples I find on google utilizes early releases of the mvc framework whereas I use the official 1.0 release.
Any examples of the view is appreciated.
```
public class NewResultsState
{
public IList<User> UsersGrossList { get; set; }
public IList<User> UsersSelectedList { get; set; }
}
``` | Use Html.ListBox in combination with IEnumerable SelectListItem
View
```
<% using (Html.BeginForm("Category", "Home",
null,
FormMethod.Post))
{ %>
<%= Html.ListBox("CategoriesSelected",Model.CategoryList )%>
<input type="submit" value="submit" name="subform" />
<% }%>
```
Controller/Model:
```
public List<CategoryInfo> GetCategoryList()
{
List<CategoryInfo> categories = new List<CategoryInfo>();
categories.Add( new CategoryInfo{ Name="Beverages", Key="Beverages"});
categories.Add( new CategoryInfo{ Name="Food", Key="Food"});
categories.Add(new CategoryInfo { Name = "Food1", Key = "Food1" });
categories.Add(new CategoryInfo { Name = "Food2", Key = "Food2" });
return categories;
}
public class ProductViewModel
{
public IEnumerable<SelectListItem> CategoryList { get; set; }
public IEnumerable<string> CategoriesSelected { get; set; }
}
public ActionResult Category(ProductViewModel model )
{
IEnumerable<SelectListItem> categoryList =
from category in GetCategoryList()
select new SelectListItem
{
Text = category.Name,
Value = category.Key,
Selected = (category.Key.StartsWith("Food"))
};
model.CategoryList = categoryList;
return View(model);
}
``` | Assuming that User model has Id and Name properties:
```
<%= Html.ListBox("users", Model.UsersGrossList.Select(
x => new SelectListItem {
Text = x.Name,
Value = x.Id,
Selected = Model.UsersSelectedList.Any(y => y.Id == x.Id)
}
) %>
```
Or with View Model
```
public class ViewModel {
public Model YourModel;
public IEnumerable<SelectListItem> Users;
}
```
Controller:
```
var usersGrossList = ...
var model = ...
var viewModel = new ViewModel {
YourModel = model;
Users = usersGrossList.Select(
x => new SelectListItem {
Text = x.Name,
Value = x.Id,
Selected = model.UsersSelectedList.Any(y => y.Id == x.Id)
}
}
```
View:
```
<%= Html.ListBox("users", Model.Users ) %>
``` | How can a multi-select-list be edited using asp.net mvc? | [
"",
"c#",
"asp.net-mvc",
"multi-select",
""
] |
I'm trying to create a temporary text file in C++ and then delete it at the end
of the program. I haven't had much luck with Google.
Could you tell me which functions to use?
---
The answers below tell me how to create a temp file. What if I just want to
create a file (tmp.txt) and then delete it? How would I do that? | Maybe this will help
```
FILE * tmpfile ( void );
```
<http://www.cplusplus.com/reference/clibrary/cstdio/tmpfile/>
> Open a temporary file
>
> Creates a temporary binary file, open
> for update (wb+ mode -- see fopen for
> details). The filename is guaranteed
> to be different from any other
> existing file. The temporary file
> created is automatically deleted when
> the stream is closed (fclose) or when
> the program terminates normally.
See also
```
char * tmpnam ( char * str );
```
> Generate temporary filename
>
> A string containing a filename
> different from any existing file is
> generated. This string can be used to
> create a temporary file without
> overwriting any other existing file.
<http://www.cplusplus.com/reference/clibrary/cstdio/tmpnam/> | Here's a complete example:
```
#include <unistd.h>
int main(void) {
char filename[] = "/tmp/mytemp.XXXXXX"; // template for our file.
int fd = mkstemp(filename); // Creates and opens a new temp file r/w.
// Xs are replaced with a unique number.
if (fd == -1) return 1; // Check we managed to open the file.
write(fd, "abc", 4); // note 4 bytes total: abc terminating '\0'
/* ...
do whatever else you want.
... */
close(fd);
unlink(filename); // Delete the temporary file.
}
```
If you know the name of the file you want to create (and are sure it won't already exist) then you can obviously just use `open` to open the file.
`tmpnam` and `tmpfile` should probably be avoided as they can suffer from race conditions - see [`man tmpfile(3)`](http://www.kernel.org/doc/man-pages/online/pages/man3/tmpfile.3.html) for the details. | How to create a temporary text file in C++? | [
"",
"c++",
"file",
""
] |
```
import java.io.*;
public class Demo{
public static void main(String[] args){
File f = new File("abc.txt") ;
try{
System.setOut(new PrintStream( new FileOutputStream(f) ) ) ;
}
catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage()) ;
}
System.out.println("Hello\n") ;
try{
//throwing exception,
//is there any method to close the f File,
//before we try to open the file referred by f.
Process p = Runtime.getRuntime().exec(f.getPath()) ;
}
catch(IOException io){
System.out.println(io.getMessage()) ;
}
}
}
```
**and the content of abc.txt after executing Demo is:-**
Hello
Cannot run program "abc.txt": CreateProcess error=32, The process cannot access the file because it is being used by another process
**how to avoid the exception.....**
as many people here suggested, i have tried the following code,
but sadly, even that is also throwing excption....:-(
```
import java.io.*;
class Demo{
public static void main(String[] args){
File f = new File("abc.txt") ;
FileOutputStream fos = null ;
try{
fos = new FileOutputStream(f) ;
}
catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage()) ;
}
PrintStream ps = new PrintStream(fos) ;
ps.println("Hello") ;
try{
fos.close() ;
//throwing exception again
Process p = Runtime.getRuntime().exec(f.getAbsolutePath()) ;
}
catch(IOException io){
System.out.println(io.getMessage()) ;
}
}
}
```
?????????? | I am assuming that the reason for calling Runtime.getRuntime().exec(f.getPath()); is to open up the abc.txt file in a text editor. It would be better to provide complete command for opening the text editor along with the file path. I tried this with notepad.exe (windows) and it worked.
```
import java.io.*;
public class Demo{
public static void main(String[] args){
File f = new File("abc.txt") ;
try{
System.setOut(new PrintStream( new FileOutputStream(f) ) ) ;
}
catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage()) ;
}
System.out.println("Hello\n") ;
try{
Process p = Runtime.getRuntime().exec("notepad.exe " + f.getPath()) ;
}
catch(IOException io){
System.out.println(io.getMessage()) ;
}
}
}
```
Following code dynamically generates java code and uses javac to compile it
```
import java.io.*;
public class Demo{
public static void main(String[] args){
File f = new File("Abc.java") ;
PrintWriter writer = null;
BufferedReader reader = null;
InputStream pStream = null;
try{
// Open File Stream and write code
writer = new PrintWriter( new FileOutputStream(f) );
String javaCode = "public class Abc { \r\n" +
"public static void main(String[] args) {\r\n" +
"System.out.println(\"Hello World!\");\r\n" +
"}\r\n" +
"}\r\n";
writer.println(javaCode) ;
writer.close();
// Run Javac to compile the code
Process p = Runtime.getRuntime().exec("javac " + f.getPath()) ;
p.waitFor();
// status = 0 => Process executed without errors
// = 1 => Process executed with errors
int status = p.exitValue();
if( status == 0 )
{
pStream = p.getInputStream();
}
else
{
pStream = p.getErrorStream();
}
// Display the output from the process
reader = new BufferedReader(new InputStreamReader(pStream));
String ln = null;
while( (ln = reader.readLine()) != null )
{
System.out.println(ln);
}
}
catch(Exception ex){
System.out.println(ex.getMessage()) ;
}
finally{
try{
if( writer != null ){writer.close();}
if( pStream != null ){pStream.close();}
if( reader != null ){reader.close();}
}
catch(Exception ex){
System.out.println(ex.getMessage()) ;
}
}
}
}
``` | Close the file before executing it (and don't redirect System.out):
```
f = new File("abc.txt");
FileOutputStream fos = new FileOutputStream(f);
// You would likely use fos.write instead, but here we go
PrintStream ps = new PrintStream(fos);
ps.println("Hello\n");
fos.close();
Process p = Runtime.getRuntime().exec(f.getPath());
``` | executing a dynamically created file | [
"",
"java",
"file-io",
""
] |
I am trying to accomplish something in C# that I do easily in Java. But having some trouble.
I have an undefined number of arrays of objects of type T.
A implements an interface I.
I need an array of I at the end that is the sum of all values from all the arrays.
Assume no arrays will contain the same values.
This Java code works.
```
ArrayList<I> list = new ArrayList<I>();
for (Iterator<T[]> iterator = arrays.iterator(); iterator.hasNext();) {
T[] arrayOfA = iterator.next();
//Works like a charm
list.addAll(Arrays.asList(arrayOfA));
}
return list.toArray(new T[list.size()]);
```
However this C# code doesn't:
```
List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
//Problem with this
list.AddRange(new List<T>(arrayOfA));
//Also doesn't work
list.AddRange(new List<I>(arrayOfA));
}
return list.ToArray();
```
So it's obvious I need to somehow get the array of `T[]` into an `IEnumerable<I>` to add to the list but I'm not sure the best way to do this? Any suggestions?
EDIT: Developing in VS 2008 but needs to compile for .NET 2.0. | The issue here is that C# doesn't support [co-variance](http://weblogs.asp.net/astopford/archive/2006/12/28/c-generics-covariance.aspx) (at least not until C# 4.0, I think) in generics so implicit conversions of generic types won't work.
You could try this:
```
List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
list.AddRange(Array.ConvertAll<T, I>(arrayOfA, t => (I)t));
}
return list.ToArray();
```
---
For anyone that strumbles across this question and is using .NET 3.5, this is a slightly more compact way of doing the same thing, using Linq.
```
List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
list.AddRange(arrayOfA.Cast<I>());
}
return list.ToArray();
``` | Edited for 2.0; it can become:
```
static void Main() {
IEnumerable<Foo[]> source = GetUndefinedNumberOfArraysOfObjectsOfTypeT();
List<IFoo> list = new List<IFoo>();
foreach (Foo[] foos in source) {
foreach (IFoo foo in foos) {
list.Add(foo);
}
}
IFoo[] arr = list.ToArray();
}
```
How about (in .NET 3.5):
```
I[] arr = src.SelectMany(x => x).Cast<I>().ToArray();
```
To show this in context:
```
using System.Collections.Generic;
using System.Linq;
using System;
interface IFoo { }
class Foo : IFoo { // A implements an interface I
readonly int value;
public Foo(int value) { this.value = value; }
public override string ToString() { return value.ToString(); }
}
static class Program {
static void Main() {
// I have an undefined number of arrays of objects of type T
IEnumerable<Foo[]> source=GetUndefinedNumberOfArraysOfObjectsOfTypeT();
// I need an array of I at the end that is the sum of
// all values from all the arrays.
IFoo[] arr = source.SelectMany(x => x).Cast<IFoo>().ToArray();
foreach (IFoo foo in arr) {
Console.WriteLine(foo);
}
}
static IEnumerable<Foo[]> GetUndefinedNumberOfArraysOfObjectsOfTypeT() {
yield return new[] { new Foo(1), new Foo(2), new Foo(3) };
yield return new[] { new Foo(4), new Foo(5) };
}
}
``` | Converting an array of type T to an array of type I where T implements I in C# | [
"",
"c#",
"arrays",
"list",
"ienumerable",
""
] |
How can I convert a `List<Integer>` to `int[]` in Java?
I'm confused because `List.toArray()` actually returns an `Object[]`, which can be cast to neither `Integer[]` nor `int[]`.
Right now I'm using a loop to do so:
```
int[] toIntArray(List<Integer> list) {
int[] ret = new int[list.size()];
for(int i = 0; i < ret.length; i++)
ret[i] = list.get(i);
return ret;
}
```
Is there's a better way to do this?
This is similar to the question
*[How can I convert int[] to Integer[] in Java?](https://stackoverflow.com/questions/880581/java-convert-int-to-integer)*. | Unfortunately, I don't believe there really *is* a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:
* `List<T>.toArray` won't work because there's no conversion from `Integer` to `int`
* You can't use `int` as a type argument for generics, so it would *have* to be an `int`-specific method (or one which used reflection to do nasty trickery).
I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(
Even though the [`Arrays`](http://java.sun.com/javase/6/docs/api/java/util/Arrays.html) class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays). | With streams added in Java 8 we can write code like:
```
int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();
```
---
Thought process:
* The simple `Stream#toArray` returns an `Object[]` array, so it is not what we want. Also, `Stream#toArray(IntFunction<A[]> generator)` which returns `A[]` doesn't do what we want, because the generic type `A` can't represent the primitive type `int`
* So it would be nice to have some kind of stream which would be designed to handle primitive type `int` instead of the reference type like `Integer`, because its `toArray` method will most likely also return an `int[]` array (returning something else like `Object[]` or even boxed `Integer[]` would be unnatural for `int`). And fortunately Java 8 has such a stream which is [`IntStream`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html)
* So now the only thing we need to figure out is how to convert our `Stream<Integer>` (which will be returned from `list.stream()`) to that shiny `IntStream`.
Quick searching in documentation of `Stream` while looking for methods which return `IntStream` points us to our solution which is [`mapToInt(ToIntFunction<? super T> mapper)`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#mapToInt-java.util.function.ToIntFunction-) method. All we need to do is provide a mapping from `Integer` to `int`.
Since [`ToIntFunction`](https://docs.oracle.com/javase/8/docs/api/java/util/function/ToIntFunction.html) is *functional interface* we can also provide its instance via *lambda* or *method reference*.
Anyway to convert Integer to int we can use [`Integer#intValue`](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#intValue--) so inside `mapToInt` we can write:
```
mapToInt( (Integer i) -> i.intValue() )
```
(or some may prefer: `mapToInt(Integer::intValue)`.)
But similar code can be generated using unboxing, since the compiler knows that the result of this lambda must be of type `int` (the lambda used in `mapToInt` is an implementation of the `ToIntFunction` interface which expects as body a method of type: `int applyAsInt(T value)` which is expected to return an `int`).
So we can simply write:
```
mapToInt((Integer i)->i)
```
Also, since the `Integer` type in `(Integer i)` can be inferred by the compiler because `List<Integer>#stream()` returns a `Stream<Integer>`, we can also skip it which leaves us with
```
mapToInt(i -> i)
``` | How can I convert List<Integer> to int[] in Java? | [
"",
"java",
"arrays",
"collections",
""
] |
For my project report, i need to show the class diagram of the software i've built which counts around 20 classes! The problem, is that when i render the class diagram in jpeg file(either using StarUML or ArgoUMl or whatever..) we can't see the details correctly (very big picture because of the large number of classes). Well, how to manage this situation correctly? Since the report is gonna be printed on A4 pages ?
Thanks ! | With 20 classes I would expect at least 3 subsystems, (modules, layers), possibly more
Make package diagram showing the relation between those, one class diagram for each subsystem.
Add class diagrams for special things you want to show. Print each on A4.
If you can't split the diagram easily into modules, I'd consider that a design smell.
Its fun to print large diagrams on huge pieces of paper (like 500 tables on A0 ;-) but it really isn't of much use. | Producing a class diagram containing 20 classes is totally useless- what does it actually show? When using class diagrams I've never created a diagram that has more than about 5-8 classes on it.
The question to ask yourself is "what useful information am I trying to show with this diagram?". Don't produce a class diagram for the sake of it!
Breaking it down to demonstrate a particular design pattern, subsystem or component is what I find class diagrams useful for. | UML - How to manage big class diagrams? | [
"",
"c++",
"uml",
""
] |
I have an SQL Query that i'm running but I only want to select a specific row. For example lets say my query was:
```
Select * from Comments
```
Lets say this returns 10 rows, I only want to select the 8th record returned by this query. I know I can do:
```
Select Top 5 * from Comments
```
To get the top 5 records of that query but I only want to select a certain record, is there anything I can put into this query to do that (similar to top).
Thanks
jack | This is a classic interview question.
In Ms SQL 2005+ you can use the [ROW\_NUMBER()](http://msdn.microsoft.com/en-us/library/ms186734.aspx) keyword and have the Predicate ROW\_NUMBER = n
```
USE AdventureWorks;
GO
WITH OrderedOrders AS
(
SELECT SalesOrderID, OrderDate,
ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
FROM Sales.SalesOrderHeader
)
SELECT *
FROM OrderedOrders
WHERE RowNumber = 5;
```
In SQL2000 you could do something like
```
SELECT Top 1 *FROM
[tblApplications]
where [ApplicationID] In
(
SELECT TOP 5 [ApplicationID]
FROM [dbo].[tblApplications]
order by applicationId Desc
)
``` | How about
```
SELECT TOP 1 * FROM
(SELECT TOP 8 * FROM Comments ORDER BY foo ASC)
ORDER BY foo DESC
``` | Selecting Nth Record in an SQL Query | [
"",
"sql",
"sql-server-2005",
""
] |
I'm attempting to instantiate a Windows Media Player COM object on my machine:
```
Guid mediaPlayerClassId = new Guid("47ac3c2f-7033-4d47-ae81-9c94e566c4cc");
Type mediaPlayerType = Type.GetTypeFromCLSID(mediaPlayerClassId);
Activator.CreateInstance(mediaPlayerType); // <-- this line throws
```
When executing that last line, I get the following error:
```
System.IO.FileNotFoundException was caught
Message="Retrieving the COM class factory for component with CLSID {47AC3C2F-7033-4D47-AE81-9C94E566C4CC} failed due to the following error: 80070002."
Source="mscorlib"
StackTrace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at MyStuff.PreviewFile(String filePath) in F:\Trunk\PreviewHandlerHosting\PreviewHandlerHost.cs:line 60
InnerException:
```
This same code works on other developer machines and end user machines. For some reason, it only fails on my machine. What could be the cause? | 80070002 is a File Not Found error.
My guess is your machine is missing a dependency. Try running the com component through depends.exe to see if you have all of the required libraries installed. | Well, 0x80070002 means File not found, so I'd check to see whether the DLL pointed to in the COM registration actually exists on your machine | Can't instantiate COM component in C# - error 80070002 | [
"",
"c#",
"com",
"interop",
"com-interop",
""
] |
I have a simple question about usage of Hibernate. I keep seeing people using JPA annotations in one of two ways by annotating the fields of a class and also by annotating the get method on the corresponding beans.
My question is as follows: Is there a difference between annotating fields and bean methods with JPA annoations such as @Id.
example:
```
@Entity
public class User
{
**@ID**
private int id;
public int getId(){
return this.id;
}
public void setId(int id){
this.id=id;
}
}
```
-----------OR-----------
```
@Entity
public class User
{
private int id;
**@ID**
public int getId(){
return this.id;
}
public void setId(int id){
this.id=id;
}
}
``` | Yes, I believe you want to search on field versus property access:
[Hibernate Annotations - Which is better, field or property access?](https://stackoverflow.com/questions/594597/hibernate-annotations-which-is-better-field-or-property-access)
The Spring preference is [field access](http://static.springframework.org/spring/docs/2.5.x/reference/orm.html). That's what I follow. | Yes, if you annotate the fields, Hibernate will use field access to set and get those fields. If you annotate the methods, hibernate will use getters and setters. Hibernate will pick the access method based on the location of the `@Id` annotation and to my knowledge you cannot mix and match. If you annotate a field with `@Id`, annotations on methods will be ignored and visa versa. You can also manually set the method with the class level annotation `@AccessType`
The [Hibernate Annotations reference guide](http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/) has proven to be an extremely useful resource for questions like this and details how access types cascade down hierarchies. | Hibernate/JPA - annotating bean methods vs fields | [
"",
"java",
"hibernate",
"orm",
"jpa",
""
] |
I am using an ObjectDataProvider and a DataTemplate to populate a MenuItem inside my Menu bar. (WPF, C#/XAML) See snipet below.
Result: The top menu item appears, when i click on it, the wrapping menu item (the one with the bound header text) appears along with the little arrow indicating the presence of children but hovering or clicking the arrow does not show the children, they cannot be accessed.
Expected result: The children are visible and behave properly.
Snippet:
```
<ObjectDataProvider x:Key="Brokers" ObjectInstance="{x:Static brokers:BrokerManager.Instance}" MethodName="GetBrokers" IsAsynchronous="True" />
<DataTemplate x:Key="BrokerMenuItem" DataType="IBroker">
<MenuItem Header="{Binding Path=Name}">
<MenuItem Header="Connect" />
<MenuItem Header="Disconnect" />
</MenuItem>
</DataTemplate>
<MenuItem Header="Brokers" ItemsSource="{Binding Source={StaticResource Brokers}}" ItemTemplate="{DynamicResource BrokerMenuItem}"/>
``` | After searching for over a week, i finally found how to make this work properly. It turns out DataTemplates don't work too great for dynamic menus. The proper way to do this is to use the ItemContainerStyle property of MenuItem. (Or is that ItemStyleContainer?)
Simply create a style to override the header and set it to whatever you need. I them overrode the ItemsSource to include my children. However be careful here, as the children will inherit the style and each have the same children and generate a recursive menu. You'll need to override the ItemsSource of your children and set it to an empty x:Array or the likes.
There are several blogs out there describing how to use ItemContainerStyle, check them out. | arsenmrkt: I have exactly the same problem, if I populate a MenuItem using a DataTemplate I cant seem to add children to any of those generated items. I don't understand your answer though, how should I use the ContentPresenter to get around this problem?
EDIT:
Actually, my problem was'nt exactly the same, since I'm trying to bind a collection of collections to a menu. I think I've gotten it to work though using the HierarchicalDataTemplate:
```
<Menu>
<MenuItem Header="{Binding Name}" ItemsSource="{Binding MenuOptions}">
<MenuItem.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Categories}">
<MenuItem Header="{Binding Name}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<MenuItem Header="{Binding Name}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
</Menu>
```
Does this help you NicholasF? | WPF MenuItem children not showing | [
"",
"c#",
"wpf",
"datatemplate",
"menuitem",
"children",
""
] |
I've checked lots of tutorials about **including header, navigation and footer** using **php "include".** But I ended up separating my html tags. For instance, `my <div id="content">` is in "header.html" while it closing `</div>` tag is in the footer. This gives me some problem when I use jQuery and looks kinda messy. Is there a better practice to generate external content? (is jQuery the solution?)
**index.php**
```
<?php include("header.html"); ?>
<?php include("navigation.html"); ?>
<div id="content">
<h2 class="clear">This is the contact page</h2>
<p>
Main content here... Main content here... Main content here... Main content here...
Main content here... Main content here... Main content here... Main content here...
Main content here... Main content here... Main content here... Main content here...
Main content here... Main content here... Main content here... Main content here...
Main content here... Main content here... Main content here... Main content here...
Main content here... Main content here... Main content here... Main content here...
</p>
</div>
<?php include("footer.html"); ?>
```
**header.html**
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Study at Best</title>
<script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="scripts/jquery.corner.js"></script>
<script type="text/javascript" src="scripts/jquery.dropshadow.js"></script>
<script type="text/javascript" src="scripts/jqueryScripts.js"></script>
<link rel="stylesheet" rev="stylesheet" href="styles/layout.css" />
<link rel="stylesheet" rev="stylesheet" href="styles/ddm.css" />
</head>
<body>
<div id="container">
<div id="header">
This is the header
</div>
```
**footer.html**
```
<div id="footer">
<p>BEST School © Copyright 2009</p>
</div>
</div>
</body>
</html>
``` | In my personal opinion this doesn't look right. I mean simply don't do this to yourself. It will be a nightmare if the site becomes more complex. What about only putting the footer div in footer.html the same for header.html? The rest belongs in index.php. If index.php becomes to complex, split it up more (javascript.html..). – merkuro Jun 20 at 21:22 | What problem is this causing? This is a fairly standard practice (I use it), and I've never known it to create any problems. jQuery shouldn't be an issue, since no jQuery code is ran until all of the html has been joined together anyway. | What's the best way to include external content using php includes? (For web developers who love optimal practices) | [
"",
"php",
"jquery",
"include",
""
] |
Here we are again with the next problem in sorting.
this is a follow up question to [this question](https://stackoverflow.com/questions/975712/asp-net-gridview-sorting-with-linq-result)
I have now made a type to contain the data I need.
however, when I try to fetch the data FROM the gridview it returns null, which means I can't sort anything that is not there in the first place...
any ideas why this returns null ...
```
IEnumerable<JointServerData> data = gvServers.DataSource;
var sorted = data;
switch (p)
{
case "domain":
sorted = data.OrderBy(o => o.DomainName);
break;
default:
break;
}
gvServers.DataSource = sorted;
gvServers.DataBind();
```
above is what I'm trying to do ... | Without seeing all your code I'd have to assume that this is a PostBack issue. Website's are intrinsically stateless and you need to resolve this by either caching information between page requests or retrieving the data each time. | I agree with Mark. It seems that this happens between postbacks. If so, you can't have access to grid's datasource, because after first binding and rendering this grid to html, you will receice only that html on postback, but not real datasource. You need to keep your datasource either in session or get it on every postback from database.
P.S. and sorry, guys, for my ugly English :-[ | ASP.net gridview datasource null when sorting | [
"",
"c#",
"asp.net",
".net",
"linq",
"sorting",
""
] |
I have a bunch of strings extracted from html using jQuery.
They look like this:
```
var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
```
I need to extract the number values in order to calculate the price difference.
(So I wend up with ≈
```
var productPriceDiff = DKK 100";
```
or just:
`var productPriceDiff = 100";`)
Can anyone help me do this?
Thanks,
Jakob | First you need to convert the input prices from strings to numbers. Then subtract. And you'll have to convert the result back to "DKK ###,##" format. These two functions should help.
```
var priceAsFloat = function (price) {
return parseFloat(price.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,''));
}
var formatPrice = function (price) {
return 'DKK ' + price.toString().replace(/\./g,',');
}
```
Then you can do this:
```
var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
productPriceDiff = formatPrice(priceAsFloat(productBeforePrice) - priceAsFloat(productCurrentPrice));
``` | try:
```
var productCurrentPrice = productBeforePrice.replace(/[^\d.,]+/,'');
```
edit: this will get the price including numbers, commas, and periods. it does not verify that the number format is correct or that the numbers, periods, etc are contiguous. If you can be more precise in the exact number definitions you expcet, it would help. | Javascript extracting number from string | [
"",
"javascript",
"jquery",
"string",
"numbers",
"extract",
""
] |
I simply love JavaScript. It's so elegant.
So, recently I have played with Lua via the [löve2d](http://love2d.org) framework (nice!) - and I think Lua is also great. They way I see it, those two languages are *very* similar.
There are obvious differences, like
* syntax
* problem domain
* libraries
* types (a bit)
but which are the more subtle ones? Is there anything a JavaScript coder would take for granted that works in Lua just slightly different? Are there any pitfalls that may not be obvious to the experienced coder of one language trying the other one?
For example: in Lua, arrays and hashes are not separate (there are only tables) - in JavaScript, they are numerical Arrays and hashed Objects. Well, this is one of the more obvious differences.
But are there differences in variable scope, immutability or something like this? | **Some more differences:**
* *Lua* has native support for [coroutines](http://www.lua.org/manual/5.1/manual.html#2.11).
+ **UPDATE**: JS now contains the yield keyword inside generators, giving it support for coroutines.
* *Lua* [doesn't convert](http://www.lua.org/manual/5.1/manual.html#2.5.2) between types for any comparison operators. In JS, only `===` and `!==` don't type juggle.
* *Lua* has an exponentiation operator (`^`); *JS* doesn't. *JS* uses different operators, including the ternary conditional operator (`?:` vs `and/or`), and, as of 5.3, bitwise operators (`&`, `|`, etc. vs. [metamethods](https://www.lua.org/manual/5.3/manual.html#2.4) ).
+ **UPDATE**: JS now has the exponentiation operator `**`.
* *JS* has increment/decrement, type operators (`typeof` and `instanceof`), additional assignment operators and additional comparison operators.
* In *JS*, the `==`, `===`, `!=` and `!==` operators are of lower precedence than `>`, `>=`, `<`, `<=`. In Lua, all comparison operators are the [same precedence](http://www.lua.org/manual/5.1/manual.html#2.5.6).
* *Lua* supports [tail calls](http://www.lua.org/manual/5.1/manual.html#2.5.8).
+ **UPDATE**: JS now [supports tail calls](http://2ality.com/2015/06/tail-call-optimization.html).
* *Lua* supports [assignment to a list of variables](http://www.lua.org/manual/5.1/manual.html#2.4.3). While it isn't yet standard in *Javascript*, Mozilla's JS engine (and Opera's, to an extent) has supported a similar feature since JS 1.7 (available as part of Firefox 2) under the name "[destructuring assignment](https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7#Destructuring_assignment_%28Merge_into_own_page.2Fsection%29)". Destructuring in JS is more general, as it can be used in contexts other than assignment, such as [function definitions & calls](https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7#Pulling_fields_from_objects_passed_as_function_parameter) and [loop initializers](https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7#Looping_across_values_in_an_array_of_objects). [Destructuring assignment](http://wiki.ecmascript.org/doku.php?id=proposals:destructuring_assignment) has been a proposed addition to ECMAScript (the language standard behind Javascript) for awhile.
+ **UPDATE**: Destructuring (and destructuring assignment) is now part of the spec for ECMAScript - already implemented in many engines.
* In *Lua*, you can [overload operators](http://www.lua.org/manual/5.1/manual.html#2.8).
* In *Lua*, you can manipulate environments with [`getfenv` and `setfenv`](http://www.lua.org/manual/5.1/manual.html#2.9) in Lua 5.1 or `_ENV` in [Lua 5.2](https://www.lua.org/manual/5.2/manual.html) and [5.3](https://www.lua.org/manual/5.3/manual.html).
* In *JS*, all functions are variadic. In *Lua*, functions must be [explicitly declared as variadic](http://www.lua.org/manual/5.1/manual.html#2.5.9).
* `Foreach` in *JS* loops over object properties. [Foreach](http://www.lua.org/manual/5.1/manual.html#2.4.5) in *Lua* (which use the keyword `for`) loops over iterators and is more general.
+ **UPDATE**: JS has [Iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) now too, many of which are built into the regular data structures you'd expect, such as `Array`. These can be looped over with the `for...of` syntax. For regular Objects, one can implement their own iterator functions. This brings it much closer to Lua.
* JS has global and function scope. *Lua* has [global and block scope](http://www.lua.org/manual/5.1/manual.html#2.6). Control structures (e.g. `if`, `for`, `while`) introduce new [blocks](http://www.lua.org/pil/4.2.html).
+ Due to differences in scoping rules, a closure's referencing of an outer variable (called "upvalues" in Lua parlance) may be handled differently in Lua and in *Javascript*. This is most commonly experienced with [closures in `for` loops](http://flightodyssey.blogspot.com/2013/09/closure.html), and catches some people by surprise. In *Javascript*, the body of a `for` loop doesn't introduce a new scope, so any functions declared in the loop body all reference the [same outer variables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake). In Lua, each iteration of the `for` loop creates new local variables for each loop variable.
```
local i='foo'
for i=1,10 do
-- "i" here is not the local "i" declared above
...
end
print(i) -- prints 'foo'
```
The above code is equivalent to:
```
local i='foo'
do
local _i=1
while _i<10 do
local i=_i
...
_i=_i+1
end
end
print(i)
```
As a consequence, functions defined in separate iterations have different upvalues for each referenced loop variable. See also Nicolas Bola's answers to [Implementation of closures in Lua?](https://stackoverflow.com/a/7781507/90527) and "[What are the correct semantics of a closure over a loop variable?](https://stackoverflow.com/a/14331073/90527)", and "[The Semantics of the Generic for](http://www.lua.org/pil/7.2.html)".
**UPDATE**: JS has block scope now. Variables defined with `let` or `const` respect block scope.
* Integer literals in *JS* can be in octal.
* *JS* has explicit Unicode support, and internally strings are encoded in [UTF-16](https://en.wikipedia.org/wiki/UTF-16) (so they are sequences of pairs of bytes). Various built-in JavaScript functions use Unicode data, such as `"pâté".toUpperCase()` (`"PÂTÉ"`). *Lua 5.3* and up have Unicode code point escape sequences in string literals (with the same syntax as JavaScript code point escape sequences) as well as the built-in `utf8` library, which provides basic support for the [UTF-8 encoding](https://en.wikipedia.org/wiki/UTF-8) (such as encoding code points into UTF-8 and decoding UTF-8 into code points, getting the number of code points in a string, and iterating over code points). Strings in Lua are sequences of individual bytes and can contain text in any encoding or arbitrary binary data. Lua does not have any built-in functions that use Unicode data; the behavior of `string.upper` depends on the C locale.
* In *Lua*, the `not`, `or`, `and` keywords are used in place of *JS*'s `!`, `||`, `&&`.
* *Lua* uses `~=` for "not equal", whereas *JS* uses `!==`. For example, `if foo ~= 20 then ... end`.
* *Lua 5.3* and up use `~` for binary bitwise XOR, whereas *JS* uses `^`.
* In *Lua*, any type of value (except `nil` and `NaN`) can be used to index a table. In *JavaScript*, all non-string types (except Symbol) are converted to strings before being used to index an object. For example, after evaluation of the following code, the value of `obj[1]` will be `"string one"` in JavaScript, but `"number one"` in Lua: `obj = {}; obj[1] = "number one"; obj["1"] = "string one";`.
* In *JS*, assignments are treated as expressions, but in *Lua* they are not. Thus, JS allows assignments in conditions of `if`, `while`, and `do while` statements, but Lua does not in `if`, `while`, and `repeat until` statements. For example, `if (x = 'a') {}` is valid JS, but `if x = 'a' do end` is invalid Lua.
* *Lua* has syntactic sugar for declaring block-scoped function variables, functions that are fields, and methods (`local function() end`, `function t.fieldname() end`, `function t:methodname() end`). *JS* declares these with an equals sign (`let funcname = function optionalFuncname() {}`, `objectname.fieldname = function () {}`). | A couple of subtle differences that will catch you out at least once:
* Not equal is spelled `~=` in Lua. In JS it is `!=`
* Lua [arrays are 1-based](http://en.wikipedia.org/wiki/Lua_(programming_language)#As_array) - their first index is 1 rather than 0.
* Lua requires a colon rather than a period to call object methods. You write `a:foo()` instead of `a.foo()` †
† you can use a period if you want, but have to pass the `self` variable explicitly. `a.foo(a)` looks a bit cumbersome. See [Programming in Lua](http://www.lua.org/pil/16.1.html) for details. | subtle differences between JavaScript and Lua | [
"",
"javascript",
"lua",
""
] |
I have over a thousand folders, each folder contains one or more files with the following names:
Unordered:
```
Alison.ext
Heather.ext
Molly.ext
Paula.ext
Sam.ext
```
Ordered:
```
Molly.ext
Sam.ext
Heather.ext
Alison.ext
Paula.ext
```
I would like to write an expression to sort this list as described above. | ```
//Creating a dictionary with the custom order
var order = "MSHAP";
var orderDict = order.Select((c,i)=>new {Letter=c, Order=i})
.ToDictionary(o => o.Letter, o => o.Order);
var list = new List<string>{"A.ext", "H.ext", "M.ext", "P.ext", "S.ext"};
//Ordering by the custom criteria
var result = list.OrderBy(item => orderDict[item[0]]);
```
Instead of calling orderDict[item[0]] you could have a nice helper method that cares for the fringe cases (non existent letters, null, and so on). But that's the idea. | Here's a method that produces keys for ordering
```
public int OrderKey(string fileName)
{
char first = fileName[0];
int result =
first == 'M' ? 1 :
first == 'S' ? 2 :
first == 'H' ? 3 :
first == 'A' ? 4 :
first == 'P' ? 5 :
6;
return result;
}
```
Here's how to call it:
```
List<File> ordered = Files.OrderBy(f => OrderKey(f.FileName)).ToList();
``` | Custom Linq Ordering | [
"",
"c#",
"linq",
"c#-3.0",
""
] |
I have a situation where some of my groovy code references my java files, but I also have different java files that reference the same groovy code. When trying to compile in maven, I either need to compile the groovy before or after the java, and that won't really work since the groovy code depends on some java files, and different java files depend on the groovy code. Is there a way to handle this sort of dependency? | You should be able to compile your code by adding the [gmaven](http://groovy.codehaus.org/GMaven) plugin to your maven pom.xml. It generates Java stubs of your groovy code to deal with the type of inter-language referencing you're dealing with. I use it quite a bit and it works very well. | Yes, just use [GMaven](https://groovy.github.io/gmaven/). Since it's a joint compiler, it automatically manages your java to groovy and groovy to java dependencies.
Briefly, you will need to:
* include the `gmaven-plugin` in your `pom.xml`;
* keep your groovy classes under `src/main/groovy` or `src/test/groovy`;
* bind the gmaven plugin to the relevant lifecycle phases.
For more details see chapter [Maven Integration](https://docs.groovy-lang.org/latest/html/documentation/tools-groovyc.html#_maven_integration) on the groovy homepage. | maven compile groovy | [
"",
"java",
"maven-2",
"groovy",
"dependencies",
"gmaven-plugin",
""
] |
I have this line of code in MATLAB, written by someone else:
```
c=a.'/b
```
I need to translate it into Python. a, b, and c are all arrays. The dimensions that I am currently using to test the code are:
a: 18x1,
b: 25x18,
which gives me c with dimensions 1x25.
The arrays are not square, but I would not want the code to fail if they were. Can someone explain exactly what this line is doing (mathematically), and how to do it in Python? (i.e., the equivalent for the built-in mrdivide function in MATLAB if it exists in Python?) | The line
```
c = a.' / b
```
computes the solution of the equation *c b = aT* for *c*. Numpy does not have an operator that does this directly. Instead you should solve *bT cT = a* for *cT* and transpose the result:
```
c = numpy.linalg.lstsq(b.T, a.T)[0].T
``` | The symbol `/` is the matrix right division operator in MATLAB, which calls the [`mrdivide`](https://www.mathworks.com/help/matlab/ref/mrdivide.html) function. From the documentation, matrix right division is related to [matrix left division](https://www.mathworks.com/help/matlab/ref/mldivide.html) in the following way:
```
B/A = (A'\B')'
```
If `A` is a square matrix, `B/A` is roughly equal to `B*inv(A)` (although it's computed in a different, more robust way). Otherwise, `x = B/A` is the solution in the least squares sense to the under- or over-determined system of equations `x*A = B`. More detail about the algorithms used for solving the system of equations is given [here](https://www.mathworks.com/help/matlab/ref/mldivide.html#bt4jslc-6). Typically packages like [LAPACK](https://en.wikipedia.org/wiki/LAPACK) or [BLAS](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms) are used under the hood.
The [NumPy package](https://numpy.org/) for Python contains a routine [`lstsq`](https://numpy.org/doc/stable/reference/generated/numpy.linalg.lstsq.html#numpy.linalg.lstsq) for computing the least-squares solution to a system of equations. This routine will likely give you comparable results to using the `mrdivide` function in MATLAB, but it is unlikely to be *exact*. Any differences in the underlying algorithms used by each function will likely result in answers that differ slightly from one another (i.e. one may return a value of 1.0, whereas the other may return a value of 0.999). The relative size of this error *could* end up being larger, depending heavily on the specific system of equations you are solving.
To use `lstsq`, you may have to adjust your problem slightly. It appears that you want to solve an equation of the form **cB = a**, where **B** is 25-by-18, **a** is 1-by-18, and **c** is 1-by-25. Applying a [transpose](https://en.wikipedia.org/wiki/Transpose) to both sides gives you the equation **BTcT = aT**, which is a more standard form (i.e. **Ax = b**). The arguments to `lstsq` should be (in this order) **BT** (an 18-by-25 array) and **aT** (an 18-element array). `lstsq` should return a 25-element array (**cT**).
*Note: while NumPy doesn't make any distinction between a 1-by-N or N-by-1 array, MATLAB certainly does, and will yell at you if you don't use the proper one.* | Array division- translating from MATLAB to Python | [
"",
"python",
"matlab",
"numpy",
"linear-algebra",
""
] |
I am writing an application in GWT and I need to detect when a user navigates away from my application or when he closes the browser window (onUnload event) and do a logout (session invalidation and few other cleanup tasks). The logout action is performed by a servlet.
I am currently doing this by hooking into the onUnload() event and opening a new window pointed to the logout servlet.
Is there a better way to do this? Any other suggestions are welcome. | Looks like GWT does have an event for exactly this.
[ClosingEvent](http://google-web-toolkit.googlecode.com/svn/javadoc/1.6/com/google/gwt/user/client/Window.ClosingEvent.html).
Looks like you need to implement a [ClosingHandler](http://google-web-toolkit.googlecode.com/svn/javadoc/1.6/com/google/gwt/user/client/Window.ClosingHandler.html "ClosingHandler") | Why not just make a very short lived session cookie that is reset with each page load, then add a tracking cookie. When the user returns you notice the tracking cookie but no session cookie. Expire the session and clear everything up at that point.
Pop up blockers will prevent your session clean up when it blocks the onUnload window open, because this is something spammers use. | Best way to detect browser closing/navigation to other page and do logout | [
"",
"javascript",
"gwt",
"logout",
"onunload",
""
] |
```
uid timestamp
1 1242420497
1 1243534661
1 1243534858
1 1243611312
1 1243611511
3 1244817764
3 1244819093
1 1244749446
```
I have this table, and I am lookng to grab the row that has the highest time stamp.
I tried using
```
SELECT uid,max(timestamp) FROM `node_revisions` WHERE nid=51
```
but that returned
```
uid timestamp
1 1244819093
```
which has the wrong uid as you can see. How would I make it grab the uid from the correct row? thanks | ```
SELECT uid, timestamp
FROM node_revisions
WHERE timestamp = (SELECT MAX(timestamp) FROM node_revisions);
```
**Updated** per Ryan Oberoi's comment; since we're getting just the one record, MAX() in the outer query is unnecessary. Thanks. | You're missing the GROUP BY clause.
```
SELECT
uid,
max(timestamp) as max_time
FROM
node_revisions
WHERE
nid = 51
GROUP BY
uid
ORDER BY
max_time DESC
LIMIT 1
``` | SQL MAX() question | [
"",
"sql",
"max",
""
] |
I am building a website and need to use a CMS.
If I use an already made CMS, I need to be able to extend it easily.
Is there a specific CMS that you recommend or should I make my own? | [OpenSourceCMS](http://php.opensourcecms.com/scripts/show.php?catid=1&cat=CMS%20/%20Portals) is an excellent place to start. They offer demos, user rankings, etc. of many different CMS systems.
You can also find relevant questions here on stackoverflow by searching for "php cms".
Personally, I like [Drupal](http://www.drupal.org), [MODx](http://www.modxcms.com) and [Concrete5](http://www.concrete5.com). Drupal and MODx because of their extensibility, Concrete5 because of its simplicity. | I have found [SilverStripe](http://www.silverstripe.com/) to be quite useful, used it on an intranet project - built in authorization, nice content editing built in, easy templating language, workflow, content versioning. I also like that they have good documentation and [Help](http://help.silverstripe.com/). The [Demo](http://demo.silverstripe.com/) is also impressive. | Which PHP CMS do you recommend for a website? | [
"",
"php",
"content-management-system",
""
] |
I am pretty new to jruby and java and want to create a servlet in jruby while using jetty as web server. I am not sure if I am on the right way with the following code which shows the input form so far. I guess I have to extend now the HttpServlet class to handle the posted data but I don't know how to do this in this case and if it is okay to do this in the same script.
```
require 'java'
Dir["./jetty-6.1.18/lib/*jar"].each { |jar| require jar }
Dir["./Java/lib/jsdk2.1/javax/*jar"].each { |jar| require jar }
include_class 'javax.servlet.ServletException'
include_class 'javax.servlet.http.HttpServlet'
include_class 'javax.servlet.http.HttpServletRequest'
include_class 'javax.servlet.http.HttpServletResponse'
include_class 'org.mortbay.jetty.Server'
include_class 'org.mortbay.jetty.handler.AbstractHandler'
include_class 'org.mortbay.jetty.servlet.Context'
include_class 'org.mortbay.jetty.servlet.ServletHolder'
def main
handler = Handler.new
server = Server.new(8080)
server.setHandler(handler)
server.start()
end
class Handler < AbstractHandler
def handle(target, request, response, dispatch)
response.setContentType("text/html")
response.setStatus(HttpServletResponse::SC_OK)
response.getWriter().print('
<form action="RequestProcessing" method="post" enctype="multipart/form-data">
<p>Select a file:<br>
<input name="file" type="file" size="20" maxlength="1000" accept="text/*">
</p>
<input type="submit" value=" Send"/>
</form>')
request.setHandled(true)
end
end
class RequestProcessing < HttpServlet
# So what do we do here?
end
main
```
I would be thankful for any hints. Many thanks in advance! | I got some external help and can present a proper solution. To offer a complete but simple set-up I use a html file for the data input (but this could be done in jetty as done above).
```
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Data input</title>
</head>
<body>
<form action="http://localhost:8080/" method="post">
<textarea name="input" cols="4" rows="20"></textarea>
</p>
<input type="submit" value=" Send"/>
</form>
</body>
</html>
```
The jruby part is confusingly simple ;):
```
require 'java'
Dir["./Java/jetty-6.1.18/lib/*.jar"].each { |jar| require jar }
Dir["./Java/lib/jsdk2.1/javax/*.jar"].each { |jar| require jar }
include_class 'javax.servlet.http.HttpServlet'
include_class 'org.mortbay.jetty.Server'
include_class 'org.mortbay.jetty.servlet.Context'
include_class 'org.mortbay.jetty.servlet.ServletHolder'
def main
server = Server.new(8080)
context = Context.new(server, '/', 0)
servlet = TestServlet.new()
holder = ServletHolder.new(servlet)
context.addServlet(holder, '/')
server.start()
end
class TestServlet < HttpServlet
def doPost(request, response)
input = request.getParameter('input')
response.writer.println("
<html>
<head><title>Output</title></head>
<body>
Raw input: <pre>#{input}</pre>
</body>
</html>")
request.handled = true
end
end
main
```
To harvest data that was sent via GET simply define doGet in similar manner. | I know this isn't really an answer to your question, but in (J)Ruby-land we tend to use mongrel or webrick instead of jetty.
<http://mongrel.rubyforge.org/web/mongrel/files/README.html>
<http://www.webrick.org/> | How can I create a servlet with jruby (running with jetty)? | [
"",
"java",
"servlets",
"jetty",
"jruby",
""
] |
How to write this query using the find statement in cakephp
```
$this->Form->query("Select id from forms order by id DESC LIMIT 1")
``` | This should do it:
```
$this->Form->find('all', array(
'fields' => array('Form.id'),
'order' => 'Form.id DESC',
'limit' => 1
));
``` | I agree with the first response here,
2 things I would like to mention
I assume you have a model called Form,Now Cakephp has its own FormHelper and sometimes there maybe a conflict of names, I got this error when I had created a FilesController in my project,
Also you will get an array back which will be of the form
```
$result['Form] => array(
[id] => 1
[name] => whatever)
```
and so on, you can easily use this to get whatever data you want. | What is the correct way to write a find() statement in CakePHP given a simple select query with ORDER and LIMIT? | [
"",
"php",
"cakephp",
""
] |
Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?
I come to believe that general bugginess of \_why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.
RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.
Generally — what is the current fad?
BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python. | I don't know about ruby2exe, but py2exe works perfeclty fine. Even with librairies like wxWidgets. **Edit**: you don't even have to ask the user to install wxWidgets, it's bundled with the app (same goes for py2app)
I use it for my very small project [here](http://github.com/loicwolff/notagapp/).
For the Mac crowd, py2app works fine too with wxWidgets. | For Ruby, the [One-Click Ruby Application Builder](http://rubyforge.org/projects/ocra/) (OCRA) is emerging as the successor to [RubyScript2Exe](http://www.erikveen.dds.nl/rubyscript2exe/).
Ocra works with both Ruby 1.8.6 and 1.9.1, and with wxRuby. Supports LZMA compression for relatively compact executables. | Distributing Ruby/Python desktop apps | [
"",
"python",
"ruby",
"user-interface",
"desktop",
"software-distribution",
""
] |
Apparently this function in SDL\_Mixer keeps dying, and I'm not sure why. Does anyone have any ideas? According to visual studio, the crash is caused by Windows triggering a breakpoint somewhere in the realloc() line.
The code in question is from the SVN version of SDL\_Mixer specifically, if that makes a difference.
```
static void add_music_decoder(const char *decoder)
{
void *ptr = realloc(music_decoders, num_decoders * sizeof (const char **));
if (ptr == NULL) {
return; /* oh well, go on without it. */
}
music_decoders = (const char **) ptr;
music_decoders[num_decoders++] = decoder;
}
```
I'm using Visual Studio 2008, and music\_decoders and num\_decoders are both correct (music\_decoders contains one pointer, to the string "WAVE", and music\_decoders. ptr is 0x00000000, and the best I can tell, the crash seems to be in the realloc() function. Does anyone have any idea how I could handle this crash problem? I don't mind having to do a bit of refactoring in order to make this work, if it comes down to that. | For one thing, it's not valid to allocate an array of `num_decoders` pointers, and then write to index `num_decoders` in that array. Presumably the first time this function was called, it allocated 0 bytes and wrote a pointer to the result. This could have corrupted the memory allocator's structures, resulting in a crash/breakpoint when `realloc` is called.
Btw, if you report the bug, note that `add_chunk_decoder` (in mixer.c) is broken in the same way.
I'd replace
```
void *ptr = realloc(music_decoders, num_decoders * sizeof (const char **));
```
with
```
void *ptr = realloc(music_decoders, (num_decoders + 1) * sizeof(*music_decoders));
``` | Make sure that the SDL\_Mixer.DLL file and your program build are using the same C Runtime settings. It's possible that the memory is allocated using one CRT, and realloc'ed using another CRT.
In the project settings, look for C/C++ -> Code Generation. The Runtime Library setting there should be the same for both. | realloc crashing in previously stable function | [
"",
"c++",
"windows",
"visual-studio-2008",
"breakpoints",
"realloc",
""
] |
After the onsubmit event has fired and the form has been submitted (via an action="mailto:yournamehere@somebox.com") , is there a way to then clear the form, close the window or what? Is there a post submit that I can hook into via JavaScript. This must be a client side only solution. | ```
function submit_form() {
document.formu1.submit();
document.formu1.reset();
}
```
```
<form name="formu1" action="action-page" method="POST" target="_blank" />
Name: <input type="text" name="name" /><br /><br />
Pass: <input type="password" name="pass" /><br /><br />
<input type="button" value="Send" onclick="submit_form();" />
</form>
``` | A quick and easy solution:
```
<form action="mailto:email@email.com"
onsubmit="this.submit(); this.reset(); return false;">
``` | How do you clear a plain HTML form after onsubmit? | [
"",
"javascript",
"html",
""
] |
How to define `operator<` on n-tuple (for example on 3-tuple) so that it satisfy **strict weak ordering** concept ? I know that boost library has tuple class with correctly defined `operator<` but for some reasons I can't use it. | ```
if (a1 < b1)
return true;
if (b1 < a1)
return false;
// a1==b1: continue with element 2
if (a2 < b2)
return true;
if (b2 < a2)
return false;
// a2 == b2: continue with element 3
if (a3 < b3)
return true;
return false; // early out
```
This orders the elements by a1 being most siginificant and a3 least significant.
This can be continued ad infinitum, you could also e.g. apply it to a vector of T, iterating over comparisons of a[i] < a[i+1] / a[i+1] < a[i]. An alternate expression of the algorithm would be "skip while equal, then compare":
```
while (i<count-1 && !(a[i] < a[i+1]) && !(a[i+1] < a[i])
++i;
return i < count-1 && a[i] < a[i+1];
```
Of course, if the comparison is expensive, you might want to cache the comparison result.
---
[edit] removed wrong code
---
[edit] if more than just `operator<` is available, I tend to use the pattern
```
if (a1 != b1)
return a1 < b1;
if (a2 != b2)
return a2 < b2;
...
``` | ### strict weak ordering
This is a mathematical term to define a relationship between two objects.
Its definition is:
> Two objects x and y are equivalent if both f(x, y) and f(y, x) are false. Note that an object is always (by the irreflexivity invariant) equivalent to itself.
In terms of C++ this means if you have two objects of a given type, you should return the following values when compared with the operator <.
```
X a;
X b;
Condition: Test: Result
a is equivalent to b: a < b false
a is equivalent to b b < a false
a is less than b a < b true
a is less than b b < a false
b is less than a a < b false
b is less than a b < a true
```
How you define equivalent/less is totally dependent on the type of your object.
Formal Definition:
[Strict Weak ordering](https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings)
Computer Science:
[Strict Weak Ordering](https://math.stackexchange.com/q/585396/15311)
How it relates to operators:
[Comparator](https://en.cppreference.com/w/cpp/named_req/Compare)
---
As a side note we can implement strict weak ordering manually. But we can do it simply using the `std::tuple` which has implemented it for you. You simply need to create a tuple without copying the objects.
```
struct S
{
ThingA a;
ThingB b;
};
bool operator<(S const& lhs, S const& rhs)
{
return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b);
}
```
Note: This assumes that `thingA` and `thingB` already implement strict weak ordering themselves.
We can also implement equality the same way:
```
bool operator==(S const& lhs, S const& rhs)
{
return std::tie(lhs.a, lhs.b) == std::tie(rhs.a, rhs.b);
}
```
Note again: This assumes that `thingA` and `thingB` already implement equality. | How to define operator< on an n-tuple that satisfies a strict weak ordering | [
"",
"c++",
"tuples",
"operator-overloading",
"strict-weak-ordering",
""
] |
i have interface:
```
public interface Inx<T>
{
T Set(Data data);
}
```
simple class with this metod
```
public class Base
{
??? Set(Data data) { ... }
}
```
and parent class like that:
```
public class Parent : Base, Inx<Parent>
{
...
}
```
i want to return Parent type from Set metod in child class
It's possible ?
I need it do to something like that:
```
list.Add(new Parent().Set(data));
```
Now i have to do that:
```
T t = new T();
t.Set(data);
list.Add(t);
```
And its little annoying, i have to use it many time
---
Sorry for spaming well hmm i can use something like that:
```
this.GetType().GetConstructor(new System.Type[] { typeof(Data) }).Invoke(new object[] { data })
```
so maybe good soluction is return a object from this method ;\ ?
well generic class with generic interface seem's be big memory waste ... beacose function of this class are same only return type is diffrent | Is this what you want?
```
interface Inx<T> {
T Set(Data data);
}
public class Base
{
public virtual T Set<T>(Data data)
{
T t = default(T);
return t;
}
}
public class Parent : Base, Inx<Parent>
{
public Parent Set(Data data)
{
return base.Set<Parent>(data);
}
}
class Program
{
static void Main(string[] args)
{
var data = new Data();
var list = new List<Parent>();
list.Add(new Parent().Set<Parent>(data));
// or
list.Add(new Parent().Set(data));
}
}
```
EDIT: It's better to move the interface implementation up to the Base class as Marc said:
```
interface Inx<T> {
T Set(Data data);
}
public class Base<T> : Inx<T>
{
public virtual T Set(Data data)
{
T t = default(T);
return t;
}
}
public class Parent : Base<Parent>
{
}
class Program
{
static void Main(string[] args)
{
var data = new Data();
var list = new List<Parent>();
list.Add(new Parent().Set(data));
}
}
``` | The only way you could do that would be to make the `Base` generic (`Base<T>`) and have `Set` return `T` - then have `Parent : Base<Parent>`. The problem is... how would `Set` know how to create the `T`? You could have the `where T : new()` clause...
A useful aside here is that you can move the interface implementation into `Base<T>`:
```
public class Base<T> : Inx<T> where T : new()
{
public T Set(Data data) {
T t = new T();
///
return t;
}
}
public class Parent : Base<Parent> { }
``` | C# child class returning a unknown type (futher: from parent) | [
"",
"c#",
"types",
"return",
"parent",
""
] |
I'm trying to link to a shared library with a template class, but it is giving me "undefined symbols" errors. I've condensed the problem to about 20 lines of code.
**shared.h**
```
template <class Type> class myclass {
Type x;
public:
myclass() { x=0; }
void setx(Type y);
Type getx();
};
```
**shared.cpp**
```
#include "shared.h"
template <class Type> void myclass<Type>::setx(Type y) { x = y; }
template <class Type> Type myclass<Type>::getx() { return x; }
```
**main.cpp**
```
#include <iostream>
#include "shared.h"
using namespace std;
int main(int argc, char *argv[]) {
myclass<int> m;
cout << m.getx() << endl;
m.setx(10);
cout << m.getx() << endl;
return 0;
}
```
This is how I compile the library:
```
g++ -fPIC -c shared.cpp -o shared.o
g++ -dynamiclib -Wl,-dylib_install_name -Wl,libshared.dylib -o libshared.dylib shared.o
```
And the main program:
```
g++ -c main.cpp
g++ -o main main.o -L. -lshared
```
Only to get the following errors:
```
Undefined symbols:
"myclass<int>::getx()", referenced from:
_main in main.o
_main in main.o
"myclass<int>::setx(int)", referenced from:
_main in main.o
```
If I remove the 'template' stuff in `shared.h/cpp`, and replace them with just 'int', everything works fine. Also, if I just copy&paste the template class code right into `main.cpp`, and don't link to the shared library, everything works as well.
How can I get a template class like this to work through a shared library?
I'm using MacOS 10.5 with GCC 4.0.1. | In addition to the other answers, you can explicitly instantiate template classes. This is only useful if you know beforehand what types the template parameters may assume. You instantiate the template with all these types in the library.
For your example to compile, just add the following to the end of **shared.cpp**:
```
// Instantiate myclass for the supported template type parameters
template class myclass<int>;
template class myclass<long>;
```
This instantiates the template with Type=int and places the instantiated code in the shared library. Add as many explicit instantiations as you need, for all the types you need.
Again, if you want to be able to instantiate the template with any arbitrary Type parameter, then you **must** add the definitions to the header file, so that the compiler knows the source code of the template when instantiating it in other compilation units. | Template function definitions must reside in header files. Move the definitions from shared.cpp to shared.h.
So, you can't compile this to a shared library and then link to it. It just doesn't work like that. | C++ Shared Library with Templates: Undefined symbols error | [
"",
"c++",
"templates",
"gcc",
"class",
"linker",
""
] |
What are the best practices for keeping referential integrity across multiple databases? since there's no built-in functions
Or is it better to partition a single database?
**Update**
See kevin's example below.
that is my situation. My inventory database has tables that reference the employeeId in the employees database.
These databases are currently maintained at different locations (Different servers) | With 2k05/2k08 it's definitely better to partition a single database. You have all the benefits of storing data like it is in multiple databases while being able to use the functions of a single database, like foreign keys.
That being said, you shouldn't keep everything in a single database. Logically when groups tables don't fit together, I normally separate them into their own databases. For example, I wouldn't necessarily combine place an orders system database and the employee management database together. I suppose there could be reasons to do so, but I am sure you get my point of logically separating data stores where appropriate.
What you should look at is how much the two databases interact. If there are lots of fields which would join across databases, then I would say that it is probably a good idea. If it's maybe one or two fields linking to the employee table, then it might not be worth doing. Your other option is, if the number of joins are small, is to duplicate the necessary tables into the inventory database, especially if it is one table and the two existing databases are large and rather complex. | Definitely better to partitition to a single DB. If you needed to do it triggers would help (yuck). Can't you just partition the DB by using schemas instead (the AdventureWorks sample DB is an example)? | Keeping referential integrity across multiple databases | [
"",
"sql",
"sql-server",
"database-design",
""
] |
Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this. | When you edit a QMainWindow you can right click the window and then choose "create menu bar".
Or are you talking about a "context menu" aka "right click menu"? | I have a single main window with a QGraphicsView and lots of QGraphicsItem objects. Each type of the Items have a different context menu.
I find that not being able to create the contextMenu's, or at least the actions that are in them a serious limitation of QtDesigner. It means that I can create about 10% or so of the actions using the designer, and I have to create 90% programaticaly. Compare that with the Microsoft resource editor which allows all of these things to be created, and maintained effortlessly.
I hope this will be addressed at some point. | how can I add a QMenu and QMenuItems to a window from Qt Designer | [
"",
"python",
"qt",
"widget",
"designer",
""
] |
What does this mean? I am returning a `IList<T>` from my business layer and then adding items from the UI, but the app is complaining that it's a fixed-size list. How can I overcome this problem? | Could you just create a new list? IE:
```
List<myObject> foo = new List<myObject>(someClass.getReadOnlyList(...))
```
If you've got to get the list *back* to the business logic, check to make sure there's not some other `add()` functionality (`insert`, `add`, `append`, `prepend`, etc). Some classes don't allow you to directly modify their internal collections as they prefer to do some sanity checking first, or perform some other type of working with the new data that might not should be exposed to the consumer. | As far as I know you can't tell programmatically whether or not you'll be able to add to a writable list. On the other hand, the most common example is probably `Array` - so you could always try:
```
if (list is Array)
{
// Copy to another list or whatever
}
```
Low-tech as it seems, I'd just indicate in the business layer the properties of the list you'll be returning - whether it'll be writable or not, etc. Or just *assume* that it won't be writable, and create a new list in the UI anyway. | IList implementations fall into three categories: read-only, fixed-size, variable-size | [
"",
"c#",
"generics",
"list",
""
] |
Is it OK to have a table with just one column?
I know it isn't illegal.
Examples:
* You have a table with the 50 valid US state codes, but you have no need to store the verbose state names.
* An email blacklist.
Someone mentioned adding a key field. But the single column would be the primary key. | Yes, it's certainly good design to design a table in such a way as to make it most efficient. "Bad RDBMS Design" is usually centered around inefficiency.
However, I have found that most cases of single column design could benefit from an additional column. For example, State Codes can typically have the Full State name spelled out in a second column. Or a blacklist can have notes associated. But, if your design really does not need that information, then it's perfectly ok to have the single column. | In terms of `relational algebra` this would be a unary relation, meaning "*this thing exists*"
Yes, it's fine to have a table defining such a relation: for instance, to define a domain.
The values of such a table should be natural primary keys of course.
A lookup table of `prime numbers` is what comes to my mind first. | Is a one column table good design? | [
"",
"sql",
"database-design",
""
] |
I have some code like this to take over the space bar's function:
```
$(document).keypress(function (e) {
e.preventDefault();
if (e.which == 32) {
// func
}
});
```
Unfortunately this destroys all key's defaults.
This:
```
$(document).keypress(function (e) {
if (e.which == 32) {
e.preventDefault();
// func
}
});
```
Is unfortunately ineffective.
How can I make it preventDefault of only spacebar?
Thanks. | Try this:
```
//e= e || window.event); you may need this statement to make sure IE doesn't keep the orginal event in motion
var code;
if (e.keyCode) {
code = e.keyCode;
} else if (e.which) {
code = e.which;
}
if (code == 32) {
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
``` | For some above things like the use of $ might be confusing a bit. So I am posting my answer with javascript code. Add this in any file to block spacebar (or you can also add other actions) .
```
window.onkeydown = function (event) {
if (event.keyCode === 32) {
event.preventDefault();
}
};
```
Keycode 32 is the spacebar. For other keycodes, check this site:
<http://www.javascripter.net/faq/keycodes.htm>
Good luck | Using prevent default to take over spacebar | [
"",
"javascript",
"jquery",
""
] |
I'm just starting out on Android and Java programming, coming in from a C++ background. I was wondering - whats the best way to go about making a library/UI widget/component that I can license to third-party developers?
In C++ I'd ship the customers my headers and \*.a files, but I don't know the equivalent in Java.
Are there any good resources or links about this, maybe even from general Java development standpoint. | Not sure about how Android handles this, but the typical distribution of Java code is a .jar file. A .jar is basically a zip file containing all of the compiled .class files in a Java project. There might also be resource/text/etc. files within the .jar. There is no concept of a header file in Java, so all you need are the .class files, and possibly a manifest file to provide some additional meta info about the .jar.
<http://java.sun.com/docs/books/tutorial/deployment/jar/>
(This is just a general Java answer, it may or may not apply to Android) | you can define activities/services that are available for any other application running on android:
"A central feature of Android is that one application can make use of elements of other applications (provided those applications permit it). For example, if your application needs to display a scrolling list of images and another application has developed a suitable scroller and made it available to others, you can call upon that scroller to do the work, rather than develop your own. "
<http://developer.android.com/guide/topics/fundamentals.html> | Making a redistributable component or library for Android | [
"",
"java",
"android",
""
] |
I'm using the Windows Event Log to record some events. Events within the Windows Event Log can be assigned a handful of properties. One of which, is an EventID.
Now I want to use the EventId to try and group related errors. I could just pick a number for each call to the logging method I do, but that seems a little tedious.
I want the system to do this automatically. It would choose an eventId that is "unique" to the position in the code where the logging event occurred. Now, there's only 65536 unique event IDs, so there are likely to be collisions but they should be rare enough to make the EventId a useful way to group errors.
One strategy would be to take the hashcode of the stacktrace but that would mean that the first and second calls in the following code would have generate the same event ID.
```
public void TestLog()
{
LogSomething("Moo");
// Do some stuff and then a 100 lines later..
LogSomething("Moo");
}
```
I thought of walking up the call stack using the StackFrame class which has a GetFileLineNumber method. The problem with this strategy is that it will only work when built with debug symbols on. I need it to work in production code too.
Does anyone have any ideas? | The IL offset number is available without debug symbols. Combined with the stack information and hashed, I think that would do the trick.
Here's an article that, in part, covers retrieving the IL offset (for the purpose of logging it for an offline match to PDB files--different problem but I think it'll show you what you need):
<http://timstall.dotnetdevelopersjournal.com/getting_file_and_line_numbers_without_deploying_the_pdb_file.htm> | Here is some code you can use to generate an EventID with the properties I describe in my question:
```
public static int GenerateEventId()
{
StackTrace trace = new StackTrace();
StringBuilder builder = new StringBuilder();
builder.Append(Environment.StackTrace);
foreach (StackFrame frame in trace.GetFrames())
{
builder.Append(frame.GetILOffset());
builder.Append(",");
}
return builder.ToString().GetHashCode() & 0xFFFF;
}
```
The frame.GetILOffset() method call gives the position within that particular frame at the time of execution.
I concatenate these offsets with the entire stacktrace to give a unique string for the current position within the program.
Finally, since there are only 65536 unique event IDs I logical AND the hashcode against 0xFFFF to extract least significant 16-bits. This value then becomes the EventId. | Unique EventId generation | [
"",
"c#",
"logging",
"event-log",
""
] |
**Background info:**
I have a function that when called creates select list inside a form and populates it. After that the script runs through the options in the list and looks for a certain value. If the value is there, the script 'selects' that option.
**Problem:**
Because the list is dynamically created and is some times very large, it takes a while to load. When this happens, the second part of the script (the part that selects an option), does not do anything because the select list has not had time to load.
**Idea for a solution:**
What would be nice is to call the second part of the function (as a separate function) in an `onload` event for the select list. But select lists are not supposed to have an `onload` attribute. The other idea is to simply add a delay, but one day the delay may not be long enough. | Ok, I have finally fixed the issue. The solution was completely different than what was discussed here. Basically, I was using 'new Option(value, text)' to add options to my list. I ended up throwing in a if statement and when a value equal what I needed is used new Option(value, text, true). and that solved the problem. All in a day's work. | How are you doing your AJAX call? Most AJAX libraries will provide the mechanism to do a callback on successful completion. For example in jQuery:
```
$("#myList").load("ajax.url", function(){
//your content has been loaded, so you can do your selection logic here
});
```
If you're handling the ajax response manually & building your list in javascript, then you're already have code that knows when the list is finished, so you can just do the selection part once that has finished rather than as a separate function (like as zyeming has suggested).
If that doesn't help you, it might be worth posting some code so people can give you a more specific answer. | Script needs to wait for an element to load | [
"",
"javascript",
"select",
"dom-events",
"delay",
""
] |
I'm needing a fast method to read and store objects with pointers and pointers to pointers in xml files in c++ . Every object has it's own id , name , and class type. | You should build a map of pointers to IDs as you serialise your data. | You can't do it for pointers, you'll need to define some other method of identifying objects - like GUIDs or some other unique identifiers. In many cases you can just store the objects themselves instead of pointers. | Fast method to read and store serialized objects with pointers and pointers to pointers in C++ | [
"",
"c++",
"pointers",
"object",
""
] |
I am a fresh graduate with a bachelor in Computer Science. As most school today, they are no longer teaching students C or advance C++ (only an Introductory course in C++... With lessons up to Pointers). The standard programming language prescribed in the curriculum is C# (.NET stack).
Just recently, I got hired as a junior software developer. 95% of our codebase is in C++ and our products are using COM/DCOM. The other 5% is in .NET. My current responsibility is to maintain a project written in .NET (ASP.NET) and I am not required to study C++ and other technology YET. But I want to learn COM as soon as possible so I can help out on other projects.
So I am seeking the advice of this community on how I can go about learning COM. My current questions are the following:
1. Any required reading? (Pre-requisite topics)
2. A Good Site in Learning the basics of COM?
3. A type of Simple Program to really appreciate the "purpose" of COM (A chat program perhaps?)
Thanks! :)
PS: Should I mark this as a community wiki? | The book of Don Box about COM is the definitive reference. [Amazon link](https://rads.stackoverflow.com/amzn/click/com/0201634465).
Beware is a tough read, but it covers everything in deep. And remember, as Don said... COM IS LOVE.
I do not believe you can find a lot of web site, COM was a up to date technology a lot of time ago, but if you can forgot about it trust me... it's better! | I have in my library these books on COM which I'd recommend:
1. 1995 - Kraig Brockschmidt - Inside OLE 2nd Edition
2. 1998 - Don Box - Essential COM
3. 1999 - George Shepherd - Inside ATL
4. 2000 - Andrew Troelsen - Developer's Workshop to COM and ATL 3.0
5. 2006 - Christopher Tavares - ATL Internals : Working with ATL 8, 2nd Edition
and if you say you have some .net background there's the
1. 2003 - Julian Templeman - COM Programming with Microsoft .NET
Hope this helps. | I want to learn COM. How should I proceed? | [
"",
"c++",
"com",
""
] |
The base class library in .NET has some excellent data structures for collections (List, Queue, Stack, Dictionary), but oddly enough it does not contain any data structures for binary trees. This is a terribly useful structure for certain algorithms, such as those that take advantage of different traversal paths. I'm looking for a correctly written, free implementation.
Am I simply blind, and not finding it... is it buried somewhere in the BCL? If not, can someone recommend a free or open-source C#/.NET library for binary trees? Preferably one that employs generics.
**EDIT:** To clarify what I'm looking for. I'm not interested in ordered dictionary collections that internally use a tree. I'm actually interested in a binary tree - one that exposes its structure so that you can do things like extract subtrees, or perform post-fix traversal on the nodes. Ideally such a class could be extended to provide the behaviors of specialized trees (ie. Red/Black, AVL, Balanced, etc). | You're right, there's nothing in the BCL. I suspect this is because the choice of whether to use a tree is typically an implementation detail and is otherwise an unconventional way to access data. That is, you don't say, "binary-search-for element #37"; instead, you say, "get me element #37".
But have you taken a look at [C5](http://www.itu.dk/research/c5/Release1.1/c5doc/frames.htm)? It's super-handy and they have several tree implementations ([1](http://www.itu.dk/research/c5/Release1.1/c5doc/types/C5.TreeBag_1.htm), [2](http://www.itu.dk/research/c5/Release1.1/c5doc/types/C5.TreeDictionary_2.htm), [3](http://www.itu.dk/research/c5/Release1.1/c5doc/types/C5.TreeSet_1.htm)). | You could define your own:
```
public class MyTree<K, V> : Dictionary<K, MyTree<K, V>>
{
public V Value { get; set; }
}
```
Or unkeyed:
```
public class MyTree<V> : HashSet<MyTree<V>>
{
public V Value { get; set; }
}
``` | Why is there no Tree<T> class in .NET? | [
"",
"c#",
".net",
"data-structures",
""
] |
I have a table with a column that I want to extract out and put into a separate table.
For example, lets say I have a table named Contacts. Contacts has a column named Name which stores a string. Now I want to pull out the names into another table named Name and link the Contact.Name column to the Id of the Name table.
I can only use SQL to do this. Any ideas on the best way to go about this?
Let me know if I can clarify anything, thanks!
[edit]
One problem is that different contacts can be tied to the same name. So when different contacts have the same name and it gets exported the Name table would only have one unique row for that name and all the contacts would point to that row. I guess this wouldn't make sense if I were actually working on a contact book, but I'm just using it to illustrate my problem. | ```
CREATE TABLE Name (NameID int IDENTITY(1, 1), [Name] varchar(50))
INSERT INTO Name ([Name])
SELECT DISTINCT [Name]
FROM Contact
ALTER TABLE Contact
ADD COLUMN NameID int
UPDATE Contact
SET NameID = [Name].NameID
FROM Contact
INNER JOIN [Name]
ON Contact.[Name] = [Name].[Name]
ALTER TABLE Contact
DROP COLUMN [Name]
```
Then add foreign key constraint, etc. | Create the new table with a Foreign key that points back to the contact table. Then insert the names and contactids from the contact table into this new table. After that you can drop the "name" column from the contact table.
```
CREATE TABLE Name
(
ContactId int,
Name nvarchar(100)
);
INSERT Name(Name)
SELECT ContactId, Name From Contact;
ALTER TABLE Contact
DROP Column name;
```
**EDIT:** Since you have edited the question to mention that one name can be associated with multiple contacts, this changes things in the opposite way.
```
CREATE TABLE Name
(
NameId int IDENTITY,
Name nvarchar(100)
);
INSERT Name(Name)
SELECT DISTINCT Name From Contact;
ALTER TABLE Contact
ADD NameId int;
UPDATE c
SET c.NameId = n.NameId
FROM Contact c
JOIN Name n on n.Name = c.Name;
ALTER Table Contact
Drop Column Name;
```
**NOTE:** Make sure that you create the appropiate foreign key between the Contact and Name tables using the NameId on the Contact table and also create a UNIQUE constraint on the "name" column in the Name table. | SQL Server: Extracting a Column Into a Table | [
"",
"sql",
"sql-server",
"t-sql",
"ddl",
"dml",
""
] |
I am looking for a clean and safe way to ensure tha a field of a class will never be set to null. I would like the field value to be set once in the class constructor and never modified later. I think that he readonly keyword in C# allows this. Is there a way to do the same in Java?
```
class foo
{
private Object bar;
public foo(Object pBar)
{
if(pBar == null)
{
bar = new Object();
}
else
{
bar = pBar
}
}
// I DO NOT WANT ANYONE TO MODIFY THE VALUE OF bar OUT OF THE CONSTRUCTOR
}
``` | Declare `bar` to be `final`, like this:
```
private final Object bar;
``` | You're looking for the keyword final.
```
class foo
{
private final Object bar;
public foo(Object pBar)
{
//Error check so that pBar is not null
//If it's not, set bar to pBar
bar = pBar;
}
}
```
Now bar can't be changed | How to ensure that a field will never be null in a Java class | [
"",
"java",
"null",
"field",
""
] |
I am wondering if I can somehow find out the location of the script and not the page it is called from. e.g. if the page is <http://xxx.yyy.com/a.htm>, and I write location.href, I get that location instead of <http://aaa.zzz.com/script.js> where the script resides. Is it possible to get the location of the script?
Thank you for your time. | Short answer: No.
Long answer: You could loop over all the elements in the page, calculate an absolute URI for each, then make a JSON-P request to a server side script on a server you control that will download each script and compare it to a master copy — but that would break if the script was changed in any way. A more robost solution might be achievable with a smarter comparison algorithum, but you'll never get 100% reliability (since there might be two copies of the same script included which you wouldn't be able to distinguish). | I had to do this exact same thing just now and came up with a slightly different solution that's working well for me. Do you own the page that the script is being referenced in? If so, you can put an id on that script element. Then in your javascript file, you can get that element and parse it "src" attribute for the domain. | Detect location of script not the page where it is called from | [
"",
"javascript",
""
] |
What is the quickest way in ColdFusion (or Java) for converting a string as such:
```
Input:
79827349837493827498
Output:
\79\82\73\49\83\74\93\82\74\98
```
I'm taking an LDAP GUID and escaping it for a query.
I can do it as a series of MID reductions like this:
```
<CFSET V1 = "">
<CFSET RetVal = "">
<CFLOOP CONDITION="#V1# NEQ''">
<CFSET RetVal = RetVal & "\" & MID(V1,1,2)>
<CFSET V1 = MID(V1,3,2000)>
</CFLOOP>
```
But it seems like there would be something more elegant, like a regular expression replace. | I haven't tested this, so the syntax might be off, but you should be able to do something like:
```
<cfset V1 = REReplace(V1,"([0-9]{2})","\\\1","all")>
``` | In Java you could do
```
String text = text.replaceAll("(..)","\\\1");
``` | Is there a better way to escape this string? | [
"",
"java",
"algorithm",
"coldfusion",
""
] |
Is there a way to embed/mashup the OpenStreetMap in your page (like the way [Google Maps API](http://code.google.com/apis/maps/) works)?
I need to show a map inside my page with some markers and allow dragging/zooming around, maybe routing.
I suspect there would be some Javascript API for this, but I can't seem to find it.
Searching gets me an [API for access to raw map data](http://wiki.openstreetmap.org/wiki/API), but that seems to be more for map editing; besides, working with that would be a heavy task for AJAX. | You need to use some JavaScript stuff to show your map. OpenLayers is the number one choice for this.
There is an example at <http://wiki.openstreetmap.org/wiki/OpenLayers_Simple_Example> and something more advanced at
<http://wiki.openstreetmap.org/wiki/OpenLayers_Marker>
and
<http://wiki.openstreetmap.org/wiki/Openlayers_POI_layer_example> | ## Simple OSM Slippy Map Demo/Example
Click on "Run code snippet" to see an embedded OpenStreetMap slippy map with a marker on it. This was created with [Leaflet](http://leafletjs.com).
### Code
```
// Where you want to render the map.
var element = document.getElementById('osm-map');
// Height has to be set. You can do this in CSS too.
element.style = 'height:300px;';
// Create Leaflet map on map element.
var map = L.map(element);
// Add OSM tile layer to the Leaflet map.
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Target's GPS coordinates.
var target = L.latLng('47.50737', '19.04611');
// Set map's center to target with zoom 14.
map.setView(target, 14);
// Place a marker on the same location.
L.marker(target).addTo(map);
```
```
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" rel="stylesheet"/>
<div id="osm-map"></div>
```
### Specs
* Uses OpenStreetMaps.
* Centers the map to the target GPS.
* Places a marker on the target GPS.
* Only uses Leaflet as a dependency.
**Note:**
I used the CDN version of [Leaflet](http://leafletjs.com) here, but you can [download](http://leafletjs.com/download.html) the files so you can serve and include them from your own host. | Openstreetmap: embedding map in webpage (like Google Maps) | [
"",
"javascript",
"maps",
"openstreetmap",
""
] |
Which is the best way to drawString at the center of a rectangleF? Text font size can be reduced to fit it. In most case the Text is too big to fit with a given font so have to reduce the font. | It is working for me know. This is what I did
```
Size textSize = TextRenderer.MeasureText(Text, Font);
float presentFontSize = Font.Size;
Font newFont = new Font(Font.FontFamily, presentFontSize, Font.Style);
while ((textSize.Width>textBoundary.Width || textSize.Height > textBoundary.Height) && presentFontSize-0.2F>0)
{
presentFontSize -= 0.2F;
newFont = new Font(Font.FontFamily,presentFontSize,Font.Style);
textSize = TextRenderer.MeasureText(ButtonText, newFont);
}
stringFormat sf;
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(Text,newFont,Brushes.Black,textBoundary, sf);
``` | This code centers the text horizontally and vertically:
```
stringFormat sf;
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
grp.DrawString(text, font, Brushes.Black, rectf, sf);
``` | Draw text at center | [
"",
"c#",
"forms",
""
] |
I've got two applications running on two different machines that communicate by sending Serializable "Message" objects over Javas Socket implementation. Each one creates a SocketServer, connects to the others server and then the following bits of (pseudo-Java, error and connection details are elided for brevity):
Receiving code:
```
while (true) {
Object received = oisFromOtherMachine.readUnshared();
dispatch(received);
}
```
Sending code:
```
synchronized void sendMessage(Message m) {
oosToOtherMachine.writeObject(m);
oosToOtherMachine.flush();
oosToOtherMachine.reset();
}
```
Which is called fairly regularly from a variety of different threads.
This all worked fine and dandy up until about 3 weeks ago, where, sometimes, in response to a particular bit of user input, the call to readUnshared will throw. So far, we've seen "java.lang.IllegalStateException: unread block data" and "java.lang.ClassCast
Exception: java.util.HashMap cannot be cast to java.io.ObjectStreamClass", both from deep in the internals of ObjectInputStream.
It happens about one time in 5, normally after the two systems have been up and talking to each other for 15+ minutes. For various reasons, we have two network cables that regularly get used between the two, one knarled and knotted 15m (ping of 30ms+), the other about 1m (ping of <1ms). Its only ever happened over the short cable (and believe me, we've tried it over the long one a large number of times).
I've tried checking everything reachable by any Message object is Serializable, no clues in the logs for either app before the message is sent, and the app that doesn't get the error continues merrily on its way, unaware of any trouble.
So. Google doesn't suggest any gotchas in OIS, OOS or Java Sockets that could cause it and my colleagues are as stumped as me... Has anyone seen anything like this before?
Edit:
Thanks for suggestions everyone. (-: In conclusion I suspect some unsynchronized access to some of the logging status objects is producing a broken object graph which is causing OIS to choke. This Needs To Be Solved Yesterday though, and a liberal application of the synchronized keyword along with the following abomination ...
```
try {/* message loop */ } catch (RuntimeException) { /* resync appstate and continue*/ }
```
... will be done much quicker and with much higher chances of success than more frustrating (25min+) attempts to reproduce the problem & associated headscratching. | My guesses: You have some data corruption between the two machines; or they run on different java versions; you have some tricky singletons in the object graph; the reset() on the sender side is messing up.
Why do you use readUnshared()? | Never seen that happen, and I'm using Sockets + ObjectStreams quite heavily.
I suggest you try newer JVM versions, IllegalStateExceptions deep in the bowels of core class libraries smell strange. The fact that it's happening only on a very fast connection *almost* makes it sound like a race condition.
Perhaps this time you did "find a bug in GCC"? | Sockets and ObjectInputStreams | [
"",
"java",
""
] |
```
<script language="javascript" type="text/javascript">
var a =10;
function test()
{
if ( a ==10) {
document.sample.checkbox1.checked = true ;
}
}
</script>
<form name="sample">
<input type="checkbox" name="checkBox1" test();>Option
</form>
```
While creating form itself its automatically call function based on it should decide whether its need to checked or not ..
Here the question . How to call the function without any click ( on click event )
Thanks ,
Chells | You could run the `test()` function in the `body`'s `onLoad` handler:
```
<body onLoad="test();">
```
This will call the function once the page's content has been loaded.
You could also just call the function in `<script>` tags after the inputs:
```
<form name="sample">
<input type="checkbox" name="checkBox1">Option
</form>
<script language="JavaScript" type="text/javascript">
test();
</script>
```
This will be called as the page is loaded. | There's always good old `document.writeln()`, even if it's been succeeded by DOM manipulation in most use cases:
```
<script type="text/javascript">
document.writeln('<input type="checkbox" name="checkBox1"' +
(a == 10 ? ' checked' : '') + '>');
</script>
<noscript>
<!-- unchecked by default -->
<input type="checkbox" name="checkBox1">
</noscript>
``` | Calling function while creating form elements in javascript | [
"",
"javascript",
""
] |
The situation:
index.php:
```
<?php
include("foo.php");
include("baz.php");
foo("bar.php");
?>
```
baz.php:
```
<?php
$x = 42;
?>
```
foo.php:
```
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
?>
```
bar.php:
```
<?php
echo $x;
?>
```
Zend **notice**: Undefined variable: x
Placing global $x; in bar.php removes the notice, but I understand why there is a notice about this in the first place.. Doesn't include pretty much work like including C headers? It would mean that the interpreted code would look like this:
```
<?php
function foo($p) {
include_once($p); // please dont mind the inclusion hole
}
$x = 42;
// this however, is included by a function...
// does the function's scope influence the stuff it includes?
echo $x; // undefined variable
?>
```
My editor is the Eclipse/Zend package. | I'm no expert, so please don't flame me if I'm wrong, but I think the file called by include\_once or require\_once is called in the context of the caller. Since function foo() won't know about $x then neither will any of its called includes. You could experiment by 'declaring' $x inside function foo() with the same setup as above. | I get a bunch of those notices since I'm almost allways goes with "$o .= 'foo'" without any definition. I'm just hiding them with error\_reporting(E\_ALL ^ E\_NOTICE), but I don't know if it's the optimal way in this case. | PHP / Zend complains about undefined variables | [
"",
"php",
"include",
"zend-studio",
"zend-debugger",
""
] |
```
function getLongLat(address)
{
geocoder = new GClientGeocoder();
if (geocoder) {
geocoder.getLatLng(address,
function(point) {
if (!point) {
return "null";
} else {
return point;
}
}
);
}
}
```
If I put alert(point) in I get the longitute and latitude. | Keep in mind that getLatLng() is asynchronus: you're passing in an anonymous function for it to execute when it completes.
Your getLongLat() function won't be able to return point in this case because that anonymous function is running in a completely different context asynchronously: your function will execute and return before Google's will, and point won't even be in scope for the outer function.
You'll need to call whatever code you want to operate on points inside that anonymous function:
```
function getLongLat(address)
{
geocoder = new GClientGeocoder();
if (geocoder) {
return geocoder.getLatLng(address,
function(point) {
// point is only in scope for this anonymous inner function
// which is called when your request to Google's service completes
if (!point) {
// your error condition if a point isn't found
// omgMissingPoint(point);
} else {
// your function to process points here.
// processPoint(point);
}
}
);
}
```
} | Try this :D
```
function getLongLat(address)
{
geocoder = new GClientGeocoder();
if (geocoder) {
return geocoder.getLatLng(address,
function(point) {
if (!point) {
return "null";
} else {
return point;
}
}
);
}
return false;
}
``` | How come this function always returns 'undefined' | [
"",
"javascript",
"google-maps",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.