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
Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Mustach posted:

code:
LinkedList<ArrayList<String>> result = new blah blah blah;
for(ArrayList<String> l : sourceList)
  result.add(new ArrayList<String>(l));

That's not a deep copy.

Adbot
ADBOT LOVES YOU

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.
There's no reason to deep copy Strings (or any other immutable object). If that's not what you mean, then I don't know what I'm missing.

Kaltag
Jul 29, 2003

WHAT HOMIE? I know dis ain't be all of it. How much of dat sweet crude you be holdin' out on me?
Whats the best way to make java do something every 3 hours then do nothing in between?

code:
while(true)
{
   Thread.sleep(3*60*60*1000);
   doSomething();
}
Seems too easy to be true. Of course I would add some code to make sure that the time that doSomething() took to run is counted, but this gets the basic idea across.

ynef
Jun 12, 2002

Kaltag posted:

Whats the best way to make java do something every 3 hours then do nothing in between?

code:
while(true)
{
   Thread.sleep(3*60*60*1000);
   doSomething();
}
Seems too easy to be true. Of course I would add some code to make sure that the time that doSomething() took to run is counted, but this gets the basic idea across.
Well, you can always over-engineer it by using a ScheduledExecutorService if you want, but what you had should work too.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Kaltag posted:

Whats the best way to make java do something every 3 hours then do nothing in between?

code:
while(true)
{
   Thread.sleep(3*60*60*1000);
   doSomething();
}
Seems too easy to be true. Of course I would add some code to make sure that the time that doSomething() took to run is counted, but this gets the basic idea across.

Use Quartz?

http://www.quartz-scheduler.org/

sonic bed head
Dec 18, 2003

this is naturual, baby!
if I have an xml string that looks like this:

code:
<word>john</word><word>mary</word><word>peter</word>
and I want to parse each word out individually using regular expressions, how would I do it? Right now, I have this:

code:
String test = "<word>john</word><word>mary</word><word>peter</word>";
 Pattern pattern = Pattern.compile("<word>.*?</word>");
	 Matcher m = pattern.matcher(test);
	 StringBuffer text = new StringBuffer();
	 while (m.find()) {
	  System.out.println(m.group());
	 }

The problem with this is that it includes all of the xml tags. Is there a way to do this without replaceAll("<word>","").replaceAll("</word>","");?

I don't want to use a sax or document parser because I think it's just way too much for what I really need. This seems like it would be a much simpler and faster solution than parsing the whole document when I only need a very small piece.

covener
Jan 10, 2004

You know, for kids!

quote:

code:
String test = "<word>john</word><word>mary</word><word>peter</word>";
 Pattern pattern = Pattern.compile("<word>.*?</word>");
The problem with this is that it includes all of the xml tags. Is there a way to do this without replaceAll("<word>","").replaceAll("</word>","");?

you're using the equiv of $0 instead of actually capturing the meat of what you're matching

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
You need to use capture groups in your regex.

So change it to <word>(.*?)</word>

then change m.group() to m.group(1).

epswing
Nov 4, 2003

Soiled Meat
Stop using regex to parse xml.

http://forums.somethingawful.com/showthread.php?threadid=2780384&pagenumber=51&perpage=40#post368046496

SplitDestiny
Sep 25, 2004

TRex EaterofCars posted:

You need to use capture groups in your regex.

So change it to <word>(.*?)</word>

then change m.group() to m.group(1).

Yeah, this is the correct way to do this with regular expressions. But parsing xml with regular expressions is almost always bad practice. I guess this will work if your xml string never changes white space, tagging, attributes etc.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
It's not terrible if it's a very small piece and he just needs a simple tool or what not. If this is going to be a part of some huge project then yeah use sax or xpath.

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.

epswing posted:

Stop using regex to parse xml.
I swear, this needs to be part of the title of every thread in this forum just to get the point across.

sonic bed head
Dec 18, 2003

