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
JoeWindetc
Jan 14, 2007
JoeWindetc

rjmccall posted:

All I mean by generic typing is that if you always use appropriate type parameters on your collections (e.g. ArrayList<String>), and you never work around the type system by letting their types decay (e.g. to a naked ArrayList), it will not be possible to ever accidentally put the wrong kinds of object in the collection (e.g. lists of strings instead of strings).

Right, and I went back and added in the types, as I figure it's probably best practice to do so. @SuppressWarnings fixed it all, but that's kind of a cop out. Thanks to yatagan also for possible solutions.

Adbot
ADBOT LOVES YOU

Vandorin
Mar 1, 2007

by Fistgrrl
I'm trying to make a copy method, and here is what I have so far
code:
public Picture paste(Picture smallPicture, int x, int y)
    {
        this.moveTo(x,y);
        System.out.print(smallPicture);
    }
It's not finished, but when I try to compile it, I get the error :
"Cannot find symbol- Method moveTo(int,int)" I'm trying to make it move the picture to a certain place, and then print it out, and am not sure why moveTo isn't working. Does anyone know?

Shavnir
Apr 5, 2005

A MAN'S DREAM CAN NEVER DIE

Vandorin posted:

I'm trying to make a copy method, and here is what I have so far
code:
public Picture paste(Picture smallPicture, int x, int y)
    {
        this.moveTo(x,y);
        System.out.print(smallPicture);
    }
It's not finished, but when I try to compile it, I get the error :
"Cannot find symbol- Method moveTo(int,int)" I'm trying to make it move the picture to a certain place, and then print it out, and am not sure why moveTo isn't working. Does anyone know?

The line

this.moveTo(x,y);

Tries to call a method in the class you're currently in. Does the Picture class have a moveTo method?

Vandorin
Mar 1, 2007

by Fistgrrl

Shavnir posted:

The line

this.moveTo(x,y);

Tries to call a method in the class you're currently in. Does the Picture class have a moveTo method?

I thought the picture class had a moveTo method. I remember using it to move little turtles around, but now I don't know.

Shavnir
Apr 5, 2005

A MAN'S DREAM CAN NEVER DIE

Vandorin posted:

I thought the picture class had a moveTo method. I remember using it to move little turtles around, but now I don't know.

Is your method in the Picture class?

Vandorin
Mar 1, 2007

by Fistgrrl

Shavnir posted:

Is your method in the Picture class?

Yes. I just added it after the last method.

Shavnir
Apr 5, 2005

A MAN'S DREAM CAN NEVER DIE

Vandorin posted:

Yes. I just added it after the last method.

Huh. Yea, I'd go double check that you've got a moveTo method taking two ints, because your compiler sure as hell thinks you don't.

Vandorin
Mar 1, 2007

by Fistgrrl

Shavnir posted:

Huh. Yea, I'd go double check that you've got a moveTo method taking two ints, because your compiler sure as hell thinks you don't.

Yeah, now that I've looked a little closer, I don't see it anywhere. Also, is it possible to paste a picture, on top of another picture, without it opening a new window? Because I sure as hell can't figure it out.

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost

Parantumaton posted:

Being interested in dynamic clustering, how does Terracotta scale in practice, do I have to bring the whole cluster down to add more nodes or can I dynamically pour more resources into it, what are the limits/caveats you've hit at with it etc?
I'm not on it, but from talking with the two other devs working on it, they haven't run into scaling problems except for I/O (typical for any clustering solution, haha) and there's nothing that would keep someone from adding more nodes on the fly, although I remember we uncovered some bugs with adding new nodes to a running cluster. The interfaces are pretty clunky and configuration looks disgusting though, which isn't surprising for such new software. The other guys have been working with the Terracotta devs to get all our stuff to work, and it does appear that we've managed to find bugs with their distributed JVM implementation that I am a little wary of recommending it for production right now. However, I do think it's worth a very serious look now for a lower-level clustering solution for your J2EE apps because everything should be fixed by the time staging is over for most environments.

Mill Town
Apr 17, 2006

Vandorin posted:

Yeah, now that I've looked a little closer, I don't see it anywhere. Also, is it possible to paste a picture, on top of another picture, without it opening a new window? Because I sure as hell can't figure it out.

That's certainly something that is possible with Java. To tell you if it's possible from within the Picture class, though, we'd have to see the code for the whole class.

Fly
Nov 3, 2002

moral compass

Parantumaton posted:

