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
Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...
Don't forget to implement Comparator on your object, or wrap it in a class that does if you're not allowed to touch it.

Of course, the "correct" answer for your instructor is probably to do the multi-array bubble sort as outlined above, so check whether your instructor cares about learning or "learning" first.

Adbot
ADBOT LOVES YOU

Defenestrategy
Oct 24, 2010

Volmarias posted:

Don't forget to implement Comparator on your object, or wrap it in a class that does if you're not allowed to touch it.

Of course, the "correct" answer for your instructor is probably to do the multi-array bubble sort as outlined above, so check whether your instructor cares about learning or "learning" first.

The assignment was to create a sort method, didn't matter what kind or how just as long as it sorted the array by ID. I used a bubble method because that's the one I know vaguely how to implement, although the instructor was hoping for a select sort I think, and it didn't take much thinking to get from a temporary variable to store a change to a temporary array to store a change. Although I do believe making a student object was the way better solution I just went with the first thing that came in to my head and worked, I'm pretty lazy with coding things I don't want to code.

Is the correct answer for most coding projects in "the real world", "use the thing that's already in the library"?

Defenestrategy fucked around with this message at 17:51 on Nov 4, 2016

Zaphod42
Sep 13, 2012

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

KildarX posted:

The assignment was to create a sort method, didn't matter what kind or how just as long as it sorted the array by ID. I use a bubble method because that's the one I know vaguely how to implement, and it didn't take much thinking to get from a temporary variable to a temporary array index. I'm pretty lazy with coding things honestly.

Is the correct answer for most coding projects in "the real world", "use the thing that's already in the library"?

Yeah, knowing that smarter people than you have come up with brilliant solutions already and using them is a big part of programming 'in the real world'. In fact there's usually multiple different libraries for any given problem and its a matter of picking which is most appropriate.

Most real world programming is a combination of filling out the necessary boilerplate code, making some library references for things that are major problems and have been solved before, and then writing a bit of custom business-specific logic on top of that.

That said, the fact that you messed up the object references means that you're still learning and so going through the motions of writing the sort yourself and learning what it does on a low level is A Good Thing™ so you should ignore the goons telling you that for now.

Bubble sort and insertion sort are kidna the same but opposite, so it could be a fun exercise to learn how to adapt your bubble sort method into an insertion sort method instead :) And then MergeSort and QuickSort are more complicated, but not too hard to understand, and have much better performance.

Zaphod42 fucked around with this message at 17:52 on Nov 4, 2016

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...
In the real world, if you can use Java 8, you'd just use streams to sort by your id and do the whole shebang in one line. That said, walk before you run, etc.

ToxicSlurpee
Nov 5, 2003

-=SEND HELP=-


Pillbug
It's also worth noting that bubble sort is a relatively simple, easy to implement algorithms. It's a tremendously inefficient one that you should never actually use but that leads to implementing a better one and seeing directly how important time complexities are.

Granted in the real world you'll just do collection.sort but you should still know about why some methods are better than others.

Then again if memory serves pretty much everything on the wild is merge sort anyway.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

ToxicSlurpee posted:

Then again if memory serves pretty much everything on the wild is merge sort anyway.

Timsort! :yayclod:

Zaphod42
Sep 13, 2012

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

ToxicSlurpee posted:

It's also worth noting that bubble sort is a relatively simple, easy to implement algorithms. It's a tremendously inefficient one that you should never actually use but that leads to implementing a better one and seeing directly how important time complexities are.

Granted in the real world you'll just do collection.sort but you should still know about why some methods are better than others.

Then again if memory serves pretty much everything on the wild is merge sort anyway.

Most things use quicksort I think, which is like the inverse of merge sort and has equal or better performance depending upon the case.

And the memory cost is worse for merge sort than quick sort too, not that it matters for most trivial cases where you're sorting.

Defenestrategy
Oct 24, 2010

These days are sort complexities actually a thing to take time in coding?

