Coding: Fleeting Thoughts

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

Moderators: phlip, Moderators General, Prelates

User avatar
cemper93
Posts: 209
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby cemper93 » Wed May 01, 2013 5:55 pm UTC

Just started to learn Scheme. I wrote a Sudoku solver and it was AWESOME.

The only bad thing was that the method that does the actual recursing came out 46 lines long, and I don't know how to shorten it any further (well, except for grouping more statements on a single line, obviously). Though on second thought that's actually a good thing, because it gives me an excuse to learn even more Scheme!

Ciber
Posts: 126
Joined: Fri Mar 15, 2013 1:33 pm UTC

Re: Coding: Fleeting Thoughts

Postby Ciber » Thu May 02, 2013 11:55 pm UTC

I have a question that has been bugging me for a bit now, I cannot find an answer on the net and my prog teacher has no idea either.
The language is Python > Tkinter module > Canvas class > drawing methods.
For some strange reason I have to add 2 to all screen coordinates to get things to render where I expect them to.
As I understand it, the documentation states the the upper-left most pixel has the coordinates of (0,0), while the lower right most pixel has coords of (canvas_width -1, canvas_height - 1)
so to draw a box in a canvas that is 256 pixels square, I would have to use the code:
create_line(0,0,0,255)
create_line(0,0,255,0)
create_line(0,255,255,255)
create_line(255,0,255,255)

But the code which actually works is:
create_line(2,2,2,257)
create_line(2,2,257,2)
create_line(2,257,257,257)
create_line(257,2,257,257)

User avatar
phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Coding: Fleeting Thoughts

Postby phlip » Fri May 03, 2013 2:27 am UTC

Does the canvas have a border around it? Possibly 2 pixels wide? I'm not too familiar with Tk, but Google does find some words (not 100% sure they're relevant, since it seems it's for a different binding of Tk, but still, probably similar):
TkCmd docs wrote:Normally the origin of the canvas coordinate system is at the upper-left corner of the window containing the canvas. It is possible to adjust the origin of the canvas coordinate system relative to the origin of the window using the xview and yview widget commands; this is typically used for scrolling. Canvases do not support scaling or rotation of the canvas coordinate system relative to the window coordinate system.

Individual items may be moved or scaled using widget commands described below, but they may not be rotated.

Note that the default origin of the canvas's visible area is coincident with the origin for the whole window as that makes bindings using the mouse position easier to work with; you only need to use the canvasx and canvasy widget commands if you adjust the origin of the visible area. However, this also means that any focus ring (as controlled by the -highlightthickness option) and window border (as controlled by the -borderwidth option) must be taken into account before you get to the visible area of the canvas.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

Ciber
Posts: 126
Joined: Fri Mar 15, 2013 1:33 pm UTC

Re: Coding: Fleeting Thoughts

Postby Ciber » Fri May 03, 2013 3:43 am UTC

Nope, can't be that. All those options default to 0 and I even checked.
Consequentially, the thing I am programming is an extension of the canvas class which acts as a graph with options for:
x_min, x_max, y_min, y_max, grid_color, grid_y_space, grid_x_space, axis_color, func_color
In addition to all of the normal canvas attributes.
I am not going to tell you what all of those do cause I want to know if they are clear enough to be easily understood.

This is my current code if anyone wants to provide feedback.
Python 2.6
Spoiler:

Code: Select all

#Christopher Overbeck
#graph_v3.py
#In this version I try to inherit directly from the canvas class

from Tkinter import *
from math import *