POI is designed to be one of those API:s which build everything in memory and then dump the final result into wherever you direct it to dump so no, any POI API -inluding HSSF - will most likely never allow you to use it for massive spreadsheets etc.
Building the spreadsheet in memory is true of Jexcel as well, but POI managed to use about ten times as much memory as Jexcel to build the same spreadsheet, which more severely limited the usefulness of POI. I think some of the memory issues may have been addressed, but I have never had a reason to reevaluate our Excel generation library.

karuna
Oct 3, 2006
I am trying to populate an array with random numbers in parallel.

When I build it using Eclipse I get the error: "There is an error in the required project - Threads"

Not very helpful! I'm at a loss as to what is wrong, any help would be appreciated.

code:

public class PopulateArray extends Thread {
	
	private int f[];
	private int a,b;
	private int x;
	
	public PopulateArray(int list[],int a, int b, int x){
		f = list; this.a = a; this.b = b; this.x = x;
	}
	
	@Override
	public void run() {
		for(int j = a; j < b; j++) {
			f[j] = x;
		}
		
	}

}

public class ShuffleResult {

	public static void main(String[] args) {
		//Populate array
		int list[] = new int[100];
	
		Thread t = new PopulateArray(list, 0 , 50 , (int)Math.random()* 100);
		Thread t1 = new PopulateArray(list, 50 , list.length , (int)Math.random()* 100);
		
		t.start(); t1.start();
		try{
			t.join(); t1.join();
		}
		catch(InterruptedException e){ }
		
		//Print array
		for(int i : list){
			System.out.print(list[i] + " ");
			
		}
	}

}

Vandorin
Mar 1, 2007

by Fistgrrl
I keep getting an array out of bounds error, and I can't figure out why.