I am currently doing a discrete structures course and we did a project comparing Bubble/Select sort which are 0^2 complex and the run time for doing a bubble sort for sorting a 500 item array 10,000 times took 3 seconds, where as a select sort took 1 second to do the same thing, is reducing the time on sorting operations gonna do that much on a modern machine? So is a OLogN sort really going to help a program?

Defenestrategy fucked around with this message at 21:08 on Nov 4, 2016

more like dICK
Feb 15, 2010

This is inevitable.
Yes it matters. In most cases the standard library has made a reasonable decision for you (java uses different algorithms depending on the collection size and system properties)

more like dICK fucked around with this message at 21:12 on Nov 4, 2016

ToxicSlurpee
Nov 5, 2003

-=SEND HELP=-


Pillbug

KildarX posted:

These days are sort complexities actually a thing to take time in coding?

I am currently doing a discrete structures course and we did a project comparing Bubble/Select sort which are 0^2 complex and the run time for doing a bubble sort for sorting a 500 item array 10,000 times took 3 seconds, where as a select sort took 1 second to do the same thing, is reducing the time on sorting operations gonna do that much on a modern machine? So is a OLogN sort really going to help a program?

Oh it matters a ton. You might think hey what does a second matter but one second 50,000 times...

Plus searching and ordering data by machine rather than by hand is pretty much fundamental to like everything cs. The difference between n^2 and nlogn gets enormous pretty fast. It doesn't matter much on small scales like you deal with in class but needing to order 1,000,000 things somehow is not a rare problem.

As the internet gobbles everything efficiency matters. 500,000 people each needing 10 ms of processor time each all at once will lead to timeouts or annoyed users.

ulmont
Sep 15, 2010

IF I EVER MISS VOTING IN AN ELECTION (EVEN AMERICAN IDOL) ,OR HAVE UNPAID PARKING TICKETS, PLEASE TAKE AWAY MY FRANCHISE

more like dICK posted:

Yes it matters. In most cases the standard library has made a reasonable decision for you (java uses different algorithms depending on the collection size and system properties)

Nah, it's TimSort in Java.
https://docs.oracle.com/javase/8/docs/api/java/util/List.html#sort-java.util.Comparator-

quote:

Implementation Note:
This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.
The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.

The implementation was adapted from Tim Peters's list sort for Python ( TimSort). It uses techniques from Peter McIlroy's "Optimistic Sorting and Information Theoretic Complexity", in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.

more like dICK
Feb 15, 2010

This is inevitable.

It's not quite that simple.

When you call List::sort, it delegates to Arrays.sort. Arrays.sort will first check to see if the java.util.Arrays.useLegacyMergeSort property has been set to true. This is for compatibility with older implementations that didn't properly check equality in comparators. If the property is set, it will use the mergeSort method, which actually uses an insertion sort for collections with fewer than 7 items.

If you haven't requested a legacy merge sort, List::sort uses TimSort.

Arrays.sort for primitives is different. For Object[], it will use TimSort, but for primitives it will check the length of the array and choose an algorithm based on that:

code:

  /**
     * The maximum number of runs in merge sort.
     */
    private static final int MAX_RUN_COUNT = 67;

    /**
     * The maximum length of run in merge sort.
     */
    private static final int MAX_RUN_LENGTH = 33;

    /**
     * If the length of an array to be sorted is less than this
     * constant, Quicksort is used in preference to merge sort.
     */
    private static final int QUICKSORT_THRESHOLD = 286;

    /**
     * If the length of an array to be sorted is less than this
     * constant, insertion sort is used in preference to Quicksort.
     */
    private static final int INSERTION_SORT_THRESHOLD = 47;

    /**
     * If the length of a byte array to be sorted is greater than this
     * constant, counting sort is used in preference to insertion sort.
     */
    private static final int COUNTING_SORT_THRESHOLD_FOR_BYTE = 29;

    /**
     * If the length of a short or char array to be sorted is greater
     * than this constant, counting sort is used in preference to Quicksort.
     */
    private static final int COUNTING_SORT_THRESHOLD_FOR_SHORT_OR_CHAR = 3200;

