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.
 
  • Locked thread
Gothmog1065
May 14, 2009
Goddamnit, that is going to be the bane of my python existence. :eng99:

e: Okay, next thing. I have a 'counter' to see how many times it takes for you to get the answer. Here's the current label:

pre:
self.count_lbl = Label(self,
                       text = str(self.counter),
                       ).grid(row = 1, column = 3, sticky = W)
Each time I guess (And it's not correct), I have a self.counter += 1. Is there something else I should be doing to get this to update in the program?

Gothmog1065 fucked around with this message at 21:57 on May 19, 2011

Adbot
ADBOT LOVES YOU

Modern Pragmatist
Aug 20, 2008

Gothmog1065 posted:

Goddamnit, that is going to be the bane of my python existence. :eng99:

e: Okay, next thing. I have a 'counter' to see how many times it takes for you to get the answer. Here's the current label:

pre:
self.count_lbl = Label(self,
                       text = str(self.counter),
                       ).grid(row = 1, column = 3, sticky = W)
Each time I guess (And it's not correct), I have a self.counter += 1. Is there something else I should be doing to get this to update in the program?

From the Documentation it looks like you should put the following in your guessing method or wherever you want to change it.

code:
self.count_lbl.config(text=str(self.counter))
When you are initializing the label it only gets the current value of self.counter so you have to force it to update.

Gothmog1065
May 14, 2009
Okay, next problem: pygame. The book I'm using uses pygame and some other package, but I cannot for the life of me to get Pygame to install. At first, it throws the error that it doesn't exist, when I move the files over to the proper folder, I get this:

pre:
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import pygame
  File "C:\Python32\lib\site-packages\pygame\__init__.py", line 95, in <module>
    from pygame.base import *
ImportError: DLL load failed: %1 is not a valid Win32 application.
What am I doing wrong?

Modern Pragmatist
Aug 20, 2008
What exactly do you mean by this:

Gothmog1065 posted:

when I move the files over to the proper folder,

With windows, you should just run the installed and select C:\Python32 as the version that you want to install pygame for. You shouldn't have to move anything.

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.

Gothmog1065 posted:

Okay, next problem: pygame. The book I'm using uses pygame and some other package, but I cannot for the life of me to get Pygame to install. At first, it throws the error that it doesn't exist, when I move the files over to the proper folder, I get this:

pre:
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import pygame
  File "C:\Python32\lib\site-packages\pygame\__init__.py", line 95, in <module>
    from pygame.base import *
ImportError: DLL load failed: %1 is not a valid Win32 application.
What am I doing wrong?

What files did you move and where to?

I have a question. I'm starting to get into web scraping and while I can do searches and pull the results, I'm having trouble figuring out how to log into a specific page, zap2it.com, so I can get the schedule from my area.

Anyone have any advice?

edit: Got it. It was easier to do on the regular login screen compared to the popup.

If anyone cares, here's the code for the login section using mechanize

code:
br.open('http://tvlistings.zap2it.com/tvlistings/ZCLogin.do?method=getStandAlonePage')
br.select_form(nr=2)
br.form['username'] = 'your email address'
br.form['password'] = 'your password'
br.submit()

chemosh6969 fucked around with this message at 02:32 on May 21, 2011

Stabby McDamage
Dec 11, 2005

Doctor Rope
What is the best way to read a null-terminated string from a socket? Right now I'm looping on recv(1). I know I could do larger reads, but the stuff after the null-terminated string needs to be read by something else. Is recv(1) the only/best way?

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

Stabby McDamage posted:

What is the best way to read a null-terminated string from a socket? Right now I'm looping on recv(1). I know I could do larger reads, but the stuff after the null-terminated string needs to be read by something else. Is recv(1) the only/best way?
Wrap the socket in a class with a buffer. That class should have a read(size) method that tries to read from the buffer first, then if there's not enough buffered input, reads from the socket.

There might already be something like this in the standard library; if not, it's very easy to write.

Gothmog1065
May 14, 2009

Modern Pragmatist posted:

What exactly do you mean by this:


With windows, you should just run the installed and select C:\Python32 as the version that you want to install pygame for. You shouldn't have to move anything.

Okay, attaching what I see in the menu when it asks to select the python install. This happens no matter where I run the .msi, and if I select the first (or second) option, and put in c:\Python32\, it still doesn't install correctly. When it runs, it drops a \lib and \include folder, which I move to my python directory. Before I move it says there's no pygame module. If I move it it throws the error I pasted earlier.

Only registered members can see post attachments!

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.

Gothmog1065 posted:

Okay, attaching what I see in the menu when it asks to select the python install. This happens no matter where I run the .msi, and if I select the first (or second) option, and put in c:\Python32\, it still doesn't install correctly. When it runs, it drops a \lib and \include folder, which I move to my python directory. Before I move it says there's no pygame module. If I move it it throws the error I pasted earlier.



You're saying you have Python 3.2(c:\python32) installed but your pygame version is for Python 3.1. You need to get the matching version and then it will install in the right spot.

Gothmog1065
May 14, 2009

chemosh6969 posted:

You're saying you have Python 3.2(c:\python32) installed but your pygame version is for Python 3.1. You need to get the matching version and then it will install in the right spot.

Does the exact same thing on my machine that has 3.1.

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.

Gothmog1065 posted:

Does the exact same thing on my machine that has 3.1.

You should have a pygame folder in c;\python\lib\site-packages and in c:\python\include

Replace python with your actual python folder and also use the version of pygame with the version on python you have installed. There's a reason they have a different version of pygame for the different versions of python.

Gothmog1065
May 14, 2009

chemosh6969 posted:

You should have a pygame folder in c;\python\lib\site-packages and in c:\python\include

Replace python with your actual python folder and also use the version of pygame with the version on python you have installed. There's a reason they have a different version of pygame for the different versions of python.

c:\python31\Lib\site-packages\pygame
c:\python31\include\pygame

pre:
Python 3.1.3 (r313:86834, Nov 27 2010, 17:20:37) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import pygame
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import pygame
  File "C:\Python31\lib\site-packages\pygame\__init__.py", line 95, in <module>
    from pygame.base import *
ImportError: DLL load failed: %1 is not a valid Win32 application.
>>> 
e: I'm actually on the computer that started all this. Same thing.

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.

Gothmog1065 posted:

64 bit (AMD64

You installed the 64 bit version of python?

If you did, the pygame you downloaded was the 32 bit version. You'd need to either find an unofficial 64 bit version of pygame or install a 32 bit version of python. This happened to me.

chemosh6969 fucked around with this message at 18:22 on May 21, 2011

Grabulon
Jul 25, 2003

What's the easiest and cleanest way to install 2.7 on OS X? Seems to be a lot of different ways to do it.

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.

Grabulon posted:

What's the easiest and cleanest way to install 2.7 on OS X? Seems to be a lot of different ways to do it.

http://www.python.org/download/releases/2.7.1/

Download the first OS X file(not the one that says IDLE may not run) and install it.

At least that's how I'd do it.

Grabulon
Jul 25, 2003

chemosh6969 posted:

http://www.python.org/download/releases/2.7.1/

Download the first OS X file(not the one that says IDLE may not run) and install it.

At least that's how I'd do it.

And I won't have any issues with the built-in Python?

chemosh6969
Jul 3, 2004

code:
cat /dev/null > /etc/professionalism

I am in fact a massive asswagon.
Do not let me touch computer.

Grabulon posted:

And I won't have any issues with the built-in Python?

I'm assuming your path is pointing to that Python and you should be able to edit it to point to the new one or put 2.7 in front of it. I'm assuming it appends itself to the path at the rear.

You are able to have multiple versions of python installed and you can call whichever one you want to run whatever python file you have. So you'd be able to install 2.5 and 2.7 and not have any issues, as long as you know which one is being executed.

bitprophet
Jul 22, 2004
Taco Defender
If I needed 2.7 specifically (I don't, and just use the default system python + virtualenv), I'd use Homebrew's python package; Homebrew is completely distinct from the rest of the system, so it'd be quite easy to nuke/modify the Homebrew-installed version later without accidentally screwing up the built-in system Python.

All you need to do is ensure that `/usr/local` is on your path (eg `/usr/local/bin`, etc -- Homebrew install should make that all clear) and anything you install via Homebrew will take precedence over (but not replace or modify!) any builtin stuff.

jony neuemonic
Nov 13, 2009

As someone's who just learning Python (as a first language, no less!) is it worth installing anything above and beyond IDLE? I was considering Eclipse/PyDev just for the tabbed windows, but it looks like it might just make things overly confusing.

Gothmog1065
May 14, 2009

fidel sarcastro posted:

As someone's who just learning Python (as a first language, no less!) is it worth installing anything above and beyond IDLE? I was considering Eclipse/PyDev just for the tabbed windows, but it looks like it might just make things overly confusing.
As someone who is about two months ahead of you learning from scratch, use IDLE until you're comfortable, then use something fancier. A lot of the features of a good programming environment (Can't remember the term off the top of my head) didn't make sense until you actually know the code.

Modern Pragmatist
Aug 20, 2008

fidel sarcastro posted:

As someone's who just learning Python (as a first language, no less!) is it worth installing anything above and beyond IDLE? I was considering Eclipse/PyDev just for the tabbed windows, but it looks like it might just make things overly confusing.

IDLE or just using running python from the command line are really good for hacking away when first getting started to understand the basic datatypes, how to call methods etc. As soon as you start writing your own classes or basically doing any real programming, I would recommend avoiding IDLE. I personally use VIM but IMHO anything is better than IDLE.

brosmike
Jun 26, 2009

Gothmog1065 posted:

As someone who is about two months ahead of you learning from scratch, use IDLE until you're comfortable, then use something fancier. A lot of the features of a good programming environment (Can't remember the term off the top of my head) didn't make sense until you actually know the code.

Modern Pragmatist posted:

IDLE or just using running python from the command line are really good for hacking away when first getting started to understand the basic datatypes, how to call methods etc. As soon as you start writing your own classes or basically doing any real programming, I would recommend avoiding IDLE. I personally use VIM but IMHO anything is better than IDLE.

These are both good pieces of advice. I'll add in that even once you start doing fancier stuff, IDLE and the python command shell are great as REPLs to quickly test out very small ideas before you include them in your bigger project.

As for which IDE to switch to once you're a bit more comfortable with the language, I'm a fan of JetBrains' PyCharm. I think it's the best mix of intuitiveness and powerful features I've seen in a Python IDE. PyDev is another common suggestion, and it's not too bad, but I found it to be slightly clunkier and significantly worse at things like code completion than PyCharm. That said, it is totally free - PyCharm isn't (unless you're using it for a class or an "active" open source project).

Vim and Emacs also tend to come up when people ask this question. They're both extremely powerful and are really useful tools to be familiar with, and once you become good at using them they are both extremely efficient. That said, they also both have pretty steep learning curves and tend to require a lot of customization to bring them from "good" to "extremely effective". I'd say that either of their learning curves is significantly steeper than Python's itself, and would probably avoid them until/unless you find yourself wanting more than something like PyCharm or PyDev can offer.

e: vvvvvvvvvvvvvvvv I totally forgot about Pyscripter, but I used that before I tried PyCharm and thought it was slightly better than PyDev. Still not as good as PyCharm.

brosmike fucked around with this message at 04:12 on May 23, 2011

Lurchington
Jan 2, 2003

Forums Dragoon
When it gets to the point you're considering an IDE, I can't say enough great things about Pycharm (it's unfortunately not free, but there's 30 day free trial and free licensing for academics and Open Source developers)

Also, for free stuff, I liked:
- Pyscripter (windows only)
- SPE

I think that Pydev/eclipse is fine, but if you're not coming from a Java background (like me) the normal way Eclipse does things just isn't intuitive.

for the emacs/vi crowd, my opinion is: if you already know it, go right ahead, otherwise, there's a lot more to be gained from purpose-built tools for python editing. Basically, echoing what brosmike ^^^^^ said, since upon review, we're covering a lot of the same territory

Lurchington fucked around with this message at 03:37 on May 23, 2011

jony neuemonic
Nov 13, 2009

Thanks for the replies, guys. I'll stick with IDLE for now, maybe pony up for PyCharm later if I stick with it.

TK422
Dec 22, 2007

I hate being right
After helping a friend to cleanse a Wordpress installation that got pwned with an uploaded shell, I made some tiny host-based IDS to help noticing breaches like this.

Now at least response time to incidents will be shorter.

http://pastebin.com/kSsxH2s6

Suggestions on code style or design are welcome.

Captain Capacitor
Jan 21, 2008

The code you say?

TK422 posted:

After helping a friend to cleanse a Wordpress installation that got pwned with an uploaded shell, I made some tiny host-based IDS to help noticing breaches like this.

Now at least response time to incidents will be shorter.

http://pastebin.com/kSsxH2s6

Suggestions on code style or design are welcome.

Only thing I could suggest would be to use the actual logging module. That way you can just redirect it at will. Plus it makes things look cleaner in the long run.

That being said, it's a good idea and I like the simple implementation.

bakersk8r6301
Mar 24, 2008
Where are the bioinformaticians in here? Anyone know if there is another thread specifically for bioinformatics programming?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I've got an idea for a project bouncing around in my head, but there's one thing I don't know how to do...

Say I create a Django-based app that lets an end-user store stuff in a db. The db has several tables.

Now, lets say I'm going to host this application and people create accounts and each person stores their own stuff. Basically like how a bajillion other websites work...you create an account and stuff is tied to your account.

The thing I'm confused about is how you handle the multiple accounts. In a single-user scenario the end user would have several tables in the db, but it definitely seems inefficient to have the hundreds of millions of users of my super awesome application each having several tables of their own.

How do I design such a thing?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Thermopyle posted:

I've got an idea for a project bouncing around in my head, but there's one thing I don't know how to do...

Say I create a Django-based app that lets an end-user store stuff in a db. The db has several tables.

Now, lets say I'm going to host this application and people create accounts and each person stores their own stuff. Basically like how a bajillion other websites work...you create an account and stuff is tied to your account.

The thing I'm confused about is how you handle the multiple accounts. In a single-user scenario the end user would have several tables in the db, but it definitely seems inefficient to have the hundreds of millions of users of my super awesome application each having several tables of their own.

How do I design such a thing?

The answer to your question has nothing to do with Django or Python, it's basic database theory. You need to create tables that can be reused by multiple users, not create the same table with the same structure for each new user that joins. Each row in these tables would have a foreign key back to the user table, so you know who that row belongs to.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

MEAT TREAT posted:

The answer to your question has nothing to do with Django or Python, it's basic database theory. You need to create tables that can be reused by multiple users, not create the same table with the same structure for each new user that joins. Each row in these tables would have a foreign key back to the user table, so you know who that row belongs to.

Ok cool. That's actually what I was thinking about, but since I have zero experience in this area I didn't know if it was a good solution. Thanks.

FoiledAgain
May 6, 2007

I'm trying to install Python 2.6, and I'm getting this error:



I get that whether C:\\python26 exists before I start the install or not.

I'm using Windows 7 so this might be part of that bug which prevents you from turning off "read-only".

I want an older version of Python because I need NLTK. Should I just install 2.5, or is there a work-around here?

A A 2 3 5 8 K
Nov 24, 2003
Illiteracy... what does that word even mean?
Try to run the installer as an administrator. Or install it to a Linux VM through VirtualBox and bypass Windows altogether.

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.
Has anyone used the Django ORM bindings to MongoDB? How well do they work? I need to write a frontend to the network monitoring system I'm building.

Marvel
Jun 9, 2010

Lurchington posted:

When it gets to the point you're considering an IDE, I can't say enough great things about Pycharm

Here's an IDE panel from pycon 2011.

http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-python-ides-panel-4901374

FWIW, I use vim, but pycharm does look cool.

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
Completely unscientific, and mostly meaningless, but after seeing http://www.phpsadness.com/?page=sad/32 I decided to test python and got http://paste.pocoo.org/show/396426/

unixbeard
Dec 29, 2004

what do you guys think of this:

pre:
def bar():
    print "hoi"
    return None.x

class A(object):

    @property
    def foo(self):
        return bar()
    
    def __getattr__(self, a):
        print 'attribute %s not found' % (a,)
    
A().foo
it prints:

hoi
attribute foo not found

it seems like __getattribute__ is interpreting the AttributeError raised in bar() as a failed lookup for foo and calling __getattr__, which in theory shouldn't happen.

quaunaut
Sep 15, 2007

WHOOSH
Okay, so, directly quoting my Stack Overflow post because I have to solve this or I can't keep working:

Basically, I'm trying to get Django to simply allow me to use Twitter information as login/logout information, basing all of the accounts of my system off of Twitter accounts. Twitter and oauth are working wonderfully- Django isn't.

I'm constantly getting the following error:

Getting a 'AttributeError at /login/authenticated', 'User' object has no attribute 'backend'


From the research I've done, this tends to come across when you try to skip your call to authenticate(), which leads me to thinking that somehow that call is failing somehow, but it isn't telling me so. This is vaguely confirmed by the fact that I don't get the error at all, and get sent straight through, when I comment out the login line.

The code in question:

code:
def twitter_authenticated(request):
    # Step 1. Use the request token in the session to build a new client.
    token = oauth.Token(request.session['request_token']['oauth_token'],
                        request.session['request_token']['oauth_token_secret'])
    client = oauth.Client(consumer, token)
    
    # Step 2. Request the authorized access token from Twitter.
    resp, content = client.request(access_token_url, "GET")
    if resp['status'] != '200':
        print content
        raise Exception("Invalid response from Twitter.")
    
    """
    This is what you'll get back from Twitter. Note that it includes the
    user's user_id and screen_name.
    {
        'oauth_token_secret': 'IcJXPiJh8be3BjDWW50uCY31chyhsMHEhqJVsphC3M',
        'user_id': '120889797',
        'oauth_token': '120889797-H5zNnM3qE0iFoTTpNEHIz3noL9FKzXiOxwtnyVOD',
        'screen_name': 'heyismysiteup'
    }
    """
    
    access_token = dict(cgi.parse_qsl(content))
    
    # Step 3. Lookup the user or create them if they don't exist.
    try:
        user = User.objects.get(username=access_token['screen_name'])
    except User.DoesNotExist:
        # When creating the user I just use their [email]screen_name@twitter.com[/email]
        # for their email and the oauth_token_secret for their password.
        # These two things will likely never be used. Alternatively, you
        # can prompt them for their email here. Either way, the password
        # should never be used.
        user = User.objects.create_user(access_token['screen_name'], '%s@twitter.com' % access_token['screen_name'], access_token['oauth_token_secret'])
        
        # Save our permanent token and secret for later.
        profile = Profile()
        profile.user = user
        profile.oauth_token = access_token['oauth_token']
        profile.oauth_secret = access_token['oauth_token_secret']
        profile.save()
        
    # Authenticate the user and log them in using Django's pre-built
    # functions for these things.

    user = authenticate(username=access_token['screen_name'], password=access_token['oauth_token_secret'])
    login(request, user) #Comment this out to 'fix' the error.
    
    return HttpResponseRedirect('/')
Any ideas why that authenticate could be failing? I'm open to anything, and showing you absolutely any of my code(save my settings.py file unedited, of course). The oauth library I'm using is here.

brosmike
Jun 26, 2009

quaunaut posted:

Any ideas why that authenticate could be failing? I'm open to anything, and showing you absolutely any of my code(save my settings.py file unedited, of course). The oauth library I'm using is here.

Unlikely, but are you using a custom value for AUTHENTICATION_BACKENDS in your settings.py? Failing that, I'd say your best bet is to put a breakpoint on the authenticate() call and step through that - a cursory glance at its source code suggests that something pretty weird is happening if it's not returning None but also not setting the backend attribute.

quaunaut
Sep 15, 2007

WHOOSH

brosmike posted:

Unlikely, but are you using a custom value for AUTHENTICATION_BACKENDS in your settings.py? Failing that, I'd say your best bet is to put a breakpoint on the authenticate() call and step through that - a cursory glance at its source code suggests that something pretty weird is happening if it's not returning None but also not setting the backend attribute.

I'll see if I can't check next time I'm on my Ubuntu box if it's returning None or what. I saw that in the auth documentation.

Adbot
ADBOT LOVES YOU

raymond
Mar 20, 2004

unixbeard posted:

what do you guys think of this:

pre:
def bar():
    print "hoi"
    return None.x

class A(object):

    @property
    def foo(self):
        return bar()
    
    def __getattr__(self, a):
        print 'attribute %s not found' % (a,)
    
A().foo
it prints:

hoi
attribute foo not found

it seems like __getattribute__ is interpreting the AttributeError raised in bar() as a failed lookup for foo and calling __getattr__, which in theory shouldn't happen.

It sort of makes sense to me but I can't really explain it. Remove the property decorator and it will act as you initially expected. When you access a property, it runs the method. If an AttributeError is raised within that method, it is caught and then __getattr__ is called.

  • Locked thread