class Graph(Canvas):
    """Placeholder"""
    def __init__(self, parent, **options):
        """Placeholder"""
        #Calling the init class of the base class like a baws.
        Canvas.__init__(self, parent)
        #Defining all the extra options that this widget adds.
        self.__graph_options = {"equation":"x",
                                "x_min":"-10",
                                "x_max":"10",
                                "y_min":"-10",
                                "y_max":"10",
                                "grid_color":"grey",
                                "grid_y_space":"1",
                                "grid_x_space":"1",
                                "axis_color":"black",
                                "func_color":"black"}
        #Calling our local config function to set up all of this objects properties.
        self.config(**options)

    def __str__(self):
        """Placeholder"""

    def draw(self):
        """Placeholder"""
        equation = str(self.get("equation"))
        width = int(self.get("width"))
        height = int(self.get("height"))
        x_min = float(self.get("x_min"))
        x_max = float(self.get("x_max"))
        y_min = float(self.get("y_min"))
        y_max = float(self.get("y_max"))
        x_scale = float((float(x_max) - float(x_min)) / float(width))
        y_scale = float((float(y_max) - float(y_min)) / float(height))

        O = 2 #Offset value that must be added to all coords to display them in the correct location. I have no idea why.
       
        self.delete(ALL)

        #Draw vertical lines to form a grid.
        for x in frange(0, x_max - x_min, self.get("grid_x_space")):
            pixel = int(x / x_scale)
            self.create_line(pixel+O, 0+O, pixel+O, height+O, fill= self.get("grid_color"))
        #Draw horizontal lines to form a grid.
        for y in frange(0, y_max - y_min, self.get("grid_y_space")):
            pixel = int(y / y_scale)
            self.create_line(O, pixel+O, width+O, pixel+O, fill= self.get("grid_color"))
        #Create X axis
        x_axis = int(ceil(y_max / y_scale))
        self.create_line(O, x_axis+O, width+O, x_axis+O, fill= self.get("axis_color"))
        #Create Y axis
        y_axis = int(floor((-1 * x_min) / x_scale))
        self.create_line(y_axis+O, O, y_axis+O, height+O, fill= self.get("axis_color"))

        #Fill "line" with a y coordinate for every x coordinate.
        line = []
        haz_had_error = 0 #Stops the console from being spammed with error messagges
        for pixel in range(width+1):
            #Finds the x value at a given pixel taking into account the difference between the window size and the canvas size.
            x = (pixel * x_scale) + x_min
            #Trys to convert the equations output back to a pixel value and prints an error message if it fails due to div by zero (very rare in this implementation) or invalid equations.     
            try:
                y = int(-1 * int(eval(equation) / y_scale) + y_max / y_scale)-1
                line.append(pixel+O)
                line.append(y+O)
                #print x, "|", y
               
            except:
                if haz_had_error == 0:
                    print "ERROR: Div by 0 or invalid equation."
                haz_had_error = 1

        self.create_line(line, fill= self.get("func_color"))
        #Calibration: WTF, why do I have to add 2 to all my measurements to get them to render like I expect them to?
        #self._canvas.create_line(2,2,2,257)
        #self._canvas.create_line(2,2,257,2)
        #self._canvas.create_line(2,257,257,257)
        #self._canvas.create_line(257,2,257,257)

    def config(self, **options):
        """Placeholder"""
        #Overwrites the current values for this classes extra options, and deleting them from options.
        for option in self.__graph_options:
            try:
                self.__graph_options[option] = options[option]
            except:
                None
            else:
                del(options[option])
        #Passing the options, now stripped of all the extras defined for this object, to the base classes config.
        Canvas.config(self,**options)
        #Updating the graph cause we probably just changed one of its properties.
        self.draw()

    def get(self, *args):
        """Takes a number of attribute names and returns their values in a tuple."""
        args = args
        values = []
        for arg in args:
            #seperates args that are defined localy an ones that were inherited from Canvas.
            if arg in self.__graph_options:
                values.append(self.__graph_options[arg])
            else:
                values.append(self.cget(arg))
        #Ensures that a tuple is only returned if more than one argument was requested.       
        values = tuple(values)
        if len(args) == 1:
            values = values[0]
               
        return values

def frange(x, y, jump):
    """Equivelant to the range function, but works with floats"""
    x = float(x)
    y = float(y)
    jump = float(jump)
    while x < y:
        yield x
        x += jump
   