Sorting in Java is secretly complicated!

more like dICK fucked around with this message at 00:33 on Nov 5, 2016

Zaphod42
Sep 13, 2012

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

KildarX posted:

These days are sort complexities actually a thing to take time in coding?

I am currently doing a discrete structures course and we did a project comparing Bubble/Select sort which are 0^2 complex and the run time for doing a bubble sort for sorting a 500 item array 10,000 times took 3 seconds, where as a select sort took 1 second to do the same thing, is reducing the time on sorting operations gonna do that much on a modern machine? So is a OLogN sort really going to help a program?

Yes and no. Its usually more an issue of making sure to use the proper data structure, using a list when you should use a hashmap can be day and night. And then when you do need to sort, its more picking the right algorithm than implementing it yourself.

As for performance, YES, very yes. If you only have 500 items it doesn't matter so much, with modern hardware being measured in the Gigahertz and having very good performance, so most of the programs you write yourself it won't matter. You CAN get by now using lists for everything and using insertion sort for everything. Your CPU has enough horsepower that it can just brute force the problem. But in the real world, with businesses, it doesn't work that way. If you have millions of clients, or if you're handling millions of units of inventory or locations or whatever, it suddenly matters a great deal.

I've participated in a couple google code jams, which are fun engineering challenges for programmers. You all compete simultaneously and the faster you submit a complete solution to a given problem, the higher you rank. Its very competitive. Google intelligently picked data sets with enough data, and problems with enough complexity, to where the naive solution, even if it works, would never complete in time. So in order to complete those larger data sets and get credit, you had not not only come up with a strategy to solve it, but implement it in a way that is very time efficient.

With a big enough sample size N, the difference between O(N log N) and O(2^N) or O(N^2) can be the difference between your program completing today and your program requiring until the heat death of the universe to complete.

The problem is simpler programs that only need to sort something a couple times on a data set of like 500 is too trivial for modern hardware. Back in the day, that'd require smart algorithms, but not anymore. But if you work on a highly complex problem with hundreds of data entries, it really really matters.

BUT the key thing to remember with performance is "Premature optimization is the devil". You need to think ahead as far as laying out the architecture of the program and making it efficient and organized, but you don't want to obsess about small lines of code too much ahead of time. Write the program, then you test it and profile it, and then you find out where the bottlenecks are. Not every sort needs to be efficient, if you're sorting 12 elements and that only happens once every few minutes, who cares. But if you're sorting 50,000 elements and it needs to happen multiple times per second, then you care a lot.

Fergus Mac Roich
Nov 5, 2008

Soiled Meat

KildarX posted:

These days are sort complexities actually a thing to take time in coding?

I am currently doing a discrete structures course and we did a project comparing Bubble/Select sort which are 0^2 complex and the run time for doing a bubble sort for sorting a 500 item array 10,000 times took 3 seconds, where as a select sort took 1 second to do the same thing, is reducing the time on sorting operations gonna do that much on a modern machine? So is a OLogN sort really going to help a program?

For a fun(no sarcasm) demonstration of how huge of a difference this kind of thing can make, go to Project Euler. Try brute forcing the problems rather than producing the correct solution. When I first started programming, I wrote a solution to one of the prime factorization problems that took days to run.

Carbon dioxide
Oct 9, 2012

Fergus Mac Roich posted:

For a fun(no sarcasm) demonstration of how huge of a difference this kind of thing can make, go to Project Euler. Try brute forcing the problems rather than producing the correct solution. When I first started programming, I wrote a solution to one of the prime factorization problems that took days to run.

What's funny about Project Euler is that solutions that were invalid 10 years ago for being to slow are completely fine on the CPUs of today.

Fergus Mac Roich
Nov 5, 2008

Soiled Meat

Carbon dioxide posted:

What's funny about Project Euler is that solutions that were invalid 10 years ago for being to slow are completely fine on the CPUs of today.

Which just goes to show: a few hours spent finding an efficient algorithm is like having a computer from ten years in the future.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

KildarX posted:

These days are sort complexities actually a thing to take time in coding?

I am currently doing a discrete structures course and we did a project comparing Bubble/Select sort which are 0^2 complex and the run time for doing a bubble sort for sorting a 500 item array 10,000 times took 3 seconds, where as a select sort took 1 second to do the same thing, is reducing the time on sorting operations gonna do that much on a modern machine? So is a OLogN sort really going to help a program?

500 items isn't very many. A million items, that's something. That's 5,000 times longer for n^2. That's a second vs an hour and a half. Nobody's got an hour and a half to sit around and wait for your program to sort it's dataset before it even does something interesting with it.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
I'm having an issue where my Swing GUI loses components after minimizing and reopening the window. The odd thing is that it also resizes various components with specified boundaries to other shapes. My initial searches indicate it may be because I'm mixing AWT Components and Swing components, but I'm not sure how better to recolor JTable cells without calling a function to change the color of the cell prior to rendering, which is about the only place in my code where the two get mixed. I might add all this is new to me and the cell color code was shamelessly swiped from an example online, but it works fine otherwise.

I've tried adding a WindowListener and revalidating/repainting on actions such as windowGainedFocus but I haven't seemed to find the cause as of yet.

Here's an example of the behavior (original versus after having minimized/restored). It's only occurring within the JPanel on the right, as far as I can tell.


I'm not sure if it helps but I have the layout set to null so I can manipulate positioning uses setBounds() (yes I know this makes me a crazy person). The right panel looks sparse because I haven't implemented all the features yet.

Volguus
Mar 3, 2009

PierreTheMime posted:

I'm having an issue where my Swing GUI loses components after minimizing and reopening the window. The odd thing is that it also resizes various components with specified boundaries to other shapes. My initial searches indicate it may be because I'm mixing AWT Components and Swing components, but I'm not sure how better to recolor JTable cells without calling a function to change the color of the cell prior to rendering, which is about the only place in my code where the two get mixed. I might add all this is new to me and the cell color code was shamelessly swiped from an example online, but it works fine otherwise.

I've tried adding a WindowListener and revalidating/repainting on actions such as windowGainedFocus but I haven't seemed to find the cause as of yet.

Here's an example of the behavior (original versus after having minimized/restored). It's only occurring within the JPanel on the right, as far as I can tell.


I'm not sure if it helps but I have the layout set to null so I can manipulate positioning uses setBounds() (yes I know this makes me a crazy person). The right panel looks sparse because I haven't implemented all the features yet.

You forgot it seems to add the links to pictures/code or whatever you wanted to. But, as a rule,yes, try to avoid mixing awt components with Swing. They don't play well. However, for having different colored cells, all you need to do is implement a CellRenderer. An example is given here: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#renderer

And ... use a layout for crying out loud. Really. The most flexible one (and some say harder to use, which I disagree, is trivial once you understand it) is GridBagLayout. tutorial here: http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

Volguus posted:

You forgot it seems to add the links to pictures/code or whatever you wanted to. But, as a rule,yes, try to avoid mixing awt components with Swing. They don't play well. However, for having different colored cells, all you need to do is implement a CellRenderer. An example is given here: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#renderer

And ... use a layout for crying out loud. Really. The most flexible one (and some say harder to use, which I disagree, is trivial once you understand it) is GridBagLayout. tutorial here: http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

Not sure why you can't see the image I provided. The only thing the firewall here lets me use reliably is tinypic, so if you have that blocked that may be that issue.

Well, the issue is even in the example you give it still uses Java.awt.Component:

Here's from the color example you provided:
code:
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import java.awt.Color;
import java.awt.Component;
Here's my imports:
code:
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
Here's the code to render the JTable, if you want to give it a once-over:
code:
private JTable resultsTable = new JTable(tableModel) {
	@Override
	public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
		Component comp = super.prepareRenderer(renderer, row, col);
	        Object value = getModel().getValueAt(row, col);
	        if (col == 5) {
		        if (value.toString().contains("ENDED_NOT_OK")) {
		            comp.setBackground(Color.red);
		        } else if (value.toString().contains("ENDED_OK")) {
		            comp.setBackground(Color.green);
		        } else if (value.toString().contains("ENDED_CANCEL")) {
		            comp.setBackground(Color.yellow);
		        } else {
		           comp.setBackground(Color.white);
		        }
	        } else {
	        	comp.setBackground(Color.white);
	        }
		return comp;
	}
};
I can try it the other way, but if they interact with the same object types I'm not sure if that's the cause.

Volguus
Mar 3, 2009

PierreTheMime posted:

Not sure why you can't see the image I provided. The only thing the firewall here lets me use reliably is tinypic, so if you have that blocked that may be that issue.

That definitely must be the issue, forgot they're weird here.

While I would have done the renderer part a bit differently (define one from Default renderer, set it on the column i need, don't worry about it), it should work just fine the way you have it (as far as I can tell, haven't done Swing in quite a bit of time). The return of the getTableCellRendererComponent method being an AWT Component is just so that they are as general as possible with respect to the objects that are returned. As long as you're returning swing components, you're fine.

Then, the only culprit as far as I can tell is the layout. I have never used the null layout so I honestly have no idea what Swing would do on minimize/restore. Just use one of the simpler ones if GridBagLayout seems too complicated.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

Volguus posted:

Then, the only culprit as far as I can tell is the layout. I have never used the null layout so I honestly have no idea what Swing would do on minimize/restore. Just use one of the simpler ones if GridBagLayout seems too complicated.

I'll duplicate the code over and try a Layout. I certainly am not going to have an issue with complexity, as setting the boundaries for literally every component is about as bad as you can get. I've known for a while that I should eventually break down and swap over, but I wouldn't think it would cause a rendering issue of all things.

Volguus
Mar 3, 2009

PierreTheMime posted:

... I wouldn't think it would cause a rendering issue of all things.

It shouldn't really. I mean, once you set the bounds of a component it should stay there, unless the parent moves, but ... ughh. Given what I know about your application (and I didn't see your screenshot either) , that's the best advice that I can give you: try a layout/many layouts.

Squashy Nipples
Aug 18, 2007

Can I get code review? (I'm pretty noobie)

How do I go about that? I've got 6 Classes in 2 Packages... I know how to jar it up, but what if I want to share source code?

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

Squashy Nipples posted:

Can I get code review? (I'm pretty noobie)

How do I go about that? I've got 6 Classes in 2 Packages... I know how to jar it up, but what if I want to share source code?

Simple way would just be pastebin with or without expiration.

Volguus
Mar 3, 2009

Squashy Nipples posted:

Can I get code review? (I'm pretty noobie)

How do I go about that? I've got 6 Classes in 2 Packages... I know how to jar it up, but what if I want to share source code?

How about you learn a new skill: version control system.

Today all the rage is git, with a fairly popular public source repository called github. On github.com they also have a ton of documentation about how one would go from zero to hero. Give it a try, it is a useful skill to have.

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

PierreTheMime posted:

Simple way would just be pastebin with or without expiration.

Volguus posted:

How about you learn a new skill: version control system.

Today all the rage is git, with a fairly popular public source repository called github. On github.com they also have a ton of documentation about how one would go from zero to hero. Give it a try, it is a useful skill to have.

or the github version of pastebin https://gist.github.com/

Squashy Nipples
Aug 18, 2007

Volguus posted:

How about you learn a new skill: version control system.

Today all the rage is git, with a fairly popular public source repository called github. On github.com they also have a ton of documentation about how one would go from zero to hero. Give it a try, it is a useful skill to have.

A totally valid point. I've used a private Git server on project for my work, but I'm not a coder so I didn't really have my hands in it much.
I'll read up.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
When it comes to acting in a GUI how often should you break up your class into multiples? It just seems to me that acting on objects within a frame should probably remain in the same area. I have all separate classes to fetch data to be fed into list lists/tables, etc, but with all the listeners and such I'm getting up on 500+ lines and it's getting to be a heavy read. I'm just not sure when you should spend the time shuttling objects back and forth between classes just for the sake of clarity.

Defenestrategy
Oct 24, 2010

Welp last question of the year;

So as prep for the final we have to create a parralel array of type String and Int sort them and then do other things with it, get the highest, lowest, etc. So I pretty much have an idea on how to do the rest of it, but I'm stuck at how to get the arrays out of a sort method

code:
	private static [insert value here] sortprint(int[] grades, String[] names)
        [insert code to sort the grades[] and then place the names[] in the correct index] 
        return something;
	
I have code to sort both arrays so that the grades[] get sorted and the names[] align correctly so that if I input an array such that

code:
 int[] grades = [20,10,05];
 String[] names = [c,b,a];
goes through sort;
output int[] grades = [ 05,10,20]
output String[] names = [ a, b, c]

I just can't figure out how to return the arrays. I certainly can't return both a String[] and an int[] from the same method right? I thought about combining them into an Object[][]; but that work around is apparently dumb according to the internet. Another weird way I thought about it is to have a array copy method, so I have two sets of arrays. I throw one into the sort method to return array set1's int[] and throw the other set through the same sort except this sort method will return Strings[], but four arrays and two methods seems a little much to have been the answer. Ideas?

Defenestrategy fucked around with this message at 21:27 on Nov 8, 2016

Volguus
Mar 3, 2009
Would something like this be allowed?

code:
class Student{
private String name;
private int grade;
}
//then the array:
Students[] students= {.....};

//then you sort the students array?

baka kaba
Jul 19, 2003

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

Or you could make an object that encapsulates the two arrays, sorts them internally, and then exposes them with getters so you can just grab them separately

more like dICK
Feb 15, 2010

This is inevitable.
Have the method sort the arrays in place instead of returning new arrays.

Volguus
Mar 3, 2009

more like dICK posted:

Have the method sort the arrays in place instead of returning new arrays.

And then you will have student A with grade 2.5 even though the grade he got was 9.5. Great job. Would have loved to have you create the grading programs for the schools I've been to, since my name starts with an Z, I would have been top of the class all the time :).

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

Data Graham posted:

Such as not using java?

I actually don't mean that to sound snarky. I'm really wondering: what are the benefits of using Java for web dev, when there are plenty of other stacks available that don't require you to muck around with IDEs or roll your own DAOs? Is the performance benefit that significant? Or is it all about scale, for maintainability of large codebases?

Java's main selling point is its ecosystem. It's historically been way ahead of the curve in terms of things like library availability, dependency management, build/test/deployment tooling, frameworks, etc. It's relatively easy to plug a few parts together and end up with something that will be easily maintainable and can be built or deployed in pretty much any software environment, without excessive bugs from the switch.

The days of poor performance from JRE 5 and 6 are long gone at this point. JRE 7 and 8 are really fast, typically among the fastest web stacks out there, especially if you use a thin web server like Jetty instead of something like Tomcat that is doing the whole Java EE stack.

It has a reputation for being excessively verbose. Frankly I think a lot of the blame here should fall on checked exceptions. High-level programming isn't bad at all, but any time you touch anything that deals with low-level I/O (f.ex network connections, SQL connections, files, streams, etc) you can pretty much guarantee that you will be swimming in exception handling. And I cannot for the life of me actually remember how you turn a stream into a string or that kind of thing, there's about five different objects involved in a simple conversion like that.

The thing is that those exceptions do represent things that can go wrong. If you are writing a network application it's important to consider "what if I can't talk to that API, or my connection disconnects, or my DB goes offline". That was the thought process behind explicitly declaring run-time failure modes in Java code. There's nothing stopping you from having every single function declare "throws Exception" and just having your application crash when something goes wrong like unhandled errors do in any language. Some APIs don't let you do that but you can always just catch Exception and return a generic "something went poorly" error page.

Another part of the blame comes down to checked exceptions that should be unchecked. The general rule of thumb nowadays is that if it's an error that happens inside the system (like the programmer asked for an illegal operation) the exception should be unchecked. That's your problem. A lot of Java stuff does not obey this rule, there are a lot of Factory classes that will throw ConfigurationException and that shouldn't happen. But in general Java has been an evolutionary thing. Java gets used in a lot of places and had a lot of weird applications in things like smart/SIM cards and microcontrollers. They made a lot of mistakes and would probably do things differently in hindsight, but they're locked into it by 20 years of legacy code. For example, the Cloneable interface is widely acknowledged to be a mistake because it doesn't do its purpose well and can open up big problems with serialization (including some security issues). But now it's there and can't be undone. I think they should be more bold on such things but it's not the Java Way (tm).

Anyway, going forward, the nice thing about Java is that you don't have to work at the bottom of the stack. Apache has put out a standard suite of tools which handle most of the boring plumbing work. IOUtils, StringUtils, StreamUtils, EntityUtils, etc are all way easier than doing things in low-level Java, and throw sensible exceptions. So really Oracle doesn't have to fix their mistakes.

rt4 posted:

I'd like to give Java web development a try. I didn't see any guides in the OP.

Anyone care to recommend some books or articles about choosing tools and writing a minimal web application?

This is the real downside to Java, there is a bunch of boring configuration bullshit. It's designed to be infinitely configurable to all kinds of tasks, but this also means that you have to make a whole bunch of decisions up front, whereas most other frameworks try to have sensible default options. It's not bad once you're used to it and have some config files you can crib from, but just getting to a Hello World web page in your desired stack is a major pain in the rear end if you don't know what you're doing. If you're totally new to webdev please forgive me for the pain I am about to lead you into. Some of this is Java-specific but a lot is generic webdev framework BS.

First, you want Maven. This is your build tool, it specifies what needs to go into the project and handles downloading the libraries for you and building. (don't actually go out and download this, your IDE will have an embedded instance, just accept it's there. And again, let Maven download the rest of this stuff for you.).

Then, you want Spring. This handles the overall application configuration, creating and attaching various parts of the application ("beans") to each other - for example, it can create/configure a connection pool (SessionFactory) as a bean object and then use a setter to put that object into a DAO class that holds specific queries you need for your application. It's really nice for testing because you can easily send in stub objects instead of the real thing. But you don't need to use it if it doesn't make sense, there's nothing wrong with passing a session around or something like that.

Then you want Spring MVC (emphasis on the controller here). This basically handles the web requests - taking a specific URL, running queries on the DB and attaching the result to the request, and then passing the request to a specific view to generate HTML.

Hibernate is the most common ORM layer. This handles translating between Java objects and database tables. The big decision you need to make here is XML mapping files or annotations. Annotations are newer and easier but XML does a better job of keeping the configuration confined to configuration files. Annotations can get really messy or entirely incompatible if (for example) you have Jackson annotations that tell Java how to map the object to a JSON format and also Hibernate annotations that tell Java how to store it in the database. You can mix and match on a per-class basis if you need.

Finally, your view is Thymeleaf. There are alternatives but this is the best practice nowadays. You have an XML skeleton, some of which may contain logical/flow-control operators (eg only display this element IF ____, write one of these elements for each item in a list, etc). Then you take objects attached to the request attribute store and the session attribute store and use them to fill in values. Thymeleaf is extra nice because a valid thymeleaf document is also valid HTML and can be displayed directly in a browser without a web server.

You also probably want Spring Security which handles stuff like logins/credentials/permissions/etc. This handles questions like "should a user with permissions X,Y,Z be allowed to load the URL '/admin'?"

You'll want to store passwords hashed in the database using a secure hash. BouncyCastle provides standard implementations of these. You want something that salts the password (adds a string to make brute forcing harder) and runs the result through a PBKDF2 derivation function. There is also a standard implementation in Java 8, see: "PBKDF2WithHmacSHA256". You actually want this to be slow, i.e. like a quarter second or so, so that it takes longer to brute force. Ideally you also want it to be resistant to GPU cracking, i.e. a hash like BCrypt. Best practice is to store metadata about how the hash was generated so that you can increase the password strength later (more PBKDF2 rounds, different hash, etc) later if you need to but also allow people to log in once and change their password to the new format.

Now, start downloading. For an IDE you want either IntelliJ Ultimate or Netbeans. I highly highly recommend IntelliJ Ultimate, especially for getting started. Use the trial, you don't have to keep using it past that, but IntelliJ is a superb piece of software and you will have a much easier time getting started.

To make a long story short: download this git repository and point your IDE to it ("open Maven POM project" or "import Maven POM" or whatever). Then do a "build project", or create a custom action for Maven with the command line "clean install". This will build and install the template. https://github.com/kolorobot/spring-mvc-quickstart-archetype

Then create an instance of the template. New Project, Maven, From Archetype, spring-mvc-quickstart-archetype.

Then you can "run" the project (custom Maven action: "run") and it will start an embedded webserver and launch the application. Start playing around from there.

Debugging a web app can be tricky. The embedded server is the easiest way - launch in debug mode and it will just work since it's running inside the IDE's JVM. You can also have a standalone web server like Jetty or Tomcat that runs the application in a separate JVM from your IDE, and you connect to it on a debug port. Tomcat doesn't open this by default, you may need the launch parameter: "-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n" added to the Java launch options.

carry on then posted:

I imagine part 2 of this will involve modifying the input in some way before writing it to output. But yeah.

For the record, in the real world you would do this with sed. :shrug:

Paul MaudDib fucked around with this message at 01:44 on Nov 9, 2016

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Volguus posted:

And then you will have student A with grade 2.5 even though the grade he got was 9.5. Great job. Would have loved to have you create the grading programs for the schools I've been to, since my name starts with an Z, I would have been top of the class all the time :).

If I were you I'd calm down on the hostility, given that you don't seem to understand what's being suggested or even what the concept of "parallel arrays" is.

To the original question: sorting in-place is probably the best solution here - typically when you use parallel arrays for something instead of creating a class type that holds all your information at once, you're prematurely optimizing doing it with performance concerns in mind. It's not something you'd do in typical business-logic code where clarity and correctness is more important than being as fast as possible.

In general though, if you want to return multiple values from a method, you create essentially a container class with fields that are the values you want to return. The code calling your method can then retrieve the individual values from your returned object.

more like dICK
Feb 15, 2010

This is inevitable.

Volguus posted:

And then you will have student A with grade 2.5 even though the grade he got was 9.5. Great job. Would have loved to have you create the grading programs for the schools I've been to, since my name starts with an Z, I would have been top of the class all the time :).

Do you not understand what sorting in place means

TheresaJayne
Jul 1, 2011

more like dICK posted:

Do you not understand what sorting in place means

I guess i would have used a treeset and had the equals method use the score for the bean object containing all the details of the student

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Paul MaudDib posted:



For the record, in the real world you would do this with sed. :shrug:

Absolutely not in my experience.

Adbot
ADBOT LOVES YOU

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
I have a Swingworker to go fetch records and hunt through them to search for a given pattern. This works great, but on larger groups of records I wanted to add a JProgressBar to give the user an idea of how much longer it would be. I'm having trouble understanding how to properly implement the Process() method, though. I looked up some examples and attempted to use it as-is, but where theirs worked mine only publishes after the entire search is completed, so it will sit at 0% and then jump to 100%. The kicker being I can do a stdout of the increment values and that works in real-time just fine.

Essentially what I have is this:
code:
	@Override
	protected void process(List<Integer> jobNums) {
		int i = jobNums.get(jobNums.size()-1);
		jpb.setValue(i);
	}
	
	@Override
	protected DefaultListModel<String> doInBackground() throws Exception {

		int i = 1;
		(do work)
		jpb.setMaximum(jobsListing.size());
		Iterator<xxxxx> jobItems = jobsListing.iterator();
		while (jobItems.hasNext()) {
			publish(i);
			(do more work)
			i++;
		}
	
		return yyyy;
	}
Tell me what dumb thing I'm doing, thread. :(

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