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
Lurchington
Jan 2, 2003

Forums Dragoon
this is from my comp sci grad school partner's code for "parsing" an XML dataset and returning information. I don't think this is really falling under the "student code" provisions of this thread since we both are getting a part time degree while working full time in software for the last 7 years.

code:
unsigned char* process_element(struct crime_data *data, float *crime_long, float *crime_lat, 
long *date, long compare_date, long time_range, unsigned int radius, unsigned char* index, 
unsigned char* previous_class){
        unsigned char* new_index = index;
        unsigned int x=0;

#ifdef print_field
        while(*(new_index+x)!='>'){
                printf("%c", *(new_index+x));
                x++;
        }
        printf(">\n");
#endif
        if(!memcmp(new_index, "<element name=\'LatX\' >", sizeof("<element name=\'LatX\' >")-1)){
                new_index = strchr(new_index, '>')+1;

                if(!strncmp(previous_class, "ciras.db.Address", sizeof("ciras.db.Address")-1)){
                        sscanf(new_index, "%08f", crime_lat);
//                      printf("Crime Event LatX %f\n", *crime_lat);                                                                                                               
                }

                new_index = strstr(new_index, "</element>");
        } else if(!memcmp(new_index, "<element name=\'LonY\' >", sizeof("<element name=\'LonY\' >")-1)){
                new_index = strchr(new_index, '>')+1;

                if(!strncmp(previous_class, "ciras.db.Address", sizeof("ciras.db.Address")-1)){
                        sscanf(new_index, "%08f", crime_long);
//                      printf("Crime Event LonY %f\n", *crime_long);                                                                                                              
                }

                new_index = strstr(new_index, "</element>");
        } else if(!strncmp(new_index, "<element name=\'StartDate\' type=\'Calendar\' >", 
                   sizeof("<element name=\'StartDate\' type=\'Calendar\' >")-1)){
                int year=0;
                int month=0;
                int day=0;
                int hour=0;
                int minute=0;
                int second=0;
                int something=0;
                new_index=strchr(new_index, '>')+1;

                //process the date of the crime event                                                                                                                              

                sscanf(new_index, "%d:%d:%d:%d:%d:%d:%d", &year, &month, &day, &hour, &minute, &second, &something);

                *date = (year-1970)*365*24*60*60 + (month-1)*30.4328499*24*60*60 + (day-1)*24*60*60 + hour*60*60 + minute*60 + second;

                if(*date >= compare_date && *date <=compare_date+time_range)
                        data->num_of_date_matched_events++;

                new_index = strstr(new_index, "</element>");
        } else {

#if 0
                unsigned int x=0;

                unsigned char* Topic = strchr(new_index, '\'');
                unsigned char* End_top = strchr(Topic, '\'');
                unsigned char* start = strchr(new_index, '>')+1;
                unsigned char* end = strchr(start, '<');

                unsigned char* temp = NULL;


                for(temp = Topic; temp <End_top ; temp++)
                        printf("%c", isascii(temp[0])?temp[0]:'.');

                printf("=");

                for(temp = start; temp<end; temp++)
                        printf("%c", isascii(temp[0])?temp[0]:'.');

                printf("\n");

#endif
                new_index = strstr(new_index, "</element>");
        }

        new_index+=sizeof("</element>")-1;

	return new_index;
}

This is actually a WORSE approach than the ole' parsing xml with regular expressions trick, in that he's making very specific assumptions about all the data everywhere always having:
- single quotes
- a space between the content and the closing angle bracket
which means like half the totally valid xml we have just doesn't get read

The date in the files are "<year>:<month>:<day>:<hour>:<minute>:<second>" which is fine and normalized, so I'm confused why the hell he's reinventing the wheel on epoch time:
{code}
*date = (year-1970)*365*24*60*60 + (month-1)*30.4328499*24*60*60 + (day-1)*24*60*60 + hour*60*60 + minute*60 + second;
{code}

That 1970 apparently got tacked on after I told him that seconds from year 0 was bad idea always and especially when all of data was after 2005. And 30.4328499 is a HELL of a magic number for the "average days in a month" which I don't think is even correct.

#if/#endif as flow control apparently? too lazy to comment out debug code? YOU DECIDE!

Also he checked in a 700 MB tarball into our mercurial repo and out of all that we're going to use 46M (uncompressed) worth of static, unchanging xml

only edits are new lines for table breaking
---

The point of this C script is to count items that occur on a date and within a radius of a given lat/long, and return the results, meaning that the xml is going to be parsed 100s of times without ever changing. That should really be a relational database holding the parsed XML data and we could make queries against it, but I'm so close to just closing out this project and being done with the class I just don't feel like doing the right way. When I gave him this portion I knew in order to not worry about it, I was ceding control and had to be willing to live with "functional but not usable"