def main():
    """Placeholder"""
    root = Tk()

    graph = Graph(root, axis_color= "lightgreen", bg= "black", func_color= "green")
    graph.pack()
    graph.config(x_max= "255", x_min= 0, width= 1024, height= 256, grid_color= "darkgreen")
    graph.config(equation= "sin(x/10)*10")
    graph.config(x_min= -.5, x_max= .5, y_min= -.5, y_max= .5, grid_x_space= .1, grid_y_space= .1)
    print graph.get("bg", "height", "x_max", "borderwidth")
   
    root.mainloop()

main()

raw_input("Press Enter to Exit.")


User avatar
xulaus
Posts: 136
Joined: Thu Jul 03, 2008 11:09 am UTC

Re: Coding: Fleeting Thoughts

Postby xulaus » Sat May 04, 2013 3:27 pm UTC

Using JavaScript and HTML5 is an awesome way to rapidly build and test ideas for algorithms that require graphics output. I'm glad I finally got round to playing with <canvas>
Meaux_Pas wrote:I don't even know who the fuck this guy is

User avatar
Aaeriele
Posts: 2127
Joined: Tue Feb 23, 2010 3:30 am UTC
Location: San Francisco, CA

Re: Coding: Fleeting Thoughts

Postby Aaeriele » Sat May 04, 2013 3:29 pm UTC

Yeah, canvas is actually pretty cool and well thought-out.
Vaniver wrote:Harvard is a hedge fund that runs the most prestigious dating agency in the world, and incidentally employs famous scientists to do research.

afuzzyduck wrote:ITS MEANT TO BE FLUTTERSHY BUT I JUST SEE AAERIELE! CURSE YOU FORA!

User avatar
tastelikecoke
Posts: 1208
Joined: Mon Feb 01, 2010 7:58 am UTC
Location: Antipode of Brazil
Contact:

Re: Coding: Fleeting Thoughts

Postby tastelikecoke » Fri May 10, 2013 5:46 am UTC

So while searching for a way to parse the C++ STL error messages, I found this:
Spoiler:
Image

C++ is freaking crazy.

That also reminds me of a question I asked one time.

What if do this:

Code: Select all

new vector<vector<int>> v(2,vector<int>());
v[0].push_back(1);

Do the whole vector of vectors get resized for that? Or is the vector of vectors only keeping a reference to those vector of ints?

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

Re: Coding: Fleeting Thoughts

Postby Ubik » Fri May 10, 2013 6:27 am UTC

In practice, yes. The vector (well, any std::vector) likely has just a pointer to the data along some size information stored in itself.

User avatar
jaap
Posts: 2094
Joined: Fri Jul 06, 2007 7:06 am UTC
Contact:

Re: Coding: Fleeting Thoughts

Postby jaap » Fri May 10, 2013 7:27 am UTC

tastelikecoke wrote:What if do this:

Code: Select all

new vector<vector<int>> v(2,vector<int>());
v[0].push_back(1);

Do the whole vector of vectors get resized for that? Or is the vector of vectors only keeping a reference to those vector of ints?


A vector is an object that contains a pointer to some array where its contents are stored. The vector object itself essentially consists of some bookkeeping data and this pointer. Therefore sizeof(vector) is constant, possibly about 24 bytes, regardless of how many elements are stored in it. The outer vector then uses a storage array with 24 bytes per element.

If you add something to one of the inner vectors, it might have to change the size of its storage array, but that is elsewhere in memory so the size of the inner vector object instance does not change. The outer vector does not change either.

It is in fact a requirement of arrays (and also of vectors because they use arrays) that all its elements have the same type, and that the size of that type is known at compile time, accessible via sizeof(type). This is the only way that pointer arithmetic can work. The one thing to look out for is object slicing so you should almost never have a vector or array of a class type that has other types derived from it.

User avatar
tastelikecoke
Posts: 1208
Joined: Mon Feb 01, 2010 7:58 am UTC
Location: Antipode of Brazil
Contact:

Re: Coding: Fleeting Thoughts

