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

Cross_ posted:

Ignoring the fact that this betrays bad design- you have to change the type declaration anyway what's the problem with doing search&replace at the same time?
It fucks over your source control change logs, and is a very blunt weapon considering that not all matching strings in the source code are necessarily matching variables.

Hungarian notation is an old technique that has no place in modern C++ programming, but there are one or two odd exceptions which are either genuinely useful, or are a strange hang-over.

The scope of variables is of critical importance in C++, and in OO programming in general. As such, you often see 'g_', 's_' and 'm_' prefixes used widely - or similar conventions for distinguishing member variables.

The 'p_' prefix is more of a comfort thing. There's not necessarily any reason why it should be used, but it's a fairly firmly entrenched an widely used habit. It generally doesn't cause as many problems as other types of type prefix though. One of the main arguments against Hungarian is that if you change the type, then you have to hunt out and change everywhere the variable is used for no good reason. Whereas if you change a variable to or from a pointer type, then you will generally have to change all of the places where it's being used anyway, so the negative impact of this particular prefix is relatively light.

I've not seen 'r' being used all that often, and I suspect it's a dirty Java habit ;)

Adbot
ADBOT LOVES YOU

Hubis
May 18, 2003

Boy, I wish we had one of those doomsday machines...

Vanadium posted:

So would you prefix a smart pointer object variable with p?

I'd prefix it with sp, which is actually quite useful because if you're using a smart pointer implementation that makes them fairly transparent related to regular pointers, it can be quite useful to track which is which.

e: and unlike most other cases of hungarian notation in C, is not made obsolete by strong typing.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Cross_ posted:

Ignoring the fact that this betrays bad design- you have to change the type declaration anyway what's the problem with doing search&replace at the same time?

Yeah, I've never seen badly designed software that uses Hungarian notation.

People make bad software, and Hungarian notation makes it worse when they do. Persuading people to drop it is step one because it's much easier than teaching good design.

floWenoL
Oct 23, 2002

JoeNotCharles posted:

The difference between an unsigned integer and a signed integer is often accidental - if you just automatically make an int, but you know it'll never get a value less than 0, you might want to change it to an unsigned int later to get more range.

No you don't.

Scaevolus
Apr 16, 2007

JoeNotCharles posted:

if you just automatically make an int, but you know it'll never get a value less than 0, you might want to change it to an unsigned int later to get more range.

never is a strong word

TSDK
Nov 24, 2003

I got a wooden uploading this one
My favourite coding horror side effect of Hungarian notation is little gems like this scattered around here and there:
code:
float uiItemSize = pItem->GetSize();
...

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

floWenoL posted:

No you don't.

That makes no grammatical sense. There's no clause in what I said that can be negated with "don't", because they're all qualified.

HAH! NOW I AM PEDANT!

Hubis
May 18, 2003

Boy, I wish we had one of those doomsday machines...

JoeNotCharles posted:

That makes no grammatical sense. There's no clause in what I said that can be negated with "don't", because they're all qualified.

HAH! NOW I AM PEDANT!

is not

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?

TSDK posted:

My favourite coding horror side effect of Hungarian notation is little gems like this scattered around here and there:
code:
float uiItemSize = pItem->GetSize();
...
Probably not exactly hungarian notation but it's along the same lines. I present you our old table and column naming scheme.
code:
select
	c.brand, c.caffeineContent
from
	tblCoffee c with(nolock)
join
	tblCoffeeType ct with(nolock)
	on c.fkCoffeeTypeId = ct.pkCoffeeTypeId
where
	ct.pkCoffeeTypeId = 5 --Decaf
My current lead engineer hates this style. I agree with him. For foreign keys I think [TableName]ID is good enough.

Edit: Missing code tag.

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

JediGandalf posted:

Probably not exactly hungarian notation but it's along the same lines. I present you our old table and column naming scheme.
code:
select
	c.brand, c.caffeineContent
from
	tblCoffee c with(nolock)
join
	tblCoffeeType ct with(nolock)
	on c.fkCoffeeTypeId = ct.pkCoffeeTypeId
where
	ct.pkCoffeeTypeId = 5 --Decaf
My current lead engineer hates this style. I agree with him. For foreign keys I think [TableName]ID is good enough.

Edit: Missing code tag.
I agree as well. Our tables here are all prefixed with random acronyms of the table names and an optional underscore. It's as awesome as you might suspect.

