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
supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
So, SwingWorker, and loading images into a table. Firstly, I'd like to gradually load row after row, instead of waiting until all the images have loaded. Secondly, when a row's been edited, to tell the worker to go over it again. Is making a bunch of workers for all the images the way to go? (Pointing at the image that needs to be loaded in the constructor.)

Adbot
ADBOT LOVES YOU

Volguus
Mar 3, 2009

supermikhail posted:

So, SwingWorker, and loading images into a table. Firstly, I'd like to gradually load row after row, instead of waiting until all the images have loaded. Secondly, when a row's been edited, to tell the worker to go over it again. Is making a bunch of workers for all the images the way to go? (Pointing at the image that needs to be loaded in the constructor.)

That would be one way, but is not needed. You can create one worker that simply loads all the images, but as soon as it loaded one it fires a propertyChangeEvent, which will be listened for in the swing thread and the actual jtable model will be updated.
When an image is edited, yes, you will want to create a worker for that particular image.

Woodsy Owl
Oct 27, 2004
I haven't managed to find any information about my question by Googling it, so here it is: are there any particular reasons or circumstances that would hinder any attempt to work with P3D mode in Processing such that it would compile and execute but display nothing and flat-out crash my PC? Whether I am coding in the Processing interpreter sandbox or wrapped within a Java project, I am unable to get any J3D jazz to work. I have no problems while working in J2D and I get no compiler errors, but the Processing canvas appears with nothing but a white canvas and, most unusually, Windows starts to poo poo-the-bed as applications start crashing and all sorts of strange nastiness happens (I'm unable to WinKey+R or Ctrl+Alt+Del to taskmgr to see exactly what the feck's going on, Explorer basically locks up, UAC also seems to lock up, web browsers refuse to respond, etc...).

Has anyone ever come across or heard about this behavior before? I thought that it might not even be specific to Processing but rather just JOGL but no amount of Googling would yield an answer to that notion also.

It's a real bummer. I've been fiddling around with Processing for a good two afternoons now and I'm just about to give up on it. I really wanted to opt for implementing Processing in my project for the sake of forgoing a lot of OpenGL boilerplate. Maybe I'll fire up a Ubuntu live session and check out if it works in a Linux environment...

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

This is a total uninformed guess, but are your graphics drivers up to date and working? Can you get any 3D functionality outside of Processing? Might be worth at least running some tests

Woodsy Owl
Oct 27, 2004
My graphics drivers are up-to-date and other OpenGL 3D applications are functioning normally.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!
Hello again, stupid idiot newbie is back with more errors that I need help solving.

Doing a project for my Web Services class and getting a poo poo tonne of errors when attempting to compile, specifically...

http://pastebin.com/L2qwBV2N

...errors mentioning not being able to find symbol, which from a cursory google search is telling me the compiler can't find enough information to assign the variable. For the life of me though, I can't figure out why...so here is my code, hopefully one of you fine people can tell me how much of an idiot I am.

http://pastebin.com/wVedktLL - My code

Thanks in advance for any help correcting my stupidity.

Edit: Helpfully, I already noticed I managed to put in a 0 instead of a O in two parts and corrected the two errors involving latitude and longitude. See what I mean about being an idiot?

Edit2: And of course the missing Capital letter in WeatherForecast corrects another two errors, at least posting this has helped me see it!

Edit3: Down to one error after I notice yet another zero that should be an "o", Jesus Christ. Just the ProxyPort giving me trouble now.

A Tartan Tory fucked around with this message at 22:54 on May 1, 2014

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
The "Cannot Find Symbol" error is a problem with how you're building your code, not with the code itself. You're referencing perfectly valid classes, but when you go to build your code, the compiler can't find them.

Are you using javac? Eclipse? Maven?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
You can also delete pretty much every comment in that code

The formatting/indentation is also really wonky and inconsistent:

