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
Moon Whaler
Jul 1, 2007

csammis posted:

Is it possible that the data type you're using to store the nanoTime result (or the subtraction result) is overflowing and wrapping?

I don't think so, I'm using a long. I'm pretty sure what' happening is sometimes it tries to compare times given by two different processors and gets a garbage result. I guess I'll just have to run it on another machine.

Adbot
ADBOT LOVES YOU

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

jstirrell posted:

Poker Stuff

Any help would be greatly appreciated!

I didn't get a chance to look at your code, but with a quick glance I noticed you had a lot of constants in your code. Read up on Enums, they replaced the public static int paradigm. As a bonus, that tutorial has some code for creating a poker deck! Some of the code might be over your head so feel free to ask us any questions about it.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I have a string that contains some HTML that has <input> and <img> tags that aren't properly closed with a />

I'm thinking I can use the string.replaceAll(regex, replacement). I found a pattern that I want on regexlib.

It seems to find them just fine, but I'm not sure what to put for the replacement string that will preserve what the rest of the attributes.

somehtml = somehtml.replaceAll("<input([^>]*[^/])>", "<input />");

Outlaw Programmer
Jan 1, 2008
Will Code For Food

fletcher posted:

I have a string that contains some HTML that has <input> and <img> tags that aren't properly closed with a />

I'm thinking I can use the string.replaceAll(regex, replacement). I found a pattern that I want on regexlib.

It seems to find them just fine, but I'm not sure what to put for the replacement string that will preserve what the rest of the attributes.

somehtml = somehtml.replaceAll("<input([^>]*[^/])>", "<input />");

The stuff inside of the parentheses in the regex is captured and can be accessed by using $1, $2, etc. (depending on the group number). So, in your case, this should work:

somehtml = somehtml.replaceAll("<input([^>]*[^/])>", "<input$1/>");

I tested and it looks OK but I suck with regular expressions so maybe someone else can chime in.

Keeper of Bees
Apr 29, 2008
I'm in somewhat dire need of help with some array methods. Specifically, 2D arrays used to store pixel information.

An example of what I'm having trouble with is rotating a given array to the left, like this:

code:
    {1 2}          { 2 4 6 }
    {3 4}  ----->  { 1 3 5 } 
    {5 6}           
    
This is certainly trivial to anyone with real experience, but I'm having trouble wrapping my head around it. As I understand it, I must create a new array and repopulate it with the correct values.

Are there any good online resources for this subject?

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Keeper of Bees posted:

image stuff

If you are using a BufferedImage you should be able to get a Grapics2D object out of it and IIRC it has some rotate methods.

If all you are doing is what is in your example though it should be hard to do manually. From your example, get the dimensions of your array using array.length and array[0].length. From that create a new array flipping the dimensions. Fill the second array using the standard double for loops just do array2[j][i] = array[i][j]. Or something to that effect.

Rounin
Sep 21, 2003
No time to read, now that I've finished shitting out my retarded opinions, I gotta go ~*~clubbin~*~ l8r bois
I have some binary data that I'd really, really like to include in a byte[] array in my source code. I've tried including it as both octal and hex, but I keep getting the compilation error "possible loss of precision". "found: int" "required: byte".

Obviously the data is in bytes, but the compiler insists that it's ints. Each byte can be cast to a byte using (byte), but that makes the source code so long the compiler gives up.

Is there some kind of secret byte notation that makes it possible to actually create byte arrays in one's source code without getting an error message?

Edit: Ah, I got it. It expects the bytes to be signed (between -127 and 128), not unsigned. Java truly has done everything to make life difficult.

What I had to do was take each hex byte, and if it was over 127, subtract 256. The output from that then went right into the source, and it all compiled nicely.

Rounin fucked around with this message at 07:54 on Mar 9, 2009

lamentable dustman
Apr 13, 2007

🏆🏆🏆

I don't normally write applets so I need some help with this badly. I have an applet that is hosted in in Tomcat that needs to communicate with a servlet on the same server. The servlet feeds the applet with the required data it uses for processing.

Here is how I connect it :

code:
URLConnection conn;
try{
   URL url = new URL("http://123.123.123.123:8080/webcontent/servlet");
   conn = url.openConnection();
   conn.setDoOutput(true);
   conn.setDoInput(true);
   ... (other setupcode, on secure system so can't c/p it)
   
   OutputStream out = conn.getOutputStream(out);
   ObjectOutputStream oos = new ObjectOutputStream(out);
   oos.writeObject(*data*);
   //receive data and close all connections
}catch(Exception e){

}
This all worked fine on my local machine. The URL pointed to htpp://localhost:8080 but now I am integrating with the server and I'm getting all kind of problems. I'm getting an error "java.security.AccessControlException: access denied (java.net.SocketPermission <url> connect, resolve)".

Now I understand all the restrictions with applets. I know they can't communicate with just any server and can't modify local files. But they are suppose to be able to communicate with a remote server IF the applet was downloaded from there, right? Any ideas? I got to get live data to the applet to be displayed.

edit: the error is thrown at "conn = url.openConnection();"



edit2: gently caress me.... figure it out.... when I was testing poo poo locally again I set the URL ip to my machines IP instead of localhost. When I tried to connect to it from my local Tomcat server I reached it via localhost:8080 instead of with my IP address. Not only can't applets communicate with remote servers, the url have to be the same I guess. So if you hard code a IP into the URL object and try to access the page it sits in via a DNS address the applet will break, right? So I need to use JSP or my web.xml file to pass the url context incase it moves or for we set up a dns for it.

I wish it was smarter then that.

lamentable dustman fucked around with this message at 16:50 on Mar 10, 2009

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
My god, whine whine whine. You don't need dynamic content to do this. You're in an applet; just fetch the applet's code base URL and grab the host out of it.

Anyway, there really is no way to decide in general that two totally different IP addresses happen to belong to the same machine. localhost (and correspondingly 127.0.0.1) have conventional meanings that are supported by default configurations everywhere; that is all. I suppose you could hack something in explicitly for this case, but ugh.

EDIT: Even if you knew two IP addresses resolved to the same machine, there are no guarantees that the same services are listening on identical ports on both addresses. Even if you could figure out that the same process was listening on a particular port on both addresses, there'd be no guarantee that it wouldn't treat connections on different IPs differently. The abstractions just intentionally don't work that way.

rjmccall fucked around with this message at 18:54 on Mar 10, 2009

lamentable dustman
Apr 13, 2007

🏆🏆🏆

It wasn't so much whining as me bitching because of my own stupidity and taking a couple hours to figure it out. Mostly because I wrote a long post then figured it out 5 minutes later, as happens whenever I post here.

Anyways, what I do now is write a little jsp to do the following

code:
<param name="url" value="<%out.print(request.getScheme()+"://"+request.getServerName()+":"request.getPort());%>">
to pass the root url to the applet, from there form the path to the corresponding servlet.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
No, seriously, you're writing this in an applet; why can't you use the applet's code base? It is almost literally what you are duplicating there, except it is free and does not require turning a static page into a dynamic one just to provide information that the browser already has.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Sorry, missed understood what you meant there. Didn't know there was a method for that. I'll update that, thanks for the tip.

Like I said, I don't do applets generally, I just happened to make a mistake of showing my boss some of the features of the library I was using (JFreeChart). I was originally going just server some static pictures, from a servlet, representing weather data. I showed him some of the applet and dynamic features of it and next thing I know I'm making applets. Just trying to hack my way trough this poo poo and be done with applets for good and focus on backend stuff again.

HondaCivet
Oct 16, 2005

And then it falls
And then I fall
And then I know


I'm working on a project for class and I am supposed to square a matrix of boolean values. I know how to multiply a matrix, but I know nothing about boolean/binary/logic whatever stuff and I don't really know what multiplying a boolean matrix would entail. How do I do this in Java? Thanks.

Mill Town
Apr 17, 2006

HondaCivet posted:

I'm working on a project for class and I am supposed to square a matrix of boolean values. I know how to multiply a matrix, but I know nothing about boolean/binary/logic whatever stuff and I don't really know what multiplying a boolean matrix would entail. How do I do this in Java? Thanks.

If you don't know how to do it on paper, you're not going to be able to do it in Java.

It's been a while since discrete class, but as far as I can tell, a boolean matrix is just a matrix of zeroes and ones, often used to represent a relation between finite sets. So, just stuff the zeroes and ones into your matrix and multiply as normal.

HondaCivet
Oct 16, 2005

And then it falls
And then I fall
And then I know


Mill Town posted:

If you don't know how to do it on paper, you're not going to be able to do it in Java.

It's been a while since discrete class, but as far as I can tell, a boolean matrix is just a matrix of zeroes and ones, often used to represent a relation between finite sets. So, just stuff the zeroes and ones into your matrix and multiply as normal.

I think I got it worked out now, thanks.

Another one: I am supposed to read some matrices from a separate Java file. Is this even possible? They are inside their own methods like this:
code:
	public static final boolean[][] CONNECTIONS = 
	{{true, true, false},
	{true, true, true},
	{false, true, true}};
We are supposed to access them like they are constants, i.e. NetworkDatabase.CONNECTIONS. Thanks again.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
...no, you do not have to write your entire program in a single Java file. I am sorry that this was not explained to you. For the purpose of your assignment, all you need to do is put the two files in the same directory; compiling one will most likely compile the other one automatically.

HondaCivet
Oct 16, 2005

And then it falls
And then I fall
And then I know


rjmccall posted:

...no, you do not have to write your entire program in a single Java file. I am sorry that this was not explained to you. For the purpose of your assignment, all you need to do is put the two files in the same directory; compiling one will most likely compile the other one automatically.

Do I need some sort of scanner to read it or will it work just the way it is as long as they are in the same directory?

Edit: Never mind, I tried it and it works. Yeah, our assignments are kinda crappy . . .

Edit2: \/\/\/\/Yeah, thanks!

HondaCivet fucked around with this message at 07:48 on Mar 12, 2009

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

HondaCivet posted:

Do I need some sort of scanner to read it or will it work just the way it is as long as they are in the same directory?

Edit: Never mind, I tried it and it works. Yeah, our assignments are kinda crappy . . .

Don't think of it as parsing the other Java code; you certainly could write something to do that, but it'd be a huge undertaking and not at all what your assignment is about. Let me try to explain what's actually happening.

Okay. You've got two Java source files; let's call them HondaCivet.java (because I don't know what it's actually called in your assignment) and NetworkDatabase.java. By the rules of Java, these files have to define two different classes, called HondaCivet and NetworkDatabase respectively. You can compile these files separately, and the Java compiler will produce .class files corresponding to the .java files. But it's the Java compiler that reads the Java files, and it only does so once, at compile-time.

(Aside: why does compiling HondaCivet seem to automatically compile NetworkDatabase? The code in the HondaCivet class relies on information from the other class. While it's compiling HondaCivet, the compiler needs to verify that you're using that information correctly (in this case, that the CONNECTIONS field exists, is static, and has the right type), so it also has to compile the other class. If you're using an IDE, most of this is hidden from you many IDEs will automatically recompile a class every time you save it.)

Later, when you start running the main method in the HondaCivet class, the Java runtime will eventually notice that your code relies on information from the NetworkDatabase class. At that point, it'll stop for a second and load the NetworkDatabase class file that you compiled before, just like it loaded the HondaCivet class when you asked it to run the main method there.

Make sense?

8ender
Sep 24, 2003

clown is watching you sleep
Does anyone here have any experience with the various persistence APIs? I'm trying to decide which ones to evaluate right now and its a maze of wierdness when it comes to who owns what and which is a standard or not.

From what I can gather Oracle bought TOP and made Toplink. Later a cut down version of Toplink was combined with some Hibernate know how to create the JPA in EJB3. Then Oracle open sourced Toplink and it became Eclipselink which is going to be JPA in JavaEE6. Then there is Hibernate just hanging out doing its thing.

We're looking at evaluating EJB3, Toplink/Eclipselink and Hibernate right now. Any others anyone can add the list? Is it worthless to look at the JPA in EJB3 with Eclipselink being the standard for JavaEE6?

lmao zebong
Nov 25, 2006

NBA All-Injury First Team
I'm trying to write an anagram solver in Java, and I'm running into some problems. I've finally got it to find and spit out a single anagram of a given phrase, and now what I need it to do is print out all the possible phrases it can.

Here is AnagramSolver.java
http://pastebin.com/m24abb12c

and here is AnagramMain.java
http://pastebin.com/m2059f33c

LetterInventory keeps track of what letters you have in your word, with 3 methods:
* contructor (String data),
* get : return a count of how many of this letters in the inventory
* subtract(LetterInventory other) return a new LetterInventory obj, null if negative count.

Now, I know the reason it is only printing one result is because I have it print my results string in my base case. What I need to do instead is, when it finds the last possible word it can make out of the string, i need it to backtrack from that word, and continue going.
Now, how should I go about this? Should, in my if statement, find that it is the last word possible, to print the results, delete it out of my results, add the letters back into my inventory, and pass back into the recursive solution? what is the best way to go about this? Thanks a lot in advance, I've been working on this for a while and I can't seem to think up any solutions.

Also, I have a very strong feeling that my recursive solution is a loving mess. I'm passing like 6 parameters every time, and I'm pretty sure that's overkill. It seems to me that my algorithm is working properly, but definitely not doing it in the cleanest way possible.

lmao zebong fucked around with this message at 22:25 on Mar 12, 2009

1337JiveTurkey
Feb 17, 2005

You've got the original list, an argument that's a copy of the original list, and an argument that's an iterator on the original list. The iterator is the only one you're currently using, but you actually don't want to pass it as a parameter.

The simplest method for getting all of the possible anagrams is to start with the collection of letters and a blank string for the anagram so far and then go through all the words in the dictionary. If it doesn't fit, skip it. If it fits, then append it to the anagram so far. If the fit was exact, print it out and continue. Otherwise recurse with the remaining letters and the new anagram. It'll obviously be slow but there are a few techniques for speeding it up if you need them.

Gary Mitchell
Apr 3, 2007

Morals are for men, not gods.
Hurray for sample code from the notes that doesn't compile!

I've got some three classes, two of which implement a binary tree and it's nodes, and the test case.

I know what the problem is, I'm just unsure as to how to fix it. Check out the class which represents nodes in the tree, specifically the highlighted line.
code:
class BTNode
{
	// public fields
	Object 	data;
	BTNode 	left;
	BTNode 	right;
	BTNode 	parent;		

	// constructor
	BTNode(Object item) { data = item; }	//<---- look at me!
	// reference fields are null
}
When I try to compile this, this is the error:

./BinaryTree.java:48: incompatible types
found : java.lang.Object
required: BTNode

BTNode here = search(ob);


Where search(Object ob) returns an object file representing the "data" for that node. I think what is supposed to be happening is that, when BTNode x = an Object, it's supposed to be calling the constructor I highlighed above, and thus creating a new BTNode with that as it's data. But it's not doing it. And in the provided test class, all of the data is Integers, which it seems can't be extended in java, so I can't just have BTNodes derive from Integer objects!

Here are all three classes on Pastebin. I have to assume this compiled in Java at one point, or else it wouldn't be in the notes.

And I certainly hope this wouldn't matter, but I might as well mention I'm on 64-bit Linux. Java version:
java version "1.6.0_0"
IcedTea6 1.3.1 (6b12-0ubuntu6.1) Runtime Environment (build 1.6.0_0-b12)
OpenJDK 64-Bit Server VM (build 1.6.0_0-b12, mixed mode)

There's probably some blindingly obvious solution, but I've tried everything I can think of, so help me out! :)

Fullets
Feb 5, 2009
code:
public Object search(Object key)
{ return search(root, key).data; }
The one argument search method returns an Object; you can make it compile by changing the line the compiler complains about to:

code:
BTNode here = (BTNode)search(ob);
Looking at the code makes me thing that perhaps this isn't what you want to do, though: while the two argument search returns the BTNode matching the object passed in, the one argument search returns the .data member of that node, so you'd probably want to use something like:
code:
BTNode here = search(root, ob);

Gary Mitchell
Apr 3, 2007

Morals are for men, not gods.
Holy poo poo Fullets. The first edit you made, BTNode here = (BTNode)search(ob); is exactly the first change I made, but you were right -- while it does compile, the depth() function always returns 0 instead of the depth of the node.

But yeah, you actually figured it out, first reply!. :dance: Skipping straight for the overloaded method (like you've done) works perfectly! That makes the whole public Object search(Object key) middle-man function completely useless... why do people make poo poo more complicated then they have to?

Thank you very much, sir!

lmao zebong
Nov 25, 2006

NBA All-Injury First Team

1337JiveTurkey posted:

You've got the original list, an argument that's a copy of the original list, and an argument that's an iterator on the original list. The iterator is the only one you're currently using, but you actually don't want to pass it as a parameter.

The simplest method for getting all of the possible anagrams is to start with the collection of letters and a blank string for the anagram so far and then go through all the words in the dictionary. If it doesn't fit, skip it. If it fits, then append it to the anagram so far. If the fit was exact, print it out and continue. Otherwise recurse with the remaining letters and the new anagram. It'll obviously be slow but there are a few techniques for speeding it up if you need them.
Thanks for the nudge in the right direction. Now I'm getting closer, but I'm having trouble having it print out the right anagram. Here is my code now:
code:
public void findWords2(LetterInventory wordLett, ArrayList<String> results, int max)
	{
		Iterator<String> iter = dictionary.iterator();

		if( wordLett.isEmpty() )
		{
			System.out.println(results);
		}
		if( wordLett.size() == 1 )
		{
			System.out.println(results);
		}
		if( results.size() >= max )
		{
			return;
		}
		while( iter.hasNext() )
		{
			String peek = iter.next();
			LetterInventory dictLetter = new LetterInventory(peek);
			LetterInventory newLett = wordLett.subtract(dictLetter);
			if(newLett != null)
			{
				results.add(peek);
				wordLett = wordLett.subtract(dictLetter);

				findWords2(wordLett, results, max);
			}
		}
	}
However, this still isn't working right. If I put in, for example, george bush, i get
code:
[bee, go, gush]
[bee, go, gush, gush]
[bee, go, gush, gush, go, gush]
[bee, go, gush, gush, go, gush, gush]
so it looks my recursion is backtracking correctly, but my logic is obviously failing somewhere. Sorry for not fully grasping this backtracking concept; i'm still relatively new to recursion and i'm having a bit of trouble wrapping my head around it.
Also, my test to print the results is obviously flawed, I have it as wordLett.isEmpty(), but this doesn't work if there is, for example, one letter left in the letter inventory. That is why i put the wordLett.size() == 1 test in there, becuase george bush ends up with only an r left, and i've been using that phrase for my testing purposes. How would be a better way to test that I have a complete anagram and should print it out?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Sarah Sherman posted:

code:
[bee, go, gush]
[bee, go, gush, gush]
[bee, go, gush, gush, go, gush]
[bee, go, gush, gush, go, gush, gush]
so it looks my recursion is backtracking correctly, but my logic is obviously failing somewhere. Sorry for not fully grasping this backtracking concept; i'm still relatively new to recursion and i'm having a bit of trouble wrapping my head around it.

You're adding things to your results list, but never removing them.

Sarah Sherman posted:

Also, my test to print the results is obviously flawed, I have it as wordLett.isEmpty(), but this doesn't work if there is, for example, one letter left in the letter inventory. That is why i put the wordLett.size() == 1 test in there, becuase george bush ends up with only an r left, and i've been using that phrase for my testing purposes. How would be a better way to test that I have a complete anagram and should print it out?

Why would it be acceptable to end when you have one letter left? It's not a complete anagram if you don't use all the letters.

lmao zebong
Nov 25, 2006

NBA All-Injury First Team

rjmccall posted:

Why would it be acceptable to end when you have one letter left? It's not a complete anagram if you don't use all the letters.
valid point, i don't know why i thought that would be a smart thing to do, becuase that was essentially giving me answers that are not correct. however, i'm still stumped as to how to amend my logic to delete the most recent word, and then run through again to find that combination.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Recursion can be tricky. Try backing away from your current code and working it out abstractly. Your algorithm is basically this:

code:
Inputs:  an inventory of letters and a list of words used so far in this anagram.
If the inventory is empty, print out the list.
Otherwise, for each word in the dictionary:
  Try to subtract that word's letters from the letter inventory.
  If it fits:
    Recursively run the algorithm with
      (1) the inventory you got from the subtraction and
      (2) the old list of words, plus the new word.
You're having a problem because you've chosen to compute "the old list of words, plus the new word" by just appending the new word to the old list. You're not making a new list, you're modifying the old list. That's not a bad thing it's often more efficient, and you can still make this algorithm work but you will have to compensate for it.

You can fix this problem in either of two ways.
A. You can stop modifying the old list: just copy the old list into a new list, then append the word to the new list instead of the old.
B. You can "undo" your changes to the old list. You're adding the new word to the end of the list every time; when you want to undo that, just remove the last word from the list.

lmao zebong
Nov 25, 2006

NBA All-Injury First Team
Thanks for all the help guys. For the small amounts of time I have between work and school I've been working on this, and I (at least) hope that I am inching towards a solution. Staring at my already written code was doing nothing for me, so I decided to compeletly start over with this method, starting with pseudocode. Here is my idea for my algorithim:
code:
Preconditions: Already filled LetterInventory, empty LinkedList to hold anagram answers
If: LetterInventory is empty
     print list
     continue
For each word in the dictionary:
     Attempt to subtract dictionary word from LetterInventory
     If it works:
         Call rescursive function again with: new LetterInventory & anagram list.
If: reach the end of the dictionary and the LetterInventory is not empty
     delete last word from the anagram list
     add that words letter inventory to current LetterInventory
     call recursive function with new LetterInventory, anagramlist, 
     and start recursion at word just after the last word that didn't work
Is this the best way to look at this problem?
Also, what would be the best way to start just after the last word that didn't work? I am using an ArrayList to hold the dictionary, should i just pass the index during the recursive call and have it start from there (and how is the best way to do that), or is there a better way?

Thanks for all the help again guys, this is a program that my professor recommended to us to try and practice our recursion techniques, and if it isn't already apparent I have a little bit of trouble grasping that concept.

lmao zebong
Nov 25, 2006

NBA All-Injury First Team
Alright looks like I'm running into the same problem again with trying to make it delete the last element in my results list. I switched from using an ArrayList to a LinkedList, but I'm still having trouble.
Here is my code again:
http://pastebin.com/ma88ee53

now, I have that if(!wordLett.isEmpty() && !iter.hasNext()) statement, which should take care of this problem. However, it seems like it's never entering that list at all, and as such never delete things out of the list. I thought those parameters would be sufficient, what is going wrong?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
My best advice for learning recursion (for learning programming at all, really) is to actually sit down and plow through what the code is actually doing not at a high level, where you're making fantasy arguments to yourself about what you think your code should be doing, but actually tracing the progress of the program as it executes, line-by-line. You should be able to do this without using a debugger; just find a piece of paper, create new variables and objects on it as necessary, and actually just walk through the program. Obviously, work with a small notional dictionary so you don't get wildly bored maybe "a", "ab", "bc", and "abc", and working with the starting letters "aaabbc".

Do that before you read the rest of this post.

Things you should notice:
  • if(!wordLett.isEmpty() && !iter.hasNext() ) you only execute this test where iter is a brand-new iterator over the dictionary. New iterators always start at the beginning of a list, so this condition will only ever be true if the dictionary is completely empty.
  • You're running the entire function even if the letter inventory is empty. If the inventory is empty, you can't possibly fit any more words into it, right? So that's a pointless exercise.
  • Why are you using a linked list for results? You're not getting anything out of it that you couldn't have gotten from an array list. Again, it's not wrong, it's just not necessary.
  • The most logical place to remove the last word from results is right after the recursive call, like this:
    results.add(peek); findWords2(newLett, results, max); results.removeLast();
    This establishes what we call a invariant over recursion: findWords2 is allowed to modify results however it pleases internally, but at the end of every call, it should leave it exactly as it found it. Convince yourself that the code I just wrote will accomplish exactly that.

  • You're always passing the same values of max and results to findWords2 (the values inside results change, but it's always the same reference). That suggests that you could make them fields instead of parameters, just like you did with dictionary.
  • Every time you reach a word, you're computing its letter inventory again. Think about how you could avoid some of that extra work.

lmao zebong
Nov 25, 2006

NBA All-Injury First Team
god drat, thank you so much. after doing what you said and going through line by line, i realized that the if statement was useless, like you said. thanks for the heads up about using invariance, that seemed to be the trick, and now it's working perfectly. thanks a lot!

mister_gosh
May 24, 2002

I have some code which reads in a file, line by line and spits out the same file to a different location.

The problem is that the file created by the FileOutputStream contains NO line endings. An example is probably not needed, but for laughs, here's one:

Mary had
a little
lamb.

becomes:

Mary had a little lamb.

Can someone tell me what I'm doing wrong?

code:
BufferedReader input =  new BufferedReader(new FileReader(in));
FileOutputStream fos = new FileOutputStream(out, true);
                        
line = null;
   
while (( line = input.readLine()) != null){
 
   byte[] Xa = line.getBytes("UTF-8");
                                
   fos.write(Xa);
                                
}
fos.close();

Merrack
Sep 15, 2007

quote:

readLine

public String readLine()
throws IOException
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

readLine doesn't include the line ending, and write doesn't generate one for you.

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!
From Sun's Java Documentation

quote:

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So you will need to manually write the line feed yourself.

E:F,b.

mister_gosh
May 24, 2002

I guess that was painfully obvious. I had thought it was something wrong in my write method. I just assumed that the readLine would preserve all special characters, control characters, etc. unless I explicitly removed them. Oops! Thanks!

F'Nog
Jul 21, 2001

8ender posted:

Does anyone here have any experience with the various persistence APIs? I'm trying to decide which ones to evaluate right now and its a maze of wierdness when it comes to who owns what and which is a standard or not.

From what I can gather Oracle bought TOP and made Toplink. Later a cut down version of Toplink was combined with some Hibernate know how to create the JPA in EJB3. Then Oracle open sourced Toplink and it became Eclipselink which is going to be JPA in JavaEE6. Then there is Hibernate just hanging out doing its thing.

We're looking at evaluating EJB3, Toplink/Eclipselink and Hibernate right now. Any others anyone can add the list? Is it worthless to look at the JPA in EJB3 with Eclipselink being the standard for JavaEE6?

The JPA is just the set of interfaces that live in the runtime and all the providers your listed implement them. I've only every used Hibernate, there isn't anything it doesn't do that I've needed. It just plops in and works. It's also got a pretty big userbase for reference material.

8ender
Sep 24, 2003

clown is watching you sleep

F'Nog posted:

The JPA is just the set of interfaces that live in the runtime and all the providers your listed implement them. I've only every used Hibernate, there isn't anything it doesn't do that I've needed. It just plops in and works. It's also got a pretty big userbase for reference material.

Sorry, I guess I meant the "Toplink Essentials/Hibernate mashup" that is bundled with the EJB 3.0 spec. How would you compare Hibernate to EclipseLink? In my case we have an existing data model and we'll be trying to match to our database.

F'Nog
Jul 21, 2001

8ender posted:

Sorry, I guess I meant the "Toplink Essentials/Hibernate mashup" that is bundled with the EJB 3.0 spec. How would you compare Hibernate to EclipseLink? In my case we have an existing data model and we'll be trying to match to our database.

I've never used Eclipselink in a project before so I'm going on what I've read, Eclipselink is apparently better at it's second-level caching and probably has an out of the box cluster aware caching ability (Hibernate requires you to pick a caching provider first), and it's also quite awesome when running against the latest Oracle instances which I guess is to be expected. It's also got a bunch of stuff embedded in it that Hibernate doesn't have like JAXB support which I'm not too confident about because the two just don't fit together. You need seperate models to do both JPA and JAXB annotations as using a feature of one always ends up meaning you can't do something with the other.

Personally for your situation I'd just go with Hibernate, annotate your domain model against the JPA as much as you can without straying into Hibernate's extensions and that way if Hibernate doesn't fit your needs substituting Eclipselink in won't be hard.

Adbot
ADBOT LOVES YOU

mister_gosh
May 24, 2002

I have a servlet which kicks off a separate jar (all my own code). I want to set up a queue for kicking off this separate operation because the operation can take some time and/or we can get multiple requests at a time. I want to process one at a time.

I think I could set up a first in/first out (FIFO) queue type process, but what I'm fuzzy on is how I can have the servlet connect to an already existing queue manager program?

Let's say John executes the servlet which in turn kicks off the separate process. 2 minutes later, John is still waiting for the separate process to finish (and the final servlet response) and Jane executes her own servlet connection. I want her to connect to the same queue manager class instance so that it can read the same queue FIFO values which are most current (and have her rightfully wait for John's to finish).

I'd prefer not to write temporary values to a filesystem in order to manage the queue. Is there something fundamental I am missing? I'm self taught, so perhaps I'm missing something very fundamental when it comes to connecting to a pre-existing class instance...

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