Steampunk Mario
Aug 12, 2004

DIAGNOSIS ACQUIRED

TSDK posted:

Hungarian notation is an old technique that has no place in modern C++ programming, but there are one or two odd exceptions which are either genuinely useful, or are a strange hang-over.

Well, not really. It was originally intended to give context to the variable's usage, not type. So you might prefix something with 'idx' or some such to indicate that it's an index, but you wouldn't put the type in the variable name since that's just stupid.

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Steampunk Mario posted:

So you might prefix something with 'idx' or some such to indicate that it's an index

The only reason that isn't type information is because languages like C don't have strong typing on typedefs. Being able to do typedef unsigned int index_t; typedef unsigned int age_t; and have the compiler warn when you use an index_t where it expects an age_t would completely remove even that flimsy justification for Hungarian notation, as you would encode all of your "usage context" in the type system where it belongs.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

ShoulderDaemon posted:

The only reason that isn't type information is because languages like C don't have strong typing on typedefs. Being able to do typedef unsigned int index_t; typedef unsigned int age_t; and have the compiler warn when you use an index_t where it expects an age_t would completely remove even that flimsy justification for Hungarian notation, as you would encode all of your "usage context" in the type system where it belongs.

You can do this in C++, but it's an enormous pain in the rear end because you have to hand-code every operation you want to provide, even those which seem to be logically derivable from others. Haskell makes that substantially easier, but converting between types is still a pain in the rear end.

But yes, a shop that demands Hungarian notation would generally be better off demanding the consistent use of type-safe wrapping types.

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

rjmccall posted:

Haskell makes that substantially easier, but converting between types is still a pain in the rear end.

I've never found converting between types in Haskell to be very painful - I just pattern match to get at the contained type I care about, or make my newtypes instances of the typeclasses I care about.

But we're getting off-topic here. To contribute, I'm dealing with code generated by automated proof systems that is sort of painful. Here's a short example, the extracted definition of sum over a list of natural numbers:
code:
sum :: (List Nat) -> Nat
sum l = foldr plus 0 l
Reasonable so far, it's folding addition over the list to make a sum. Let's see how foldr is written...
code:
foldr :: (a1 -> a2 -> a2) -> a2 -> (List a1) -> a2
foldr f a0 l = list_rec a0 (\a l0 iHl -> f a iHl) l
Okay... there's some sort of list recursion primitive or something, and it's passing in the base-case value and what appears to be an inductive rule that takes three parameters and applies the folding function to two of them...
code:
list_rec :: a2 -> (a1 -> (List a1) -> a2 -> a2) -> (List a1) -> a2
list_rec f f0 l = list_rect f f0 l

list_rect :: a2 -> (a1 -> (List a1) -> a2 -> a2) -> (List a1) -> a2
list_rect f f0 l = case l of
  Nil -> f
  Cons a l0 -> f0 a l0 (list_rect f f0 l0)
Two functions later, we finally discover the actual recursive step. Apparently those mystrey parameters earlier are the current element in the list, the remainder of the list, and the accumulated value we've created so far working through the list. Also, for some reason there's a function stuck in the middle here that does absolutely nothing.

I'm sure all these layers of indirection represent something useful within the context of the proof-checker, but when the code it's spitting out is so far removed from what any human would write even on simple examples like this, it's very hard to correctly use extracted code on complicated models, where it would be most useful.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

ShoulderDaemon posted:

I've never found converting between types in Haskell to be very painful - I just pattern match to get at the contained type I care about, or make my newtypes instances of the typeclasses I care about.

It's certainly much better than C++, but you and I seem to have different attitudes about obnoxiousness --- I think having to introduce little function calls everywhere is annoying. I fully understand why I have to do it, I just think it's annoying.

ShoulderDaemon posted:

I'm sure all these layers of indirection represent something useful within the context of the proof-checker, but when the code it's spitting out is so far removed from what any human would write even on simple examples like this, it's very hard to correctly use extracted code on complicated models, where it would be most useful.

If you're curious, list_rect is the axiom of structural induction for lists, derived from the structure of the type declaration. list_rec is probably there to catch some corner case in the code generation which doesn't happen to arise with this type --- possibly something with higher-rank polymorphism.

Also, while I agree that the code is far from what a human would write, I don't understand why it's any more difficult to use: the sum function, which is what you actually extracted, is called in exactly the usual manner.