this is naturual, baby!
Thanks! I know how to use the SAXParser, I even mentioned it in my post. This is a really small thing where there'll never be more than 4 or 5 words and I control the input xml. If it gets to be a problem, I have no issues in changing it, but for right now I think this small thing is all I need.

I get what you all are saying though, and I would never use this kind of thing with XML from a remote source.

I guess it would be fair to ask how much of a performance difference there is between using a parser and using regex for something as short as my example. I have a feeling it'd be a lot, but I don't really know.

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

Mustach posted:

I swear, this needs to be part of the title of every thread in this forum just to get the point across.

Quoting this as a proper source for answer doesn't hurt either http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454

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.

sonic bed head posted:

I get what you all are saying though, and I would never use this kind of thing with XML from a remote source.
If it is read by your program from a file (any file, anywhere), you can't trust it.

quote:

I guess it would be fair to ask how much of a performance difference there is between using a parser and using regex for something as short as my example. I have a feeling it'd be a lot, but I don't really know.
Using a real parser is probably more costly, but whether it truly is or if that cost has a noticeable impact on your program is an answer that only performance profiling can provide.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
What the gently caress, this is turning into the 21st century's version of "goto considered harmful." If he identified his problem domain and knows the solution for parsing this small portion of his document can be satisfied by a regular expression then who cares? He probably saved time by just doing the simplest thing that works and moving on. If the spec changes in the future and the document format changes he'll probably have to change the code anyhow.

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.
Oh no, three people told some guy he would be better off parsing XML instead of using regexes. It's outta control.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Mustach posted:

Oh no, three people told some guy he would be better off parsing XML instead of using regexes. It's outta control.

So you're saying we shouldn't listen to what you said?

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.
Sorry, I thought your "what the gently caress" reaction was overblown and responded to it sarcastically!

epswing
Nov 4, 2003

Soiled Meat
code:
String myString = ...
String xpath = ...
Document document = new SAXBuilder().build(new ByteArrayInputStream(myString.getBytes()));
List<Element> elements = XPath.newInstance(xpath).selectNodes(document);
My word, that was a lot of work. I'm going to lie down for a minute. Such complex code makes me weak at the knees. My hands tremble just thinking about it. I only have the strength and sheer willpower to use such magic for huge projects.

It's a one-liner :ssh:

Edit: On a more serious note, I personally find that creating a Pattern, giving it to a Matcher, and then iterating over groups to be particularly annoying considering how easy this is to do in other languages. I'm not sure why people flock to this error-prone method when XML is involved, considering just parsing the XML and selecting exactly what you want takes as much or maybe even less work.

To each his own, I suppose.

epswing fucked around with this message at 21:48 on Apr 6, 2010

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Mustach posted:

Sorry, I thought your "what the gently caress" reaction was overblown and responded to it sarcastically!

I get riled up when I hear a bunch of bleating about "ALWAYS DO THIS" or "NEVER DO THAT". Never and always are dangerous words, especially in something like programming. Plus it wasn't just those 3 posts that got me going; as evidenced by the stack overflow thread, it's starting to get pretty prevalent in the programming community.

Also ^^^ yeah matcher and pattern are poo poo but it's not like he's trying to make a browser here.

1337JiveTurkey
Feb 17, 2005

ynef posted:

Well, you can always over-engineer it by using a ScheduledExecutorService if you want, but what you had should work too.

I'd say that 90% of my stress at work is from people ignoring established solutions to complex problems in favor of their own hacked together solutions that mistake their inability to understand the entirety of the problem for an eye for elegance. It's one loving object with a one argument constructor and a method that takes the exact same Runnable he'd have to write otherwise plus however long he wants to wait. It doesn't get any loving simpler than:

code:
Runnable periodicTask = new Runnable(){/* stuff */} 
// One thread in the pool since it's just running this task
ScheduledExecutorService myService = new ScheduledThreadPoolExecutor(1);
// No initial delay, 3 hours from task start to start
myService.scheduleAtFixedRate(periodicTask, 0, 3, TimeUnit.HOURS);
I tossed in a couple of comments to hopefully make the purely numeric method arguments as obvious as humanly possible for someone who's never touched the API before. It's far easier for someone new to understand than the alternative while still allowing for a great deal of future flexibility.

Long story short: Use java.util.concurrent unless you're using Swing or JEE in which case consider the more specialized variants that they provide.

epswing
Nov 4, 2003

Soiled Meat

1337JiveTurkey posted:

I'd say that 90% of my stress at work is from people ignoring established solutions to complex problems in favor of their own hacked together solutions

Yes. I'd say this is closer to 60% of my stress at work. Unless I'm doing something that no one else in the world has ever done (hah), I'm a fan of following established solutions aka doing things The Right Way (tm) (r) (c). Software is too complicated, otherwise.

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

epswing posted:

Edit: On a more serious note, I personally find that creating a Pattern, giving it to a Matcher, and then iterating over groups to be particularly annoying considering how easy this is to do in other languages. I'm not sure why people flock to this error-prone method when XML is involved, considering just parsing the XML and selecting exactly what you want takes as much or maybe even less work.

To each his own, I suppose.

code:
Matcher m = Pattern.compile(regex).matcher(string);
for (int i=1;i<m.groupCount();i++) {
    doWhateverWith(m.group(i));
}
:confused:

epswing
Nov 4, 2003

Soiled Meat
I'm saying that regexing XML is error-prone.

And I said using Pattern/Matcher is about the same amount of code as just parsing the XML, which you just demonstrated.

I'm not sure how you missed the point, which was "use the right tool for the job."

epswing fucked around with this message at 17:34 on Apr 7, 2010

Fly
Nov 3, 2002

moral compass

TRex EaterofCars posted:

I get riled up when I hear a bunch of bleating about "ALWAYS DO THIS" or "NEVER DO THAT". Never and always are dangerous words, especially in something like programming. Plus it wasn't just those 3 posts that got me going; as evidenced by the stack overflow thread, it's starting to get pretty prevalent in the programming community.

Also ^^^ yeah matcher and pattern are poo poo but it's not like he's trying to make a browser here.
However, I think it's good to practice doing simple things the right way, particularly when it's easy. The habit makes doing the right thing in more complex situations much more natural.

r2x
Jan 13, 2008
What did the teapot say to the chalk?

Nothing, you silly. Teapots can't talk.
I've been reading up on Java (and a bit of C#) and I was wondering if theres any good beginner project ideas out there to get me motivated (and maybe some decent toolkits/apis/libraries). I've gone through chapters on recursion/inheritance/collections and etc (only real chapters with crucial ideas left are networking and threads).

Flamadiddle
May 9, 2004

As a beginner in Java myself, I can just recommend making up your own project. I made a game of battleships, made pong and have recently built a decent website and server testing utility using inheritance and interfaces properly. What sort of stuff are you interested in?

Threading has been the hardest thing to get right, so far. I've been learning by building a representation of a traffic light system, but there are so many applications which could use threads that there's no end of possible projects to try them out in.

epswing
Nov 4, 2003

Soiled Meat
Threading: elevator simulator!

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Can anyone here tell me why this is overflowing?

I'm trying to insert a value into a hash table using quadratic probing.

code:
	public boolean insert(String str)
	{
		int key = hash(str);
		int probe = key;
		int k = 1;
		
		do
		{
			if((table[probe] == null)) // overflow loops to here
			{
				table[probe] = str;
				count++;
				
				return true;
			}
			// it makes the overflow around here
			probe = (key + step(k)) % length();
			if(probe < 0)
				System.out.println(step(k));
			k++;
		}
		while(probe != key);
		
		System.out.println(str + " collided at key " + key);
		return false;
	}

	private int step(int k)
	{
		return (k * k) % length();
	}

	public int length()
	{
		return table.length;
	}
hash() generates a positive integer.

Wooper
Oct 16, 2006

Champion draGoon horse slayer. Making Lancers weep for their horsies since 2011. Viva Dickbutt.
step(k) overflow at k = 2^(15.5). The mod-operator may also return a negative number I believe.

Other than that I don't know.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Wooper: the % operator in Java is not a modulus, it's a remainder. If the left-hand operand is negative, % will have no effect.

edit:
drcru: If hash() returns an int that could be as high as about 2^31, any length greater than zero could reasonably overflow.

Internet Janitor fucked around with this message at 00:54 on Apr 13, 2010

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Unless hash() is guaranteed to be less than length(), you're quite likely to get an ArrayIndexOutOfBoundsException the first time through the loop, before quadratic probing ever kicks in. Do you see why?

EDIT: Actually, since you're pretty clearly practicing the "throw % around and pray" technique, you're probably doing it in hash(), too. Your basic problem is that % implements round-towards-zero division, as IJ mentions, which means that it can (and probably will) be negative when the dividend is negative. Just test for this and add length(); who knows, the JIT might even be smart enough to compile this with a round-towards-negative-infinity modulus instruction if the processor has one.

EDIT 2: Note that % does not "have no effect" when the dividend is negative. All sensible division operators obey the identity (a/b)*b + (a%b) == a (for b != 0). Java's / and % implement round-towards-zero division, so that e.g. -7 / 3 == -2, which (if the identity is to hold) means that -7 % 3 == -1. There is no way to request a round-towards-negative-infinity division/modulus directly.

rjmccall fucked around with this message at 01:30 on Apr 13, 2010

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Well drat, you're right. Good call, rjmccall.

These threads are always teaching me things.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Welp. I added a check if it's negative after the first probe loop and added length() like you guys suggested.

code:
probe = (key + step(k)) % length();
if(probe < 0)
	probe += length();
Does that seem right to you guys? It seems to be filling my hash table 100% now like it's supposed to. If that is right... why is that right? Are we rolling the index over for overflows?

My hash() didn't seem to return any negative integers after 230k or so dictionary words either. I'm hoping that it wasn't my hashing making the probe negative.

Thanks goons.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

drcru posted:

Are we rolling the index over for overflows?

That is indeed exactly what we are doing.

rawstorm
May 10, 2008

by Ozma
I made a program in Java and it runs fine, but just recently for some unknown reason when I ran it it ran about 10 times faster than it should have. Basically there are balls moving on the screen, except the balls were moving a lot faster then they should have been. I ran it on the same computer I've been running it for a while, so it isn't that my computer is faster. I think it had something to do with the fact that I had Firefox open and Eclipse open and was running another Java app at the time. Can someone shed some light on this. I use a timer in my program that I set to 1ms because I want the program to go as fast as possible.

e:

Wow, this is really weird. I had Firefox open, and then I opened the program and it was running fine. Then I opened a new blank tab in Firefox and the program kept running fine. Then I went to https://www.cnn.com in the new tab, switched quickly back to my program, and it ran at normal speed for about 2 seconds and then suddenly started going really fast. What the hell is going on !?

rawstorm fucked around with this message at 06:09 on Apr 14, 2010

epswing
Nov 4, 2003

Soiled Meat
It's a known fact that CNN speeds up Java (tm) (r) (c) programs.

rawstorm
May 10, 2008

by Ozma

epswing posted:

It's a known fact that CNN speeds up Java (tm) (r) (c) programs.

Well it actually happens when I go to SA also, so I don't think it's a website specific thing.

Adbot
ADBOT LOVES YOU

8ender
Sep 24, 2003

clown is watching you sleep

sonic bed head posted:

I don't want to use a sax or document parser because I think it's just way too much for what I really need.

I know you don't want to use a parser and I'm late to the game here but check this out:
http://xstream.codehaus.org/

XML to Objects. Its like magic. If your XML is going to be pretty consistant its a great tool.

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