code:
  public void paste()
     {
         // create the butterfly pictures
         Picture butterflyPicture = new Picture(FileChooser.getMediaPath("butterfly.jpg"));
         
         // Declare the source and target pixel variables
         Pixel sourcePixel = null;
         Pixel targetPixel = null;
         // save the heights of the pictures
         int butterflyHeight = butterflyPicture.getHeight();

         /*Copy the first butterfly picture to 5 pixels from the bottom lfeft corner of the current picture
          *
          */
         for (int sourceX = 0, targetX = 0;sourceX < butterflyPicture.getHeight();sourceX++, targetX++)
         {
             for( int sourceY = 0, targetY = this.getHeight() - butterflyHeight - 5; sourceY < butterflyPicture.getHeight(); sourceY++,targetY++)
             {
                 sourcePixel = butterflyPicture.getPixel(sourceX,sourceY);
                 targetPixel = this.getPixel(targetX,targetY);
                 targetPixel.setColor(sourcePixel.getColor());
                }
          }
          

tef
May 30, 2004

-> some l-system crap ->

Vandorin posted:

I keep getting an array out of bounds error, and I can't figure out why.

X is width, Y is height?

Vandorin
Mar 1, 2007

by Fistgrrl

tef posted:

X is width, Y is height?

Yes, shouldn't it be?

Shavnir
Apr 5, 2005

A MAN'S DREAM CAN NEVER DIE

Vandorin posted:

Yes, shouldn't it be?

I think he was hinting at what was wrong :ssh:

RussianManiac
Dec 27, 2005

by Ozmaugh

karuna posted:

I am trying to populate an array with random numbers in parallel.

When I build it using Eclipse I get the error: "There is an error in the required project - Threads"

Not very helpful! I'm at a loss as to what is wrong, any help would be appreciated.

code:

public class PopulateArray extends Thread {
	
	private int f[];
	private int a,b;
	private int x;
	
	public PopulateArray(int list[],int a, int b, int x){
		f = list; this.a = a; this.b = b; this.x = x;
	}
	
	@Override
	public void run() {
		for(int j = a; j < b; j++) {
			f[j] = x;
		}
		
	}

}

public class ShuffleResult {

	public static void main(String[] args) {
		//Populate array
		int list[] = new int[100];
	
		Thread t = new PopulateArray(list, 0 , 50 , (int)Math.random()* 100);
		Thread t1 = new PopulateArray(list, 50 , list.length , (int)Math.random()* 100);
		
		t.start(); t1.start();
		try{
			t.join(); t1.join();
		}
		catch(InterruptedException e){ }
		
		//Print array
		for(int i : list){
			System.out.print(list[i] + " ");
			
		}
	}

}


I got it to compile just fine. The one thing that could be wrong is that both of those classes are in same file. You need separate .java file for each public class. Just move PopulateArray into ShuffleResult and declare it as public static class. I compiled it using javac on my machine without any errors.

karuna
Oct 3, 2006

RussianManiac posted:

I got it to compile just fine. The one thing that could be wrong is that both of those classes are in same file. You need separate .java file for each public class. Just move PopulateArray into ShuffleResult and declare it as public static class. I compiled it using javac on my machine without any errors.


I had them in separate files within a package, I just created a new package and is compiling fine now.

My threads don't seem to be running though, the list[] output is 100 zeros.

Shouldn't the run method in PopulateArray be executed for each thread and apply to the list[]? So why isn't the list been populated with random numbers?

lamentable dustman
Apr 13, 2007

🏆🏆🏆

karuna posted:

I had them in separate files within a package, I just created a new package and is compiling fine now.

My threads don't seem to be running though, the list[] output is 100 zeros.

Shouldn't the run method in PopulateArray be executed for each thread and apply to the list[]? So why isn't the list been populated with random numbers?

take a look at the java order of precedence

karuna
Oct 3, 2006

osama vin diesel posted:

take a look at the java order of precedence

Ok I think I'm understanding you, is there an issue with casting the Math.random()?

When I change

code:
Thread t = new PopulateArray(list, 0 , 50 , (int)Math.random()* 100);
to

code:
Thread t = new PopulateArray(list, 0 , 50 , 2);
The output of the whole thread is 2 but it is only meant to apply to the first 50 elements?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

karuna posted:

Ok I think I'm understanding you, is there an issue with casting the Math.random()?

When I change

code:
Thread t = new PopulateArray(list, 0 , 50 , (int)Math.random()* 100);
to

code:
Thread t = new PopulateArray(list, 0 , 50 , 2);
The output of the whole thread is 2 but it is only meant to apply to the first 50 elements?
Your cast is truncating the Math.random() to a 0 then multiplying by 100.

RussianManiac
Dec 27, 2005

by Ozmaugh
Are you getting compile time error or run-time? Because there are no compile time errors in your code on javac 1.6

the onion wizard
Apr 14, 2004

karuna posted:

The output of the whole thread is 2 but it is only meant to apply to the first 50 elements?

code:
	//Print array
	for(int i : list){
		System.out.print(list[i] + " ");
		
	}
Take another look at this section.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

oval office.exe posted:

code:
	//Print array
	for(int i : list){
		System.out.print(list[i] + " ");
		
	}
Take another look at this section.

why? that is fine, it is printing out the same number 50 times because he is passing an int as x and only gets set once per thread

karuna
Oct 3, 2006
I've solved this now, can see now why it was only generating 0's or printing the same number when directly defined.

I am using the random class now and works fine calling get nextInt() within the loop in the run method.

Thanks for the help, I'm sure I'll be back ;)

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've never done anything concurrently with threads and such in java. What's a good small project I can do to learn about them?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
In one of my classes they had us make a multi threaded expression solver. It was really neat because it entailed finding all the parts of the expression that could be solved independently, then solving them, and then putting it all back together again.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

fletcher posted:

I've never done anything concurrently with threads and such in java. What's a good small project I can do to learn about them?

Make a simple GUI where the user write a file name in a text box and then presses a button, and in the background you load the file and then display it in a text box. Now make it work even if the user changes his mind while you're still loading the file.

Very simple, but still a good introduction to threads.

the onion wizard
Apr 14, 2004

osama bin diesel posted:

why? that is fine, it is printing out the same number 50 times because he is passing an int as x and only gets set once per thread

He's gotten his loops confused. He probably wants either:
code:
for (int i : list) {
	System.out.print(" " + i);
}
or
code:
for (int i = 0; i < list.length; i++) {		
	System.out.print(" " + list[i]);
}
Edit: or he's trying to print it in a random order, and I'm the one that's confused.

the onion wizard fucked around with this message at 11:30 on Oct 17, 2009

dis astranagant
Dec 14, 2006

I'm writing a simple http proxy to learn socket programming (it currently only implements GET), but all the output it sends has a null byte (0x00) before each byte of the expected output. I am using DataOutputStream.writeChars(String) to send http headers and DataOutputStream.write(byte[],int offset, int length) to send the body of an http response. Anyone know what's causing this?

e: switching from writeChars to writeUTF almost fixes it, except for 2 extraneous bytes at the start of the body that make no sense and aren't in the original string. No clue what's going on with the byte array output, though.