code:
        public double getLongitude (String country, String region, String place) throws AxisFault {
                double longitudeList=0;
                        try{
                                String countrytwo = country;
                                String regiontwo = region;
                                String placetwo = place;
                                Locator longitude = new Locator();
                                longitudeList = longitude.getLongitude(countrytwo,regiontwo,placetwo);
                        }
                catch(Exception exception){
                        System.err.println(exception);
            }
            return longitudeList;
}
Should be:
code:
        public double getLongitude(String country, String region, String place) throws AxisFault {
            double longitudeList = 0;
            try {
                String countrytwo = country;
                String regiontwo = region;
                String placetwo = place;
                Locator longitude = new Locator();
                longitudeList = longitude.getLongitude(countrytwo, regiontwo, placetwo);
            } catch(Exception exception) {
                System.err.println(exception);
            }
            return longitudeList;
        }
Also, catching Exception is bad, you should never do that. The System.err.println(exception) adds insult to injury :D

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

Gravity Pike posted:

The "Cannot Find Symbol" error is a problem with how you're building your code, not with the code itself. You're referencing perfectly valid classes, but when you go to build your code, the compiler can't find them.

Are you using javac? Eclipse? Maven?

jEdit for the most part. I know that the remaining error is trying to bind the Proxy Port, but I guess that is probably an error in my WSDL.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

fletcher posted:

You can also delete pretty much every comment in that code

The formatting/indentation is also really wonky and inconsistent:

I know, I haven't bothered cleaning it up yet, I will once I finish (I am terrible and lazy, a good combination!).

fletcher posted:

Should be:
code:
        public double getLongitude(String country, String region, String place) throws AxisFault {
            double longitudeList = 0;
            try {
                String countrytwo = country;
                String regiontwo = region;
                String placetwo = place;
                Locator longitude = new Locator();
                longitudeList = longitude.getLongitude(countrytwo, regiontwo, placetwo);
            } catch(Exception exception) {
                System.err.println(exception);
            }
            return longitudeList;
        }
Also, catching Exception is bad, you should never do that. The System.err.println(exception) adds insult to injury :D

Should I just straight up take out the exception stuff and rely on the general axis fault? I guess it's just something I have done automatically since Java 101 last year.

Edit: And double posting now, goddamn am I tired.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

A Tartan Tory posted:

I know, I haven't bothered cleaning it up yet, I will once I finish (I am terrible and lazy, a good combination!).


Should I just straight up take out the exception stuff and rely on the general axis fault? I guess it's just something I have done automatically since Java 101 last year.

Edit: And double posting now, goddamn am I tired.

It's not really something you should have to go back and do after the fact though, you just write code that is consistently formatted from the get-go and it's not a problem. If you're too lazy to clean it up you can always have your IDE automatically do the formatting for you.

That method will never throw AxisFault the way you have it written, since you are catching Exception.

Couple other things about that snippet...why is the double called longitudeList? It's not a Java List, the variable name doesn't make sense.

Why do you have to declare copies of country, region, and place? Why can't you just pass the originals into getLongitude?

Why is your instance of Locator called longitude and not locator?

I would write it as something like this:
code:
public double getLongitude(String country, String region, String place) {
    Locator locator = new Locator();
    return locator.getLongitude(country, region, place);
}
It's only two lines now...does that need to have its own method? It also no longer returns 0 if there was an exception, but would you really want it to just return 0 if there were an exception? The code calling that method would have no idea if something bad happened and it returned 0, or if the longitude just happens to be 0 for the given input values.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

fletcher posted:

It's not really something you should have to go back and do after the fact though, you just write code that is consistently formatted from the get-go and it's not a problem. If you're too lazy to clean it up you can always have your IDE automatically do the formatting for you.

That method will never throw AxisFault the way you have it written, since you are catching Exception.

Couple other things about that snippet...why is the double called longitudeList? It's not a Java List, the variable name doesn't make sense.

Why do you have to declare copies of country, region, and place? Why can't you just pass the originals into getLongitude?

Why is your instance of Locator called longitude and not locator?

I would write it as something like this:
code:
public double getLongitude(String country, String region, String place) {
    Locator locator = new Locator();
    return locator.getLongitude(country, region, place);
}
It's only two lines now...does that need to have its own method? It also no longer returns 0 if there was an exception, but would you really want it to just return 0 if there were an exception? The code calling that method would have no idea if something bad happened and it returned 0, or if the longitude just happens to be 0 for the given input values.