Postby tastelikecoke » Sun May 12, 2013 3:05 pm UTC

So I guess I'm not beheading kittens when I do the nested vectors, yay :D
One thing I liked about C++ is they let your objects be objects and not funky references, so no need for clone() or freaking copy.deepcopy(). I just wish they were consistent with the naming. For example, queue<T> has front(), priority_queue<T> has top(), and vector<T> has push_back()...

lgw
Posts: 437
Joined: Mon Apr 12, 2010 10:52 pm UTC

Re: Coding: Fleeting Thoughts

Postby lgw » Fri May 17, 2013 11:18 pm UTC

tastelikecoke wrote:So I guess I'm not beheading kittens when I do the nested vectors, yay :D
One thing I liked about C++ is they let your objects be objects and not funky references, so no need for clone() or freaking copy.deepcopy(). I just wish they were consistent with the naming. For example, queue<T> has front(), priority_queue<T> has top(), and vector<T> has push_back()...


Actually, nesting vectors in that particular way is pretty bad. Vectors are not (required by the standard to be) safe to copy. A vector generally copies its elements when it grows past a threshold. Using vector<vector<int>> could lead to very odd behavior indeed if you modified any of the ints. So, your objects need to be funky references, sad to say.

The upside of C++ is you can do vector<int> instead of ArrayList<Integer>, so you're not forced into using a nullable primitive type where it makes no sense. The downside is, because of explicit memory management, you need to be very careful of implicit copying. The upside is, shared_ptr<T> makes it all easy to do in practice. The downside is, you have to know about shared_ptr<T> and the sytax is way uglier than ArrayList<Integer>. The upside is, you can trivially define a MyVector<T> to be vector<shared_ptr<T>>. The downside is, people do stuff like that all the freaking time.

Yup, powerful but complicated, that's our C++. Also, std::algorithm really rocks.
"In no set of physics laws do you get two cats." - doogly

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

Re: Coding: Fleeting Thoughts

Postby Yakk » Sat May 18, 2013 12:50 am UTC

Huh? What kind of strange behavior?

In C++03 it had some performance issues, but C++11 fixed that.
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
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Fleeting Thoughts

Postby TheChewanater » Sat May 18, 2013 10:02 pm UTC

FT:

I just started learning Haskell. Is this sort of thing considered evil?

Code: Select all

data PointFunction = GetX | GetY | GetLength
makePoint 
:: Float -> Float -> PointFunction -> Float
makePoint x y GetX 
= x
makePoint x y GetY 
= y
makePoint x y GetLength 
= sqrt (x*+ y*y)

main =
    let point = makePoint 10 20 in do
        print 
(point GetX)
        print (point GetY)
        print (point GetLength) 


I'm not actually using this, just wondering.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

User avatar
b.i.o
Green is the loneliest number
Posts: 2519
Joined: Fri Jul 27, 2007 4:38 pm UTC
Location: Hong Kong

Re: Coding: Fleeting Thoughts

Postby b.i.o » Sun May 19, 2013 6:15 am UTC

That seems pretty weird: your data is represented as a function, and your functions are sort of represented as data. It's also pretty limiting. What you have here works right now, but if you ever want to write a function that returns something other than a Float this is going to have to change substantially. I'm also not really sure how you expect to be able to write functions that deal with multiple floats (like, say, comparison functions). You also don't get to use lots of standard idioms like function composition. And, as far as I can see, you're not gaining anything anyway, since Haskell functions are first-class.

So yes: don't do that, unless you have some really good reason to do so.

User avatar
3rdtry
Posts: 152
Joined: Sat Feb 16, 2013 1:46 pm UTC

Re: Coding: Fleeting Thoughts

Postby 3rdtry » Sun May 19, 2013 5:17 pm UTC

Python has a datetime module, that provides four classes: datetime, time (an idealized time, independent of any particular day), timedelta and tzinfo. OK. What I don't understand is why the now() method, that returns the current datetime, is inside the datetime class. Wouldn't it make more sense for it to be an external method on the same module (i.e. datetime.now() instead of datetime.datetime.now())? Or even something like datetime.datetime("now")?