VVV who the hell knows argggggggg

Lurchington fucked around with this message at 01:06 on Nov 26, 2011

Adbot
ADBOT LOVES YOU

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Why do those printf lines have 75 spaces after them?

Pollyzoid
Nov 2, 2010

GRUUAGH you say?

Lurchington posted:

And 30.4328499 is a HELL of a magic number for the "average days in a month" which I don't think is even correct.

It's not far though :v:
(((365 * 4) + 1) / 4) / 12 = 30.4375

VVVVV Oh, right. I forgot about century leap years. The fact I'm having this conversation feels very wrong.

Pollyzoid fucked around with this message at 14:43 on Nov 25, 2011

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Pollyzoid posted:

It's not far though :v:
(((365 * 4) + 1) / 4) / 12 = 30.4375

(365 * 400 + 97) / (400 * 12) = 30.436875

I think you'll find. :smug:

Opinion Haver
Apr 9, 2007

perl owns

code:
$x = "02";
$y = "02";
$x++;
int($y);
$y++;
print "> $x $y\n";

> 03 3

tef
May 30, 2004

-> some l-system crap ->
edit: mmnngn

Salynne
Oct 25, 2007
Here is a java one from Games forum superstar java programmer Notch. It made my head hurt trying to follow it in the obfuscated code. (there was more jumps that led me to this, renames are mine)

Old method:
code:
    public float thingWithColor(int red, int blue)
    {
        return biomeCache.useColor(red, blue);
    }
New methods:
code:
   public float thingWithColor(int red, int green, int blue) {
      return this.removeGreen(this.biomeCache.useColor(red, blue), green);
   }

   public float removeGreen(float color, int green) {
      return color;
   }
I had to jump through stuff calling stuff calling stuff calling stuff trying to figure out what this mysterious new argument that the method wanted was. Turns out: anything I want to put in there!

Optimus Prime Ribs
Jul 25, 2007

code:
public float removeGreen(float color, int green) {
      return color;
   }
:psyduck:

Does this make as little sense as I think it does?

Opinion Haver
Apr 9, 2007

Optimus Prime Ribs posted:

code:
public float removeGreen(float color, int green) {
      return color;
   }
:psyduck:

Does this make as little sense as I think it does?

Yep.

Salynne
Oct 25, 2007

Optimus Prime Ribs posted:

code:
public float removeGreen(float color, int green) {
      return color;
   }
:psyduck:

Does this make as little sense as I think it does?

It was obfuscated, I have no idea what it was called or what its purpose is, but I can't think of basically any good reason. Here was my logic for what probably happened:

Notch: I think this method should take 3 color args for RGB even though it only needs two, because consistancy for color methods (Okay I will buy this)

Oh drat, it gave me a compiler warning because I don't use the argument anywhere in the method.

Well, if I just write a quick useless method that uses the arg, then I can get rid of the compiler warning! (Gone into insanity)

EDIT: Original decompiled, deobfuscated looks like this:

code:
   public float func_35554_b(int var1, int var2, int var3) {
      return this.func_40540_a(this.biomeCache.func_35722_b(var1, var3), var2);
   }

   public float func_40540_a(float var1, int var2) {
      return var1;
   }

Salynne fucked around with this message at 00:16 on Nov 26, 2011

Optimus Prime Ribs
Jul 25, 2007

Well that certainly is something.

1337JiveTurkey
Feb 17, 2005

General Olloth posted:

It was obfuscated, I have no idea what it was called or what its purpose is, but I can't think of basically any good reason.

For confusing people looking at decompiled code, perhaps. At runtime it's just going to be inlined (JIT allows inlining of virtual methods with only one implementation in practice) and then eliminated entirely. So performance-wise, it's pretty close to zero cost and there's a definite nonzero cost for anyone trying to decompile and understand the code. I haven't messed around with obfuscators enough to tell if that's something commonly done, but there's nothing technically preventing it.

mjau
Aug 8, 2008
It's probably also been optimized, so the original could look more like this:
code:
return var1 + FOO * var2;
...where FOO is some compile time constant that currently evaluates to 0, but can be updated to something else for some future feature.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Here's some article I read:
"Yoda Conditions", "Pokémon Exception Handling" and other programming classics

Salynne
Oct 25, 2007

1337JiveTurkey posted:

For confusing people looking at decompiled code, perhaps. At runtime it's just going to be inlined (JIT allows inlining of virtual methods with only one implementation in practice) and then eliminated entirely. So performance-wise, it's pretty close to zero cost and there's a definite nonzero cost for anyone trying to decompile and understand the code. I haven't messed around with obfuscators enough to tell if that's something commonly done, but there's nothing technically preventing it.

