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
TSDK
Nov 24, 2003

I got a wooden uploading this one

CeciPipePasPipe posted:

Oh ok, wouldn't it be easier to just do "int breakme=1/0;" or something then?
No, because div by zero exceptions aren't necessarily enabled or available.

Adbot
ADBOT LOVES YOU

Entheogen
Aug 30, 2004

by Fragmaster
why couldn't one do this
code:
#define DEBUG_BREAK exit(1)
then the program will exit where ever you use DEBUG_BREAK, and when you don't want it to exit on that just change the #define.

I don't remember the code for error on exit, but i think 1 is it.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Entheogen posted:

why couldn't one do this
code:
#define DEBUG_BREAK exit(1)
Because we're talking about coding horrors, not trying to create more of them?

StickGuy
Dec 9, 2000

We are on an expedicion. Find the moon is our mission.

TSDK posted:

Because we're talking about coding horrors, not trying to create more of them?
code:
#define DEBUG_BREAK char foo[10000000000]; fclose(fopen(new char [10000000000])); exit(1);

Cazlab
Oct 25, 2003

Rottbott posted:

You certainly can in Visual C and Visual C#, I do it every day.

And on braces.

I too am confused by this confusion.

standard
Jan 1, 2005
magic
We found this in a large J2EE app today. (after it came back from vietnam).

During some PDF generation:

code:
...

} catch (Exception e) {
      System.exit(-1);
}

Entheogen
Aug 30, 2004

by Fragmaster
what is so horrible on exiting when exception occurs? For some exceptions it makes sense, and you can print out what the message was before you exit anyways.

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.

Entheogen posted:

what is so horrible on exiting when exception occurs? For some exceptions it makes sense, and you can print out what the message was before you exit anyways.
Because that example doesn't do anything with the exception(s) and manages to give less information than if the exception(s) had just been left uncaught.

CeciPipePasPipe
Aug 18, 2004
This pipe not pipe!!

Entheogen posted:

what is so horrible on exiting when exception occurs? For some exceptions it makes sense, and you can print out what the message was before you exit anyways.

It will shut down the entire web server/app server, which is probably not what you want to happen if a single PDF report gets screwed up.

standard
Jan 1, 2005
magic

CeciPipePasPipe posted:

It will shut down the entire web server/app server, which is probably not what you want to happen if a single PDF report gets screwed up.

This is what happened.
We only found the code after the app server mysteriously went AWOL

AzraelNewtype
Nov 9, 2004

「ブレストバーン!!」

CeciPipePasPipe posted:

It will shut down the entire web server/app server, which is probably not what you want to happen if a single PDF report gets screwed up.

I think he was talking about his own example, not the java one. It's astonishing how many people don't know exit() will take down the parent app, not just kill the current child process. You'd think with the number of people making this mistake they'd come across it firsthand at some point and realize.

JediGandalf
Sep 3, 2004

I have just the top prospect YOU are looking for. Whaddya say, boss? What will it take for ME to get YOU to give up your outfielders?
Why put it on the brace when you can put it on the catch statement itself?

Click here for the full 915x888 image.


(untested on earlier versions of VS. This is VS2008)

Heffer
May 1, 2003




What functionality does this 6500 line code project comprised of over one hundred files provide you?

It gets you web page. A single web page with a data grid that lists rows from a table in a database, and lets you approve them.

I really really don't know what happened here, other than a Java app programmer decided to learn Visual Studio, C#, ASP.NET, CSS, Model-View-Control design, Test Driven Development, and umm some sort of -on Rails based naming methodology, all at the same time.

Best part is it didn't work when it was handed off to me. Faced with understanding and debugging the code, I opted to rewrite it.

StickGuy
Dec 9, 2000

We are on an expedicion. Find the moon is our mission.
100 files, 6500 lines. It seems like the author subscribed to the OO philosphy from that blog posted earlier in the thread.

zootm
Aug 8, 2006

We used to be better friends.

JediGandalf posted:

Why put it on the brace when you can put it on the catch statement itself?

Click here for the full 915x888 image.


(untested on earlier versions of VS. This is VS2008)
I'm not certain this worked in the version of VS we were using at the time (2003) but really the problem was the existence of the catch statement at all; the code was only supposed to have a finally block.

uksheep
Jul 23, 2007

do andriods dream of electric sheep

Heffer posted:

ungodly project


I love how you have titled it OhGod

Sebastian Flyte
Jun 27, 2003

Golly
Well, it is best to be *really* sure that absolutely nothing goes wrong when deleting stuff from the database:

code:

public void DeleteRecipient(int recipientId)
{
  SqlTransaction transaction = db.StartTransaction();

  try
  {
    string sql = @"DELETE FROM NewsletterRecipient
                   WHERE recipientId = @id";

    SqlCommand cmd = db.buildCommand(sql);
    cmd.Parameters.Add("@id", recipientId);

    db.Open();
    cmd.ExecuteNonQuery();
  }
  catch (Exception)
  {
    transaction.Rollback();
    throw;
  }

  transaction.Commit();
}

Lurchington
Jan 2, 2003

Forums Dragoon
I've been trying to improve my coding, and so I've started a little python project that attempts to parse a filename, then use the information I parsed to find applicable information on websites.

I had a lot of the trappings of "professional" programs:

  • fairly robust and explanatory command line options (thanks to python's optparse module)
  • embraced an extensible OOP approach, highlighting my subject matter expertise
  • allowed a deep level user configuration via configuration files (thanks to python's ConfigParser module)

It's the last one I concentrate on in this example. ConfigParser will basically allow you to get a value as a string, given where to look for it. I decided regular old strings weren't enough and I coded a brilliant way to allow a user to specify regular expression flags in a config file.

Observe:
code:
lineFindAllRegexFlag:re.DOTALL+re.IGNORECASE+re.MULTILINE

        for section in _sourceConfig.sections():
            _sectionDict = {}
            for option in _sourceConfig.options(section):
                if re.search("[i]flag$[/i]",option,re.IGNORECASE):
[b]                    _regexFlag=0
                    flags=_sourceConfig.get(section,option)
                    if re.search(r"re\.I",flags,re.I):
                        _regexFlag=_regexFlag+re.IGNORECASE
                    if re.search(r"re\.M",flags,re.I):
                        _regexFlag=_regexFlag+re.MULTILINE
                    if re.search(r"re\.D",flags,re.I):
                        _regexFlag=_regexFlag+re.DOTALL
                    _sectionDict[option]=_regexFlag[/b]
yeah, so I was basically trying to parse a string that contained python code, and then evaluate that python code using my personal favorite textual hack "split()".

I have since discovered python's builtin function: eval()
that parses a string that contains python code, and then evaluates that python code.


Special bonus, later on in that code: trying to turn a configuration option that is of the form:

original_text=text_swap_in[,original_text=text_swap_in]

into a dictionary.

code:
[b]                elif re.search("[i]swapterms$[/i]",option,re.IGNORECASE) and len(_sourceConfig.get(section,option)):
                    _swapDict={}
                    for _swapTerm in _sourceConfig.get(section,option).split(","):
                        _swapDict[_swapTerm.split("=")[0]]=_swapTerm.split("=")[1]
                    _sectionDict[option]=_swapDict
                else:
                    _sectionDict[option]=_sourceConfig.get(section,option)
                    
            _sourceDict[section.lower()]=_sectionDict
[/b]

Vanadium
Jan 8, 2005

I do not want to mock the dude because he obviously did not know better and his compiler did not give sufficient warnings, but trying to free a bunch of dynamically allocated objects with

delete foo, bar, baz;

is pretty depressing. :(

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.
Good Christ, you took the time to define a bunch of enums and you use them all in switches internally, stop using "long" as the parameter type in all your interfaces! Why do you hate type checking so much?

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Sebastian Flyte posted:

Well, it is best to be *really* sure that absolutely nothing goes wrong when deleting stuff from the database:

code:

public void DeleteRecipient(int recipientId)
{
  SqlTransaction transaction = db.StartTransaction();

  try
  {
    string sql = @"DELETE FROM NewsletterRecipient
                   WHERE recipientId = @id";

    SqlCommand cmd = db.buildCommand(sql);
    cmd.Parameters.Add("@id", recipientId);

    db.Open();
    cmd.ExecuteNonQuery();
  }
  catch (Exception)
  {
    transaction.Rollback();
    throw;
  }

  transaction.Commit();
}

What's wrong with this? The only weird thing I can see is that db.Open is called after creating the transaction, but that doesn't have anything to do with your comment so I assume that's just the way the API works.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

LurchDawg posted:

yeah, so I was basically trying to parse a string that contained python code, and then evaluate that python code using my personal favorite textual hack "split()".

I have since discovered python's builtin function: eval()
that parses a string that contains python code, and then evaluates that python code.

Your way is better - you don't want people to be able to put 'os.system("rm -rf /")' in your config file and have it blindly executed.

EDIT: I swear when I hit Quote there I had big plans of copying the quoted text and editting it into my last post to avoid triple-posting, but somehow I just forgot. Oh well.

JoeNotCharles fucked around with this message at 15:44 on Jul 10, 2008

Smackbilly
Jan 3, 2001
What kind of a name is Pizza Organ! anyway?

JoeNotCharles posted:

Your way is better - you don't want people to be able to put 'os.system("rm -rf /")' in your config file and have it blindly executed.

Eh? As long as it's not running suid or something, there's nothing a user can put in his config file that he couldn't just type into the commandline. It's not a program's job to stop a user from doing something stupid when they go out of their way to do it.

Volte
Oct 4, 2004

woosh woosh

JoeNotCharles posted:

What's wrong with this? The only weird thing I can see is that db.Open is called after creating the transaction, but that doesn't have anything to do with your comment so I assume that's just the way the API works.
I think it's because there is only one command being executed in that transaction. In other words, it's not really doing anything.

chocojosh
Jun 9, 2007

D00D.

JoeNotCharles posted:

What's wrong with this? The only weird thing I can see is that db.Open is called after creating the transaction, but that doesn't have anything to do with your comment so I assume that's just the way the API works.

I imagine the catch all Exception instead of an SqlException?

To be honest though I use catch-all exceptions due to lazyness. I don't really care *why* I can't delete from the DB.. just that it failed.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Smackbilly posted:

Eh? As long as it's not running suid or something, there's nothing a user can put in his config file that he couldn't just type into the commandline. It's not a program's job to stop a user from doing something stupid when they go out of their way to do it.

What if somebody wants to install it with a web server frontend? Or some malicious person sends a complex config file saying, "Here, this'll do exactly what you're looking for!" when it actually has some bad commands embedded in it? Blindly executing anything handed to you is a terrible habit to get into.

chocojosh posted:

I imagine the catch all Exception instead of an SqlException?

To be honest though I use catch-all exceptions due to lazyness. I don't really care *why* I can't delete from the DB.. just that it failed.

Well, exactly - it's rethrowing, so this is exactly what should be done. Otherwise if it can't delete for some reason you haven't considered (any class other than SqlException) your data gets inconsistent.

I guess the fact that there's only one statement makes the transaction kind of pointless, but it's still good defensive programming - you wouldn't want somebody to come along and add a second statement (say, updating a log table after every delete) without locking.

JoeNotCharles fucked around with this message at 17:16 on Jul 10, 2008

hey mom its 420
May 12, 2007

Yeah, that's true. I don't know C# but what's the type of the exception being propagated upwards in that code? Because in Java, for instance, if you just blanket catch exceptions and then just do throw new Exception(), you're losing the info about what kind of exception it was, but if you do something like:
code:
  catch (Exception e)
  {
    transaction.Rollback();
    throw e;
  }
then any exception will be caught but the type of the exception propagated upwards will stay in tact. At least I think so, my Java is pretty rusty.

hey mom its 420
May 12, 2007

edit: doubelpost

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Bonus posted:

Yeah, that's true. I don't know C# but what's the type of the exception being propagated upwards in that code?

I believe "throw" with no parameters means to re-throw the current exception.

Victor
Jun 18, 2004

Bonus posted:

code:
  catch (Exception e)
  {
    transaction.Rollback();
    throw e;
  }
then any exception will be caught but the type of the exception propagated upwards will stay in tact. At least I think so, my Java is pretty rusty.
The above is horrible, as you lose the stack trace. Either throw;, or throw new DeleteFailedException(e); so that the stack trace is maintained via InnerException.

hey mom its 420
May 12, 2007

Aha, I see, cool.
Yeah, like I said, I don't really know C#, I just wanted to know if that piece of code kept the information about the exception.

Smackbilly
Jan 3, 2001
What kind of a name is Pizza Organ! anyway?

JoeNotCharles posted:

What if somebody wants to install it with a web server frontend? Or some malicious person sends a complex config file saying, "Here, this'll do exactly what you're looking for!" when it actually has some bad commands embedded in it? Blindly executing anything handed to you is a terrible habit to get into.

If you're allowing untrusted web users (or untrusted ANYONE) to make arbitrary changes to the configuration file for one of your apps, you're pretty hosed regardless.

I could send someone a .emacs config file that wipes their hard drive (or at least their home directory), but that's not considered to be security problem with emacs.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.
I also can't figure out why this Qt code keeps using "dialog->setModal(true); dialog->show();" and then connecting the Ok and Cancel buttons to slots in the main window, instead of just using "dialog->exec();" and checking the return code.

grapesmoker
Apr 19, 2003

This moon-cheese will make me very rich... very rich indeed!
I'm not a regular poster in this subforum, but I've been reading this thread for a while, and I thought that the current clusterfuck of a program I'm dealing with would amuse people.

I'm not a professional programmer, I'm a graduate student in physics. However, for my project, I do a lot of coding, since I'm reasonably competent at it. I'm currently working on an astrophysics project in which my part involves the construction of a star tracker. A star tracker is basically a CCD camera controlled by an embedded system that takes images of the sky and cross-references a catalog to find where the telescope is pointing (it's a little more complicated than that, but that's the important bit). Anyway, my PI was on a project with some guy who had written just such a program for controlling a star tracker, and when it came time for me to build one, he suggested that I recycle the code from the old program since that code had been tested and shown to work. I took a day to look at the code and came back to him arguing for a complete rewrite of the program, but he basically put me off and I got stuck maintaining code written by some dude from a previous project.

The problems with this piece of software were legion. Keep in mind that there are probably over 6000 lines of C/C++ code in this thing, which may not be all that much for a serious project, but it's still a lot to go through. Strap yourselves in; this thing contained the following features:

  • It was written in a barely-readable mixture of C and C++. The mixture by itself doesn't strike me as being that bad, but if half your program is already in C++, why not go the whole way and write the entire thing in C++? And if you're going to write in C, must your printf statements be totally opaque and your variables named things like "ma" and "ce"?
  • For some reason, this program was seriously multithreaded. I can understand perhaps splitting the network functionality into a different thread, but he made the exposure process its own thread as well. The camera gets its own external trigger that is independent of the software, so all you actually have to do is to poll the state and read it out; no need for it to have its own thread. What's more, most of the threads don't actually need to run concurrently with the main thread. They were apparently implemented so that virtually any process could be killed externally by the main thread, a rationale I'm still struggling to understand.
  • As a consequence of the above point, virtually every variable of any import is global. This would be understandable for semaphores, but we're talking about everything from the current status of the camera to the data buffers themselves. Also every function is declared
    code:
    void function()
    . That's right, about half the functions in this program don't take arguments or return values. Why bother when everything is global anyway?!
  • The threading isn't even done properly. There are some semaphores that basically signal things like network events or camera exposures, but absolutely no concurrency checking is done; this means that it's possible (unlikely, but possible) for the camera parameters to change mid-exposure. There are no mutexes or anything that would make sense to have in a threaded program.
  • There are several classes implemented in this software that are essentially reinventions of the wheel. For example, when analyzing an image, you want to know how many stars (blobs) there are in it, and you want to store them and their coordinates. Logic would dictate (to me; correct me if I'm wrong) that one would create a class called Blob and make a vector<Blob> variable. You could even get away with a struct, since blobs are just coordinate pairs that don't need methods. What logic would not dictate would be to reinvent the concept of the doubly-linked list. That's right, he just coded a linked-list class, complete with all the usual operations (insert, delete, etc.) so he could store blobs. But this isn't even the best thing.
  • The best thing about this program is that it's linked against Qt. Now, you might ask yourselves, why would a program that is essentially autonomous and has no graphical interface to speak of need to be linked against Qt? What possible features could Qt provide for this project? Whatever they are, you would think they're worth it; after all, building Qt for Microsoft Visual Studio is a huge pain in the rear end and it takes up a ton of space. Well, I'm going to put in a few lines to let you ponder what function Qt serves in this project.





    Have you figured it out yet?




    The answer is lists! :psyduck:


    That's right, dude linked against Qt so he could use a generic structure which is already present in standard C++. I nearly poo poo a brick when I figured out what Qt was for; I mean, you don't have to be a C++ wizard to use the STL, you just have to be aware of its existence. Now his reinvention of doubly-linked lists makes perfect sense to me; he probably wasn't even aware such a function already existed. Nevertheless, he did take the time to figure out how to do graphics programming with the Windows API (to display the camera images on the screen), which is the one area where I would (and eventually did) bring in an outside library just for programming simplicity.
  • To add insult to injury (and this is a highly specialized point, but one that is immediately obvious to people in astronomy), instead of saving all the images in FITS format (which is the most popular format for saving astronomical data) he wrote his own wrapper class for libtiff. Also, large chunks of the code and the structure of the program are highly specific to the hardware they were using at the time and could not be easily changed.

That's what I've been working with nearly every day now for over a year. It's a loving nightmare and I routinely wish for death while debugging this code. I can't scrap it and start over because my PI won't let me, and I've gotten it to more or less a state of functionality, but it's been an uphill struggle all the way. A couple of times I phoned the guy who had written it with questions, and he sounded very apologetic over the phone, so I don't really hold it against him too much.

Hopefully my tale of woe is amusing. At the very least, it should serve as a cautionary tale against having scientists develop software.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Motherfucking this.

code:
        for timestamp, count in raw_data:
            timestamp = list(time.strptime(timestamp,'%m-%d-%Y %H:%M'))
            timestamp[-1] = time.daylight
            timestamp = tuple(timestamp)
            timestamp = int(time.mktime(timestamp))
I spent 3 hours this morning trying to figure out what the gently caress was going on with my code before I finally figured out that time.strptime() conveniently forgets about DST during conversion. The end result is this retarded clusterfuck where I cast the time tuple to a list and proceed to shoot myself in the head. gently caress you time.strptime(). That should have been one line of code.

atomic johnson
Dec 7, 2000

peeping-tom techie with x-ray eyes
Found this in the code for an NT service that's actually part of a commercial software package:

code:
	HRESULT InitializeSecurity() throw()
	{
		// TODO : Call CoInitializeSecurity and provide the appropriate security settings for 
		// your service
		// Suggested - PKT Level Authentication, 
		// Impersonation Level of RPC_C_IMP_LEVEL_IDENTIFY 
		// and an appropiate Non NULL Security Descriptor.

		CoInitializeSecurity(
		  NULL,	    // what the gently caress is a security descriptor anyways
		  -1,
		  NULL,
		  NULL,
		  RPC_C_AUTHN_LEVEL_PKT,
		  RPC_C_IMP_LEVEL_IDENTIFY,
		  NULL,
		  0,
		  NULL
		);

		return S_OK;
	}
So... yeah, let's ignore the autogenerated text saying to use a non-NULL security descriptor, and then just throw away the return from CoInitializeSecurity and say everything's S_OK.

Sebastian Flyte
Jun 27, 2003

Golly

Volte posted:

I think it's because there is only one command being executed in that transaction. In other words, it's not really doing anything.

Exactly. Doing a transaction with a single SQL command deleting one single row is pretty pointless.

zootm
Aug 8, 2006

We used to be better friends.

Sebastian Flyte posted:

Exactly. Doing a transaction with a single SQL command deleting one single row is pretty pointless.
There is occasionally value in doing the "right thing" in order that correctness is preserved if you add one more line, though.

BattleMaster
Aug 14, 2000

ryanmfw posted:

I've seen some elegant solutions at programming competitions:

code:
for(int i=1; i<1000; i++)
if(i==1){ printf("One");}
if(i==2){ printf("Two");}
if(i==3){ printf("Three");}
....
if(i==999){ printf("Nine Hundred And Ninety Nine");}
}
Took a team the entire length of the competition to write (6 hours), and it didn't even pass.

God drat, I wrote something in Python that was under 200 lines that could do the same thing, except it went from 0 to 999,999. And it sure as hell didn't take me 6 hours!

Adbot
ADBOT LOVES YOU

sarehu
Apr 20, 2007

(call/cc call/cc)

BattleMaster posted:

God drat, I wrote something in Python that was under 200 lines that could do the same thing, except it went from 0 to 999,999. And it sure as hell didn't take me 6 hours!

I wrote one in XSLT :(

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