Maelstrom.
Posts: 76
Joined: Tue Oct 21, 2008 12:18 pm UTC

Re: Coding: Fleeting Thoughts

Postby Maelstrom. » Sun May 19, 2013 11:45 pm UTC

3rdtry wrote:Python has a datetime module, that provides four classes: datetime, time (an idealized time, independent of any particular day), timedelta and tzinfo. OK. What I don't understand is why the now() method, that returns the current datetime, is inside the datetime class. Wouldn't it make more sense for it to be an external method on the same module (i.e. datetime.now() instead of datetime.datetime.now())? Or even something like datetime.datetime("now")?

Because there is also a datetime.date.today(), which returns a date, while datetime.datetime.now() returns a datetime. Having the method as a class method on the datetime class keeps everything contained nicely.

User avatar
Aaeriele
Posts: 2127
Joined: Tue Feb 23, 2010 3:30 am UTC
Location: San Francisco, CA

Re: Coding: Fleeting Thoughts

Postby Aaeriele » Mon May 20, 2013 5:17 am UTC

Also, the decision to name both the library and the class 'datetime' has made a lot of people very angry and has been widely regarded as a bad move.
Vaniver wrote:Harvard is a hedge fund that runs the most prestigious dating agency in the world, and incidentally employs famous scientists to do research.

afuzzyduck wrote:ITS MEANT TO BE FLUTTERSHY BUT I JUST SEE AAERIELE! CURSE YOU FORA!

Nyktos
Posts: 138
Joined: Mon Mar 02, 2009 4:02 pm UTC

Re: Coding: Fleeting Thoughts

Postby Nyktos » Mon May 20, 2013 4:47 pm UTC

Well, if you only need to work with datetime objects and not dates, times, or tzinfos, you can do "from datetime import datetime" and then now() comes along for free. Having it as a class method is pretty reasonable, since it is sort of a constructor.

User avatar
rath358
The bone of my bone
Posts: 945
Joined: Wed Jan 14, 2009 6:02 am UTC
Location: west Camberville

Re: Coding: Fleeting Thoughts

Postby rath358 » Tue May 21, 2013 6:35 pm UTC

TheChewanater:
What are you using to learn Haskell? I am going to learn it for a project this summer, and am looking for a good tutorial.
My friend has pointed me to Real World Haskell, but I am looking for alternatives in case it doesn't work well for me.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Tue May 21, 2013 7:50 pm UTC

There is also Learn You A Haskell. I can't comment on good/badness of it.

User avatar
cemper93
Posts: 209
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby cemper93 » Tue May 21, 2013 8:33 pm UTC

EvanED wrote:There is also Learn You A Haskell. I can't comment on good/badness of it.

I tried it, and I found it meh. The explanations aren't bad, plus it has nice cartoon figures, however, I found it lacked a common theme. It just progressed from issue to issue, sometimes going into ridiculous detail (like listing about fifty different higher-order functions from the standard library plus explanations of what they do, all nicely arranged below one another, without any further relation to one another), without ever really connecting the dots or giving real-life examples that would help doing that.

EDIT: I had quit trying to learn Haskell, but the ToC of Real World Haskell looks promising. I might try that.

User avatar
TheChewanater
Posts: 1279
Joined: Sat Aug 08, 2009 5:24 am UTC
Location: lol why am I still wearing a Santa suit?

Re: Coding: Fleeting Thoughts

Postby TheChewanater » Tue May 21, 2013 11:57 pm UTC

rath358 wrote:TheChewanater:
What are you using to learn Haskell? I am going to learn it for a project this summer, and am looking for a good tutorial.
My friend has pointed me to Real World Haskell, but I am looking for alternatives in case it doesn't work well for me.