I don't think the obfuscator he uses does this but I could be wrong. I have "insider information" from the Bukkit team who has/had access to his real source that it is just as insane in many places.

The only thing his obfuscator seems to do is put all the classes in one package (3000 classes in the same package, that's fun) and rename everything to jibberish.

The Gripper
Sep 14, 2004
i am winner

General Olloth posted:

The only thing his obfuscator seems to do is put all the classes in one package (3000 classes in the same package, that's fun) and rename everything to jibberish.
Apparently he's using ProGuard for it, I don't have javac to test but it seems like it'd be able to add some useless methods if you passed a Class to a method i.e. originally:
code:
Color myColor;
myColor = new Color(131,024,255);
...
thingWithColor(myColor);
...
public float thingWithColor(Color color) {
      return this.biomeCache.useColor(color.red, color.blue);
   }
Where color only contained red, green, blue values, expand call and method into:
code:
thingWithColor(myColor.red, myColor.blue, myColor.green);
...
public float thingWithColor(int cr, int cb, int cg) {
      return this.biomeCache.useColor(cr, cb);
   }
and further mess with it by having a method that does nothing that the original return wouldn't do on its own, though takes all arguments the original method took whether they are used or not. I don't know about the performance of that, but if 1337JiveTurkey has it right then it'd be zero cost against the original.

(This doesn't absolve notch from not just calling this.biomeCache.useColor(red, blue) in the first place :o)

Opinion Haver
Apr 9, 2007

The Gripper posted:

(This doesn't absolve notch from not just calling this.biomeCache.useColor(red, blue) in the first place :o)

I think the argument was that if you use three arguments then he can make it depend on green without refactoring every single reference.

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...
Also Thing.thingWithColor() is a lot better than Thing.biomeCache.useColor(). For one, biomeCache should be private.

The Gripper
Sep 14, 2004
i am winner

Dessert Rose posted:

Also Thing.thingWithColor() is a lot better than Thing.biomeCache.useColor(). For one, biomeCache should be private.
Yeah I wasn't really thinking straight and thought useColor was returning the same thing as thingWithColor, so I retract the last part of my post!

Zombywuf
Mar 29, 2008

I did not know Java generics were this bad http://a-dimit.blogspot.com/2011/11/re-highbrow-java-or-java-generics-and.html

Give me C++ templates or give me death.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Zombywuf posted:

I did not know Java generics were this bad http://a-dimit.blogspot.com/2011/11/re-highbrow-java-or-java-generics-and.html

Give me C++ templates or give me death.

This is just my Stockholm syndrome, but it's much better than the poo poo we had to do before. Also of all the things he mentions the only one I've ever run into is trying to create a generic array, so meh.

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

MEAT TREAT posted:

This is just my Stockholm syndrome, but it's much better than the poo poo we had to do before. Also of all the things he mentions the only one I've ever run into is trying to create a generic array, so meh.

Java generics are terrible but mostly from a theoretical pov. For the day to day "I'm a 2010-era COBOL programmer" they're perfectly fine. No one working in the salt mine really gives a poo poo about how Java-style generics work.

Zombywuf
Mar 29, 2008

They're an utterly terrible piece of poo poo if you're used to C++.

TasteMyHouse
Dec 21, 2006

Zombywuf posted:

They're Java is an utterly terrible piece of poo poo if you're used to C++.

the thing I ran into a lot was attempting to overload on instantiated generic types -- you can't have a function that overloads different behaviors on a ArrayList<Foo> vs. an ArrayList<Bar> because they have the same erasure.

1337JiveTurkey
Feb 17, 2005

TasteMyHouse posted:

the thing I ran into a lot was attempting to overload on instantiated generic types -- you can't have a function that overloads different behaviors on a ArrayList<Foo> vs. an ArrayList<Bar> because they have the same erasure.

Just give the methods different names if they have different parameters. In this case having the information at runtime still wouldn't help because overloaded and static methods are always resolved with the declared types at compile time.

TasteMyHouse
Dec 21, 2006

1337JiveTurkey posted:

Just give the methods different names if they have different parameters.

doesn't work with ctors :P

1337JiveTurkey
Feb 17, 2005

TasteMyHouse posted:

doesn't work with ctors :P

Try a static factory method then. Overloading based on the generic parameter of a method is just going to confuse the crap out of people, especially if they think the type is covariant on its parameter.

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

TasteMyHouse posted:

the thing I ran into a lot was attempting to overload on instantiated generic types -- you can't have a function that overloads different behaviors on a ArrayList<Foo> vs. an ArrayList<Bar> because they have the same erasure.

Wasn't there some supertype of Foo & Bar that you could have used?

pseudorandom name
May 6, 2007

You can't overload on ArrayList<FooBarSupertype> either

TasteMyHouse
Dec 21, 2006

1337JiveTurkey posted:

Try a static factory method then. Overloading based on the generic parameter of a method is just going to confuse the crap out of people, especially if they think the type is covariant on its parameter.

yeah, I think I ended up doing something like this. Still, struck me as weak as hell that I had to make functions like MakeThingFromFooContainer(Container<Foo> p) and MakeThingFromBarContainer(Container<Bar> p).

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

pseudorandom name posted:

You can't overload on ArrayList<FooBarSupertype> either

You wouldn't overload in that case. Change the class to something like this:
code:
public MyShittyClass <T extends FooBarSupertype> {
    public void MyShittyClass(T val) { ... } 
}
and then it should just work as long as Foo and Bar implement or extend FooBarSupertype correctly. If that doesn't hold (aka Foo and Bar are not subclasses of the same super) I'd argue that it's a code smell to have an overloaded constructor operate on those types in one class.

Plorkyeran
Mar 22, 2007

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

TRex EaterofCars posted:

Java generics are terrible but mostly from a theoretical pov. For the day to day "I'm a 2010-era COBOL programmer" they're perfectly fine. No one working in the salt mine really gives a poo poo about how Java-style generics work.

Java developers don't seem to give a poo poo about endless amounts of duplicated boilerplate so it's not surprising that they don't care about problems with a feature useful for cutting down on that.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Zombywuf posted:

I did not know Java generics were this bad http://a-dimit.blogspot.com/2011/11/re-highbrow-java-or-java-generics-and.html

The Java array design would be totally different if generics had existed from the beginning; the possibility of polymorphism over array types would make it acceptable to eliminate the covariance rule for array types, and element types would probably be subject to the same erasure rules as everything else.

C++ only kindof-sortof overcomes the code/metadata bloat of templates; Java would have a much harder time of it, and I'm not offended enough by the lack of enforcement of generic casts to think that's a good price to pay.

Qwertycoatl
Dec 31, 2008

I think C# does a reasonable job of it. You can't do the nearly as much with C# generics as with C++ templates, but unlike Java it doesn't have type erasure, so generics make sense and don't need heaps of stupid casts everywhere.

It still managed to inherit the array covariance misfeature though.

NotShadowStar
Sep 20, 2000
The last page reaffirms my belief that Java itself is as much of a horror as PHP and I'm justified in having plausible deniability about anything related.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

NotShadowStar posted:

The last page reaffirms my belief that Java itself is as much of a horror as PHP and I'm justified in having plausible deniability about anything related.

I don't know if this is the case. PHP gives you a bunch of horrors by default, a set of mostly broken tools to try and fix them, and documentation and a community that either pretends the problems don't exist or gives bad advice as to how to fix them. The most commonly trotted out example of this would be the addslashes()/magic_quotes/mysql_escape_string()/mysql_real_escape_string()/mysqli_prepare() debacle.

Java on the other hands gives you a bunch of inconvenience by default, a set of mostly broken tools to try and make things less verbose or more convenient, and documentation and a community that either pretends the language isn't verbose and generally inconvenient or pretends this is an advantage.

If given the choice, I would always choose the latter over the former.

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


Isn't that the programming language equivalent of saying Hellraiser 3 can't be a bad film, because The Gingerdead Man is a really bad film?

Luckily enough, more than two options exist, and in the context of all of them, both are not too great.

Zombywuf
Mar 29, 2008

rjmccall posted:

The Java array design would be totally different if generics had existed from the beginning;

The idea of arrays having a design that prevents this kind of polymorphism boggles the mind.

On the plus side, I now know why Java coders get angry when you mention type erasure.

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

NotShadowStar posted:

The last page reaffirms my belief that Java itself is as much of a horror as PHP and I'm justified in having plausible deniability about anything related.

Really? You think that Java's jacked up Generics and array semantics, caused by conscious decisions to maintain backwards compatibility are even in the same ballpark as PHP's travesty of engineering?

I mean don't get me wrong, writing Java sucks as much as slogging through a swamp for sure, but the lead designer of PHP literally goes out of his way to eschew computer science, and Java has been worked on by some of the greatest minds in the field. I don't really see how they can be compared in that manner.

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Zombywuf posted:

The idea of arrays having a design that prevents this kind of polymorphism boggles the mind.

My understanding is that they had a problem, a deadline, and subtype polymorphism. Parametric polymorphism is more appropriate, but it's also a much more complicated language feature, particularly if you don't want "instantiations" to require independent type-checking. I mean, Java's generics support is already too sophisticated by some metrics — most programmers don't understand the mathematics and just work around (misuses of) the type system with casts. And there's a lot more yet that Java generics can't express, like the co-/contra-variance of List<T> with T.

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