Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
geeves
Sep 16, 2004

tkinnun0 posted:

I don't see relatedLinks being initialized, so it's probably null. Another thing is that arrays in Java do not expand after creation.

Taken together, relatedLinks should be

List<String> relatedLinks = new ArrayList<String>();

Thanks!

That took care of it. I've been switching between Java, JavaScript, Sling and PHP too much the past few days and I've pretty much just been cross-eyed because of it.

Adbot
ADBOT LOVES YOU

yatagan
Aug 31, 2009

by Ozma
In an Apache Tapestry page, static variables should be shared among all instances, right? Meaning that assuming you preserve thread safety, the various instances can happily share a single resource object?

yatagan
Aug 31, 2009

by Ozma

yatagan posted:

In an Apache Tapestry page, static variables should be shared among all instances, right? Meaning that assuming you preserve thread safety, the various instances can happily share a single resource object?

After extensive testing, this is definitely true, but you have to create instance level accessor methods if the static components are in different classes.

New question:
Do you think it's bad form to do this?

code:
ArrayList<String> someStringList = new ArrayList<String>();
while (iterationOverUnknownSize) {
	someStringList.add(someString);
}
return new MethodThatOnlyTakesStringArrays(someStringList.toArray(new String[0]));
Referring in particular to the call to toArray().

Max Facetime
Apr 18, 2009

yatagan posted:

Do you think it's bad form to do this?

Referring in particular to the call to toArray().

No, Strings are immutable and while arrays are not, the responsibility for the array contents is clearly passed to the called method.

Brain Candy
May 18, 2006

yatagan posted:

code:
someStringList.toArray(new String[0]);

Since you know the size after the iteration, why don't you just pass it in instead of making two arrays?

funkatron3000
Jun 17, 2005

Better Living Through Chemistry
I have a slightly challenging design problem, looking for second opinions...

Given
1) A slow InputStream with an arbitrarily large unknown amount of data (up to several gigabytes)
2) A vertically scrolling viewer that swaps in chunks of data from the InputStream as requested by the user
3) Enough disk space to cache everything, but we want to minimize its use.

So... I figure I need some kind of caching mechanism between the InputStream and the viewer to provide random access, if not per character, at least by some arbitrarily sized chunk.

The best idea I've been able to come up with is some kind of two file solution. One index file that maps offsets of chunks from the stream to offsets in a second file containing the data. Chunks of data would be written to the file as requested by the user by scrolling. So you'd ask the index file where bytes 50k - 55k are, if they don't exist then seek in the InputStream and write the data to the data file and update the index, otherwise read from its existing location in the data file.

Does anyone know of a better way to tackle this? Or know of any existing packages/design patterns?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What's a good way of figuring out the difference between two calendar objects and offsetting another calendar object by that amount?

Right now I'm using Calendar.getTimeInMillis(), which returns a long, and then just casting it to an int and using Calendar.add(). There's got to be a better way than that. Maybe using a loop and increment it one day at a time and just count the number of iterations to get to the other calendar?

Fly
Nov 3, 2002

moral compass

yatagan posted:

code:
ArrayList<String> someStringList = new ArrayList<String>();
while (iterationOverUnknownSize) {
	someStringList.add(someString);
}
return new MethodThatOnlyTakesStringArrays(someStringList.toArray(new String[0]));
I think it's nicer to use a more expressive syntax:
code:
return new ArrayList<String>() {{
    for (String someString : someArrayOrCollectionOfStrings) {
      add(someString);
    }
  }}.toArray(new String[0]);
Creating your extra String[0] is trivially cheap. The someArrayOrCollectionOfStrings has to be a member variable or final so the closure will work, but that's good (more functional) style, too.

Fly
Nov 3, 2002

moral compass

funkatron3000 posted:

I have a slightly challenging design problem, looking for second opinions...

Given
1) A slow InputStream with an arbitrarily large unknown amount of data (up to several gigabytes)
2) A vertically scrolling viewer that swaps in chunks of data from the InputStream as requested by the user
3) Enough disk space to cache everything, but we want to minimize its use.

So... I figure I need some kind of caching mechanism between the InputStream and the viewer to provide random access, if not per character, at least by some arbitrarily sized chunk.