From what I've seen, most tutorials are just ramblings about how great the authors think Haskell is, but "Learn You a Haskell" is still a good guide. I haven't finished it yet, but I would recommend it.
ImageImage
http://internetometer.com/give/4279
No one can agree how to count how many types of people there are. You could ask two people and get 10 different answers.

Maelstrom.
Posts: 76
Joined: Tue Oct 21, 2008 12:18 pm UTC

Re: Coding: Fleeting Thoughts

Postby Maelstrom. » Wed May 22, 2013 12:59 am UTC

cemper93 wrote:
EvanED wrote:There is also Learn You A Haskell. I can't comment on good/badness of it.

I tried it, and I found it meh. The explanations aren't bad, plus it has nice cartoon figures, however, I found it lacked a common theme. It just progressed from issue to issue, sometimes going into ridiculous detail (like listing about fifty different higher-order functions from the standard library plus explanations of what they do, all nicely arranged below one another, without any further relation to one another), without ever really connecting the dots or giving real-life examples that would help doing that.

EDIT: I had quit trying to learn Haskell, but the ToC of Real World Haskell looks promising. I might try that.

I found the same issue with LYAH. It was good to start with, but the chapter on the standard functions was just completely out of place and I couldnt get past it. I took a bit of a break, and then read Real World Haskell. Real World Haskell is not as great to start with in my opinion, as it is a bit too dense. Pairing the two tutorials, doing LYAH then Real World Haskell, is my suggestion. Then find a small project to do to learn Haskell for real.

User avatar
Aaeriele
Posts: 2127
Joined: Tue Feb 23, 2010 3:30 am UTC
Location: San Francisco, CA

Re: Coding: Fleeting Thoughts

Postby Aaeriele » Wed May 22, 2013 3:18 am UTC

Nyktos wrote:Well, if you only need to work with datetime objects and not dates, times, or tzinfos, you can do "from datetime import datetime" and then now() comes along for free. Having it as a class method is pretty reasonable, since it is sort of a constructor.


From someone who works professionally with Python, please never do "from datetime import datetime" in any code that is going to be maintained by more than just you. It leads to all sorts of confusion.
Vaniver wrote:Harvard is a hedge fund that runs the most prestigious dating agency in the world, and incidentally employs famous scientists to do research.

afuzzyduck wrote:ITS MEANT TO BE FLUTTERSHY BUT I JUST SEE AAERIELE! CURSE YOU FORA!

Maelstrom.
Posts: 76
Joined: Tue Oct 21, 2008 12:18 pm UTC

Re: Coding: Fleeting Thoughts

Postby Maelstrom. » Wed May 22, 2013 3:54 am UTC

Aaeriele wrote:
Nyktos wrote:Well, if you only need to work with datetime objects and not dates, times, or tzinfos, you can do "from datetime import datetime" and then now() comes along for free. Having it as a class method is pretty reasonable, since it is sort of a constructor.


From someone who works professionally with Python, please never do "from datetime import datetime" in any code that is going to be maintained by more than just you. It leads to all sorts of confusion.


This. I once worked on someone elses codebase. There was a mysterious error where `datetime.datetime.now()` threw an error of `datetime class has no attribute datetime`. Thinking someone did a `from datetime import datetime`, I looked at the imports, but there was only a `import datetime`. Strangely, though, the value of `datetime` was most certainly the `datetime` class.

Further on in the imports list was a `from foo import *`. The `foo` module did a `from datetime import datetime` which then overrode the previously imported `datetime` module :cry:

User avatar
Aaeriele
Posts: 2127
Joined: Tue Feb 23, 2010 3:30 am UTC
Location: San Francisco, CA

Re: Coding: Fleeting Thoughts

Postby Aaeriele » Wed May 22, 2013 4:09 am UTC

Aaack. I pretty much never use star imports, for that and other reasons.

Heck, I rarely use from imports nowadays, either. Between "import foo" and "import foo as bar", that's pretty much all I need.
Vaniver wrote:Harvard is a hedge fund that runs the most prestigious dating agency in the world, and incidentally employs famous scientists to do research.