dis astranagant fucked around with this message at 19:38 on Oct 19, 2009

Max Facetime
Apr 18, 2009

Short answer: when getting a byte representation of a String for transmission, you want to specify the encoding to use, in this case ASCII or UTF-8.

Longer answer: Java Strings are stored in memory as a 2-byte Unicode variant codepoints, and the deal with data stream classes is that they closely mimic the memory storage. So those zeros are what's in memory.

e: also, DataOutputStream writes the lengths of Strings so that a DataInputStream could read them back in, so you probably shouldn't use it unless there's a corresponding class reading it back in.

Max Facetime fucked around with this message at 19:58 on Oct 19, 2009

dis astranagant
Dec 14, 2006

tkinnun0 posted:

Short answer: when getting a byte representation of a String for transmission, you want to specify the encoding to use, in this case ASCII or UTF-8.

Longer answer: Java Strings are stored in memory as a 2-byte Unicode variant codepoints, and the deal with data stream classes is that they closely mimic the memory storage. So those zeros are what's in memory.

That doesn't explain the behavior I'm getting just trying to send a byte array down the pipe (they seem to get converted to shorts or something), nor the random 2 bytes (0x248) at the start of the header when I send using writeUTF() (which is supposed to be UTF8).

tkinnun0 posted:

e: also, DataOutputStream writes the lengths of Strings so that a DataInputStream could read them back in, so you probably shouldn't use it unless there's a corresponding class reading it back in.

Ugh, and I was told that DataOutputStream was the only way to send text and binaries over the same socket. JAVA :argh:

dis astranagant fucked around with this message at 20:09 on Oct 19, 2009

Max Facetime
Apr 18, 2009

dis astranagant posted:

Ugh, and I was told that DataOutputStream was the only way to send text and binaries over the same socket. JAVA :argh:

It's a good way if you're transmitting between Java programs and don't mind using your own protocol.

But interfacing with the rest of the world, it's better to use a dedicated library or low-level calls like

String.getBytes(String charsetName) and
OutputStream.write(byte[] bytes, int off, int len)

dis astranagant
Dec 14, 2006

tkinnun0 posted:

String.getBytes(String charsetName) and
OutputStream.write(byte[] bytes, int off, int len)

Worked beautifully. I could even browse the forms with it if I turned up the max object size.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
It's incredibly unlikely to actually happen, but if you start caring about performance and this section shows up as a hot spot, consider switching to the ByteBuffer and CharsetEncoder APIs; they're pretty clean to work with, and you can avoid a lot of unnecessary buffer allocations and copies.

Fly
Nov 3, 2002

moral compass

dis astranagant posted:

e: switching from writeChars to writeUTF almost fixes it, except for 2 extraneous bytes at the start of the body that make no sense and aren't in the original string. No clue what's going on with the byte array output, though.
Could that be a byte-order mark (BOM)? http://unicode.org/faq/utf_bom.html#BOM

1337JiveTurkey
Feb 17, 2005

Fly posted:

Could that be a byte-order mark (BOM)? http://unicode.org/faq/utf_bom.html#BOM

It's the length of the encoded string in bytes. The actual string encoding isn't exactly UTF-8, but instead a modified version which preserves surrogate pairs and null characters without leaving any embedded nulls in the encoded bytes. That method is more for quick and efficient byte-for-byte precision in the deserialized data than it is for byte-for-byte precision in the serialized form.

Fly
Nov 3, 2002

moral compass

1337JiveTurkey posted:

It's the length of the encoded string in bytes.
Thanks. Obviously I would know this had I bothered to look at the on-line Javadoc for DataOutputStream.writeUTF().

geeves
Sep 16, 2004

This isn't exactly elegant or the best solution.

I have 1000s of XML files that reference each other. Each xml file has a "story_id" and may contain a "related_story_id".

The related_story_id matches the file's name story_[related_story_id].xml

Then it reads the related file and adds the primary_uri element value to a String[].

This is all output of Bricolage (an archaic and terrible CMS) via SOAP; unfortunately there's no time to go through and traverse the DB schema, but after spending the past few hours on this, I'm starting to wonder if it would be quicker.

in "parseRelatedStory" I'm getting a NullPointerException and no values are being added to String[] relatedLinks and the line after which should output to the log file does not work.

Should String[] relatedLinks actually be a HashMap? This nearly same block of code (except for a different subset of elements in the same XML file) works. I'm not sure why it may be failing here.