To answer your questions.

1. Yeah I forgot about Eclipse cleaning stuff, thanks for reminding me, will save a lot of work!
2. I guess I just didn't think about it after I did the methods beforehand that were string lists.
3. I didn't think that would work, don't ask I can't explain why I thought that.
4. Again, I thought I had to declare something new there, I can just use another instance of locator?
5. I was specifically told that if there were faults, it had to return a fault error. I thought the axis error did that but the exception stuff was just second nature. It does need a way to show faults though.

Thanks for your help!

Futuresight
Oct 11, 2012

IT'S ALL TURNED TO SHIT!
So I'm messing around with swing and JLayeredPane and I'm running into a problem where semi-transparent labels block any labels fully beneath them, but will be properly transparent for labels that they only partially cover. Here's an example of what I'm talking about :

code:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class TestPane extends JPanel {
	public static void main(String[] args) {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TestPane pane = new TestPane();
        pane.setOpaque(true);
        frame.setContentPane(pane);

        frame.pack();
        frame.setVisible(true);
	}

	public TestPane () {
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
        
        JLayeredPane layeredPane = new JLayeredPane();
        layeredPane.setPreferredSize(new Dimension(200, 200));
        layeredPane.setBackground(new Color(255,255,255));
        layeredPane.setOpaque(true);
        
        JLabel low = new JLabel();
        low.setBounds(25, 25, 100, 100);
        low.setBackground(new Color(255,0,0));
        low.setOpaque(true);
        layeredPane.add(low, new Integer(0));
        
        JLabel mid = new JLabel();
        mid.setBounds(100, 100, 50, 50);
        mid.setBackground(new Color(0,0,0));
        mid.setOpaque(true);
        layeredPane.add(mid, new Integer(1));
        
        JLabel high = new JLabel();
        high.setBounds(50, 50, 100, 100);
        high.setBackground(new Color(0,255,0,100));
        high.setOpaque(true);
        layeredPane.add(high, new Integer(10));
        
        add(layeredPane);
	}
}
If I comment out high then the output looks like this:



As soon as I turn it on I get this:



The transparency obviously works, but the black block is no longer showing. Is there a way to fix that?

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I'm a newbie, but I read up on opaqueness, and according to this http://stackoverflow.com/questions/2451990/setopaquetrue-false-java you may want not to set it to true, because as mid is completely covered by high, Swing doesn't paint mid out of economy. Or something. Also, it's too late for me now to actually test it myself... Or you may want to forget using "setOpaque" at all, according to that link.:shrug:... Alternatively, call repaint manually?

Futuresight
Oct 11, 2012

IT'S ALL TURNED TO SHIT!
The thing is I can't not use setOpaque if I try to do it this way as that is required to show the background of the JLabel. Reading through your link it seems that the only way around it (aside from splitting the image into small enough parts that none of them cover up another label) is to not use the JLabel background for this purpose. It should be fine to just draw the friggin thing so I'll do that now that I know this other approach is untenable. Thanks for that page, everything I found about transparency never mentioned the setOpaque problem so I never had reason to think I had to change approach.

Futuresight fucked around with this message at 23:43 on May 3, 2014

Brad Pitt
Nov 7, 2009

:smugdog::smugdog::smugdog::regd09:
Hey guys. I'm pretty dumb and am not figuring this out at all. I can't figure out how to plug in my array numbers into these equations for this assignment for my programming class. Here is what he wants:

code:
In this assignment you will initialize arrays and use them as input to methods.  
To begin, you will create two integer arrays named x and y.  
Next, you will initialize these arrays in your main method to the following:

X:100   7    49   -16 35  -9   81

Y:22    41   18    -28   33   27

Next, you will initialize a two dimension array name data where this array is
 a collection of x and y values. 
Next, initialize your array to the following:

Column 0:            50           3              22           -9            87

Column 1;            25           13           41           18           -2

With these initialize array you will create a method named compute that has as 
input parameters the x and y arrays.  In the first compute method you will code 
he following equation using the x and y arrays:

