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
That Turkey Story
Mar 30, 2003

Dren posted:

I'd just like to say, even if I've said it before, gently caress #define.

I keep running into C libraries where something is #define'd that fucks up the STL if I try to use them in C++.

Don't hate the game, hate the playa.

Microsoft

Adbot
ADBOT LOVES YOU

yippee cahier
Mar 28, 2005

Quick one:
code:
/* Clock settings at 64MHz */
MASTER_CLK_FREQ = 59000000;

Fuck them
Jan 21, 2011

and their bullshit
:yotj:
code:
private static string ObjectToString(object anyFrigginObject)
{
    string str;
    try
    {
        if (anyFrigginObject == null)
        {
            return "[Nothing]";
        }
        if (Information.IsDBNull(RuntimeHelpers.GetObjectValue(anyFrigginObject)))
        {
            return "[DBNull]";
        }
        str = "\"" + anyFrigginObject.ToString() + "\"";
    }
    catch (Exception exception1)
    {
        ProjectData.SetProjectError(exception1);
        str = "Error in ObjectToString: " + exception1.ToString();
        ProjectData.ClearProjectError();
        return str;
        ProjectData.ClearProjectError();
    }
    return str;
}

 
I find this humorous.

Is it a horror or just a funny convenience method?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

2banks1swap.avi posted:

Is it a horror or just a funny convenience method?

That's a horror for sure.

The entire purpose of the ToString method is to give a string representation of an object.

Here's a less horror-y but still totally useless version:
code:
      public static string ShittyToString(object s)
        {
            if (s == null)
            {
                return "[Nothing]";
            }
            if (s is DBNull)
            {
                return "[DBNull]";
            }

            return string.Format("\"{0}\"", s);
        }

New Yorp New Yorp fucked around with this message at 18:25 on Jul 11, 2013

Fuck them
Jan 21, 2011

and their bullshit
:yotj:
Is it bad that I'm just laughing about it instead of getting mad?

The only real teething problem I've had here was that I'm used to projecting my voice due to my past jobs and programmers in cubes like it quiet. That and I have allergies/reflux and I'm between docs because my new insurance hasn't come in yet and I'm coughing. Bleh.

Y'all programmers are touchy.

Bunny Cuddlin
Dec 12, 2004

Ithaqua posted:

That's a horror for sure.

The entire purpose of the ToString method is to give a string representation of an object.

Here's a less horror-y but still totally useless version:
code:
      public static string ShittyToString(object s)
        {
            if (s == null)
            {
                return "[Nothing]";
            }
            if (s is DBNull)
            {
                return "[DBNull]";
            }

            return string.Format("\"{0}\"", s);
        }

Tangential but is there anything inherently wrong with if (s == DBNull.Value) vs if (s is DBNull)?

Scaevolus
Apr 16, 2007

tef posted:

i'd make a lilliputian reference to big-endian and little-endian, but satire is dead.

http://en.wikipedia.org/wiki/Endianness#Etymology

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Bunny Cuddlin posted:

Tangential but is there anything inherently wrong with if (s == DBNull.Value) vs if (s is DBNull)?

I don't think so. I've never had a need to use DBNull, honestly.

Plorkyeran
Mar 22, 2007

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

Bunny Cuddlin posted:

Tangential but is there anything inherently wrong with if (s == DBNull.Value) vs if (s is DBNull)?

There's no functional difference worth caring about (in theory == is faster than is, but it's not going to be a measurable difference). I personally think is DBNull reads a little better (and ceteris paribus I favor the shorter version), but the it's not exactly a big difference here.

Bunny Cuddlin
Dec 12, 2004

Ithaqua posted:

I don't think so. I've never had a need to use DBNull, honestly.


Plorkyeran posted:

There's no functional difference worth caring about (in theory == is faster than is, but it's not going to be a measurable difference). I personally think is DBNull reads a little better (and ceteris paribus I favor the shorter version), but the it's not exactly a big difference here.

Alright cool, just curious since I saw "is DBNull" and I know Ithaqua is competent so I thought I'd check.

Dren
Jan 5, 2001

Pillbug
From the code review I am doing:
C++ code:
/**
 * CLASS::getFilesize()
 */