The best idea I've been able to come up with is some kind of two file solution. One index file that maps offsets of chunks from the stream to offsets in a second file containing the data. Chunks of data would be written to the file as requested by the user by scrolling. So you'd ask the index file where bytes 50k - 55k are, if they don't exist then seek in the InputStream and write the data to the data file and update the index, otherwise read from its existing location in the data file.

Does anyone know of a better way to tackle this? Or know of any existing packages/design patterns?
If you want to give the user random access to the file, I think you'll need to store it all as a local file and just use something like FileInputStream.skip(n) and reset() to move through the data, if you need to allow the user completely random access because you don't want to cache Gigabytes of data in the JVM heap.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Functions: still a more fundamental tool of abstraction than anonymous classes.

Just put this somewhere in your project. Unfortunately, it's still not bound anywhere in the standard libraries that I know of.

code:
import java.util.Collection;
import java.lang.reflect.Array;

public class Assist {

  @SuppressWarnings("unchecked")
  public static <T> T[] toArray(Collection<? extends T> col, Class<T> cls) {
    T[] array = (T[]) Array.newInstance(cls, col.size()); // unavoidable warning
    int i = 0;
    for (T el : col) array[i++] = el;
    return array;
  }
}
And now, voilą.

code:
Assist.toArray(someStringList, String.class);

Brain Candy
May 18, 2006

rjmccall posted:

Functions: still a more fundamental tool of abstraction than anonymous classes.

Just put this somewhere in your project. Unfortunately, it's still not bound anywhere in the standard libraries that I know of.

code:
import java.util.Collection;
import java.lang.reflect.Array;

public class Assist {

  @SuppressWarnings("unchecked")
  public static <T> T[] toArray(Collection<? extends T> col, Class<T> cls) {
    T[] array = (T[]) Array.newInstance(cls, col.size()); // unavoidable warning
    int i = 0;
    for (T el : col) array[i++] = el;
    return array;
  }
}

This gives a warning for a reason. If T is also generic, T[] will be of the erased type. Arrays do not play nicely with generics.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Brain Candy posted:

This gives a warning for a reason.

Yes, but in this case the warning can be safely ignored because of untypable guarantees made by Array.newInstance. The only way you can "break" this method is by passing (say) Integer.TYPE instead of an object class, and it will still throw an exception instead of being quietly wrong.

Brain Candy posted:

If T is also generic, T[] will be of the erased type. Arrays do not play nicely with generics.

That is not the reason it gives a warning. Also, the situation you describe is impossible without intentionally working around the type system; you cannot construct a Class object with a generic parameter type. Sadly, this does mean that you can't use my function on collections whose type parameter is itself parameterized, because you can't provide an appropriate Class. This is all Yet Another Compelling Reason why dynamically-checked array types were a terrible mistake.

Also, I must note that every implementation of Collection.toArray has to do exactly what I'm describing here, uncheckable cast and all.

Max Facetime
Apr 18, 2009

fletcher posted:

What's a good way of figuring out the difference between two calendar objects and offsetting another calendar object by that amount?

Right now I'm using Calendar.getTimeInMillis(), which returns a long, and then just casting it to an int and using Calendar.add(). There's got to be a better way than that. Maybe using a loop and increment it one day at a time and just count the number of iterations to get to the other calendar?

Well, the simple and straightforward way is

code:
long time1 = cal1.getTimeInMillis();
long time2 = cal2.getTimeInMillis();
long difference = time2 - time1;
long time3 = cal3.getTimeInMillis();
time3 += difference;
cal3.setTimeInMillis(time3);
Things get more complicated if the difference is not simply a difference in milliseconds. It could also be a difference in full days, full months, full months+days or something else. Are leap days going to affect things? Or daylight saving time?

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

Fly posted:

I think it's nicer to use a more expressive syntax:
code:
return new ArrayList<String>() {{
    for (String someString : someArrayOrCollectionOfStrings) {
      add(someString);
    }
  }}.toArray(new String[0]);
Creating your extra String[0] is trivially cheap. The someArrayOrCollectionOfStrings has to be a member variable or final so the closure will work, but that's good (more functional) style, too.
This makes me :barf:. Initializing an array is not worth having an entire class definition sitting around in your jar.