Z = 4*x2y + 2xy -7xy2

In the second compute method you will code the following equation using the data array:

Z = 9*x2y - 3xy + 7xy2

In both compute methods you will return the total summed value for z.

Last, in your main method you will invoke each method and print the following:

Value of Z for the x and y arrays is ___

Value of Z for data array is ___
And here is where I am stuck:

code:
public static void main(String[] args) {
		
		int x[]= {100,7,49,-16,35,-9,81};
		int y[]= {22,41,18,-28,7,33,27};
		
		compute(x);
		compute(y);
		
		int data[][]={{50,3,22,-9,87},{25,13,41,18,-2}};

		}

	public static void compute(int counter[]){
Be kind as I am really new to this, and thanks in advance for any help!

Fellatio del Toro
Mar 21, 2009

I think the most challenging part here is figuring out exactly what he's asking you to do.

I had to read it a few times but I think he wants two methods: the first one takes two arrays and returns an int, the second overloads the first and takes a two dimensional array.

The methods should take the result of the respective equations for each X/Y pair, add the results together, and return the total.

The last part should be self explanatory.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."

rhag posted:

That would be one way, but is not needed. You can create one worker that simply loads all the images, but as soon as it loaded one it fires a propertyChangeEvent, which will be listened for in the swing thread and the actual jtable model will be updated.
When an image is edited, yes, you will want to create a worker for that particular image.

I've finally gotten to it, and I've never worked with property changes before, because in the tutorial it has to be a bound property of the bean kind. Here I'm even more clueless how to go about it. Should I have the image list as the property, or an individual image? In the latter case, it probably won't be retrieved in a timely enough fashion.

For now, I decided that it should be the worker's internal list, which gets passed as the new value each time, and from it I retrieve the last value as the one that's just been added.

Edit: Am I doing it wrong?
code:
private class ImageWorker extends SwingWorker<Void, Void> {

        public final static String imageListProperty = "image list";

        ArrayList<ImageIcon> internalList = new ArrayList<>();

        @Override
        public Void doInBackground() {
            log("Started working");
            log("row count = " + table.getRowCount());
etc
For some reason it doesn't even output the row count. :(

supermikhail fucked around with this message at 10:51 on May 4, 2014

Brad Pitt
Nov 7, 2009

:smugdog::smugdog::smugdog::regd09:

Fellatio del Toro posted:

I think the most challenging part here is figuring out exactly what he's asking you to do.


That has definitely been the biggest challenge in this class. Just asking him how your pseudo code looks returns a very confusing and poorly worded responses.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Brad Pitt posted:

That has definitely been the biggest challenge in this class. Just asking him how your pseudo code looks returns a very confusing and poorly worded responses.

Yeah, basically what FdT said - he specifically says you need to create a method named compute which takes your x and y arrays as input parameters. So he's defined the method signature there - it needs to be named compute, and take two input parameters, both of which are 1-dimensional integer arrays (explicitly defined in the second line of your quote).

Take a look at the equation that compute() is meant to... compute. You have three variables in there - x, y and z. The spec says "in both compute methods you will return the total summed value for z" - so basically, your compute() method needs to work out the value of z when you give it two other values x and y.

The key word there is summed, that implies you need to produce a bunch of values for z and return the sum of them, and it makes sense seeing as you're not passing in a single value for x and y, you're passing in several values for each. So your compute() method will have to run that equation several times, once for each pair of x and y in the input arrays you're feeding it, and sum all of the results.

The phrasing "you will create a method named compute" and "in the second compute method" definitely implies both methods are supposed to be called compute(), except in the second one you're passing your data array instead, which is a 2-dimensional array. That means it has a different method signature than the first, and you're overloading it. If that's new to you have a quick look here: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
It basically means you can call compute() with different types of parameters and it will just use the appropriate code, instead of having to name everything differently.

If that all makes sense, hopefully you pretty much know how your program is meant to flow, and it's just a case of turning it into the appropriate Java code!

Volguus
Mar 3, 2009

supermikhail posted:

I've finally gotten to it, and I've never worked with property changes before, because in the tutorial it has to be a bound property of the bean kind. Here I'm even more clueless how to go about it. Should I have the image list as the property, or an individual image? In the latter case, it probably won't be retrieved in a timely enough fashion.

For now, I decided that it should be the worker's internal list, which gets passed as the new value each time, and from it I retrieve the last value as the one that's just been added.

Edit: Am I doing it wrong?
code:
private class ImageWorker extends SwingWorker<Void, Void> {

        public final static String imageListProperty = "image list";

        ArrayList<ImageIcon> internalList = new ArrayList<>();

        @Override
        public Void doInBackground() {
            log("Started working");
            log("row count = " + table.getRowCount());
etc
For some reason it doesn't even output the row count. :(

Honestly, I have no idea what you're doing there. Here's a simple sample project that does (hopefully) what you need: https://github.com/rhag/swingsample

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
:unsmigghh:

I haven't had time to check it out yet, but I just want to mark the occasion when other people have begun to do parts of my tasks. :dance:

hooah
Feb 6, 2006
WTF?
I'm going through the Java Trails, and for the Exercises here, I'm having a little trouble. Here's my PlayingCard class:
Java code:
package tutorial;

public class PlayingCard {
	private int rank;
	private String suit;
	public PlayingCard(){
		rank = 0;
		suit = null;
	}
	public PlayingCard(int r, String s){
		rank = r;
		suit = s;
	}
	public int getRank(){
		return rank;
	}
	public String getSuit(){
		return suit;
	}
	
}
The class for the deck of cards:
Java code:
package tutorial;

public class DeckOfCards {
	private int numberOfCards = 52;
	private PlayingCard[] myCards;
	public DeckOfCards(int num){
		numberOfCards = num;
		if(num == 52){
			for(int i = 0; i < 13; ++i){
				myCards[i] = new PlayingCard(i, "Hearts");
			}
			for(int i = 0; i < 13; ++i){
				myCards[i + 13] = new PlayingCard(i, "Diamonds");
			}
			for(int i = 0; i < 13; ++i){
				myCards[i + 26] = new PlayingCard(i, "Clubs");
			}
			for(int i = 0; i < 13; ++i){
				myCards[i + 39] = new PlayingCard(i, "Spades");
			}
		}
		else{
			for(int i = 0; i < num; ++i){
				myCards[i] = new PlayingCard();
			}
		}
	}
	public int howManyCards(){
		return numberOfCards;
	}
	public void printDeck(){
		for(PlayingCard card : myCards){
			System.out.println(card.getRank() + " " + card.getSuit());
		}
	}
}
And the test program:

Java code:
package tutorial;

public class CardTest {
	public static void main(String[] args){
		DeckOfCards deckOne = new DeckOfCards(52);
		DeckOfCards deckTwo = new DeckOfCards(10);
		deckOne.printDeck();
		deckTwo.printDeck();
	}
}
When I try to run the test, I get a null pointer exception on line 10 of the DeckOfCards class. I tried debugging it (I know next to nothing about the Eclipse debugger), and I was told that it couldn't find the source for "Thread.dispatchUncaughtException(Throwable)".

What's wrong with my solution? It appears that the error happens when it tries to add the first card, but the solution seems to do something similar:
Java code:
public class Deck {

    public static int numSuits = 4;
    public static int numRanks = 13;
    public static int numCards = numSuits * numRanks;

    private Card[][] cards;

    public Deck() {
        cards = new Card[numSuits][numRanks];
        for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++) {
            for (int rank = Card.ACE; rank <= Card.KING; rank++) {
                cards[suit-1][rank-1] = new Card(rank, suit);
            }
        }
    }

    public Card getCard(int suit, int rank) {
        return cards[suit-1][rank-1];
    }
}

Fellatio del Toro
Mar 21, 2009

You haven't initialized myCards.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Looks like you are trying to do a thing with myCards[i] before myCards itself is initialized

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

A NullPointerException is a sign that you're trying to access an object that doesn't exist. Take a look at the line where you're getting that exception, and see if there are any objects around that look suspicious. Here's some hints in some vague order of hintingness, although someone is probably gonna post before me!


Look at the Arrays bit of the trail, especially the "Creating..." section

Arrays are objects, even when they hold primitive data types (which yours doesn't, but still)

Look at the equivalent line in their solution, and look at the objects they're using. Work back through the code and see what they do with that object

:siren: THE ANSWER :siren: You haven't initialised your array. When you define private PlayingCard[] myCards you're creating a reference to an object. You're saying that myCards is a reference to an array object, that holds PlayingCard objects. You haven't actually created the array object itself, which is the first thing the solution code does.

When your loop goes to create the PlayingCard objects to put into the array, it isn't there. Your reference doesn't point to an object yet. Always gotta create the object before you can use it, or you'll hit a null, and probably get a NullPointerException to point you in the right direction (little joke there to keep my spirits up since I know two people already answered this before me)


e- welp

baka kaba fucked around with this message at 02:21 on May 7, 2014

hooah
Feb 6, 2006
WTF?
Ah, I see. Thanks, guys. I made a mental note when I read about initializing stuff that it's different than C++, but I didn't really take that to heart.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

hooah posted:

Ah, I see. Thanks, guys. I made a mental note when I read about initializing stuff that it's different than C++, but I didn't really take that to heart.

You still have to call new in C++ or malloc in C so its not really different... the syntax for declaring the array is just slightly different, I guess I see what you mean.

Zaphod42 fucked around with this message at 16:34 on May 7, 2014

HFX
Nov 29, 2004
Coding Practice question:

How common of a practice is it for you guys to clone the reference to a mutable object that is passed into your class (including arrays)?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
It's required to make any kind of hard guarantee that your code will always do the right thing, be immutable, or thread safe. Of course you can achieve a softer kind of guarantee if there's an agreement in your team to never modify those values once you pass them in, but that gets hard to enforce on larger teams and goes out the window once you have 3rd parties using the code, it's just easier to make the defensive copies than having that bite you in the rear end in the future.

HFX
Nov 29, 2004

Janitor Prime posted:

It's required to make any kind of hard guarantee that your code will always do the right thing, be immutable, or thread safe. Of course you can achieve a softer kind of guarantee if there's an agreement in your team to never modify those values once you pass them in, but that gets hard to enforce on larger teams and goes out the window once you have 3rd parties using the code, it's just easier to make the defensive copies than having that bite you in the rear end in the future.

It seems like if those are an issue, you are probably dealing with a direct interface that requires security, or you really shouldn't be using Java in the first place.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

HFX posted:

Coding Practice question:

How common of a practice is it for you guys to clone the reference to a mutable object that is passed into your class (including arrays)?

On our team, it is common practice to clone an object that we want to mutate unless the function looks specifically like it's intended to mutate the object. The function private void filterBadMatches(Set<Advertisement> adSet); would mutate adSet. It would be looked at as a bug if the function private Advertisement pickMostProfitableAdvertisement(Set<Advertisement> adSet) modified adSet in any way.

I mean, I understand that if you're passing around a List containing tens or hundreds of thousands of complex Objects, that this can be expensive to copy. I don't run into this situation very frequently. Our practice is to make things as immutable as possible - declare variables final whenever possible, use Builders instead of Beans, use Guava's ImmutableList, ImmutableMap, ImmutableSet where ever it makes sense. It's just easier to reason about things that you know will never change, which results in fewer bugs. As a developer, performance is like, my number three concern. I'm much more concerned about making sure that my code is bug-free and maintainable than about wasting a couple millis copping lists unnecessarily. I mean, hell, I'm going to be doing I/O at some point, probably with a database, maybe with a user over the Internet. That's where my application will spend 95% of it's time. Everything else is premature optimization.

We, uh, hardly ever use arrays. Byte-arrays are fairly typical when we're doing crypto/binary file stuff, I guess, but in almost every other case, we prefer Lists. An ArrayList has about the same performance of an array, but it implements the List interface, which is incredibly useful.

No no serious
Mar 24, 2010

It's working
I haven't written a line of java in years, so I'm out of the loop. I'm building a distributed app, doing mostly back-end stuff (maintain router configs, importing & exporting from & to other systems...). How does this sound as an architecture:

    * Three geographic datacenters, each with 2 machines, each with 2 VMs (existing deployment, can't change), plenty of ram, disk, & cpu...
    * Glassfish on each vm
    * Web load balancer in front for http
    * JMS configured
    * Clients (both web & cli) send device operation requests over JMS bus
    * Clients may be written in a scripting language (groovy, Perl, JavaScript) since there will end up being hundreds of different clients written mostly by a team of scriptors.
    * Any server that handled that device recently pulls the message from the bus (to reuse a possible existing connection).
    * If none, the least-busy & geographically-closest server pulls the message.
    * The device operation is performed, a response returned on JMS, and the device connection is kept alive for x minutes in case of near-future requests

I'm also thinking of using zookeeper to handle each server node configuration & state.

Sound reasonable? Would just GlassFish and possibly a scripting engine / bridge be enough?

No no serious fucked around with this message at 03:35 on May 9, 2014

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
What's the load going to look like? JMS is notoriously hard to log/debug; would a REST architecture work here? If clients are making GET requests, it's easy to set up Haproxy as a load balancer, log every request, keep track of who's handling what, etc. You can either balance round-robin, or configure your servers to report back to Haproxy with some sort of "healthiness" metric.

How are you determining "least busy and geographically closest?" Ideally, I'd want DNS to handle closest, and then allow my load-balancer to guess at least busy.

How cacheable are these requests? Do you want someone (like a CDN) obeying cache-control headers in the middle? A distributed cache, ie memcached? A local, in-memory cache, ie Guava Cache? How much "work" is being done to respond to a given request? Are there some requests that are more "difficult" than others, or are they all roughly equal? Where is the largest chunk of your round-trip-time being spent: the database, http, waiting in a queue for server resources?

How disparate can you get your VMs? We try to make sure that the same service is deployed on different blades (at least) or racks (ideally) within a given datacenter, so a blown fan doesn't disrupt the eastern United States.

I would definitely recommend using something like Zookeeper to handle node configuration and deployment. We use Chef, and are very happy with it.

hooah
Feb 6, 2006
WTF?

Zaphod42 posted:

You still have to call new in C++ or malloc in C so its not really different... the syntax for declaring the array is just slightly different, I guess I see what you mean.

What? You generally don't, unless you want to instantiate something on the heap. Creation of, say, a string on the stack is just string myString = "whatever";. Unless you were implicitly talking about using the heap. Speaking of, does Java use the heap for all non-primitive types?

Vicar
Oct 20, 2007

All objects are stored on the heap, yes

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."

rhag posted:

Honestly, I have no idea what you're doing there. Here's a simple sample project that does (hopefully) what you need: https://github.com/rhag/swingsample

It works! Thank you, rhag.

I look at that neat code, and then look at my code, where the model, renderers, editors, worker, and miscelaneous listeners are all in the same class... and just have to wonder if there's something wrong.

I apparently now only code at weekends. :ughh:

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

hooah posted:

What? You generally don't, unless you want to instantiate something on the heap. Creation of, say, a string on the stack is just string myString = "whatever";. Unless you were implicitly talking about using the heap. Speaking of, does Java use the heap for all non-primitive types?

We were explicitly talking about arrays.

You can allocate an array on the stack with just char *strs[10]; yeah, but that still allocates the size.

String[10] strs; isn't valid Java. You'd have to do String[] strs; which doesn't specify the size.

String[] strs = new String[10]; is just the java syntax for the same thing. Yeah you don't need the explicit keyword 'new' in that case on C, but the same syntax doesn't work, this is the closest. And like you said, its exactly the same as how it is handled in C++ on the heap.

String myString = "whatever"; works in Java too.

hooah
Feb 6, 2006
WTF?

Zaphod42 posted:

We were explicitly talking about arrays.

Yeah, I guess we were. Thanks for the expansion.

Adbot
ADBOT LOVES YOU

born on a buy you
Aug 14, 2005

Odd Fullback
Bird Gang
Sack Them All
If there a Java equivalent to Ruby's ||= operator?

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