code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assets xmlns="http://bricolage.sourceforge.net/assets.xsd">
 <story id="37903" uuid="387EB6AC-3BCA-11DE-97D9-53C038788F35" element_type="product_page">
  <primary_uri>/pubs/corporate_pubs/CP558/index.html</primary_uri>
  <elements>
   <container order="15" element_type="linkbar">
    <container order="0" element_type="bricolage_link" related_story_id="37485">
     <field order="0" type="link_text">Catalog</field>
    </container>
    <container order="1" element_type="bricolage_link" related_story_id="37482">
     <field order="0" type="link_text">Brochure</field>
    </container>
    <container order="2" element_type="bricolage_link" related_story_id="37483">
     <field order="0" type="link_text">Brochure</field>
    </container>
    <container order="3" element_type="bricolage_link" related_story_id="37484">
     <field order="0" type="link_text">East Brochure</field>
    </container>
   </container>
  </elements>
 </story>
</assets>
php:
<?

private String[] relatedLinks;

public String[] execute() {

    Iterator<Element> childs = null;
    Element child = null;

// field is private, but set here by a setter
    childs = field.getChildren().iterator();
    while (childs.hasNext()) {
        child = (Element) childs.next();
        if ("linkbar".equals(kid.getAttributeValue("element_type"))) {
            parseStoryXml(child);
        }
    }
    return relatedLinks;
}

private void parseStoryXml(Element elements) {

    Iterator<Element> containers = elements.getChildren().iterator();
    Element container = null;
    int i = 0;
    while (containers.hasNext()) {
        container = (Element) containers.next();
        if ("bricolage_link".equals(container.getAttributeValue("element_type"))) {
            if (!"".equals(container.getAttributeValue("related_story_id"))) {
                String story_id = "story_" + container.getAttributeValue("related_story_id");
                parseRelatedStory(story_id, i);
                i++;
            }

        } else if ("non_cms_link".equals(container.getAttributeValue(element_type))) {
            parseExternalLink(container, i);
            i++;
        }
    }
}

private void parseRelatedStory(String story_id, int i) {

    try {
        Document doc = null;
        String fileName = getRelatedUri(story_id);
        boolean isPrimaryUri = false;
  
            SAXBuilder sax = new SAXBuilder();
            doc = sax.build(fileName);

            Element assets = doc.getRootElement();
            Element story = null;
            Element field = null;

            Iterator<Element> fields = null;
            Iterator<Element> stories = assets.getChildren().iterator();

            while (stories.hasNext()) {

                story = (Element) stories.next();
                fields = story.getChildren().iterator();

                while (fields.hasNext()) {
                    field = (Element) fields.next();
                    if ("primary_uri".equalsIgnoreCase(field.getName())) {
                        if (!"".equals(field.getValue())) {
                            isPrimaryUri = true;
                            log.info("main story: " + storyId);
                            log.info("FileName: " + fileName);
                            log.info("Primary URI: " + i + " : " + field.getValue());
                            
                            // All of these logs show up when the script is running.
                            // nothiing is added to relatedLinks
                            relatedLinks[i] = field.getValue();

// this does not output to the error.log file!
                            log.info("relatedLinks length: " + relatedLinks.length);
                        }
                        // no need to continue parsing the XML file
                        break;
                    }
                }
                if (isPrimaryUri) {
                // no need to continue parsing the XML file
                    break;
                }
            
        } else {
            log.error("fileName is NULL");
        }
    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        log.error("parseRelatedStory:JDOM: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.error("parseRelatedStory:IOException - Most likely FileNotFound " + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) { // also tried this with NullPointerException  - catch works, no message
    // e.getMessage doesn't show anything
        log.error("parseRelatedStory:Exception " + story_id + " " + e.getMessage());
    }
}

?>
^^ I also tried to specifically use NullPointerException - also worked, but no additional info.


Log file output this repeats for each main story_id
code:
*INFO* GET /pubsImport.html ] BricXMLParseHelper main story: 37899
*INFO* GET  /pubsImport.html ] BricXMLParseHelper FileName: /dev1/product_page_xml/story_37939.xml
*INFO* GET  /pubsImport.html ] BricXMLParseHelper Primary URI: 0 : /CP562.1/index.html
*ERROR* GET  /pubsImport.html ]BricXMLParseHelper parseRelatedStory:Exception story_37939

Any thoughts? Am I blatantly missing something?

Adbot
ADBOT LOVES YOU

Max Facetime
Apr 18, 2009

geeves posted:

Any thoughts? Am I blatantly missing something?

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>();

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