Coding: Fleeting Thoughts

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
Sizik
Posts: 1256
Joined: Wed Aug 27, 2008 3:48 am UTC

Re: Coding: Fleeting Thoughts

Postby Sizik » Wed Jul 15, 2015 3:30 pm UTC

Xanthir wrote:So, like, Rust has traits, which classes can opt into. A trait describes some set of methods/etc that the class has to implement, and then you can use the trait in your type declarations. For example, the Error trait requires that you already implement the Debug and Display traits, and then description() and cause() methods. You can then write a function that operates on Errors generically, depending just on the properties guaranteed by the Error trait (compile-time enforced), and pass in any object you want so long as it derives Error.

This is a first-class handling of the same sort of thing that type erasure is a hack around, yes?

(Sorry if I'm sounding dumb or something; every single time Yakk has talked about type erasure and provided sample code, it goes straight over my head.)


I don't know how familiar you are with Java, but that sounds like how interfaces work. Interfaces are basically a list of methods that a class must implement (e.g. a class with the Runnable interface must have a run() method). You can then use the interface like you would any other class (e.g. function arguments, variables, etc.), except you can't create a new instance of it.

Type erasure, as used in Java, is used for generic classes. So, if you wanted a List of Foos, you don't have to create a FooList class specifically for containing Foos, nor do you have to use a List of Objects, and have to cast whatever you get out of it back to Foo. Instead, you create a List<Foo> that is treated at compile time like a List specifically for containing Foos (so you can only insert Foos into it and you only get Foos out of it), but at run-time it is really a List of Objects that happen to all be Foos.
she/they
gmalivuk wrote:
King Author wrote:If space (rather, distance) is an illusion, it'd be possible for one meta-me to experience both body's sensory inputs.
Yes. And if wishes were horses, wishing wells would fill up very quickly with drowned horses.

User avatar
Xanthir
My HERO!!!
Posts: 5413
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Coding: Fleeting Thoughts

Postby Xanthir » Wed Jul 15, 2015 3:49 pm UTC

Yakk wrote:
Xanthir wrote:So, like, Rust has traits, which classes can opt into. A trait describes some set of methods/etc that the class has to implement, and then you can use the trait in your type declarations. For example, the Error trait requires that you already implement the Debug and Display traits, and then description() and cause() methods. You can then write a function that operates on Errors generically, depending just on the properties guaranteed by the Error trait (compile-time enforced), and pass in any object you want so long as it derives Error.

What does "derives Error" mean?

If you have the properties of Error "accidentally", do you qualify as an Error?

Depends on the language. In Rust and Haskell, no, you have to declare that you're a given trait/typeclass. In Go, it happens automatically - you satisfy a Go interface duck-typely. The latter's a little more convenient, the former is safer and more precise (and lets you declare multiple traits that depend on the same methods but imply different constraints, like Eq and PartialEq in Rust).

Sizik wrote:Type erasure, as used in Java, is used for generic classes. So, if you wanted a List of Foos, you don't have to create a FooList class specifically for containing Foos, nor do you have to use a List of Objects, and have to cast whatever you get out of it back to Foo. Instead, you create a List<Foo> that is treated at compile time like a List specifically for containing Foos (so you can only insert Foos into it and you only get Foos out of it), but at run-time it is really a List of Objects that happen to all be Foos.

I understand how this is describing the same phenomenon, but it sounds like this is completely different from the C++ notion of type-erasure-as-hack-for-interfaces.

This also, tho, sounds like it's an artifact of an insufficiently strong type system. In stronger typed languages, nesting types like this isn't some weird technique, it's just how the type system works.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

DaveInsurgent
Posts: 207
Joined: Thu May 19, 2011 4:28 pm UTC
Location: Waterloo, Ontario

Re: Coding: Fleeting Thoughts

Postby DaveInsurgent » Wed Jul 15, 2015 3:55 pm UTC

I didn't think type erasure was "used" in Java but rather was as a concession that was made for the sake of backwards compatibility. C# (or rather, the CLR) does not have the same type erasure yet offers the "same" language features you're describing as having come "from" type erasure.

User avatar
Yakk
Poster with most posts but no title.
Posts: 11128
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Wed Jul 15, 2015 5:54 pm UTC

Can you, external to a class, make a class qualify for an interface?

An example might be the printable concept.

foo is printable if a call to print(foo) works.

The default implementation of print invokes foo.print(), so if you have a method print() it also works.

You can make a type Foo printable by simply creating a print(Foo) function in its namespace.

(The print concept could also be multi-layered, like a variable is printable if there is a do_print<Foo,void>{}(foo) trait specialization, or (failing that) if there is a print(foo), or (failing that) if there is a foo.print() method, with the trait being able to "disable" the later lookups.)
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Wed Jul 15, 2015 7:49 pm UTC

DaveInsurgent wrote:I didn't think type erasure was "used" in Java but rather was as a concession that was made for the sake of backwards compatibility. C# (or rather, the CLR) does not have the same type erasure yet offers the "same" language features you're describing as having come "from" type erasure.
That poses a question I don't know the answer to: Does type erasure actually offer any features over runtime types? I guess maybe simpler compiler/runtime design... but I was thinking more features to developers.

I know without it you get neat things like runtime reflection in C#, but I was under the impression the only reason you would want to build that in is if you didn't already have generics and didn't want to break backwards compatibility (like Java).


Unrelated FT:

I wonder why C# doesn't have something like Array.IsNullOrEmpty in the framework.

User avatar
Xanthir
My HERO!!!
Posts: 5413
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Coding: Fleeting Thoughts

Postby Xanthir » Wed Jul 15, 2015 10:20 pm UTC

Yakk wrote:Can you, external to a class, make a class qualify for an interface?

An example might be the printable concept.

foo is printable if a call to print(foo) works.

The default implementation of print invokes foo.print(), so if you have a method print() it also works.

You can make a type Foo printable by simply creating a print(Foo) function in its namespace.

Depends on the language. Go interfaces are purely duck-typing; Haskell can newtype its way into anything; Rust can declare that a class derives a trait as long as the module defines one of them. (Currently, you can't declare that an arbitrary class derives an arbitrary trait in Rust.)
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7368
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Sun Jul 19, 2015 3:40 am UTC

I feel kind of proud of myself, right now:
Spoiler:

Code: Select all

class Template:

    def __init__(self, name, parent, *attributes):
        if attributes:
            for attribute in attributes:
                if not isinstance(attribute, str):
                    raise TypeError('attributes must be strings')
            attributes = frozenset(attributes)
        else:
            attributes = frozenset()
        if parent:
            try:
                parent.children.add(self)
            except AttributeError:
                raise TypeError('invalid parent')
        self.name = name
        self.attributes = attributes
        self.parent = parent
        self.children = set()

    def __eq__(self, other):
        try:
            if (self.__class__ == other.__class__ and
                self.name == other.name and
                self.attributes == other.attributes):
                return True
            return False
        except AttributeError:
            return False
           
    def __hash__(self):
        return hash((self.name, self.attributes))

The above code kept raising a TypeError ('invalid parent') the instant I created a template with another template as a parent -- no matter what. Took me a while to realize why:

AttributeError was going off because when I added the object to the set of its parent's children, it had to do an equality test against the set's members (to make sure it wasn't already an element!). When it went to do an equality test, it looked for attributes that I had yet to define (name and attributes). So, to fix, I just have to define those two attributes before I try to add the template to a set.

User avatar
Link
Posts: 1408
Joined: Sat Mar 07, 2009 11:33 am UTC
Location: ᘝᓄᘈᖉᐣ
Contact:

Re: Coding: Fleeting Thoughts

Postby Link » Sun Jul 19, 2015 1:38 pm UTC

I have a large amount of SVG files (all nearly identical) which I want to put on a single page in a simple rectangular tiled layout. This is pretty trivial to do with Inkscape using snapping, but considering the amount of files this is impractical. Does anyone know of any way to automate this? I basically want to be able to just say "the lower left corner of this SVG's bounding box should go to this coordinate", and I'm hoping that's simple enough that there's a pre-existing program or library that can do this without too much hassle. (In case of a library, I'd highly prefer Python, but C or C++ is also acceptable.)

User avatar
Xanthir
My HERO!!!
Posts: 5413
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Coding: Fleeting Thoughts

Postby Xanthir » Sun Jul 19, 2015 5:27 pm UTC

Use Flexbox? Like:

Code: Select all

<div class=container>
  <svg>...</svg>
  ...
</div>
<style>
.container {
  display: flexbox;
  flex-flow: row wrap;
}
.container svg {
  width: ...;
  height: ...;
  margin: ...;
}
</style>
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
PM 2Ring
Posts: 3713
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Sydney, Australia

Re: Coding: Fleeting Thoughts

Postby PM 2Ring » Mon Jul 20, 2015 8:43 am UTC

Link wrote:I have a large amount of SVG files (all nearly identical) which I want to put on a single page in a simple rectangular tiled layout.

I assume you want to tile all these files into a single SVG file, rather than into a HTML / XHTML Web page. If so, svg_stack may be helpful.
svg_stack wrote:svg_stack combines multiple SVG elements into a single SVG element. It can be called from the command line (less flexible) or called from the Python interface (more flexible).

This tool exists primarily exists to automatically composite SVG files into a single SVG file that remains compatible with Inkscape.

Disclaimer: I've never used svg_stack myself, but it looks good from the description. :)

OTOH, since your SVG files are all nearly identical it probably wouldn't be too hard to write a bit of Python to do the tiling yourself, assuming that the files were built in a sane fashion. :)
When writing SVG, I find the SVG Tutorial by Jakob Jenkov quite useful.

User avatar
Link
Posts: 1408
Joined: Sat Mar 07, 2009 11:33 am UTC
Location: ᘝᓄᘈᖉᐣ
Contact:

Re: Coding: Fleeting Thoughts

Postby Link » Mon Jul 20, 2015 3:38 pm UTC

PM 2Ring wrote:
Link wrote:I have a large amount of SVG files (all nearly identical) which I want to put on a single page in a simple rectangular tiled layout.

I assume you want to tile all these files into a single SVG file, rather than into a HTML / XHTML Web page. If so, svg_stack may be helpful.
svg_stack wrote:svg_stack combines multiple SVG elements into a single SVG element. It can be called from the command line (less flexible) or called from the Python interface (more flexible).

This tool exists primarily exists to automatically composite SVG files into a single SVG file that remains compatible with Inkscape.

Disclaimer: I've never used svg_stack myself, but it looks good from the description. :)
Yes! That looks like it's exactly what I want. I'll give it a try soon.

ETA: yep, it's perfect. Thanks!

PM 2Ring wrote:OTOH, since your SVG files are all nearly identical it probably wouldn't be too hard to write a bit of Python to do the tiling yourself, assuming that the files were built in a sane fashion. :)
When writing SVG, I find the SVG Tutorial by Jakob Jenkov quite useful.
Yeah, I can do it myself with a bit of Python, but I don't want to reinvent the wheel. I don't have the time to properly learn SVG at the moment.

User avatar
PM 2Ring
Posts: 3713
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Sydney, Australia

Re: Coding: Fleeting Thoughts

Postby PM 2Ring » Tue Jul 21, 2015 7:14 am UTC

Link wrote:ETA: yep, it's perfect. Thanks!

No worries. When you're done, it'd be great if you could let us know what you think of svg_stack.

Link wrote:
PM 2Ring wrote:OTOH, since your SVG files are all nearly identical it probably wouldn't be too hard to write a bit of Python to do the tiling yourself, assuming that the files were built in a sane fashion. :)
When writing SVG, I find the SVG Tutorial by Jakob Jenkov quite useful.
Yeah, I can do it myself with a bit of Python, but I don't want to reinvent the wheel. I don't have the time to properly learn SVG at the moment.

Fair enough. I've had a couple of goes of learning SVG. I haven't done anything with it since late last year, so I'm a bit rusty, but I still remember the basic principles & (most of) the main elements.

I totally agree that it's wise to not reinvent the wheel. OTOH, a "hand-rolled" program designed to process SVGs with a known structure may be able to produce more optimal output than a generic SVG tool, but I guess that depends on the structure of the input files, and the capabilities of svg_stack.

User avatar
Link
Posts: 1408
Joined: Sat Mar 07, 2009 11:33 am UTC
Location: ᘝᓄᘈᖉᐣ
Contact:

Re: Coding: Fleeting Thoughts

Postby Link » Wed Jul 22, 2015 6:34 am UTC

PM 2Ring wrote:
Link wrote:ETA: yep, it's perfect. Thanks!

No worries. When you're done, it'd be great if you could let us know what you think of svg_stack.

The Python API is quite powerful, though it's Python 2 only. It does what it's supposed to do, but unfortunately it appears to change the absolute sizes of the SVGs as seen in Inkscape ('course, since SVG is scalable, that doesn't have to be a problem). If you need to tabulate or stitch together hundreds of SVGs, then svg_stack is probably one of the easiest ways to do it. :)

User avatar
Xenomortis
Not actually a special flower.
Posts: 1448
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: Coding: Fleeting Thoughts

Postby Xenomortis » Wed Jul 22, 2015 9:26 am UTC

I have an Autocloseable class in Java that wraps a resource handle given by some library (to allow try with resource).
Writing a close() method that can throw an exception leaves a bad taste in my mouth.
But so does swallowing a library exception and simply logging an error.

I cannot decide which is more distasteful.
And in either case, the resource is likely leaked and I don't think there's much I can do about it.
Image

Ubik
Posts: 1016
Joined: Thu Oct 18, 2007 3:43 pm UTC

Re: Coding: Fleeting Thoughts

Postby Ubik » Wed Jul 22, 2015 9:38 am UTC

Looking at AutoCloseable, close() has "throws Exception" in its signature, so it throwing shouldn't be unexpected. Still not a nice thing, I agree.

User avatar
Xenomortis
Not actually a special flower.
Posts: 1448
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: Coding: Fleeting Thoughts

Postby Xenomortis » Wed Jul 22, 2015 9:53 am UTC

Here's the thing, any exception thrown by an automatically called close call (following a close block) is, I believe, suppressed and you're recommended to ensure the resource is released, which I can't do because it's the attempt to release that throws.

That is is, the library call "closeX( handle )" has a throws declaration without specifying circumstance.
In fact, all calls to this library can throw, even ones that look like they have no business throwing.
Image

Ubik
Posts: 1016
Joined: Thu Oct 18, 2007 3:43 pm UTC

Re: Coding: Fleeting Thoughts

Postby Ubik » Wed Jul 22, 2015 12:25 pm UTC

I just did some reading and a small try-with-resources test. The exception does get suppressed if something in the try block throws and the close() throws, in which case the exception thrown by close() is not lost, but attached to the primary exception from the try block. If only close() throws, the exception is the primary exception and nothing is attached to anything. In either case, the exception from close() does not seem to get completely lost, though it's probably easy to forget to check Throwable.getSuppressed() after an exception has been caught. (Maybe that was what you were referring to when mentioning the exception being suppressed?)

I haven't done much with try-with-resources or suppressed exceptions, so not trying to give a lesson, or anything like that - I think I got plenty of education from here myself.

User avatar
You, sir, name?
Posts: 6983
Joined: Sun Apr 22, 2007 10:07 am UTC
Location: Chako Paul City
Contact:

Re: Coding: Fleeting Thoughts

Postby You, sir, name? » Wed Jul 22, 2015 7:47 pm UTC

I have a vector<EntityRef> entities. I have a vector<int> collisionEntities.

This code does some hilariously bizarre things, it seems to happen when entities grows (I assume, it appears to happen after pushing 16 or so entries to entities)

Code: Select all

    collisionIndices.resize(entities.size(), 0);
    std::iota(collisionIndices.begin(), collisionIndices.end(), 0);
    std::sort(collisionIndices.begin(), collisionIndices.end(), [this](int a, int b) {
        return entities[a]->getBounds().center.x - entities[b]->getBounds().center.x;
    });

I get values of a and b that are literally all over the map. Anyone have a clue what might cause this? They *should* reasonably speaking
be bounded between 0<(a,b)<entities.size(). But the numbers I'm seeing look like random memory junk with a segfault as result.

This is virtually every operation I perform on entities

Code: Select all

    newEntities.clear();

    // (operation here that may add stuff to newEntities)

    entities.erase(
            std::remove_if(entities.begin(), entities.end(), isDead),
            entities.end());

    std::move(newEntities.begin(), newEntities.end(), std::back_inserter(entities));

    // here is the code above in the other [code] segment


--edit--

... and I immediately find the error after half an hour of head scratching leading up to this post. The lambda should return a < b, not a - b. I'm stuck in strcmp-land it seems...
I edit my posts a lot and sometimes the words wrong order words appear in sentences get messed up.

User avatar
WanderingLinguist
Posts: 237
Joined: Tue May 22, 2012 5:14 pm UTC
Location: Seoul
Contact:

Re: Coding: Fleeting Thoughts

Postby WanderingLinguist » Thu Jul 23, 2015 8:14 am UTC

I really wish Java had continuations.

I know there are some libraries that do it by messing with the bytecode, but it seems they only work with JVM.

If there were continuations that could be used on DVM/ART, it would make asynchronous task management on Android so much easier.

I mean something like "yield return" in C#.

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7368
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Thu Jul 23, 2015 12:02 pm UTC

I code as a hobby; I enjoy it. I enjoy both solving problems and exploring the limits of problems themselves; stretching my understanding around a problem until I see ways in which it may not be a problem at all.

That being said, I oscilliate between feeling good and bad about my hobby. On one hand, coding has taught me a lot of interesting things -- and it's fun! On the other hand, my hobby doesn't produce... well, anything. I have literally never compiled a single executable.

And... I'm not sure if I ever will? I mean, I want to -- but at a certain point I have to acknowledge this pattern: Something interests me. I make a project out of it, working toward some end. In investigating the means to that end, I'm left fascinated by the means -- and they become my end. As I investigate the means to this new end, I'm left fascinated by the means, and... so on. I get lost in abstracting abstractions and pursuing solutions to problems that emerged in trying to implement a solution for a different problem. I am perpetually refactoring everything I've written.

The most significant problem with my failure to produce is that it leaves me feeling deeply insecure about my hobby. Not in just a 'I hope I'm not terrible at this' kind of way -- but also in a 'I have no idea how to even tell if I'm terrible at this' kind of way. Among programmers, I sometimes feel like a philosophy major sitting in on a discussion between physicists and engineers -- all theory, no practice. And I don't even know if I'm good at the theory.

This uneasiness is reduced when I learn things about my own competence. Solving Project Euler problems tells me something. If I can recognize a bug in someone else's code, that also tells me something (I felt immensely pleased with myself when I suspected I had stumbled on a minor bug in Python's inspect module -- then looked it up and found out that it's confirmed). But I suspect the unease will not completely go away until I've broken the pattern I described above -- by building something that interests me -- and is functional.

Does anyone else have any experience with this sort of problem? Or similar feels regarding their competence? (Hearing that this problem is not unique to me also tells me something)
Last edited by The Great Hippo on Thu Jul 23, 2015 12:40 pm UTC, edited 1 time in total.

User avatar
Flumble
Yes Man
Posts: 2249
Joined: Sun Aug 05, 2012 9:35 pm UTC

Re: Coding: Fleeting Thoughts

Postby Flumble » Thu Jul 23, 2015 12:40 pm UTC

I'm a bit uneasy admitting it here, but, yes, I encounter the same pattern.
Well, except for the part where I did actually make some executables. (and batch programs when I was younger)

There's just so utterly many possibilities to solve a problem and insanely many choices to make along the way. And, because it's a computer, I get the impression that every choice has one best alternative, so it would be wise to investigate and compare all the alternatives.
The worst case is when the problem isn't clearly specified, in which case I'm free (=self-obliged) to extend the problem to no end.

User avatar
Yakk
Poster with most posts but no title.
Posts: 11128
Joined: Sat Jan 27, 2007 7:27 pm UTC
Location: E pur si muove

Re: Coding: Fleeting Thoughts

Postby Yakk » Thu Jul 23, 2015 2:43 pm UTC

WanderingLinguist wrote:I mean something like "yield return" in C#.

Well, C++ is getting them shortly, and Java not having something that both C# and C++ has usually results in a least a hacked together solution. ;)
One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision - BR

Last edited by JHVH on Fri Oct 23, 4004 BCE 6:17 pm, edited 6 times in total.

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7368
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Thu Jul 23, 2015 3:37 pm UTC

Flumble wrote:There's just so utterly many possibilities to solve a problem and insanely many choices to make along the way. And, because it's a computer, I get the impression that every choice has one best alternative, so it would be wise to investigate and compare all the alternatives.
Yeah -- I definitely have this problem. I keep thinking there's one perfect way to accomplish something (most modular, most clear, etc), and my current solution is sub-optimal.

User avatar
ucim
Posts: 6860
Joined: Fri Sep 28, 2012 3:23 pm UTC
Location: The One True Thread

Re: Coding: Fleeting Thoughts

Postby ucim » Thu Jul 23, 2015 5:23 pm UTC

The Great Hippo wrote:...and my current solution is sub-optimal.
'twill always be thus, because you can only optimize for one thing; that makes your anybody's code sub-optimal for all other things. And since your code is likely to be revised, you should probably make it optimal for revision. Make the computer do the work, so you can sit on the beach sipping mai-tais. Computers don't appreciate mai-tais or salt water. :)

To answer your original fleeting thought, I'm self taught. This means that there's a whole bunch of stuff I don't know, and I don't know what it is. Every new technique I learn is a technique I could have been using all along.

I'm also stuck in the past (after structured programming but before OOP took over), so I don't think in terms of objects (and have no clue what a lambda is). However, I seem to be extending my use of structs and associative arrays almost to the point where I wonder if I'm inventing OOP (badly). I suppose I could stop what I'm doing and learn a new paradigm, but then I'd have to stop what I'm doing (developing a web application), and though I like learning new things, I also like learning them in a useful context (like, doing what I'm doing). And I want to get what I'm doing done. So, there you have it.

Jose
Order of the Sillies, Honoris Causam - bestowed by charlie_grumbles on NP 859 * OTTscar winner: Wordsmith - bestowed by yappobiscuts and the OTT on NP 1832 * Ecclesiastical Calendar of the Order of the Holy Contradiction * Heartfelt thanks from addams and from me - you really made a difference.

User avatar
Xanthir
My HERO!!!
Posts: 5413
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Coding: Fleeting Thoughts

Postby Xanthir » Thu Jul 23, 2015 9:12 pm UTC

That's one reason I prefer working in the web - easier to produce programs that more than just myself can use and benefit from, reducing the time between "I have an idea" and "my idea is real and people are using it".
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
WanderingLinguist
Posts: 237
Joined: Tue May 22, 2012 5:14 pm UTC
Location: Seoul
Contact:

Re: Coding: Fleeting Thoughts

Postby WanderingLinguist » Fri Jul 24, 2015 5:54 am UTC

Yakk wrote:
WanderingLinguist wrote:I mean something like "yield return" in C#.

Well, C++ is getting them shortly, and Java not having something that both C# and C++ has usually results in a least a hacked together solution. ;)

Well, Java has a few hacked together solutions, but they all work by modifying the bytecode. That's all fine and good if you're running in the JVM, but Dalvik and ART (on Android) use a different bytecode format, so those hacks don't work. Meh.

Being that this is for an API that will be used by some large-ish companies in apps with millions of users, a hacked together solution is probably not a good idea anyway. It just would've made the API so much cleaner. Ah well.... maybe someday. In the meantime, I get to suffer in my jealousy of C++ and C# developers ;-)

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Fri Jul 24, 2015 9:52 pm UTC

The Great Hippo wrote:I code as a hobby; I enjoy it. I enjoy both solving problems and exploring the limits of problems themselves; stretching my understanding around a problem until I see ways in which it may not be a problem at all.

That being said, I oscilliate between feeling good and bad about my hobby. [...] But I suspect the unease will not completely go away until I've broken the pattern I described above -- by building something that interests me -- and is functional.

Does anyone else have any experience with this sort of problem? Or similar feels regarding their competence? (Hearing that this problem is not unique to me also tells me something)

Oh yes do I recognize this. I am part formally taught, part self-taught, and I love coding as something that can be a goal in itself. I have delivered end products, but only if there was some kind of external motivation, e.g. Project Euler, course assignments at university, the RSP and work. I have started countless other programming projects just for the fun of it, but none of them has led to an end product so far (well, at least not useful for somebody else). I guess when there is no external motivation, there isn't really any need for an end product anyway; you achieve your goal as soon as you start programming for fun. If you want the satisfaction of an end product instead (or in addition), you can look for an external source of motivation.

Donald Knuth is famous for doing a bit of both. He felt like writing a very thorough in-depth series of books on computer programming. He was dissatisfied with existing typesetting systems, so he decided to write his own first. The typesetting system took ten years of his life, and the end result was TeX. Then he could finally start writing his books, The Art of Computer Programming. If I'm right, part 4A is the last published; parts 4B, 4C, 5, 6 and 7 are still to come. If he survives long enough, part 7 might be done by about 2050.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
Xenomortis
Not actually a special flower.
Posts: 1448
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: Coding: Fleeting Thoughts

Postby Xenomortis » Sat Jul 25, 2015 8:27 pm UTC

A few hours ago, I wanted to write a small C++ program.
Somehow, I've ended up recompiling vim twice and am waiting for git to finish cloning the LLVM repository...

I hate software.
Image

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 6580
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

Re: Coding: Fleeting Thoughts

Postby Thesh » Sat Jul 25, 2015 10:19 pm UTC

They should make some sort of manager for software packages to simplify the process.
Summum ius, summa iniuria.

User avatar
Xenomortis
Not actually a special flower.
Posts: 1448
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: Coding: Fleeting Thoughts

Postby Xenomortis » Sat Jul 25, 2015 10:26 pm UTC

The idea of using software to fix problems caused by software does not fill me with confidence...
Although I've reached the compiling stage. And suddenly distributed binaries don't seem so bad.
Image

User avatar
Flumble
Yes Man
Posts: 2249
Joined: Sun Aug 05, 2012 9:35 pm UTC

Re: Coding: Fleeting Thoughts

Postby Flumble » Sat Jul 25, 2015 11:05 pm UTC

Xenomortis wrote:vim

Well, there's your problem, obviously. Butterflies are far more extensible, don't need recompiling and any error can be resolved at runtime. (data loss may occur, but that just means you didn't implement enough sanity checks and added enough backups)

But seriously, why would vim need recompiling? Aren't the highlighting and toolchain interfaces compiled into the default binary? What does vim do besides being a text editor (the only thing I know it does, since I exclusively use nano and eclipse)?

And hey look, LLVM provides binaries for every sensible platform. (except for a generic linux/*nix x86 binary)

User avatar
Xenomortis
Not actually a special flower.
Posts: 1448
Joined: Thu Oct 11, 2012 8:47 am UTC

Re: Coding: Fleeting Thoughts

Postby Xenomortis » Sat Jul 25, 2015 11:08 pm UTC

The distributed 64bit Windows binary for vim isn't up to date.
The LLVM recompile is something of an act of desperation.

For some context, I've been wanting to try out the clang_complete plugin for a while (C++ auto-complete provided by clang).
Turns out this isn't so easy.
Image

User avatar
firechicago
Posts: 621
Joined: Mon Jan 11, 2010 12:27 pm UTC
Location: One time, I put a snowglobe in the microwave and pushed "Hot Dog"

Re: Coding: Fleeting Thoughts

Postby firechicago » Sun Jul 26, 2015 11:59 am UTC

Xenomortis wrote: 64bit Windows


I think I see your problem. :P

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7368
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Sun Jul 26, 2015 1:28 pm UTC

I've finally started using unittest; it helps subdue my desire to refactor everything. Because the pattern tends to be that my code becomes very complex -- to a point where I no longer understand it in its totality -- and I stop trusting the outputs. Rather than building an extensive test every time that happens to make sure I can trust the outputs, I refactor, trying to make it clean and simple enough for me to understand why I can trust the outputs.

But now, with unittest, I can build a test model up as I build the code -- so even when it gets really complex, if I don't trust the outputs, I just run the unittest!

...now the only problem is I keep wanting to refactor my unittests to make sure I model all the inputs I can reasonably expect.

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Mon Jul 27, 2015 9:03 am UTC

Have you considered writing the tests before the code, instead of the other way around? If you write the test first, you write your code in order to make the test succeed, and once the test succeeds, you know you're done (for the time being, until you write a new test or change your mind about the contents of an existing test). If you do it the other way around, you are trying to write a test that checks everything your existing code does, even irrelevant implementation details. In the first case your tests work as a specification, in the second case your tests are like overly detailed regression tests.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
The Great Hippo
Swans ARE SHARP
Posts: 7368
Joined: Fri Dec 14, 2007 4:43 am UTC
Location: behind you

Re: Coding: Fleeting Thoughts

Postby The Great Hippo » Mon Jul 27, 2015 1:24 pm UTC

That might help a lot, for two reasons I can think of; first, it forces me to actually figure out what I want a component to do before I write it, and second, it solves this problem I've encountered with building my test cases where I'm not sure if the reason I'm getting an exception is because the code is wrong -- or the test is testing the wrong thing. I've had to stop a couple of times and debate whether or not the test really should consider a case to be a test failure.

Looking at my tests, I see a few of them perform introspection on the object they're testing ('test to make sure all the attributes were assigned properly after initialization'). I'm getting the sense a more 'build to the test' model of programming doesn't do this, because it doesn't matter what properties your object has so long as their behavior satisfies your needs?

My other question about unit tests: I've gotten the impression unittests should be entirely enclosed, each testing only one class in isolation. However, I've got two objects which work in conjunction -- object A accepts object B as a parameter for one of its methods, and returns a 'True' or 'False' based on a comparison of B to A. To test A, I create a Dummy of B and inject it with the attributes it needs to pass A's comparison method. But this requires that the test perform reflection on the Dummy class -- which means I'm building into the test itself how A looks at B.

Would it be better in cases like this to just test A and B in conjunction, as a single 'unit'? This is a small, special case; it shouldn't often come up (A is an observer, B is an observable thing).

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Mon Jul 27, 2015 2:40 pm UTC

It's neat how Azure (and probably other cloud services I don't have free credit for) is already set up for commonly used things like Node.js, and I just have to include a ".deployment" file and script to tell it which commands to run.

I just check that into GitHub and everything just auto-deploys.

That's neat. :mrgreen:

User avatar
Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

Re: Coding: Fleeting Thoughts

Postby Jplus » Tue Jul 28, 2015 6:21 am UTC

@Hippo: apart from the obvious aim to test everything that really matters, there are no hard rules in testing. Using a single testcase to test a single class or object in isolation is a sensible default, but if it doesn't work in some particular case, there is no reason why you should jump through hoops in order to somehow still test each class in isolation. I often find myself creating instances of other classes or running other functions in order to test a particular class or function. If two things are deeply intertwined, I can also imagine myself writing a single test or testcase for both. It's mostly a matter of emphasis; are you testing the interaction between the objects, or are you testing aspects of one object that happen to depend on another object? The unittest module is just a toolbox, so you can use it however you want.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

User avatar
Xeio
Friends, Faidites, Countrymen
Posts: 5101
Joined: Wed Jul 25, 2007 11:12 am UTC
Location: C:\Users\Xeio\
Contact:

Re: Coding: Fleeting Thoughts

Postby Xeio » Tue Jul 28, 2015 8:08 pm UTC

Xeio wrote:It's neat how Azure (and probably other cloud services I don't have free credit for) is already set up for commonly used things like Node.js, and I just have to include a ".deployment" file and script to tell it which commands to run.

I just check that into GitHub and everything just auto-deploys.

That's neat. :mrgreen:
I lied.

So like 20 commits later, I got it working, but apparently one of the NPM packages the project uses requires Node.exe to be in the path, which Azure doesn't do by default. And of course the error message is completely useless. Cue a bunch of commits printing to the deploy log to see what the hell is going on ad trying workarounds.

Relatedly, I learned that PATH is actually a command in Windows, so if you don't have SETX permissions that may work instead.

User avatar
Flumble
Yes Man
Posts: 2249
Joined: Sun Aug 05, 2012 9:35 pm UTC

Re: Coding: Fleeting Thoughts

Postby Flumble » Tue Jul 28, 2015 11:24 pm UTC

Today, I was trying to learn someone pure functions and mapping (both by example, teaching it by concept won't go anywhere since they can't grasp the idea of return values from a function at this point) in matlab.

As it turns out (as if you'd think otherwise), matlab is a horrible language for higher order functions. You'd guess resList = arrayfun(funcPtr, argList...) doesn't care what the inputs and outputs are, as long as they can be listified vectorized matricized list-like. But it turns out the funcPtr has to return a scalar.
Not that it would've worked out anyway, because I wanted the map to return [(Scalar a,Point a,Point a)], whereas matlab doesn't support vectors containing scalars and matrices containing scalars. So we used a for loop for now and finding the minimum while iterating.

So if anyone with matlab experience can show me a good way to write minimumBy (\(traitA,_,_) (traitB,_,_) -> compare traitA traitB) (map (someFunction constantArgument otherConstantArgument) inputList) the Matlab Way®, please do. In human talk: the practical example is that I want to check intersections between line segment AB and a list of segments and retrieve the intersection (and other information!) that's the closest to A. Preferably concise, outsourcing all the work to matlab functions and without an explicit for loop.
Oh and without any anonymous functions. I hate the syntax and they confuse the hell out of the other person.

Also, the shift to pure functions (passing around and not mutating values instead of overwriting global variables everywhere) seems like it slows down the simulation a lot. It is my pure (heh) guess that matlab is bad at optimizing function calls and recognizing non-mutated variables.

Lastly, it took me a day to find out matlab does have a function to get the magnitude of a vector: norm. It was neither length nor size and magnitude doesn't exist at all. Nor do normalize or unit exist for normalizing a vector. :cry:


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 13 guests