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
Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

Bob Morales posted:

I was writing a program to strip data from XML files, and give me [tagname, data] pairs.

Of course I ran into problems with nested tags. Would a linked list be a good way to keep track of which tag I am in?
A stack could work, but what you really want is an XML parser (sorry, TRex EaterofCars).

Adbot
ADBOT LOVES YOU

MononcQc
May 29, 2007

Bonus posted:

Sup mate!

If you have a binary tree and a list like [Left,Right,Left,Left,Left] that tells you where you are in the tree i.e. the current node, and you want to modify it, you have to traverse the whole list before getting to your desired node and modifying it, so that's O(n) (or O(log n) if you consider n to be the number of elements in the tree and the tree is balanced). If you want to move around the tree a lot, you have to start from the root for each movement and traverse that list of Left and Right, so you'll be doing a lot of O(n) operations.

If you have a zipper, moving around is O(1) and so is modifying the element under focus. Instead of explaining zippers, I'll point to this excellent article about them: http://www.haskell.org/haskellwiki/Zipper also this new blog post about them is cool too: http://blog.ezyang.com/2010/04/you-could-have-invented-zippers/
I had read http://scienceblogs.com/goodmath/2010/01/zippers_making_functional_upda.php and it did feel like it would be possible to get similar effects that way by just storing a bunch of nodes.

I could compare it to how it's basically possible to have a doubly-linked list by just having something like this implementation (sorry, going with scheme. It's the only non-php interpreter I have at the moment):

code:
;; the linked list is a list of two list -- one acts as the stack
;; of seen nodes, the other as nodes not yet seen
(define (make-dl l) (list '() l))
;; fetches the stack of seen nodes
(define (prevs dl) (first dl))
;; fetches the stack of unseen nodes
(define (nexts dl) (second dl))

;; map over the dl
(define (dl-map f dl)
  (cond ((null? (nexts dl)) dl)                              ; done, return as is
        (else 
          (let* ((current (first (nexts dl)))                ; get the current elem
                 (new-nexts (cdr (nexts dl)))                ; pop from the stack
                 (new-prevs (cons (f current) (prevs dl))))  ; push modified on seen stack
            (dl-map f (list new-prevs new-nexts))))))        ; recurse

;; reverse of map. Takes from a different stack
(define (dl-rmap f dl)
  (cond ((null? (prevs dl)) dl)
        (else 
          (let* ((current (first (prevs dl)))
                 (new-prevs (cdr (prevs dl)))
                 (new-nexts (cons (f current) (nexts dl))))
            (dl-rmap f (list new-prevs new-nexts))))))
And then, both dl-map and dl-rmap can work forward or on reverse in the same exact manner, with the same time complexity.
code:
> (dl-map (lambda (x) (+ x 1)) (make-dl '( 1 2 3)))
((4 3 2) ())
> (dl-rmap (lambda (x) (- x 1)) '((4 3 2) ()))
(() (1 2 3))
EDIT: here's the code with syntax highlight and results (made to fit with Guile): http://ideone.com/lajTI

I pretty much just made the following mental transition: if it's possible to simulate a purely-functional doubly-linked list by keeping a stack of just seen nodes, then the same could logically apply to trees, given the parent node pointer is pretty much the same as the previous node pointer in the doubly-linked list.

To put it back in the context of trees, I could see myself having lists like [[direct-parent, parent2, ..., root], current-node=[val, left, right]] or adding whatever quick-access fields you want for other stuff placed in that kind of list.

Again, I *think* I understand the principle of zippers from there (correct me if I don't). What I think I don't understand is what do continuations do better in order to have different gains in time complexity when compared to the stack-based approach? If it's the same, then what are the gains?

MononcQc fucked around with this message at 19:37 on Apr 8, 2010

tef
May 30, 2004

-> some l-system crap ->

Bob Morales posted:

I was writing a program to strip data from XML files, and give me [tagname, data] pairs.
Thoughts?

use an xml library and xpath?

Bob Morales
Aug 18, 2006


Just wear the fucking mask, Bob

I don't care how many people I probably infected with COVID-19 while refusing to wear a mask, my comfort is far more important than the health and safety of everyone around me!

Mustach posted:

A stack could work, but what you really want is an XML parser (sorry, TRex EaterofCars).

I know that, I was just doing it for the exercise.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
Then a stack is ideal!

shrughes
Oct 11, 2008

(call/cc call/cc)
When parsing HTML, I ended up mapping the sequence of start tag/end tag/text node/comment/weird tag atoms into a sequence of stacks, with the stack of start tags supporting each node.

code:
> (define txt (string-append "<!DOCTYPE HTML><html lang=\"en\"><head><title>"
                             "Hello</title>  </head><body>text</body></html>"))
> (for ([x (in-html-segments (open-input-string txt))]) (printf "~s\n" x))
#(struct:weird-tag #"!DOCTYPE HTML")
#(struct:start-tag #"html" ((#"lang" . "en")) #f)
#(struct:start-tag #"head" () #f)
#(struct:start-tag #"title" () #f)
#(struct:text-node "Hello")
#(struct:end-tag #"title")
#(struct:text-node "  ")
#(struct:end-tag #"head")
#(struct:start-tag #"body" () #f)
#(struct:text-node "text")
#(struct:end-tag #"body")
#(struct:end-tag #"html")
> (for ([x (in-html-stacks-from-segments
            (in-html-segments (open-input-string txt)))])
    (pretty-print x))
(#(struct:weird-tag #"!DOCTYPE HTML"))
(#(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:start-tag #"head" () #f)
 #(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:start-tag #"title" () #f)
 #(struct:start-tag #"head" () #f)
 #(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:text-node "Hello")
 #(struct:start-tag #"title" () #f)
 #(struct:start-tag #"head" () #f)
 #(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:end-tag #"title")
 #(struct:start-tag #"head" () #f)
 #(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:text-node "  ")
 #(struct:start-tag #"head" () #f)
 #(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:end-tag #"head") #(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:start-tag #"body" () #f)
 #(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:text-node "text")
 #(struct:start-tag #"body" () #f)
 #(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:end-tag #"body") #(struct:start-tag #"html" ((#"lang" . "en")) #f))
(#(struct:end-tag #"html"))
I ended implementing some search 'n capture code that mostly operates by grouping things over some tag-matching chain of predicates, with a completely ugly API which is too shameful to post here. You can capture information, among other ways, using the capture groups of regexes when matching attributes, as in (has-attr-match #"id" #px"thread(\\d+)") which would capture the thread id for the node it groups stacks of elements by. The whole point of this was that I needed a stream-processing HTML parsing library.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

OverloadUT posted:

D&D poo poo

I actually did this for django project, I'll upload it later so that you can all laugh at how bad it is :)

Farchanter
Jun 15, 2008
Hey, all.

I'm looking at connecting an XBox controller to a PC for use in a game design project built in AS3, but I'm completely at a loss as to how to get that interface to work. Does anyone have any ideas?

e: nevermind, I think I've got it. Thanks, though.

Farchanter fucked around with this message at 00:54 on Apr 9, 2010

Ularg
Mar 2, 2010

Just tell me I'm exotic.
I'm completely green in programming, I literally just started 2 days ago and I've been using BlitzPlus from advice from a few people. I've so far stringed together a few modified example code from the program's help window to a menu that lets me go to each one or repeat that particular part of code.

Then following a surprisingly decent youtube tutorial I tried making a space invaders mock game and I've come to the point where there's score, highscore, lives, levels, respawning and moving and firing enemies, and the whole shebang, even music and sounds.

The problem I'm having is that I've been trying to add a real simple background that just displays huge colored text that I can maybe swap out later for something more reasonable and I've been having problems trying to figure out how to add the background correctly.

From what I googled this was what I was supposed to use:

code:
GRAPHICS 640,480,32,2   ;creates a 640x480 windows with 32 bit depth and 2 for windowed mode

GLOBAL myimage=LOADIMAGE("myimage.bmp") ;loads the image into memory.  Make sure the "myimage.bmp" is in the same directory as the source or you'll get an error

SETBUFFER BACKBUFFER()  ;sets the backbuffer for drawing.  When you draw an image in B+ (as well as other languages), you're really just drawing to somewhere "behind the screen"

WHILE NOT KEYHIT(1) ;while you have not pressed escape...
  CLS ;Clear the screen each fram
  DRAWIMAGE myimage,0,0  ;draws the image at 0,0, the top left corner of the screen
  FLIP  ; "flip" the 'behind the screen' part you drew to actually to the screen so you can see it
WEND  ;end of while loop

END ;end the program
But for whatever reason it just doesn't appear on screen. I can change "DRAWIMAGE myimage,0,0" to "myimage,x,y" and that makes the background move with the player controlled character, but unless I make a background that wouldn't really change from moving on the X axis then I really have an annoying problem.

The other issue I'm running in is wanting to be able to limit the number of shots that can be generated from the player controlled character. Basically like in the space invader games I was trying to limit the amount of shots you can fire to 3, either by deleting ones in midair or not being able to fire until they disappear.

I think this is the part of code I want to add the line, but I'm not really sure what to add to make it work. Hell, I don't even know what phrase to use to google the problem, so I've been stumped.

code:
;update bullets and draw them
	For b.bullet = Each bullet
		b\y = b\y - 5
		DrawImage img_bullet,b\x,b\y
		If b\y < 0 Then Delete b
	Next
I'm happy with the current incarnation of what I've been working on with it, so I kind of just let it sit, but these two problems are just nagging at me because I know it's something I should know.

The other thing I'm currently working on to try and teach myself the language is making a cheesy and possible repulsive TF2 Choose your own adventure, a lot more of 'Print "x"' then If's and For's, but it will help me immensely in organization skill of code and making it look cleaner. Also a lot of "Goto" commands, I may have to make a list of where each one goes as I continue to add more stuff to it.

And you even bothered to skim my post, and because I want to show off the stuff, here's a picture:


Click here for the full 1920x1080 image.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Ularg: first off, welcome to the wonderful world of programming. You have a great deal to learn, but I applaud your enthusiasm.

I'm afraid I don't have any experience with Blitz, but are you certain (0,0) is a valid set of coordinates in drawing space? Have you tried (1,1), for example? If you could Pastebin the code to your game, we might be able to offer more suggestions.

With respect to bullets, if you wish to limit how many bullets the player can produce it seems like it would make more sense to look at the code that creates them in the first place, rather than the code that updates their positions. When the player presses fire, for example, check how many bullets are in the air before creating a new one.

Text adventure games can teach you a great deal, but simply using a nest of GOTOs is going to turn into a mess no matter what you do. I'd recommend doing a lot of planning ahead of time (or at least starting over from scratch a few times over the course of the project) and thinking about what you can generalize. What common logic takes place in every room, with every item, etc. If you want to learn about Structured Programming (which, in a nutshell, is the practice of using control structures like while and for loops instead of GOTO) read up on Finite State Machines. This article gives a reasonably straightforward example of one implemented in C.

ymgve
Jan 2, 2004


:dukedog:
Offensive Clock
I am trying to parallelize http://en.wikipedia.org/wiki/Conjugate_gradient_method with OpenMP. But I don't get the speed improvements I'd expect - using 2 cores I only get about 1.5x the speed of the single thread variant, and when using 4 cores it actually goes slower than the 2-core variant.

I've tried almost everything - only using OpenMP directives for the O(n^2) operation of the algoritm, using OpenMP separately for each matrix/vector operation, and wrapping my whole algorithm in a parallel directive (Which caused a LOT of headaches), and the running time is still in the same ballpark.

Just to be sure, I also made a quick O(n^3) function, and that one sees the proper speed improvements I was expecting.

edit: Seems like I'm bottlenecked by memory bandwidth. Not much to do then.

ymgve fucked around with this message at 03:26 on Apr 12, 2010

Ularg
Mar 2, 2010

Just tell me I'm exotic.

Internet Janitor posted:

Ularg: first off, welcome to the wonderful world of programming. You have a great deal to learn, but I applaud your enthusiasm.

I'm afraid I don't have any experience with Blitz, but are you certain (0,0) is a valid set of coordinates in drawing space? Have you tried (1,1), for example? If you could Pastebin the code to your game, we might be able to offer more suggestions.

With respect to bullets, if you wish to limit how many bullets the player can produce it seems like it would make more sense to look at the code that creates them in the first place, rather than the code that updates their positions. When the player presses fire, for example, check how many bullets are in the air before creating a new one.

Text adventure games can teach you a great deal, but simply using a nest of GOTOs is going to turn into a mess no matter what you do. I'd recommend doing a lot of planning ahead of time (or at least starting over from scratch a few times over the course of the project) and thinking about what you can generalize. What common logic takes place in every room, with every item, etc. If you want to learn about Structured Programming (which, in a nutshell, is the practice of using control structures like while and for loops instead of GOTO) read up on Finite State Machines. This article gives a reasonably straightforward example of one implemented in C.

While using coords (1,1) didn't work, I learned that Blitzplus, when fliping an image on the screen, uses the center of the image as 0,0 (or something like that). So I had to center the image on screen (540,400) was able to place the image correctly and where I needed it.

As for the bullets I took the advice and tried a few things with

code:
;fire bullets
	If KeyHit(57) Then
		PlaySound(snd_shipshot)
		b.bullet = New bullet
		b\x = x + 15
		b\y = y
		
	EndIf
I would try during that If

code:
if b > 3 then delete b
(Replacing b with b.bullet and bullet to make sure that wasn't the issue. This would give me the message "Illegal operator for custom type objects"

Puting another "endif" after that line would give me "Have Endif without if" command.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
Seems like as a good a time as any of not only have a C++/Java flamewar, but throw in GUI toolkits at the same time:

I'm oscillating between C++ and Java for some stock trading strategy development software I've been messing with in my free time. I wanted to beef up on C++ so I started to port some of it over just to get comfortable. I've used C++ on and off but this is the biggest plunge so far. I'm seeing that I have to earn any performance gains. In terms of the deep math calculations, it's at least 2x faster which is a very compelling reason to switch. In other aspects it's 1:1, with the C++ code being much harder to manage; a memory leak blew through about 6GB of RAM and then 5GB of virtual memory on top of that before I terminated it; shared pointers helped a lot.

I think it's going to come down to UI performance. I was using SWT in Java originally since it was the first I really came to understand. However, it gets real slow dealing with some of the larger data sets I use, and a save dialog still takes about 10 seconds to become responsive. Something unavoidable on the Java side is creating tons of little classes to do all the event handling and message passing, when I seem to be fine with a function pointer or something else. My charting code is hard to manage and slow; it's awkward to use the canvas control and sync up everything.

So here's the issue. What will yield me a responsive UI, while providing a tool kit that preferable has a good list component for tables worth of data? I also have to do a lot of charting and I've about settled on drawing it in OpenGL, so I wanted to have an OpenGL canvas. With decent acceleration I'm banking on being able to brute force render all the chart data with some basic accounting for size, and then hopefully get good scrolling and zooming to work rather easily. On the C++ time I'm playing with wxWidgets because previously of the big ones that was the one I grok'ed the most. I am reconsidering FLtk since it's apparently very efficient, but I don't know how well it could handle my tables.

LuckySevens
Feb 16, 2004

fear not failure, fear only the limitations of our dreams

Are you using this by any chance?

1337JiveTurkey
Feb 17, 2005

Rewriting an entire GUI application in hopes that there's going to be a sudden massive performance boost is a fool's errand. If the GUI is doing everything in the event dispatch thread then there's no language or API that's going to be highly responsive and you're going to be looking at five second waits instead if you're really, really lucky.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
Much as I like C++ and hate Java, if you are getting a factor of 2 performance increase in basic math, you are doing something horribly wrong in Java.

TagUrIt
Jan 24, 2007
Freaking Awesome
Rocko, are you doing your data processing on the Event Dispatching Thread, or are you working with other threads (hopefully through an Executor service) and merely updating the GUI using SwingUtilities.invokeLater? If a save dialog is taking 10 seconds to become responsive, it sounds like you are either doing a lot of heavy lifting on the EDT (a big nono), or you are blocking the EDT while you wait on something else (an even bigger nono; try using a SwingWorker to automate the "do in background, then update the GUI" process).

As for charting, I've used JFreeChart in the past and it works well enough for my needs (though I make no promises about how well it works on gigabytes of data at the same time).

I am a swing developer, not a SWT guy. I don't know anything about SWT. Hell most of this advice probably doesn't help. Other than the "don't do stuff or block on stuff from your event thread" part.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
Hey guys I responded to all this last night but I don't know where the hell it went.

Regarding the Java/C++ performance, Java cannot vectorize and the bastards refuse to allow it into the spec, and it forces floating point operations to go in the order they are defined. There's nothing like fast FP in Java. So IMO the C++ code that is doing my moving average test benchmark should have been even faster.

That being said, the integer logic is just as fast if not faster. My code for pulling all the data down from mysql initially is running much slower in C++. I need to figure out what and why, and determine if all the effort required to hit par is ultimately worth it. I could pass off the hard math to C++ code using JNI, and with a larger enough data set the overhead would be mitigated. That's another path to take.

I'm not using QuantLib but it looks like a good thing for post-processing. My mind is in a million directions right now and given I'm thinking about starting over and starting over right, I probably won't touch that library for awhile.

As for GUI drawing threads, I first ran into the drawing thread when I discovered stuff wouldn't draw after updating the GUI. I haven't completely come to terms with how to interact properly with a GUI drawing thread across multiple windows and components. That being said, when using an Eclipse SWT open dialog widget, it shouldn't just sit there with its tongue hanging out when I want to type in a file name into a text box. I have no code going on there other than what called it.

TagUrIt posted:

Rocko, are you doing your data processing on the Event Dispatching Thread, or are you working with other threads (hopefully through an Executor service) and merely updating the GUI using SwingUtilities.invokeLater? If a save dialog is taking 10 seconds to become responsive, it sounds like you are either doing a lot of heavy lifting on the EDT (a big nono), or you are blocking the EDT while you wait on something else (an even bigger nono; try using a SwingWorker to automate the "do in background, then update the GUI" process).

As for charting, I've used JFreeChart in the past and it works well enough for my needs (though I make no promises about how well it works on gigabytes of data at the same time).

I am a swing developer, not a SWT guy. I don't know anything about SWT. Hell most of this advice probably doesn't help. Other than the "don't do stuff or block on stuff from your event thread" part.
Well would you recommend a few GUI design pattern examples or general code examples that overtly and clearly takes the drawing thread into consideration?

I heard about JFreeChart and might look back at it again, depending on language selection and such. I can't remember what kept me from using it so it was probably a bad reason.

DrBouvenstein
Feb 28, 2007

I think I'm a doctor, but that doesn't make me a doctor. This fancy avatar does.
can I just say I hate MATLAB?

Anyway...I have to read data from a file, and for this assignment we can't use load, wee have to use lower-level I/O.

I have a text file which has a header that has 13 columns, the year, and then the twelve months. Under each header is a number, the first one is the year, obviously, and the others are average temps for that given month. So it looks sort of like this:

code:
Year  Jan  Feb Mar Apr
1900  12   20  32  55  
1901  11   19  35  49
And so on.
So going from the hints from the homework (which is to read all of this into a variable and then make plots from it,) the instructor says:

quote:

There are many ways to import this data. I do not want you to use load (we’ve practiced that already). I want you to use fgetl, fgets, fscanf or textscan. I found textscan the easiest. It is ok to manually enter the number of rows of data (i.e., 115) instead of trying to detect eof. I read the entire file in two statements (one to read the headers and one to read the data). Textscan returns a
cell array – not a vector or matrix

Ok, simple enough, so I just started with the code to read the header, and it doesn't give me what I expected or what I want. I wrote this:
code:
Data = textscan(fid, '%s', 13);
So it would only repeat 13 times, and thus only get strings for the headers. I was expecting a 1x13 cell array...what I got was a 1x1 cell array, and the only cell in that array was itself a 13x1 array. That array has the correct info, but I need it both
a) Transposed so it's 1x13, and
b) not for some reason be a cell within in a cell...seems quite needless.

And, of course, given that I messed up just the first line, I certainly can't continue on to try and get all the numbers loaded into the cell either.

Edit: I said screw it and just went with:
code:
data = textscan(fid, '%s %s %s %s %s %s %s %s %s %s %s %s %s' );
It loads all the data from the file, not just the header, but it's all there in a 1x13 cell, each one 116x1 (115 years of data...) so it's basically what i want. I'll worry about how to convert only cells 2-116 in each of the main cells later.

DrBouvenstein fucked around with this message at 01:37 on Apr 14, 2010

huge sesh
Jun 9, 2008

Is there any way to give GDB an expression that uses arguments to a function? I want to break on free() being called on a specific memory address.

MrMoo
Sep 14, 2000

I would guess cond 1 0x123 == ptr and break free

1337JiveTurkey
Feb 17, 2005

Rocko Bonaparte posted:

As for GUI drawing threads, I first ran into the drawing thread when I discovered stuff wouldn't draw after updating the GUI. I haven't completely come to terms with how to interact properly with a GUI drawing thread across multiple windows and components.
Are you trying to have all those threads actually work with the GUI directly? You don't really want to have a thread-per-window programming model because it's impossible to get right and unless you're using BeOS, it's not supported anyhow.

Just have the event dispatch thread do all the UI stuff such as scheduling repaints for everything. Your other threads should be part of a worker pool. Different UI frameworks have their own versions but the idea is that you send the task off to a worker every time you want to do something that will take a long time. It updates the model behind the scenes and then notifies the event dispatch thread when it's done. Then the event dispatch thread repaints the section of the table that was modified.

quote:

That being said, when using an Eclipse SWT open dialog widget, it shouldn't just sit there with its tongue hanging out when I want to type in a file name into a text box. I have no code going on there other than what called it.

Try running your program inside of a profiler and see what it turns up since odds are it's doing something you're not expecting due to a forced repaint or something. JProfiler is pricey but you can try it out for free and that's usually enough to spot what's holding things up. NetBeans also has a less sophisticated profiler inside of it as well, but it's free.

TagUrIt
Jan 24, 2007
Freaking Awesome

Rocko Bonaparte posted:

I could pass off the hard math to C++ code using JNI, and with a larger enough data set the overhead would be mitigated.
I'm truly boggled at how there would be such a perf advantage doing this. Can you give an example of the code that runs 2x faster in C++ than in java?

Rocko Bonaparte posted:

As for GUI drawing threads, I first ran into the drawing thread when I discovered stuff wouldn't draw after updating the GUI. I haven't completely come to terms with how to interact properly with a GUI drawing thread across multiple windows and components.
I'm not sure how SWT does it, but in Swing there is exactly one Event Dispatching Thread (EDT). So there isn't any trickery other than "only touch the GUI from the EDT". So if you're on the EDT, you can play with every swing component in your application, regardless of whether they are in the same JWindow.

Rocko Bonaparte posted:

Well would you recommend a few GUI design pattern examples or general code examples that overtly and clearly takes the drawing thread into consideration?

I'd strongly recommend Java Concurrency in Practice for getting it correct. But if you want to see some nasty code examples to get a rough idea, here you go.

I'm making a button that will calculate successive prime numbers when clicked. If I do everything on the EDT thread, my code might look like this:
code:
private long nextnum = 10; //confined to EDT
public JButton createPrimeButton() {
	JButton primeButton = new JButton("I do processing on the EDT");
	primeButton.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent e) {
			handleButton();
		}
	});
}

private void handleButton() {
	long currentNumber = currentPrime+1;
	while (true) {
		for (long i = 2; i < currentNumber; i++) {
			if (currentNumber % i == 0) {
				break;
			}
			if (i == currentNumber - 1) {
				currentPrime = currentNumber;
				doStuffWithThePrime(currentPrime);
				return;
			}
		}
		currentNumber++;
	}
}
Besides my retarded prime finding code, it is pretty concise, and seems to work well enough. Sort of. If we started with currentPrime = 10000000000 instead of 10, you would notice that it is really slow and the button is always pressed in until it finishes calculating (and the rest of your GUI is unresponsive).

So if we want to do this a little better, we probably want to do it in a different thread. (Managing threads you create can be a real headache, so I like using ExecutorServices which handle all of that for you. But be aware that EXECUTOR.submit(...) fundamentally puts that code into a queue and waits for the next worker thread to be open, who will then execute the code.)
code:
private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
private void handleButton() {
	EXECUTOR.submit(new SwingWorker<Long,Void>() {
		@Override
		protected Long doInBackground() throws Exception {
			long currentNumber = getCurrentNumberThreadsafe()+1;
			while (true) {
				for (long i = 2; i < currentNumber; i++) {
					if (currentNumber % i == 0) {
						break;
					}
					if (i == currentNumber - 1)
						return currentNumber;
				}
				currentNumber++;
			}
		}
		
		@Override
		protected void done() {
			long value = currentPrime;
			try { value = get(); } 
			catch (InterruptedException e) { Thread.currentThread().interrupt(); } 
			catch (ExecutionException e) { e.printStackTrace(); }
			
			currentPrime = value;
			doStuffWithThePrime(currentPrime);
		}
	});
}
Woah! It actually isn't that complicated, though. Here's a quick walkthrough:
1. We have a static ExecutorService. Java sets up the threads and worker pool and all of that stuff. All we need to do is tell it stuff that it needs to execute.
2. In the handleButton() method, we create a SwingWorker. A SwingWorker encapsulates the idea of "do this in the background, and then update the UI".
3. Because the doInBackground method of the SwingWorker isn't running on the EDT, we shouldn't just reference currentPrime. Instead, we need a threadsafe way to get the value. I imagine that my fictional method has to hop onto the EDT to get the value and then return in. (The smarter way to fix this is to make currentPrime volatile.)
4. After the doInBackground method returns, the done() method will be called on the EDT. We can then reap the fruits of our labor using the get() call.

While this approach is more complicated and error-prone, it doesn't block our precious EDT, so the interface can still react to mouse clicks and the like.

I'm really bad at examples and coding in general, but if you want some more clarifications send me a pm. And, yes, I know this code is terrible and is probably wrong at least once.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

TagUrIt posted:

I'm truly boggled at how there would be such a perf advantage doing this. Can you give an example of the code that runs 2x faster in C++ than in java?

Let's see:
C++: http://pastebin.com/J5Jgzenw

Java: http://pastebin.com/qeCkt8RZ

It's doing something like exponential moving average, mimicking using the open, high, low, and close of a bar but expanding the series to triplets like [open, (high + low) / 2, close]. It then calculate the EMA of that extended series. Then it takes every third to collapse it back down to the original size. The data size reflect running across a huge poo poo pile of data.

In truth they both run very fast overall but moving averages are common enough that I might run it multiple times or make it part of something more complicated.

Currently numbers are all set to 1 so in my basic check I can have some basic comparison between the two languages. Of course the timing code is different too. I am doing this on Linux and using Linux timer code.

I was screwing up a lot on the C++ code but f



As for the GUI threads, I was reading up last night on what Swing does and I don't know if SWT has the same model. There's a single thread for drawing but I don't think it has some concept about worker threads. So I'm trying to understand in SWT what it might mean to hog that thread. To be fair, when I open up a table stocks with, say, more than 8,000 entries, the table itself is fine enough. Sorting rows is slow, and all I could give the SWT table was a comparison operator since it sorted it itself. My main issue with the SWT thread is making sure it gets the memo when it needs to draw. That and the save dialog that sits on its butt.

Fly
Nov 3, 2002

moral compass

Rocko Bonaparte posted:

Let's see:
C++: http://pastebin.com/J5Jgzenw

Java: http://pastebin.com/qeCkt8RZ
I would not create a new Random every time you call genFloats(). I think Random's constructor may have to make a system call if you don't specify a seed. Because you do not want to create a new Random with the same seed, I would put it in an initializer (static initializer in your case) and just reuse the same Random object to get success floats.

Also, using static for everthing is not idiomatic object-oriented programming style.


edit: System calls should be avoided for performance:
public Random() { this(++seedUniquifier + System.nanoTime()); }

TagUrIt
Jan 24, 2007
Freaking Awesome
Quick response on my way to work:
Because of the way that that most JVM's work, testing over a single run is slower than repeated calls. (The first run is JIT compiled to machine code, and the following 10 or so aren't optimized much if at all.) There's a recent post in the Java thread about this, but basically if you want to benchmark correctly, you'll want to "warm up" the JVM by running your test code and throwing out the results a couple of times (I'd recommend 10+) before taking the real timing.

There's a good post on this in the Java thread around two pages back, I think.

Flying Guillotine
Dec 29, 2005

by angerbot
I have a simple HTML question:

code:
<table border="1" width=100%>
<tr>
    <td bgcolor="#66CCFF" align="center"<b><font color="FFFFFF">Header Text</td>
</tr>
<tr>
    <td align="left">Section Text 01</td>
    <td align="left">Blog Text Lorem ipsum blah blah blah blah blah blah blah</td>
</tr>
<tr>
    <td bgcolor="#66CCFF" align="center"<b><font color="FFFFFF">Footer Text</td>
</tr>
</table>
I want the blue header and the footer to stretch all the way across the table, not be their own box.

How do I do this?

Also, any links to good HTML pages on learning HTML.


edit: Already got my answer

Flying Guillotine fucked around with this message at 03:14 on Apr 15, 2010

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

Fly posted:

I would not create a new Random every time you call genFloats(). I think Random's constructor may have to make a system call if you don't specify a seed. Because you do not want to create a new Random with the same seed, I would put it in an initializer (static initializer in your case) and just reuse the same Random object to get success floats.

Also, using static for everthing is not idiomatic object-oriented programming style.


edit: System calls should be avoided for performance:
public Random() { this(++seedUniquifier + System.nanoTime()); }
Sure I can do that, but that's not being timed. If it's creating spurious objects that might force GCs then I guess it could get in the way of the performance during the timed section.

Edit: One concession I should make is that the C++ code isn't doing array bounds checking while the Java code has to do it. So to be fair for that perhaps I should use std::vector and the .at() operator or something similar to have similar array overhead. But OTOH perhaps it's fair game to be able to use C++ arrays as they stand whenever I can if I'm trying to get some performance out of it and accept the risks.

Rocko Bonaparte fucked around with this message at 20:19 on Apr 14, 2010

Fly
Nov 3, 2002

moral compass

Rocko Bonaparte posted:

Sure I can do that, but that's not being timed. If it's creating spurious objects that might force GCs then I guess it could get in the way of the performance during the timed section.
Sorry, I see that now.

quote:

Edit: One concession I should make is that the C++ code isn't doing array bounds checking while the Java code has to do it. So to be fair for that perhaps I should use std::vector and the .at() operator or something similar to have similar array overhead. But OTOH perhaps it's fair game to be able to use C++ arrays as they stand whenever I can if I'm trying to get some performance out of it and accept the risks.
You might want to try that in C++ just to test your code, but bounds checking does have a performance cost in Java. Array initialization also has a performance cost in Java that C++ does not have because it sets all values to zero or null.

edit: I wonder whether using the Java 5 syntax sugar to iterate over an array has a shortcut to disable bounds checking because the user's code never has to do a bounds check.

You might also want to put all of your float values in a struct and put them in a single array so that you have to do fewer bounds checks.
code:
   /// Seven bounds checks.
   for(int inIdx = 0; inIdx < close.length; inIdx++) {
       EMAin[EMAInBase + 0] = open[inIdx];
       EMAin[EMAInBase + 1] = (high[inIdx] + low[inIdx]) / 2.0f;
       EMAin[EMAInBase + 2] = close[inIdx];
       EMAInBase += 3;
    }

   // Four bounds checks
   for(int inIdx = 0; inIdx < close.length; inIdx++) {
       SomeStruct ohlc = oneArray[inIdx];
       EMAin[EMAInBase + 0] = ohlc.open;
       EMAin[EMAInBase + 1] = (ohlc.high + ohlc.low) / 2.0f;
       EMAin[EMAInBase + 2] = ohlc.close;
       EMAInBase += 3;
    }

    // Hypothetically could be optimized by the compiler to be just three bounds checks.
    for (SomeStruct ohlc : oneArray) {
       EMAin[EMAInBase + 0] = ohlc.open;
       EMAin[EMAInBase + 1] = (ohlc.high + ohlc.low) / 2.0f;
       EMAin[EMAInBase + 2] = ohlc.close;
       EMAInBase += 3;
    }
This assumes you populate oneArray with structs that contain your open, high, low, and close values. I would never worry about this except in the case that one determines performance really (really) matters. It is worth benchmarking, IMO.

Fly fucked around with this message at 21:33 on Apr 14, 2010

Painless
Jan 9, 2005

Turn ons: frogs, small mammals, piles of compost
Turn offs: large birds, pitchforks
See you at the beach!
Bounds checks are trivially easy to optimize away in a loop that simply goes through every element in an array in order, and even in cases where they're not removed, they are fairly unlikely to cause a performance hit on a modern superscalar processor. But yeah, test with more than one iteration.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



GPL 2 question - if someone is distributing a compiled program that was built from GPLed code as part of a larger software suite and promises that they have not modified the source of the compiled program at all, are they required to provide a copy of the exact source used to compile that GPL-licensed program? To clarify, the GPLed code is compiled into a regular command line utility that their (closed) GUI code runs as a separate process, so nothing is linked against the GPLed code.

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Munkeymon posted:

GPL 2 question - if someone is distributing a compiled program that was built from GPLed code as part of a larger software suite and promises that they have not modified the source of the compiled program at all, are they required to provide a copy of the exact source used to compile that GPL-licensed program? To clarify, the GPLed code is compiled into a regular command line utility that their (closed) GUI code runs as a separate process, so nothing is linked against the GPLed code.

They are required to disclose exactly the source code which results in the object code they are distributing.

They are not required to disclose source code which may live in the same place but isn't used to build the GPL'd object code.

They may or may not be required to disclose their build system; almost certainly it is acceptable for them not to if they can provide an equivalent build system that just builds the GPL'd object code, but if the build system plays a significant part in the construction of the GPL'd object and cannot be replaced, it may count as "source" (this matter has been disputed several times, and will probably need to be settled in a court at some point).

They are not required to disclose internal documentation or data files, unless such files are actually integrated into the GPL'd object code.

If they have not changed the source code to the GPL'd object code, they can provide the source by simply providing access to publically-available copies of the source. If those copies become unavailable, the company must find some other way to make the source code available.

shrughes
Oct 11, 2008

(call/cc call/cc)

Munkeymon posted:

GPL 2 question - if someone is distributing a compiled program that was built from GPLed code as part of a larger software suite and promises that they have not modified the source of the compiled program at all, are they required to provide a copy of the exact source used to compile that GPL-licensed program? To clarify, the GPLed code is compiled into a regular command line utility that their (closed) GUI code runs as a separate process, so nothing is linked against the GPLed code.

Read section 3 of the GPL v2.

IShallRiseAgain
Sep 12, 2008

Well ain't that precious?

So I'm trying to figure out how to make a lex/yacc parser capable of handling variables of multiple types. Anyone know any good tutorials for doing that?

newsomnuke
Feb 25, 2007

What's the syntax you're trying to parse?

Flamadiddle
May 9, 2004

I've been tasked with writing an extended stored procedure for SQL Server to run up against a telnet server. I've got something working using synchronous ports in C#, but would rather use asynchronous ports. Can I do this without setting up server-side code to handle the requests? I can't even get my BeginConnect async method to spit out command line stuff to let me know it's been called at the moment.

magic_toaster
Dec 26, 2003
No.
Why would you ever use | or & in an equality check rather than || or &&?

At work today we had our monthly programmer meeting, and it was brought up as a "tip/trick" to use && and ||. Not quite a tip or a trick in my opinion, since I've never known any to NOT to use these, but we started to wonder why you would ever use it.

And now we're really curious. Searching it only seems to bring up articles about why you should use || or &&, but that's not what we're after!

Scaevolus
Apr 16, 2007

magic_toaster posted:

Why would you ever use | or & in an equality check rather than || or &&?

At work today we had our monthly programmer meeting, and it was brought up as a "tip/trick" to use && and ||. Not quite a tip or a trick in my opinion, since I've never known any to NOT to use these, but we started to wonder why you would ever use it.

And now we're really curious. Searching it only seems to bring up articles about why you should use || or &&, but that's not what we're after!
You might use & to test a bitmask, e.g.:
code:
#define FLAG (1<<2)

int value = 5;

if (value & FLAG) { ... }
...but that's not really an equality check.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
In most languages with short-circuiting the bitwise operators don't short circuit, so that could occasionally be desirable. I can't think of an instance where that would make code clearer, though.

Adbot
ADBOT LOVES YOU

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Internet Janitor posted:

In most languages with short-circuiting the bitwise operators don't short circuit, so that could occasionally be desirable. I can't think of an instance where that would make code clearer, though.
"Most" is a bit of an understatement. A short-circuiting bitwise operator would be like short-circuiting multiplication.

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