afuzzyduck wrote:ITS MEANT TO BE FLUTTERSHY BUT I JUST SEE AAERIELE! CURSE YOU FORA!

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

Re: Coding: Fleeting Thoughts

Postby Link » Wed May 22, 2013 7:06 am UTC

Namespace poisoning is one of those things that make my skin crawl. Personally, I prefer to just not use star-imports (or even from-imports, unless it's for simple stuff), using namespace and other such malarkey if I can reasonably avoid it. I'm not too fond of typedefs either, but I do use them occasionally if when using them actually improves legibility (because 50-character type names with nested templates and calls to constexpr functions aren't exactly easy on the eyes). Also, in C, I abhor the typedef struct {...} my_struct; paradigm that many people seem to love. It's easy enough to just use struct my_struct {...}; and some_function (struct my_struct *foo) instead of some_function (my_struct *foo).

FWIW, my university uses Python with essentially all of NumPy, SciPy and Matplotlib star-imported by default, and it makes me want to Gibbs-slap someone.

Nyktos
Posts: 138
Joined: Mon Mar 02, 2009 4:02 pm UTC

Re: Coding: Fleeting Thoughts

Postby Nyktos » Thu May 23, 2013 3:03 am UTC

Maelstrom. wrote:
Aaeriele wrote:
Nyktos wrote:Well, if you only need to work with datetime objects and not dates, times, or tzinfos, you can do "from datetime import datetime" and then now() comes along for free. Having it as a class method is pretty reasonable, since it is sort of a constructor.


From someone who works professionally with Python, please never do "from datetime import datetime" in any code that is going to be maintained by more than just you. It leads to all sorts of confusion.


This. I once worked on someone elses codebase. There was a mysterious error where `datetime.datetime.now()` threw an error of `datetime class has no attribute datetime`. Thinking someone did a `from datetime import datetime`, I looked at the imports, but there was only a `import datetime`. Strangely, though, the value of `datetime` was most certainly the `datetime` class.

Further on in the imports list was a `from foo import *`. The `foo` module did a `from datetime import datetime` which then overrode the previously imported `datetime` module :cry:
I would blame the star import (from a module without an __all__, no less) for that, not the datetime import. But, eh, I won't deny that it's a reasonable objections.

User avatar
cemper93
Posts: 209
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby cemper93 » Thu May 23, 2013 5:12 pm UTC

Where we're talking about imports, I've recently done this:

Code: Select all

=== dog.py ===
def make_sound(): print("woof")

=== cat.py ===
def make_sound(): print("meow")

=== main.py ===
if NEED_DOG:
    import dog as animal
else:
    import cat as animal
animal.make_sound()

Of course, in this simple example, I should have just used classes for polymorphism. However, in my actual usecase, both my dog.py and cat.py contain dozens of functions and classes - all ultimately equal (it's two different backends which essentially do the same thing, and they will never be needed at the same time).

What do you say: acceptable pattern or not?

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Coding: Fleeting Thoughts

Postby EvanED » Thu May 23, 2013 8:13 pm UTC

It sounds a bit like, say, the os.path "module". (That's old source but presumably it looks about the same now. See lines 49, 63, 78, 80, 96, and 110, which switch between the different implementations.)

Is it like that? If so, I'd definitely say it's reasonable.

elminster
Posts: 1560
Joined: Mon Feb 26, 2007 1:56 pm UTC
Location: London, UK, Dimensions 1 to 42.
Contact:

Re: Coding: Fleeting Thoughts

Postby elminster » Thu May 23, 2013 9:36 pm UTC

Microsoft, Y U NO support initializer_list!
Ran into a few cases recently where it would be nice to use. In general there's been a number of things I've come across recently where I've thought "wouldn't it be nice if you could use this syntax", then google it only to find replies of "in C++0X you'll be able to do this" or "in C++11 you can do this"

On the plus side, their latest compiler supports variadic templates which can do some crazy stuff. In our case it solves a problem of packaging an arbitrary number of arbitrary pieces of data with compile time size calculations in very little code without predefining the collection of data.
Image

User avatar
cemper93
Posts: 209
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby cemper93 » Fri May 24, 2013 7:42 am UTC

EvanED wrote:It sounds a bit like, say, the os.path "module". (That's old source but presumably it looks about the same now. See lines 49, 63, 78, 80, 96, and 110, which switch between the different implementations.)

Is it like that? If so, I'd definitely say it's reasonable.

Yes, that's precisely what I was doing, just without the star imports. Cool, thanks!

User avatar
phlip
Restorer of Worlds
Posts: 7573
Joined: Sat Sep 23, 2006 3:56 am UTC
Location: Australia
Contact:

Re: Coding: Fleeting Thoughts

Postby phlip » Fri May 24, 2013 7:52 am UTC

I've also seen a couple of Python modules which have a heavily-optimised C implementation, and a more-portable (but slower) Python implementation, and they recommend you import it by:

Code: Select all

try:
    import cSomeLibrary as SomeLibrary
except ImportError:
    import SomeLibrary
For a more extreme example, look at the docs for lxml.

Code: Select all

enum ಠ_ಠ {°□°╰=1, °Д°╰, ಠ益ಠ╰};
void ┻━┻︵​╰(ಠ_ಠ ⚠) {exit((int)⚠);}
[he/him/his]

User avatar
cemper93
Posts: 209
Joined: Sun Feb 20, 2011 2:35 pm UTC
Location: `pwd`

Re: Coding: Fleeting Thoughts

Postby cemper93 » Fri May 24, 2013 7:58 am UTC

For a more extreme example, look at the docs for lxml.

Wut.

Not only that that looks so weird, they also catch the innermost failed import as well, which means that the code will even be run when no etree module could be imported at all. Which is just wrong.

User avatar
Nautilus
Posts: 105
Joined: Thu Feb 25, 2010 1:19 am UTC
Location: That's a strange place to put a piano

Re: Coding: Fleeting Thoughts

Postby Nautilus » Sat May 25, 2013 9:40 pm UTC

I want to compile v8 with emscripten and then run it recursively.

Javascript all the way down.
My flagella bring all the boys to the yard

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 May 28, 2013 9:51 pm UTC

Today I Learned: Construction of static fields in C# when the class does not have a static constructor are non-deterministically run, and only guaranteed to run at least at the last possible time prior to access.

This makes sense (I was mostly looking up how lazy/eager construction of static fields was), though I did not realize the mere existence of an empty static constructor changes the behavior to be deterministic.

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

Re: Coding: Fleeting Thoughts

Postby Thesh » Wed May 29, 2013 3:50 pm UTC

I hate the windows API. I was using the following function:

Code: Select all

BOOL WINAPI SetProcessAffinityMask(
  _In_  HANDLE hProcess,
  _In_  DWORD_PTR dwProcessAffinityMask
);


That DWORD_PTR parameter - that's neither a DWORD nor a PTR. Whereas a DWORD is always a 32-bit unsigned integer, that type is a 32 bit unsigned integer on a 32 bit system and a 64 bit unsigned integer on a 64 bit system.
Summum ius, summa iniuria.

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

Re: Coding: Fleeting Thoughts

Postby Xenomortis » Wed May 29, 2013 3:59 pm UTC

I would expect a type with the name DWORD_PTR to be 64 bits on a 64 bit system and 32 bits on a 32 bit system.
Image

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

Re: Coding: Fleeting Thoughts

Postby Thesh » Wed May 29, 2013 4:01 pm UTC

What would you expect WORD to be? The first "D" in DWORD stands for "Double."
Summum ius, summa iniuria.

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

Re: Coding: Fleeting Thoughts

Postby Ubik » Wed May 29, 2013 4:44 pm UTC

I'd say the PTR part is the meaningful one here, when it comes to the size of it. That said, that definitely isn't a very descriptive name for a type for that task. (Took a look at what that function does.)


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 9 guests