Hubis
May 18, 2003

Boy, I wish we had one of those doomsday machines...

rjmccall posted:

You can do this in C++, but it's an enormous pain in the rear end because you have to hand-code every operation you want to provide, even those which seem to be logically derivable from others. Haskell makes that substantially easier, but converting between types is still a pain in the rear end.

But yes, a shop that demands Hungarian notation would generally be better off demanding the consistent use of type-safe wrapping types.

Shouldn't there really be an easy way to do this? Like

code:
template <class T> StrongType
{
    // Define all your basic ops
};

#define STRONG_TYPEDEF(base, name) \
    class name : StrongTypedef<base> {};

gold brick
Jun 19, 2001

no he isn't

Steampunk Mario posted:

Well, not really. It was originally intended to give context to the variable's usage, not type. So you might prefix something with 'idx' or some such to indicate that it's an index, but you wouldn't put the type in the variable name since that's just stupid.
I found this a few years back.
code:
private int foo()
{
   int intReturn;

   // 2-3 lines of code I forget

   return intReturn
}

Evis
Feb 28, 2007
Flying Spaghetti Monster

Mick posted:

I found this a few years back.
<snip>

Treat warnings as errors is the best thing ever.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Evis posted:

Treat warnings as errors is the best thing ever.

Speaking of which, I'm cleaning up warnings right now:

code:
int open(const char *filename,int oflag, ...)
{
	char mode[3]; /* mode[0] ="w/r/a"  mode[1]="+" */
	mode[2]=0;
	if ( oflag==(O_WRONLY|O_CREAT) )
		mode[0]="w";
	else if (oflag==O_RDONLY)
		mode[0]="r";
	return fopen(filename, mode);
This code gives three instances of "warning C4047: 'X': 'Y' differs in levels of indirection from 'Z'", with (X,Y,Z) in {(=, char, char[2]), (return, int, FILE *)}

How do you get int confused with FILE * and not notice?

EDIT: I was so annoyed that this idiot used "fopen" instead of "open" that I posted immediately. I just realized what this code actually <i>does</i>. Christ, that's even worse!

JoeNotCharles fucked around with this message at 01:59 on Oct 7, 2008

Vanadium
Jan 8, 2005

JoeNotCharles posted:

How do you get int confused with FILE * and not notice?

Well, if he is calling it like FILE* f = open("foo", O_RDONLY); and not getting a warning for that conversion either, the whole thing might just work!

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Vanadium posted:

Well, if he is calling it like FILE* f = open("foo", O_RDONLY); and not getting a warning for that conversion either, the whole thing might just work!

Actually, what it's doing is implementing open(), read() and write() on Windows CE (which lacks them, I guess?) in terms of fopen(), fread() and fwrite().

code:
int fd = open("foo", O_WRONLY);
write(fd, buf, bufsize);
That happens to work because ints and pointers are the same size, and the implementation of write() casts fd right back to a FILE *.

narbsy
Jun 2, 2007

JoeNotCharles posted:


That happens to work because ints and pointers are the same size

Only on 32-bit machines...


e: Also true. My mistake.

narbsy fucked around with this message at 04:00 on Oct 7, 2008

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

narbsy posted:

Only on 32-bit machines...

I'm not aware of any 64-bit machines running Windows CE...

StickGuy
Dec 9, 2000

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

JoeNotCharles posted:

I'm not aware of any 64-bit machines running Windows CE...
Yeah, man, no one will be using this program in the year 2000.

Evis
Feb 28, 2007
Flying Spaghetti Monster

StickGuy posted:

Yeah, man, no one will be using this program in the year 2000.

#define int __int64 will solve all these problems

Roseo
Jun 1, 2000
Forum Veteran
I'm not a great programmer, but at least I know enough to not do this:

code:
$n++;
$odd_test = $n/2;
if (preg_match("/\.5/",$odd_test))
{
	$color = "bgcolor=\"#FFCC99\"";
}
else
{
	$color = "bgcolor=\"#FFFFFF\"";
}

Lexical Unit
Sep 16, 2003

I need to test if this number is odd. Think man, think! Hey isn't there something about odd numbers and dividing by two that I learned in kindergarten?

<A couple of hours later, after three of four pages of scratch work>

Oh hey, look at this, whenever I divide an odd number by 2 I get .5 on the end... regex to the rescue!

ashgromnies
Jun 19, 2004

Roseo posted:

I'm not a great programmer, but at least I know enough to not do this:

code:
$n++;
$odd_test = $n/2;
if (preg_match("/\.5/",$odd_test))
{
	$color = "bgcolor=\"#FFCC99\"";
}
else
{
	$color = "bgcolor=\"#FFFFFF\"";
}

code:
$color = 'bgcolor="#F' . ($n++ % 2 ? "C9" : "") . '"';
:c00l:

Who wants to go golfing? :)

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