Brain Candy
May 18, 2006

rjmccall posted:

Also, I must note that every implementation of Collection.toArray has to do exactly what I'm describing here, uncheckable cast and all.

:ssh: don't use arrays.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
The whole point of this conversation was that the guy was using an API that wanted an array instead of a collection.

Brain Candy
May 18, 2006

Mustach posted:

The whole point of this conversation was that the guy was using an API that wanted an array instead of a collection.

Yes, yes, but if you use arrays enough to require a helper method you've got more problems than making the arrays.

Fly
Nov 3, 2002

moral compass

Mustach posted:

This makes me :barf:. Initializing an array is not worth having an entire class definition sitting around in your jar.
That is a fair point. It adds 546 bytes (uncompressed) to the jar to have the extra .class, and that can add up. I am not sure how much overhead is needed by the JVM, but I assume it won't matter in most cases as the class definitions get garbage collected.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Brain Candy posted:

Yes, yes, but if you use arrays enough to require a helper method you've got more problems than making the arrays.

Heaven save us from the vicious tyranny of having too many helper functions.

Brain Candy
May 18, 2006

rjmccall posted:

Heaven save us from the vicious tyranny of having too many helper functions.

Way to miss the point!

epswing
Nov 4, 2003

Soiled Meat

Brain Candy posted:

Yes, yes, but if you use arrays enough to require a helper method you've got more problems than making the arrays.

This is easy to say without actually sitting in front of code/libs which you may or may not have the power to change.

yatagan
Aug 31, 2009

by Ozma

epswing posted:

This is easy to say without actually sitting in front of code/libs which you may or may not have the power to change.

And sometimes even if you do have the power to change it, that doesn't mean you should go editing library files to better mesh with your code.

Brain Candy
May 18, 2006

If only there were some way to hide the interaction with bad code without re-writting it. :rolleye:

yatagan
Aug 31, 2009

by Ozma

Brain Candy posted:

If only there were some way to hide the interaction with bad code without re-writting it. :rolleye:

Wait what? Or do you mean "hide so that I don't have to stare at it but I still have to write it" type of hide?

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
I have a problem, and absolutely no idea what the cause could be. Code is essentially like this:

code:
public void someMethod() {
...
  try {
    doThing1();
    doThing2();
    ...
  } catch (Throwable t) {
    log(t);
  }
...
}

public void doThing1() {
  log(...);
  doSomeStuff();
  ...
  log(<more stuff>);
}

etc.
I can see the code entering doThing1(), because of the log statement. However, at some point in doThing1(), something is happening to cause all the rest of the code to be skipped. All remaining code in doThing1(), and even all remaining code in someMethod() is simply not executed. I tried the catch(Throwable) to see if I was missing something, but there's nothing.

Is there any possible explanation for such behavior? I could try to give some more specific details, but I don't know if they'd really be helpful.

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

Kilson posted:

I can see the code entering doThing1(), because of the log statement. However, at some point in doThing1(), something is happening to cause all the rest of the code to be skipped. All remaining code in doThing1(), and even all remaining code in someMethod() is simply not executed. I tried the catch(Throwable) to see if I was missing something, but there's nothing.

Is there any possible explanation for such behavior? I could try to give some more specific details, but I don't know if they'd really be helpful.
Can you step through it in a debugger?

Alternatively, pepper in some more log statements to narrow down the problem.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

Jethro posted:

Can you step through it in a debugger?

Not easily (this is a part of a big application that depends on third-party jar files and communication with multiple external servers to produce the error). I'll certainly try to set all this up locally and see if I can get it to work.

quote:

Alternatively, pepper in some more log statements to narrow down the problem.

I know exactly which line of my code that's the last one to be executed. Beyond that, it goes into a third-party jar to do some axis communication. That still leaves me questioning exactly how this can cause my problem. It's as if the entire callstack is being obliterated and the program is silently continuing on its merry way. Any kind of problem should either be caught (by catch(Throwable t)) or cause a program crash, right?

The Sweetling
May 13, 2005

BOOMSHAKALAKA
Fun Shoe
Ok this may sound retarded but it's bugging me and I can't find an explanation anywhere:

"fagsfags".compareTo("123") indicates that numeric strings are always less than lower-case alphabetical ones, so can this approach safely be used to differentiate the two? For my purposes I'm butchering a string, and I want to see if the substring contains some numbers. Is this approach acceptable?


Edit: I just realised I can accomplish the same thing much more elegantly with Character.isDigit(string), cool.

The Sweetling fucked around with this message at 02:58 on Nov 3, 2009

RussianManiac
Dec 27, 2005

by Ozmaugh
Also: http://www.asciitable.com/

Fly
Nov 3, 2002

moral compass

Kilson posted:

I know exactly which line of my code that's the last one to be executed. Beyond that, it goes into a third-party jar to do some axis communication. That still leaves me questioning exactly how this can cause my problem.
My first guess is that your third party code may be hanging, though if you say it is skipped, then that indicates you have something else later confirming that the thread is running (another log statement somewhere?).

If it is hanging, then you can create a thread stack dump (`kill -QUIT <pid>` on Linux/Unix) to see why that thread is waiting.

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa

Kilson posted:

I have a problem, and absolutely no idea what the cause could be. Code is essentially like this:

code:
public void someMethod() {
...
  try {
    doThing1();
    doThing2();
    ...
  } catch (Throwable t) {
    log(t);
  }
...
}

public void doThing1() {
  log(...);
  doSomeStuff();
  ...
  log(<more stuff>);
}

etc.
I can see the code entering doThing1(), because of the log statement. However, at some point in doThing1(), something is happening to cause all the rest of the code to be skipped. All remaining code in doThing1(), and even all remaining code in someMethod() is simply not executed. I tried the catch(Throwable) to see if I was missing something, but there's nothing.

Is there any possible explanation for such behavior? I could try to give some more specific details, but I don't know if they'd really be helpful.

That is the expected behaviour according to your code assuming doSomeStuff(); throws an instance of RuntimeException (aka unchecked exception). Exception is basically a directive to tell the program to stop doing immediately whatever it is doing and return back in the call stack to the point until some mechanism catches the exception, in this case that is the catch(Throwable t) in someMethod.

Because the thrown exception sort of backtracks itself all the way to the beginning of that try..catch block and then skips over to the matching catch block, any method on that level after the method that caused the exception to be thrown isn't called.

If you want to run doThing2() anyway, you need to place it into another try..catch block or if it's something you always want to run afterwards doThing1(), you could place it into a finally block to ensure it's run after everything is run in try block.

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!
Unless he did a fantastically bad job of explaining his problem, I think he was saying that the program was dieing, but even once he added in the try...catch no exceptions were being caught.

If this was actually his problem, then you have some excellent question deciphering skills.

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa

Jethro posted:

Unless he did a fantastically bad job of explaining his problem, I think he was saying that the program was dieing, but even once he added in the try...catch no exceptions were being caught.

If this was actually his problem, then you have some excellent question deciphering skills.

Well English is my third language so there's always margin for error. I did read the question through multiple times to try to understand it since it's a bit vague and by the wonderful process of elimination came to the conclusion that's the issue. There's of course possibility for infinite loops and maybe even System.exit(); somewhere in there but without additional details I'm just going to go for the seemingly simplest (well, simplest for me) solution.

tl;dr: I'm once again trying to cover my rear end on this wonderful subforum.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

Jethro posted:

Unless he did a fantastically bad job of explaining his problem, I think he was saying that the program was dieing, but even once he added in the try...catch no exceptions were being caught.

If this was actually his problem, then you have some excellent question deciphering skills.

You are correct. If there's an exception thrown in doThing1(), I'm not expecing doThing2() to be executed. I'm expecting the exception to be caught where it should be caught, and for execution of the main method to continue.

The problem is that even with catch(Throwable t), there's nothing being caught. The execution simply stops. Furthermore, anything in the main method AFTER the try/catch block is also not getting executed.

As I said, it makes no sense whatsoever, which is why I'm asking if anyone has ever seen anything like it, or has any ideas of what I can try.