uintmax_t
CLASS::getFilesize(const char *filePathname)
{
    uintmax_t fileSize = boost::filesystem::file_size(filePathname);
    return(fileSize);
}
It's not wrong it's just not good.

BigRedDot
Mar 6, 2008

So this works:
code:
(Math.floor(extent/rounding) + 1) * rounding
But this:
code:
(Math.floor(extent/rounding) +1) * rounding # oops forget a space
generates this:
code:
(Math.floor(extent / rounding)(+1)) * rounding;
Thanks, coffeescript.

raminasi
Jan 25, 2005

a last drink with no ice

That Turkey Story posted:

Don't hate the game, hate the playa.

Microsoft

Microsoft is far from the only vendor that pulls this poo poo. I'm using a third-party library that has to be included after boost or else it breaks boost.

Dren
Jan 5, 2001

Pillbug

GrumpyDoctor posted:

Microsoft is far from the only vendor that pulls this poo poo. I'm using a third-party library that has to be included after boost or else it breaks boost.

'sup crappy third party library buddy :(:hf::(

Gazpacho
Jun 18, 2004

by Fluffdaddy
Slippery Tilde
C# code:
catch(SomeException ex)
{
    Assert.IsTrue(ex is SomeException);
}

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Gazpacho posted:

C# code:
catch(SomeException ex)
{
    Assert.IsTrue(ex is SomeException);
}

That's silly, especially if you're using MStest when you can just decorate the test method with [ExpectedException(typeof(SomeException))]

I've written unit tests where I wanted to verify the contents of the exception, so I've had to do goofy stuff like
code:
public void TestMethod()
{
	var expected = "Whatever message";
	try 
	{
		ThingIWantToTest();
	}
	catch (WhateverException ex)
	{
		Assert.IsTrue(expected, ex.Message);
		return;
	}
	Assert.Fail("WhateverException was not thrown.");
}
In a similar vein, I saw something along these lines in a client's codebase recently:

C# code:
catch (Exception ex)
{
	if (ex is SomeException) {}
	else if (ex is SomeOtherException) {}
	else
	{
		throw ex;
	}
}

New Yorp New Yorp fucked around with this message at 05:00 on Jul 12, 2013

coaxmetal
Oct 21, 2010

I flamed me own dad
i've wanted to learn and use c# for a long while but haven't because I don't have anything to do with it. Sure sounds like a solid language though if you are making stuff to run on winders.

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer

Ithaqua posted:

That's silly, especially if you're using MStest when you can just decorate the test method with [ExpectedException(typeof(SomeException))]

The problem with ExpectedException is that you can't distinguish between an exception in your test code and an exception in the code under test. You can end up with tests that pass even though they never even get to the actual test part of the test, because your test setup happens to throw the same exception that you were asserting on. Okay, it's not particularly likely, but the day it happens to you you'll be none the wiser. I also view it as a bad thing that asserting on exceptions is so structurally different from asserting on values, which is why I always use this little snippet instead of ExpectedException:
C# code:
public static void AssertThrows<T>(Action action) where T : Exception
{
    try
    {
        action.Invoke();
        Assert.Fail("Exception of type {0} should've been thrown", typeof(T));
    }
    catch (T exception)
    {
        // You could drop this line if you're okay with matching subclasses of exceptions, or you could add a parameter like "bool allowSubclasses"
        Assert.IsInstanceOfType(exception, typeof(T));
    }
}
You call it like this (although you'll probably want to put it in a utility class somewhere):
C# code:
AssertThrows<MyExpectedException>(() => ThingUnderTest());
Edit: woops, I thought I was in the .NET thread. Nevermind.

LOOK I AM A TURTLE fucked around with this message at 11:09 on Jul 12, 2013

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
I'm sure this is entirely valid code but I still laughed at the name.
Java code:
    /**
     * Adds the given gamma value, g, to the given seed value s, mod
     * George (2^64+13). We regard s and g as unsigned values
     * (ranging from 0 to 2^64-1). We add g to s either once or twice
     * (mod George) as necessary to produce an (unsigned) result less
     * than 2^64.  We require that g must be at least 13. This
     * guarantees that if (s+g) mod George >= 2^64 then (s+g+g) mod
     * George < 2^64; thus we need only a conditional, not a loop,
     * to be sure of getting a representable value.
     *
     * @param s a seed value
     * @param g a gamma value, 13 <= g (as unsigned)
     */
    private static long addGammaModGeorge(long s, long g) {
        long p = s + g;
        if (Long.compareUnsigned(p, g) >= 0)
            return p;
        long q = p - 13L;
        return (Long.compareUnsigned(p, 13L) >= 0) ? q : (q + g);
    }

Beef
Jul 26, 2004

spitefulcrow posted:

For the Python developers in this thread, some truly horrible things you can do to Python: http://www.slideshare.net/r1chardj0n3s/dont-do-this-24000445.

A brief taste:

code:
>>> def f():
...     print('ohai there!')
...
>>> def g():
...     print('hello, world!')
...
>>> g.__code__ = f.__code__
>>> g()
ohai there!
:doh:

Hi! You seem to be pretty new at this programming thing. You might want to look at some interesting dynamic programming languages such as: Javascript, Lua, Scheme, Common Lisp, Ruby, Smalltalk, R, etc.

But seriously. Why do you consider changing a function body a horror. (Besides the horrible underscores-based names and Rossum's ignorance of common programming language engineering terms.)

Hammerite
Mar 9, 2007

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

Beef posted:

Hi! You seem to be pretty new at this programming thing. You might want to look at some interesting dynamic programming languages such as: Javascript, Lua, Scheme, Common Lisp, Ruby, Smalltalk, R, etc.

But seriously. Why do you consider changing a function body a horror. (Besides the horrible underscores-based names and Rossum's ignorance of common programming language engineering terms.)

I don't have Python installed on this machine, or I'd check, but...

I assume that changing a function in that way mutates the function. A competent Python programmer is au fait with mutable objects, but I think most people wouldn't really think of callables as mutable (exception: generators)

If you pass a function into another function as a parameter, wouldn't you be surprised to find it got changed in place?

Beef
Jul 26, 2004
Don't hate the game, hate the playa. :v:

No, you wouldn't want your junior programmer to be doing that. But a lot of those meta-programming options that change the basic behaviour of the language (or as in this case any object) is an extremely powerful tool for designing clean frameworks and DSLs.

In some sense, it is similar to the operator overloading discussion in Java vs C++. It can be bad if you operator+() is overloaded by some dumb library to send an email to your mom. But simultaneously it allows Intel to make a nice parallel Vector library.

edit: vvv Ooh yeah, decorators are a good example, I have to remember that when another of these discussion pop up.

Beef fucked around with this message at 18:07 on Jul 12, 2013

Hammerite
Mar 9, 2007

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

Hammerite posted:

If you pass a function into another function as a parameter, wouldn't you be surprised to find it got changed in place?

that's what decorators do, which are powerful and good tools, so maybe my argument isn't so good.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Decorators rarely change in-place, since they usually have the opportunity to simply return another one directly.

Beef posted:

Hi! You seem to be pretty new at this programming thing. You might want to look at some interesting dynamic programming languages such as: Javascript

Since I've actually never seen it, how do you change a function body in JavaScript? As far as I can tell, you can build new functions with the Function constructor or eval, but never change a function's body. I'd also say that it would never get added to JavaScript, since the semantics of what it means are complicated, and would make JIT compilation more hell than it already is.

Beef
Jul 26, 2004
Quicky checked the Python spec:
code:
function	__doc__	documentation string
 	__name__	name with which this function was defined
 	__code__	code object containing compiled function bytecode
So you are basically just swapping out the function body, as if you would redefine a function. A JIT will not crap out at that, especially not a trace-based JIT.

Of course, you wouldn't want your actual AST to be something you can mutate freely (as in, destructively assign parts of it). It used to be something common back in the 50's style LISP, but f-expressions got dumped in favor of macros.

Only R is retarded enough to still do that. Decades after it's been shown that f-expr are an uncompilable mess, R comes out with semantics where functions get applied by literally substituting the actual arguments for the formal arguments in the body code of the function.

4% of a typical R runtime is spent on variable lookup, since the above semantics make lexical addressing impossible :psyduck:

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
No popular JS JIT is a tracing JIT anymore. Turns out trace trees aren't really representative of real-world performance and you get knocked off-trace way too often, causing your perf to task.

What it really means is that you can't accurately do inlining. If you have:

JavaScript code:
function butt() {
    return 3;
}

function poop(f) {
    return function() {
        return f() + 6;
    };
}

var fart = poop(butt);
In this case, we know that in fart's case, f is always butt, and can be inlined (and with Crankshaft, peephole optimized to be a constant) effectively. If functions are mutable, this optimization is void.

UraniumAnchor
May 21, 2006

Not a walrus.

Munkeymon posted:

"Languages that have first class functions and decent reflection support can do crazy poo poo if you really want them to :supaburn:"? As someone who's been using JavaScript for years, I'd just like to say: you don't loving say.

Intentionally being horrible can be pretty interesting, but it's not nearly as funny as, say, 10gen's decision to eat some error 90% of the time.

Edit: or that example from Ruby where something in a conditional block that wasn't executed changing the surrounding scope (or something like that - it was a couple months back, I think) and maybe that was only surprising because I haven't learned Ruby yet.

You mean this one?

UraniumAnchor posted:

So I ran across this while trying to write some Ruby:

code:
$ cat gently caress.rb 
def what
       return 'the'
end

puts "'#{what}'"

if false then
       puts "hello"
       what = "gently caress"
end

puts "'#{what}'"
$ ruby gently caress.rb 
'the'
''
On what planet is this sane behavior? Can somebody explain to me what is going on here?

I think the eventual consensus was that the assignment in the non-executing block still causes the interpreter to make "what" a local variable from that point on, instead of a function. So I guess Ruby functions aren't truly first class?

Edit: Yup.

code:
$ cat fuck2.rb 
def what
       return 'the'
end

puts "'#{what}'"
puts what.class

if false then
       puts "hello"
       what = "gently caress"
end

puts "'#{what}'"
puts what.class
$ ruby fuck2.rb 
'the'
String
''
NilClass
Though I'm not sure why the first "what.class" is returning String. Guess functions aren't a type?

UraniumAnchor fucked around with this message at 19:07 on Jul 12, 2013

Plorkyeran
Mar 22, 2007

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

UraniumAnchor posted:

Guess functions aren't a type?
Sort of, yes. Ruby "functions" are actually just methods on a semi-global object, and ruby uses message-based OO, which results in methods not actually being concrete things - conceptually they're move of just syntatic sugar for a big switch statement in method_missing.

Ruby semantics tend to be very misleading to people unfamiliar with the language due to that it's basically smalltalk's OO system wrapped up in a very non-smalltalk syntax.

Dren
Jan 5, 2001

Pillbug

Amazon Reviewer posted:

Additionally I found the "D is for deconstructor" subtext of "Let your mom clean up after you. That's her job." to be very sexist and added no value to the entry or related to the discussion of a deconstructor.

http://www.amazon.com/Array-Brandon...=A+is+for+Array

Munkeymon
Aug 14, 2003

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



Yes, that's what I meant and

Plorkyeran posted:

Sort of, yes. Ruby "functions" are actually just methods on a semi-global object, and ruby uses message-based OO, which results in methods not actually being concrete things - conceptually they're move of just syntatic sugar for a big switch statement in method_missing.

Ruby semantics tend to be very misleading to people unfamiliar with the language due to that it's basically smalltalk's OO system wrapped up in a very non-smalltalk syntax.

:psyduck: just confuses me more. Maybe I should learn SmallTalk first :v:

UraniumAnchor
May 21, 2006

Not a walrus.
Yeah, for me the confusing part of that block is why a statement that clearly never executes still has a side effect. Maybe that's unavoidable due to the language design or something, but it's still weird.

Beef
Jul 26, 2004
It is due to amateur language design :cb:

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
The parser needs to know if something is a local variable or a function, otherwise what does what +1 mean? The parser doesn't know the result of if expressions, so it just blindly tracks which is what.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Apparently ruby's parser/lexer is a horror.

http://programmingisterrible.com/post/42432568185/how-to-parse-ruby

Also tried to help out on topaz project, I know a goon works on that right?

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
Conceptually, that ruby code is parsed as something vaguely along the lines of the following in Python:

Python code:
class Global:
    methods = {
        'what': lambda: 'the'
    }
    def call(self, message, *args):
        if message in self.methods:
            return self.methods[message](*args)
        raise MethodNotFound()

g = Global()

print("'{}'".format(g.call("what")))
print("what".__class__)

if False:
    print('hello')
    what = 'gently caress'

print("'{}'".format(what))
print(what.__class__)
Given this translation, I think ruby's behavior makes sense: it's not that the unreachable code in the if is overwriting things, it's that the first puts "'#{what}'" is syntatic sugar for something completely different from what people who don't know ruby well would expect, and the decision for what the references to what do is made before any of the code is run.

(I'm not claiming that this behavior is good, just that it's not pure insanity)

Munkeymon posted:

:psyduck: just confuses me more. Maybe I should learn SmallTalk first :v:
Learning Objective-C made ruby a lot more understandable for me, since it's basically the same OO model but with far less magic involved (both syntatic and cultural).

spitefulcrow
Jun 16, 2013

Beef posted:

Hi! You seem to be pretty new at this programming thing. You might want to look at some interesting dynamic programming languages such as: Javascript, Lua, Scheme, Common Lisp, Ruby, Smalltalk, R, etc.

But seriously. Why do you consider changing a function body a horror. (Besides the horrible underscores-based names and Rossum's ignorance of common programming language engineering terms.)

Thanks for talking down to me (for the record I'm going on my fourth year working in the industry professionally after finishing a CS degree… not an aged wizard but also not totally wet behind the ears).

As I mentioned in my other reply, it's not strictly a horror, but if I saw it in someone's code that wasn't a testing framework or DSL implementation (or…) I'd probably slap them for being too clever.

I would indeed consider it at least a little bit surprising if I handed a function object as a regular parameter to someone else's function and the original function I passed in was mutated to execute different code.

Decorators achieve this in a non-destructive and repeatable way by wrapping the inner function's invocation with a new function. Yes, the original function's name is then re-bound to the decorated version, but the syntax makes it obvious that the decorator has been used and that the named function now has behavior other than what is directly inside its body.

Even the example of a testing framework probably doesn't need this — since object attributes are mutable by default, mock.patch achieves the same goal in most cases without overwriting the innards of the actual function. It's conceptually cleaner to monkey-patch the entire function rather than violating the abstraction boundary. Yes, I know Python doesn't have real encapsulation because everything's mutable and this is just another case of that, but why break the conventions when you don't need to?

Amarkov
Jun 21, 2010

spitefulcrow posted:

As I mentioned in my other reply, it's not strictly a horror, but if I saw it in someone's code that wasn't a testing framework or DSL implementation (or…) I'd probably slap them for being too clever.

Well, I mean... yeah. Like all reflection features, it's horribly inappropriate for most situations. But the language shouldn't make it more complicated to do just for the sake of disguising it. That's how you end up with things like Java reflection.

shrughes
Oct 11, 2008

(call/cc call/cc)

Beef posted:

Why do you consider changing a function body a horror.

Because of obviosity? Why would you ever change a function body via spooky action at a distance? Maybe if you wanted to confuse everybody or had some other malicious goal in mind.

Doctor w-rw-rw-
Jun 24, 2008

shrughes posted:

Because of obviosity? Why would you ever change a function body via spooky action at a distance? Maybe if you wanted to confuse everybody or had some other malicious goal in mind.

Objective-C has a similar thing called swizzling where you can swap methods, so calling a method calls another, which can then call the original one.

It's used to implement KVO, which lets allows classes to subscribe to get notified when the value of a variable changes.

Adbot
ADBOT LOVES YOU

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

Doctor w-rw-rw- posted:

Objective-C has a similar thing called swizzling where you can swap methods, so calling a method calls another, which can then call the original one.

It's used to implement KVO, which lets allows classes to subscribe to get notified when the value of a variable changes.

KVO uses isa-swizzling, not method swizzling. (That is, it dynamically changes your object's class.)

And for what it's worth, both kinds of swizzling are generally considered "horrors" in Objective-C land right up until the minute you need them, at which point they're very handy.

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