ashgromnies posted:

code:
$color = 'bgcolor="#F' . ($n++ % 2 ? "C9" : "") . '"';
:c00l:

Who wants to go golfing? :)

Instead of doing a modulus, just keep making $n = !$n after the assignment.

Cross_
Aug 22, 2008
The int/FILE* conversion did not jump out at me and shouldn't be a problem with WinMobile at all. On the other hand I am wondering about all the possible values that an uninitialized mode[1] might contain.

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!

TRex EaterofCars posted:

Instead of doing a modulus, just keep making $n = !$n after the assignment.

gently caress not.

code:
$color = 'bgcolor="#F' . ($n ^= 'C9') . '"';

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

Cross_ posted:

The int/FILE* conversion did not jump out at me and shouldn't be a problem with WinMobile at all. On the other hand I am wondering about all the possible values that an uninitialized mode[1] might contain.

Hey, good catch - I'll make sure to fix that while I'm there.

Roseo
Jun 1, 2000
Forum Veteran

TRex EaterofCars posted:

Instead of doing a modulus, just keep making $n = !$n after the assignment.

Well, $n's also used to number the table, so it needs to stay as being incremented by 1 each time through the loop. I just set $color to equal 0xFF0000 + (0xCC99 * ($n % 2)), and stuck 'color="#<?php echo $color ?>"' into the HTML. It's not the cleanest code out there. But it's a drat sight better than regexing the loving thing to figure out if the line is odd or even.

Edit: Argh, that's not right.