(I haven't had a chance to seriously try the debugger yet, been working on on-site interop testing all week :puke:)

1337JiveTurkey
Feb 17, 2005

Install a custom SecurityManager just before the code is called such that checkExit() throws a SecurityException every time. Then in the finally block remove the manager so that you can actually exit normally. If you reach the catch block with a SecurityException, some brilliant soul decided to handle an error by calling Runtime.exit() or Runtime.halt().

Fly
Nov 3, 2002

moral compass

Kilson posted:

You are correct. If there's an exception thrown in doThing1(), I'm not expecing doThing2() to be executed. I'm expecting the exception to be caught where it should be caught, and for execution of the main method to continue.

The problem is that even with catch(Throwable t), there's nothing being caught. The execution simply stops. Furthermore, anything in the main method AFTER the try/catch block is also not getting executed.

As I said, it makes no sense whatsoever, which is why I'm asking if anyone has ever seen anything like it, or has any ideas of what I can try.

(I haven't had a chance to seriously try the debugger yet, been working on on-site interop testing all week :puke:)
If it is stopping and not exiting, just take a thread dump and see what's going on. Post the (relevant portions of the) thread dump if you would like us to take a look.

edit: or install VisualVM from Sun and see what's going on. http://java.sun.com/javase/6/docs/technotes/guides/visualvm/index.html

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
It doesn't stop or exit, it just continues running (after skipping whatever code it skips) as if nothing ever happened.

epswing
Nov 4, 2003

Soiled Meat

Kilson posted:

It doesn't stop or exit, it just continues running (after skipping whatever code it skips) as if nothing ever happened.

I've had this happen to me before in tomcat/spring. I couldn't believe it. Everything in a controller was in a try/catch(Throwable) { log('hi!') }, something was breaking, yet the page would still partially load in the browser, no errors.

Never could explain why/how.

FreshShoez
Oct 15, 2009
So I'm writing this program that detects deadlock, given a number of resources, process, requests, and releases. I wrote out my design, everything looks gravy. The actual program itself isn't turning out so well. I've isolated the problem (I think) to this little segment of code, that is supposed to take the n+1 power of an n x n matrix.

code:
    int[][] tempMatrix = new int[system.arrayWidth][system.arrayWidth];
    int[][] progressMatrix = new int[system.arrayWidth][system.arrayWidth];
    for(int m=0; m<system.arrayWidth - 1; m++){
            for(int n=0; n<system.arrayWidth - 1; n++){
                progressMatrix[m][n] = system.graphMatrix[m][n];
            }
        }

    for(int i=2;i < system.arrayWidth + 2; i++){
        tempMatrix = initializeToZero(tempMatrix, system.arrayWidth);
        for(int j=0; j<system.arrayWidth; j++){
            for(int k=0; k<system.arrayWidth; k++){
                for(int l = 0; l<system.arrayWidth; l++){

                tempMatrix[j][k] = tempMatrix[j][k] + (progressMatrix[j][l] * system.graphMatrix[l][k]);
                
                }
            }
        }
        for(int m=0; m<system.arrayWidth - 1; m++){
            for(int n=0; n<system.arrayWidth - 1; n++){
                progressMatrix[m][n] = tempMatrix[m][n];
            }
        }

 }

What I'm trying to make it do: take the matrix system.graphMatrix, make a copy to the progressMatrix, set all of values in tempMatrix to 0, and then use the values in progressMatrix and system.graphMatrix, along with matrix multiplication to add up the appropriate values in the appropriate spaces of tempMatrix. After each "power", the values of tempMatrix are assigned to the values in progressMatrix, and tempMatrix is set back to zero, and the process continues until i = n + 1. Unfortunately, this is not at all what this chunk of code does for me. Instead, from echo checking, I've found that it gives me seemingly random matrices. Is there anyone who could help me out?

Adbot
ADBOT LOVES YOU

yatagan
Aug 31, 2009

by Ozma

FreshShoez posted:

Is there anyone who could help me out?

Your first loop doesn't even copy the matrices, it misses the outside edge.

Your "oh god why" fourth order quadratic time clusterfuck loop does something that I'm not going to bother figuring out.

Try this:
http://math.nist.gov/javanumerics/jama/

Or this:
http://www.ujmp.org/

Or this:
http://acs.lbl.gov/~hoschek/colt/

Or this:
http://commons.apache.org/math/

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply