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
FateFree
Nov 14, 2003

Parantumaton posted:

If your desired range is 1...7 billion and you can get to 2 billion, why not just do that one to three times, add those three together and then add another billion?

Well the chances are completely different. To hit 7,000,000,000 exactly should allow 1/7,000,000,000. Your way requires 1/2,000,000,000 three times in a row, which is (1/2,000,000,000) ^ 3 which is astoundingly higher

Adbot
ADBOT LOVES YOU

Schism.
Mar 19, 2009
I'm writing a method add which takes as input a linked list and returns the result of adding up every integer stored in the linked list. So add [1,4,6] = 11 and I can't figure out how to get the main method working to test it.

code:
public class addLList {
	public class LList {
		int data;
		LList next;
		public LList (int n) {data = n; next = null;}
		public LList (int n, LList l) {data = n; next = l;}
		}
	
	public static int add(LList l) {
		
		if (l == null) {
			return 0;
		} else {
			return l.data + add(l.next);
		}
		
	}
	public static void main(String args[]) {
	    System.out.println(add(********));

monads mo problems
Nov 27, 2007
It should look something like this:
code:
public static void main(String args[]) {
	    System.out.println(add(new LList(6, new LList(4, new LList(1)))));
}
But you will have to make the LList class static, that way you don't need an instance of an AddLList in order to make a new LList.
code:
public class addLList {
	public static class LList {
......

Schism.
Mar 19, 2009
Yeah it dawned on me as soon as I posted that should've been static. Cheers, though. Got it working now. These lists are going to be such a pain to work with, eurgh.

Psychorider
May 15, 2009

FateFree posted:

How do i generate a random long from 1-7 billion, when there is no range function like there is with integer?

The same way you do it if you don't have a range function for integer seems to work.
code:
long random = 1000000000L + (Math.abs(new Random(seed).nextLong()) % 6000000000L);
Or to modify Parantumaton's idea slightly
code:
Random r = new Random(seed);
long random = 1000000000L + (r.nextInt(3) * 2000000000L) + r.nextInt(2000000000);
Although the first way is better obviously.

FateFree
Nov 14, 2003

Psychorider posted:

The same way you do it if you don't have a range function for integer seems to work.
code:
long random = 1000000000L + (Math.abs(new Random(seed).nextLong()) % 6000000000L);
Or to modify Parantumaton's idea slightly
code:
Random r = new Random(seed);
long random = 1000000000L + (r.nextInt(3) * 2000000000L) + r.nextInt(2000000000);
Although the first way is better obviously.

Hmm i see where the confusion is, i didn't mean from 1 billion to 7 billion, just the old school 1 to 7 billion. So should this be the correct approach?

code:
Math.abs(new Random(seed).nextLong() % 7000000000L) + 1
I guess what makes me worry is that the absolute value function basically gives two random values that are the same, 10, -10 for example.

Psychorider
May 15, 2009

FateFree posted:

Hmm i see where the confusion is, i didn't mean from 1 billion to 7 billion, just the old school 1 to 7 billion. So should this be the correct approach?

code:
Math.abs(new Random(seed).nextLong() % 7000000000L) + 1

Yes, exactly.

FateFree posted:

I guess what makes me worry is that the absolute value function basically gives two random values that are the same, 10, -10 for example.

That shouldn't matter because there is the exact same double probability for every number (actually more than that because of the modulo operation) but every number still has the same odds of coming up.

dorkface
Dec 27, 2005
I'm betting this is impossible due to security restrictions, but I would like to produce an applet/scriplet that would be able to gather WMI information from a host machine and display it on a web page. Is this possible, or am I entirely stupid for even thinking about it?

LakeMalcom
Jul 3, 2000

It's raining on prom night.
For the random number/long guy: how about this: http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html#BigInteger(int,%20java.util.Random)

Max Facetime
Apr 18, 2009

LakeMalcom posted:

For the random number/long guy: how about this: http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html#BigInteger(int,%20java.util.Random)

Do this, but use it to implement nextInt(int n) from earlier using BigIntegers. Using modulo to limit the random number range is a really bad idea. In short, if you have range and distribution

----
[0-3]

doing a % 3 gives you:

-
---
[0-2]

so number 0 is now twice as likely.

HFX
Nov 29, 2004

dorkface posted:

I'm betting this is impossible due to security restrictions, but I would like to produce an applet/scriplet that would be able to gather WMI information from a host machine and display it on a web page. Is this possible, or am I entirely stupid for even thinking about it?

Look into setting your own security manager which the user will have to authorize.

yatagan posted:

Post your code, and the code of the generator.

Sadly, I can't do to the draconian NDA's.

HFX fucked around with this message at 14:27 on Nov 23, 2009

Mulloy
Jan 3, 2005

I am your best friend's wife's sword student's current roommate.
I'm either really dumb or incredibly dumb.

I have a main class which handled the creation and maintenance of a custom object which is essentially an array with a bunch of instance variables like rows, cols, contents at various locations, etc... It got ridiculously huge with file i/o so I moved the i/o to its own class and extended the original since its intended to manage everything in the primary.

The issue I'm running into seems like a really fundamental misunderstanding of Java.

The first class properly gives the second the file to process. The array object is declared in the first class. The second does not declare it, and it renders the information in the array. When the first class attempts to manipulate the array object, it dies for null pointer exceptions.

It seems that even though I thought I had both classes pointing to the same instance of the object, they're not. I've googled a bit trying to see what I'm missing, but I was wondering if anyone had any suggestions to point me in the right direction, or if I'm just thinking about this all retardedly and am trying to do something that can't/shouldn't be done.

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

I am in posted:

Do this, but use it to implement nextInt(int n) from earlier using BigIntegers. Using modulo to limit the random number range is a really bad idea. In short, if you have range and distribution


Yes this is what I was getting at. Do this. Unless you have some retarded speed requirement, BigInteger will do exactly what you want.

epswing
Nov 4, 2003

Soiled Meat

Mulloy posted:

:words:

You really need to post your code rather than referring to your "first class" and your "second class."

RichardA
Sep 1, 2006
.
Dinosaur Gum
Edit: I was wrong.

RichardA fucked around with this message at 07:50 on Nov 26, 2009

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

Parantumaton posted:

If your desired range is 1...7 billion and you can get to 2 billion, why not just do that one to three times, add those three together and then add another billion?
I'm almost certain that would introduce bias, which may or may not be acceptable depending upon how severe the bias is.

dreamality
Nov 23, 2009

Mulloy posted:

I'm either really dumb or incredibly dumb.

I have a main class which handled the creation and maintenance of a custom object which is essentially an array with a bunch of instance variables like rows, cols, contents at various locations, etc... It got ridiculously huge with file i/o so I moved the i/o to its own class and extended the original since its intended to manage everything in the primary.

The issue I'm running into seems like a really fundamental misunderstanding of Java.

The first class properly gives the second the file to process. The array object is declared in the first class. The second does not declare it, and it renders the information in the array. When the first class attempts to manipulate the array object, it dies for null pointer exceptions.

It seems that even though I thought I had both classes pointing to the same instance of the object, they're not. I've googled a bit trying to see what I'm missing, but I was wondering if anyone had any suggestions to point me in the right direction, or if I'm just thinking about this all retardedly and am trying to do something that can't/shouldn't be done.

post your code

FateFree
Nov 14, 2003

LakeMalcom posted:

For the random number/long guy: how about this: http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html#BigInteger(int,%20java.util.Random)

Thanks, I have taken this approach and am stumped by a simple math problem.

So 2^33 is the lowest power greater than 7billion, so I can use new BigInteger(33, rand) and discard anything over my range. My question is how I can determine the number 33 dynamically.

In math terms, how do I find the smallest power of 2 thats greater than a given number, in fast java code?

ynef
Jun 12, 2002

FateFree posted:

In math terms, how do I find the smallest power of 2 thats greater than a given number, in fast java code?

In math, you'd probably get away with ceil(log2(given_number)), but Java doesn't have a general logarithm function like that (just the natural logarithm). You'd have to use the Change of Base theorem to compensate.

1337JiveTurkey
Feb 17, 2005

ynef posted:

In math, you'd probably get away with ceil(log2(given_number)), but Java doesn't have a general logarithm function like that (just the natural logarithm). You'd have to use the Change of Base theorem to compensate.

ceil(log2 n) = 32 - Integer.numberOfLeadingZeroes (n - 1) for all positive n.

Max Facetime
Apr 18, 2009

Also http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html#bitLength%28%29

FateFree
Nov 14, 2003


Ah thanks that seems to work perfectly. Heres what I ended up with:

code:
/**
	 * Return a random long from 0 to max, exclusive
	 * 
	 * @param max
	 * @return long
	 */
	public long randomLong(long max) {
		if(max < 0)
			throw new IllegalArgumentException("Max must be greater than 0");
		
		long value = new BigInteger(BigInteger.valueOf(max).bitLength(), getRandom()).longValue();
		return value < max ? value : randomLong(max);
	}

Mulloy
Jan 3, 2005

I am your best friend's wife's sword student's current roommate.
code:
public class Engine extends JFrame
{
public static Grid aGrid;

public static void main( String[] args )
{
       JFrame window = new TwoWindows();
       window.setLocation(280,350);
       window.show();
}

public void processGrid()
{
      switch(aGrid.arrayContents())
      {
         react to current value of the array.
      }

}


}

----

public class TwoWindows extends Engine
{

     A bunch of stuff to create windows and buttons and listeners.
     public class WindowOpener implements Runnable
     {
           public void run()
           {
                engine.processGrid();
           }
      }

}
When I try to run processGrid() from within TwoWindows it throws a null exception. Not sure what I'm misunderstanding. It's specifically the array class Grid I'm trying to have everything reference the same instance of that seems to be failing.

FateFree
Nov 14, 2003

Mulloy posted:

code:

     A bunch of stuff to create windows and buttons and listeners.
     public class WindowOpener implements Runnable
     {
           public void run()
           {
                engine.processGrid();
           }
      }

}
When I try to run processGrid() from within TwoWindows it throws a null exception. Not sure what I'm misunderstanding. It's specifically the array class Grid I'm trying to have everything reference the same instance of that seems to be failing.

I'm surprised it even compiles. What is engine referring to? I dont see an instance variable.

But anyway, assuming there is one, are you instantiating aGrid anywhere? you set it statically but its not set to anything, so by default its null.

dreamality
Nov 23, 2009

Mulloy posted:

code:
public class Engine extends JFrame
{
public static Grid aGrid;

public static void main( String[] args )
{
       JFrame window = new TwoWindows();
       window.setLocation(280,350);
       window.show();
}

public void processGrid()
{
      switch(aGrid.arrayContents())
      {
         react to current value of the array.
      }

}


}

----

public class TwoWindows extends Engine
{

     A bunch of stuff to create windows and buttons and listeners.
     public class WindowOpener implements Runnable
     {
           public void run()
           {
                engine.processGrid();
           }
      }

}
When I try to run processGrid() from within TwoWindows it throws a null exception. Not sure what I'm misunderstanding. It's specifically the array class Grid I'm trying to have everything reference the same instance of that seems to be failing.

Mulloy, Paste the complete source of the class Engine.

NullPointerExceptions are "most of the time" easy to tell by looking at the code.

What you pasted is in incomplete, specially: I don't see when the array is instantiated. All I can tell you from what I see is that you never do the following:
code:
aGrid = new Grid();
so, yes, when calling:
code:
switch(aGrid.arrayContents())
it will definitely fail. But again, I'm assuming, I need to see the code.

RichardA
Sep 1, 2006
.
Dinosaur Gum
Edit: I was wrong.

RichardA fucked around with this message at 07:49 on Nov 26, 2009

Fly
Nov 3, 2002

moral compass

RichardA posted:

A subclass can not access anything in a super class simply because it is a subclass. It gets its own entirely separate copy of the fields.
Would you explain what you mean by this because I am not sure what you are claiming?

RichardA
Sep 1, 2006
.
Dinosaur Gum
Edit: I was wrong.

RichardA fucked around with this message at 07:49 on Nov 26, 2009

8ender
Sep 24, 2003

clown is watching you sleep
We've just started using IBatis after a long and troubled struggle with Eclipselink and I think I'm in love. I can write regular SQL and have it map to objects like an ORM, it takes almost any object for parameters, outputs the results to almost anything, lazy loading, caching, dynamic SQL, the list goes on. Its everything I like about ORMs with all the lovely parts removed, and without having to rely on the framework to write dubious SQL.

Has anyone else here used it on any big projects? I'm worried I'm in some sort of honeymoon phase here and I'm going to start to hate it.

dreamality
Nov 23, 2009

8ender posted:

We've just started using IBatis after a long and troubled struggle with Eclipselink and I think I'm in love. I can write regular SQL and have it map to objects like an ORM, it takes almost any object for parameters, outputs the results to almost anything, lazy loading, caching, dynamic SQL, the list goes on. Its everything I like about ORMs with all the lovely parts removed, and without having to rely on the framework to write dubious SQL.

Has anyone else here used it on any big projects? I'm worried I'm in some sort of honeymoon phase here and I'm going to start to hate it.

One of my peers has been using it for a long time for big projects. Although, I haven't even looked at it, I can tell from "his" opinion towards it that Ibatis is really good. One problem he encountered was the ability to use Stored Procedures, but he found a solution shortly.

Good Luck.

geeves
Sep 16, 2004

I'm having a problem setting a cookie via the HttpServletResponse object with all flavors of IE. When in debug mode, everything is set as it should be and I can follow the Response through the Servlet and the JSP code. But it fails to be set.

Is there something I'm missing with IE? I have never run into this problem with JavaScript or PHP or even Java before. Firefox, Opera, Safari, Chrome all work as expected. It's just IE.

In a method for UserLogin I have the following:

php:
<?

Cookie fooCookie = Bar.addCookeu(handler, request);
if(null != fooCookie) {
  reponse.addCookie(fooCookie);
}

.....

// in Class Bar:
public static Cookie addCookie(ContactHandler handler, HttpServletRequest request) {
        Cookie fooCookie = null;
        String uuid = "";
        String pass = "";
        int age = -1000;
        String cookieString = null;
        
        if(null != handler) {
            uuid = handler.getUuid();
            pass = handler.getPassword();
            age = (handler.isRememberMe()) ? Constants.COOKIE_LENGTH_REMEMBER : Constants.COOKIE_LENGTH_DEFAULT;
            cookieString = uuid + ";" + pass;
            log.info("Cookie String: " + cookieString);
        }
        try {
            fooCookie = new Cookie(Constants.COOKIE, cookieString);
            String serverName = ".foo.org";
            
            fooCookie.setDomain(serverName);
            
            fooCookie.setPath("/");
            fooCookie.setMaxAge(age);
           
        } catch (Exception e) {
            log.error("CAN'T ADD COOKIE: " + e.getMessage());
        }
        return fooCookie;

    }
?>

dreamality
Nov 23, 2009

geeves posted:

I'm having a problem setting a cookie via the HttpServletResponse object with all flavors of IE. When in debug mode, everything is set as it should be and I can follow the Response through the Servlet and the JSP code. But it fails to be set.

Is there something I'm missing with IE? I have never run into this problem with JavaScript or PHP or even Java before. Firefox, Opera, Safari, Chrome all work as expected. It's just IE.

In a method for UserLogin I have the following:

php:
<?

Cookie fooCookie = Bar.addCookeu(handler, request);
if(null != fooCookie) {
  reponse.addCookie(fooCookie);
}

.....

// in Class Bar:
public static Cookie addCookie(ContactHandler handler, HttpServletRequest request) {
        Cookie fooCookie = null;
        String uuid = "";
        String pass = "";
        int age = -1000;
        String cookieString = null;
        
        if(null != handler) {
            uuid = handler.getUuid();
            pass = handler.getPassword();
            age = (handler.isRememberMe()) ? Constants.COOKIE_LENGTH_REMEMBER : Constants.COOKIE_LENGTH_DEFAULT;
            cookieString = uuid + ";" + pass;
            log.info("Cookie String: " + cookieString);
        }
        try {
            fooCookie = new Cookie(Constants.COOKIE, cookieString);
            String serverName = ".foo.org";
            
            fooCookie.setDomain(serverName);
            
            fooCookie.setPath("/");
            fooCookie.setMaxAge(age);
           
        } catch (Exception e) {
            log.error("CAN'T ADD COOKIE: " + e.getMessage());
        }
        return fooCookie;

    }
?>

I believe it's got something to do with
code:
String serverName = ".foo.org";
fooCookie.setDomain(serverName);
remove the domain or place a correct domain, if running on localhost, might want to try localhost.

If that still doesn't work try removing all other "sets" and do a simple cookie:
code:
fooCookie = new Cookie("name","value");
see if that works, at least that will point you to the right direction.

Good Luck

Fly
Nov 3, 2002

moral compass

RichardA posted:

Mulloy said "The array object is declared in the first class. The second does not declare it, and it renders the information in the array.". This, along with the lack of a Engine instance or a aGrid reference being passed to TwoWindows in the posted code, left me with the impression that Mulloy may not have a good understanding of classes and thinking that a instance of TwoWindows has access to WindowOpener fields; i.e. that aGrid in TwoWindows will be a reference to the same aGrid in WindowOpener.(I know considering how classes can have more than one instance will reveal how nonsensical that is but I have seen someone make this mistake before)
I don't see how you get that from the posted code.

quote:

By its own copy I meant that state that while a subclasses inherited fields have the same name and type as the fields of the superclass, they are separate variables. Copy was a poor chose of word to use.
I still do not know what you're trying to state. The only nonlocal variable is aGrid, so there is only one instance of a Grid in his code, and it's on the Engine class. It is bad style, and may not be what he wants, but there are not separate aGrid variables for the different classes, just one, and only one---Engine.aGrid.

RichardA
Sep 1, 2006
.
Dinosaur Gum
^^^^^
Thanks. I was mistaken; I had not noticed that aGrid variable was static in the posted code.

RichardA fucked around with this message at 08:03 on Nov 26, 2009

geeves
Sep 16, 2004

dreamality posted:

I believe it's got something to do with
code:
String serverName = ".foo.org";
fooCookie.setDomain(serverName);
remove the domain or place a correct domain, if running on localhost, might want to try localhost.

If that still doesn't work try removing all other "sets" and do a simple cookie:
code:
fooCookie = new Cookie("name","value");
see if that works, at least that will point you to the right direction.

Good Luck

foo.org is just replacing my company's domain.)

I'll try a simpler one and it fails with and without setDomain().

PT6A
Jan 5, 2006

Public school teachers are callous dictators who won't lift a finger to stop children from peeing in my plane
I'm involved in a small project with two other guys. One of the other guys says that my code isn't integrating properly with his, because one of his GUI panels does not center correctly in the parent's BorderLayout (which I was responsible for). I maintain that it's his problem, since every other widget works properly and I'm sure the problem is the fact that he decided to override all of Swing's helpful functions to draw and handle events entirely through his own code -- specifically, I'm guessing his paint() method doesn't take into account the element's preferred size, or something o that nature.

So, who's in the wrong here? Should it be my responsibility to figure out why the BorderLayout is not centering his widget, or his responsibility to make sure his code works as Swing/AWT expects? I'm obviously leaning towards it being his problem, but I'd like to make sure I'm not being unreasonable before I call him out on it.

I realize this isn't a Java question per se, but I figured someone with more experience than me in this area might be able to answer the question.

epswing
Nov 4, 2003

Soiled Meat
Does he have a really good reason why he isn't using Swing?

dreamality
Nov 23, 2009
PT6A, I believe he should stick to the standards no matter what. Since he did not follow the standards, then it will be hard to tell where the problem is.

I would recreate the scenario using standards and figure out where the problem is, but that is me.

Good Luck.

PT6A
Jan 5, 2006

Public school teachers are callous dictators who won't lift a finger to stop children from peeing in my plane

epswing posted:

Does he have a really good reason why he isn't using Swing?

This is for the card game I mentioned in passing earlier, and he's doing it so that cards can overlap and then move up when you click them, which would be slightly difficult to do in Swing. In my crappier-looking-but-functional version of the player's hand, I just have a bunch of JLabels in a row with the preferred width set to 0.2 times the icon width, and when a card is selected, I draw a yellow outline around it. Admittedly, if his worked the way it was supposed to, I'd have no problem using it because it looks much nicer, but I think it might be a whole lot of work for very little gain when all is said and done.

I just wanted an outside opinion as to whether I was being lazy, or getting too invested in my own code or anything like that before I launch into an argument as to why we shouldn't spend hours trying to integrate his code and/or that it's not my responsibility to figure out why his panel won't center itself.

EDIT: I swear to god, if he commits extremely buggy code to the CVS one more time or does not enter a descriptive message, or does both at the same time (like he did just now), I will cut him.

PT6A fucked around with this message at 18:42 on Nov 29, 2009

Adbot
ADBOT LOVES YOU

LP0 ON FIRE
Jan 25, 2006

beep boop
Sorry, wrong thread.

LP0 ON FIRE fucked around with this message at 19:51 on Dec 1, 2009

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