0xFFFFFF - (0x3366 * ($n % 2) I think is what I did.

Roseo fucked around with this message at 05:42 on Oct 9, 2008

Intel Penguin
Sep 14, 2007
hooray
php:
<?
function returnshow (){ 
    global $_SESSION, $godlyness, $exequeries_1__,$return;
    $this->canshow = true;
    if (!$this->directory AND $this->root_dir){
        $this->directory($this->root_dir);
    }
    if (!is_dir($this->directory)){
        $this->canshow(false); 
        $this->error_message($this->message_nodir);
    }
    
    if ($this->mode == "gallery"){
        $this->lockfolder(false); 
        $this->radio_name("settings_avatarchange_copy_file");
        $this->hide_icons(true);
    } elseif ($this->mode == "attachments_show"){
        $this->lockfolder(true); $this->radio_name(false);
    } elseif ($this->mode == "attachments_edit"){
        $this->lockfolder(true); $this->radio_name(false);
    }

    if (!substr($this->directory,0,strlen($this->root_dir)) == $this->root_dir){
        $this->canshow(false); 
        $this->error_message("Out of root dir: ".$this->directory.", ".$this->root_dir);
    }
    
    if ($this->canshow == true){
        $scanned_files = scandir($this->directory);
    
        $return_code .= "<table border=\"0\" width=\"75%\">";
        $return_code .= "<tr><td></td><td colspan=\"3\">".(substr($this->directory,strlen($this->root_dir)))."</td></tr>";

        if ($this->lockfolder == false AND 
        strlen($this->directory) > strlen($this->root_dir) AND 
        substr($this->directory,0,strlen($this->root_dir)) == $this->root_dir){
            $return_code .= "<tr><td valign=\"middle\"><a href=\"forums.php?roomA=gallery&change_dir=".
            $dir."/..\">"."<img src=\"images/folder_up.gif\" align=\"middle\" border=\"0\" width=\"32\" ".
            "height=\"32\"></a></td><td colspan=\"3\"><a href=\"forums.php?roomA=gallery&change_dir=".
            $this->directory."/..\">Up a level"."</a></td></tr>";        
        }
        if (empty($this->ext_filter)){
            $this->ext_filter = ".*";
        }
        $fi = 0;
        
        foreach($scanned_files as $file){
            if (preg_match("/(".$this->ext_filter.")/i",substr($file,strlen($file)-4,4)) AND $file != "." AND $file != ".."){
                $fi++;
                $return_code_sub .= "<tr><td valign=\"middle\">";
                if ($this->mode == "attachment_view"){
                    $str_a = "<a href=\"".$this->directory."/".$file."\" target=\"_blank\">"; $str_b = "</a>";
                } else {
                    $str_a = ""; $str_b = "";
                }
                if (!$this->hide_icons) {
                    $return_code_sub .= $str_a.file_icon_image($file).$str_b;
                }
                $return_code_sub .= 
                "</td><td width=\"98%\">" . $str_a.$file.$str_b . "<br>" . format_filesize(filesize($this->directory . "/" . $file)) . ".</td>";
                if ($this->mode == "gallery"){
                    $return_code_sub .= "<td>".avatar_image($file,($this->directory."/"))."</td>";
                }
                $return_code_sub .= "\n";
                if ($this->radio_name AND !($this->select_name)){
                    $return_code_sub .= 
                    "<td><input name=\"settings_avatarchange_copy_file\" type=\"radio\" value=\"".
                    $this->directory."/".$file."\"></td><td>";
                }
                if ($this->select_name AND !($this->radio_name)){
                    $return_code_sub .= "<td><input type=\"checkbox\" name=\"".
                    substr($this->select_name,0,strlen($this->select_name))."\" value=\"$file\">";
                } // attached_file_do[]

            } elseif (is_dir($this->directory."/".$file) AND (substr($file,0,1) != ".")){
                $avatar_dir_output .= "<tr><td><a href=\"forums.php?roomA=gallery&change_dir=".
                $this->directory."/".$file."\">".
                "<img align=\"middle\" src=\"images/folder.gif\" border=\"0\" width=\"32\" height=\"32\">". 
                "</a></td><td><a href=\"forums.php?roomA=gallery&change_dir=".
                $this->directory."/".$file."\">".$file."</a></td></tr>\n";
            }
            
        } // end of foreach
        
        // Select all checkbox
        if ($this->select_name AND !($this->radio_name) AND $fi > 1){
            $return_code .= "<tr><td colspan=\"2\"></td><td>".
            "<input type=\"checkbox\" name=\"CheckAll\" value=\"Check All\" ".
            "onChange=\"UcheckAll(document.workform1['attached_file_do[]'],this.checked)\"></td></tr>";
        } 
        
        if ($this->mode == "gallery" AND (is_file($this->directory."/info.txt") OR is_file($this->directory."/credits.txt") )){
        $info = file_get_contents($this->directory."/info.txt");
        $return_code .= "<tr><td></td><td colspan=\"3\">Info: <font face=\"courier\">".$info."</font></td></tr>"; unset($info);}

        $return_code .= $avatar_dir_output.$return_code_sub;

        if ($this->mode == "attachment_edit"){
            if ($fi == 0){
                $return_code .= "<tr><td colspan=\"2\">There are currently no attached files.</td></tr>";
            }
            $return_code .= "<tr><td colspan=\"2\"><select name=\"attach_select\">";
            $return_code .= "<option value=\"nothing\">-- Select --</option>";
            if ($fi > 0) {
                $return_code .= "<option value=\"removeattach\">Remove</option>";
            }
            $return_code .= "<option value=\"removeallattach\">Remove All</option>";
            $return_code .= "</select></td><td align=\"right\"><input type=\"submit\" name=\"AttachFilesDo\" value=\"Do\"></td></tr>";
        }

        if ($this->mode == "gallery" AND !empty($return_code_sub)){
            $return_code .= "<tr><td colspan=\"2\" align=\"center\"><p>".
            "<input type=\"submit\" name=\"Set Avatar\" value=\"Set Avatar\"></td></tr>";
        }

        $return_code .= "</table>";
        return $return_code; unset($return_code);
    } else {
        $return_code .= $this->error_message;
        return $return_code; unset($return_code);
    }
}
?>
This is from a forum I made a while back in PHP. Back in the day before I knew what objects were for exactly. I monkey patched this generic file viewing/avatar selector. I'm still buggle hosed as to how it even still works.

UraniumAnchor
May 21, 2006

Not a walrus.
I was looking through some old code for a 'project' I was doing to try to teach myself OpenGL about six years ago, and I came across a few horrors:

code:
void cActor::AddActor(cActor *Head) {			
	// Until I figure out how to override constructors properly...
<init stuff snipped>
	if (!Head) {
		if (Header) {
			ERR("Warning: Attempt to initialize new actor head ignored.
			 (Actor will exist but won't be updated.)\n");
			Prev = Next = NULL;
		} else {
			Prev = this;
			Next = this;
			_Head = this;
			Header = true;
		}
	} else {
		Prev = Next = NULL;
		Prev = Head->GetPrev();
		Next = Head;
		Prev->SetNext(this);
		Head->SetPrev(this);
		_Head = Head;
	}
}
Static class variable? What's that? :v:

I think I knew they existed but couldn't figure out how to make it work. Whoops. I can't even figure out what the hell the top comment was supposed to mean.

Also this absolute horror that was the cActor:: Draw() function.

code:
void cActor:: Draw(bool Blend)
{
	Translate(Position.x, Position.y, Position.z);

	Scale(vScale.x, vScale.y, vScale.z);

	switch(RotOrder) {
		case(ROT_ORDER_XYZ) : {
			RotateX(Rotation.x);
			RotateY(Rotation.y);
			RotateZ(Rotation.z);
			break;
		}
<repeat five more times for the other permutations>
	}

	if (NumPieces) {
		Pieces[0]->Draw(Blend);
	}

	switch(RotOrder) {
		case(ROT_ORDER_XYZ) : {
			RotateZ(-Rotation.z);
			RotateY(-Rotation.y);
			RotateX(-Rotation.x);
			break;
		}
<oh god why again>
	}

	Scale(rScale.x, rScale.y, rScale.z);

	Translate(-Position.x, -Position.y, -Position.z);
}
rScale being 'reciprocal scale'... apparently I hadn't yet realized you could store save and restore the working matrix.

I don't even know what the gently caress I was doing with 'ROT_ORDER'. Must have seemed like a good idea at the time, though. :sigh:

I stopped working on this about the time I couldn't figure out how to make the 'car' tilt with the ground properly. ODE, what's that? :v:

And poo poo like this was littered through the 'code'.

code:
void cVehicle::Build()
{	
	Uint32 Loop;
	WheelTex[0] = LoadGLTexture("newwheel.tga");
	WheelTex[1] = LoadGLTexture("newwheel2.tga");
	WheelTex[2] = LoadGLTexture("newwheel3.tga");
	WheelTex[3] = LoadGLTexture("newwheel4.tga");
	Pieces = new cPiece *[NumPieces];
	PiecePositions = new cVector[NumPieces];
	PieceRotations = new cRotator *[NumPieces];
	Models = new cModel *[NumModels];
	for (Loop = 0; Loop < NumPieces; Loop++) {
		Pieces[Loop] = new cPiece;
		PieceRotations[Loop] = Pieces[Loop]->GetRotationP();
	}
	Models[0] = AddModel(MODEL_BODY, "body.mdl");
	Models[1] = AddModel(MODEL_WHEEL, "wheel.mdl");
	Models[2] = AddModel(MODEL_HUBCAP, "hubcap.mdl");
	Models[3] = AddModel(MODEL_TCUBE, "tcube.mdl");
	Pieces[0]->SetModel(Models[0]);
	for(Loop = 1; Loop < 5; Loop++) {
		Pieces[Loop]->SetTexture(0);
		Pieces[Loop]->SetModel(Models[1]);
		Pieces[Loop]->SetRotOrder(ROT_ORDER_YXZ);
	}
	for(Loop = 6; Loop < 10; Loop++) {
		Pieces[Loop]->SetTexture(WheelTex[0]);
		Pieces[Loop]->SetModel(Models[2]);
	}
	Pieces[0]->SetPosition(cVector(0.0, 0.0, 0.0));
	Pieces[0]->SetRotation(cRotator(0.0, 0.0, 0.0));
<repeat for other 4 pieces>
	for (Loop = 0; Loop < NumPieces; Loop++) {
		PiecePositions[Loop] = Pieces[Loop]->GetPosition();
	}
}
Fun note: That second parameter on AddModel? Not a filename. It's an identifier so you can do FindModel on it if you need to for some reason. The model was actually built in a display list that was part of a gigantic switch statement controlled by the first parameter.

Sebastian Flyte
Jun 27, 2003

Golly
I just found this gem when testing a newsletter for a client, who was wondering why the system was sending newletter previews successfully, but they never got any.

code:
try
{
  newsletterApi.SendPreview(newsletterId);
}
catch(Exception ex)
{
  errorMessage.Message = ex.Message;
}
errorMessage.Message = "Preview sent successfully to your email address.";
Sometimes I want to hit my co-workers with a lead pipe.

functional
Feb 12, 2008

Sartak posted:

gently caress not.

code:
$color = 'bgcolor="#F' . ($n ^= 'C9') . '"';

Doesn't work on PHP 5.2.6 (cli) (built: Jul 17 2008 23:04:49)

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"
Here's one for you Python programmers out there:

code:
def get_info_from_package_name (filename):
	"""Return all info we can get from the package-name or return None
	if something went wrong. If nothing failed, the returned value is
	a 4-tuple of the form: (name, version, basename, extension)."""
	base	= os.path.basename(filename)
	ext	= str(filename)[len(str(filename)) -3:]
	# prepend "tar." if we have a bz2 or gz archive
	tar_opts = 'xfz'
	if ext == 'bz2':
		tar_opts = 'xfj'
	if ext == 'skz': 
		screenlets.show_error(None,_('This type of karamba theme is not supported yet\n Only older versions can be used'))
		return False
	# extract archive to temporary dir

	if not os.path.isdir('/tmp/screenlets/'):
		os.system('mkdir ' + '/tmp/screenlets/')
	try: os.system('rm -rf /tmp/screenlets/install-temp')
	except: pass		
	tmpdir = '/tmp/screenlets' + '/install-temp/'
	os.system('mkdir %s' % tmpdir)

	os.system('tar %s %s -C %s' % (tar_opts, chr(34)+filename+chr(34), tmpdir))
	for dd in os.listdir(tmpdir):
		if str(dd).endswith('.theme'):
			os.system('mv ' + tmpdir + ' ' + '/tmp/screenlets/' + dd[:-6])
			os.system('mkdir %s' % tmpdir)
			os.system('mv ' + '/tmp/screenlets/' + dd[:-6] + ' '+ tmpdir)
			name = dd[:-6]
			return (name, ext)

	for d in tmpdir : #for each item in folders
		if os.path.exists(d) and os.path.isdir(d): #is it a valid folder?
			for f in os.listdir(tmpdir): 
				name = f
	try:
		print name
		return (name, ext)
	except:
		return False
:psypop:

Filburt Shellbach
Nov 6, 2007

Apni tackat say tujay aaj mitta juu gaa!

functional posted:

Doesn't work on PHP 5.2.6 (cli) (built: Jul 17 2008 23:04:49)

Tested only in Perl. v:)v

Adbot
ADBOT LOVES YOU

Kharya
Sep 23, 2005
So how DO you chase off a half blind, crazed, sugar addict?
Ok, I'm not an ActionScript programmer and I'm trying to recall this from memory. Bear with me if the syntax isn't exactly correct. You get the idea:

code:
class GalleryClass {
    private var XMLData;
    function loadImages(start:int, count:int, sizeX:int, sizeY:int) {
        var listeners:Object;
        listeners.onLoad = parseXML;
        loadXML('http://foo.com/api/XML/images.php?start='+start+'&count='+count+'&sizeX='+sizeX+'&sizeY='+sizeY, listeners);
        // That's probably not the REAL function an AS3 developer would call.  I'm making this up.
        // Also, loadXML is non-blocking.  This is a very important point.
        // parseXML will be called when the data is finished loading.
    }

    function parseXML(data) {
        XMLData = data;
        /* Do unnatural things with XMLData */
        /* Do more things.  This takes some time */
        /* Display images on the screen, lots of loops still using XMLData */
        delete(XMLData);  // Probably wrong function name.  Basically it gets nulled out.
    }
}
Ok? Everyone following? Property in the class scope, non-blocking call. parseXML could be run at any time...ok...ok...now:

code:
var foo = new GalleryClass();
foo.loadImages(0, 20, 320, 240);

// Do some other stuff.

foo.loadImages(20, 20, 320, 240);
Him: Hey, why does it sometimes randomly cut off one of the galleries? Sometimes the first page is cut, sometimes the second, and sometimes they both work! I don't get it.
Me: *sigh* Let me teach you about concurrency and scope....

Kharya fucked around with this message at 16:29 on Nov 2, 2008

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