content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: QGraphicsView not displaying in QMainWindow I'm not sure why this application is not displaying anything. I'll reproduce in a few lines to provide the gist of the issue. Using PyQt4 class SomeScene(QtGui.QGraphicsScene): def __init__(self, parent = None): QtGui.QGraphicsScene.__init__(self, parent) ...
QGraphicsView not displaying in QMainWindow
I'm not sure why this application is not displaying anything. I'll reproduce in a few lines to provide the gist of the issue. Using PyQt4 class SomeScene(QtGui.QGraphicsScene): def __init__(self, parent = None): QtGui.QGraphicsScene.__init__(self, parent) pixmap = QtGui.QPixmap('someImage') # path ...
[ "The view is blank because the scene has been destroyed. The scene is destroyed if it is not stored in a member variable. The view does not take ownership of the scene since a scene can have multiple views. With the example below, the tmpScene will be destroyed (causing a \"tmpScene destroyed\" message to be printe...
[ 2 ]
[]
[]
[ "frameworks", "pyqt", "python", "qt", "user_interface" ]
stackoverflow_0003664129_frameworks_pyqt_python_qt_user_interface.txt
Q: Publishing to a Facebook Page Wall - With Graph API? I want to publish to the wall of a Facebook Fan Page, from a python/django web application. The new Graph API looks nice and simple, so I'd like to use that. Unless there is a much easier way :-) I'm guessing the pyFacebook package would do want I want, but it...
Publishing to a Facebook Page Wall - With Graph API?
I want to publish to the wall of a Facebook Fan Page, from a python/django web application. The new Graph API looks nice and simple, so I'd like to use that. Unless there is a much easier way :-) I'm guessing the pyFacebook package would do want I want, but it appears to use the old rest interface. pyFacebook is pro...
[ "If your fan page allows wall posts from any user in its settings, your app should be able to just post to <page_id>/feed\nIf you are fan page admin and want to post on fan page's wall on behalf of the page itself (without showing your name), then read about it here or in more details here.\n" ]
[ 6 ]
[]
[]
[ "django", "facebook", "facebook_graph_api", "python" ]
stackoverflow_0003664195_django_facebook_facebook_graph_api_python.txt
Q: What kind of python process to monitor a queueing system like kestrel or rabbitmq? I'm fairly new to python, and I was wondering what kind of application would you create to constanstly monitor a queueing service like kestrel or rabbitmq? How would it run, and under what context? Would it be a simple python scrip...
What kind of python process to monitor a queueing system like kestrel or rabbitmq?
I'm fairly new to python, and I was wondering what kind of application would you create to constanstly monitor a queueing service like kestrel or rabbitmq? How would it run, and under what context? Would it be a simple python script that would have a infinit while loop? I'm looking for a long running, stable python se...
[ "Sounds like you're wanting to implement an event loop. The simplest of these are indeed implemented with what's basically a while True: (and then having some shutdown handler that can break out of the loop if it's time to exit by request or some such).\n" ]
[ 0 ]
[]
[]
[ "python", "queue" ]
stackoverflow_0003664536_python_queue.txt
Q: Django Permissions and Security for Basic Chat App If I wanted to implement some sort of chat tool in my django webapp, implemented with basic ajax polling as opposed to comet, what should I do to secure it, besides running over SSL. Should I just use the permissions app for each chat session and generate a random...
Django Permissions and Security for Basic Chat App
If I wanted to implement some sort of chat tool in my django webapp, implemented with basic ajax polling as opposed to comet, what should I do to secure it, besides running over SSL. Should I just use the permissions app for each chat session and generate a random token to be accessed in my urlconf? Are there better/di...
[ "I think I could just make a room model with a ManytoMany Field indicating users, a queue for the chat history, and as users leave, I'd just remove their username from that model. So, when submitting post requests, I could just use the cookie in django.contrib.auth for sessions to validate data transfer. I think th...
[ 0 ]
[]
[]
[ "chat", "django", "permissions", "python", "security" ]
stackoverflow_0003664519_chat_django_permissions_python_security.txt
Q: Sqlalchemy seems to commit changes when it's not supposed to Consider the following snippet of Python code: from sqlalchemy import * from sqlalchemy.orm import * db = create_engine('postgresql:///database', isolation_level='SERIALIZABLE') Session = scoped_session(sessionmaker(bind=db, autocommit=False)) s = Sessio...
Sqlalchemy seems to commit changes when it's not supposed to
Consider the following snippet of Python code: from sqlalchemy import * from sqlalchemy.orm import * db = create_engine('postgresql:///database', isolation_level='SERIALIZABLE') Session = scoped_session(sessionmaker(bind=db, autocommit=False)) s = Session() s.add(SomeInstance()) s.flush() raw_input('Did it work? ') It...
[ "Nevermind, there was a bug in the psycopg2.py implementation in sqlalchemy 0.6.3; upgrading to 0.6.4 solved this problem.\n" ]
[ 2 ]
[]
[]
[ "postgresql", "python", "sqlalchemy" ]
stackoverflow_0003664624_postgresql_python_sqlalchemy.txt
Q: When using paster web server, does it service requests by creating a new thread? Does paster create a new thread per request? Can you set the maximum number of threads for paster to use i.e. a thread pool? How can you if this is possible? A: Per the docs, paster supports different server choices, depending on t...
When using paster web server, does it service requests by creating a new thread?
Does paster create a new thread per request? Can you set the maximum number of threads for paster to use i.e. a thread pool? How can you if this is possible?
[ "Per the docs, paster supports different server choices, depending on the configuration -- including wsgiutils, \"the start of support for twisted.web2 ... patches welcome\" (that would be an async server instad), and \"SCGI, FastCGI and AJP protocols, for connection an external web server (like Apache) to your app...
[ 1 ]
[]
[]
[ "paster", "python" ]
stackoverflow_0003664656_paster_python.txt
Q: What is the use of FieldStorage in Python I want to know whats the difference between FieldStorage in Python and wsgi_input? A: FieldStorage is useful in CGI contexts and can help in some other cases in which you want to do your own parsing and handling of (e.g.) a form posted (or also sent by a GET;-) to your s...
What is the use of FieldStorage in Python
I want to know whats the difference between FieldStorage in Python and wsgi_input?
[ "FieldStorage is useful in CGI contexts and can help in some other cases in which you want to do your own parsing and handling of (e.g.) a form posted (or also sent by a GET;-) to your server, without necessarily involving WSGI in any way. It provided a nicely accessible, somewhat dict-like object for accessing th...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003664742_python_python_3.x.txt
Q: Django profiling module error I have an error from the following code. I am sure it is obviuous to someone with more Python experience. This is a snippet from http://djangosnippets.org/snippets/727/ import sys import cProfile from cStringIO import StringIO from django.conf import settings class ProfilerMiddleware...
Django profiling module error
I have an error from the following code. I am sure it is obviuous to someone with more Python experience. This is a snippet from http://djangosnippets.org/snippets/727/ import sys import cProfile from cStringIO import StringIO from django.conf import settings class ProfilerMiddleware(object): def process_view(self...
[ "Thanks for your input Seth and Nick,\nI fixed it. I don't understand what caused it but it is to do with the order my middleware is called in. \nI debugged it based on Nick's comment that process_view hadn't been called to create the object. (I'm still not used to Python error messages to pick it up!) I got rid of...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003664817_django_python.txt
Q: Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx such filter, value_list or ... A: Probably most pythonic way: myset = Customer.objects.filter...
Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx
Django, What's the best ,fastest way to get only first and last element from something, Customer.objects.xxxx such filter, value_list or ...
[ "Probably most pythonic way:\nmyset = Customer.objects.filter(<something>).order_by(<something>)\nfirst, last = myset[0], myset.reverse()[0]\n\n", "\nWhat's the best ,fastest way to get only first and last \n\nLet us see. \ncustomers = Customer.objects.filter(**conditions)\nfirst = customers.order_by('id')[0]\nla...
[ 10, 4, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003664708_django_django_models_python.txt
Q: Python 3 I think I have a type mismatch but can't find it I'm using Python 3.1 to write a simple game involving naming state capitols. I think I have some kind of type mismatch but I don't know what it is. I think it's when I compare the player's answer to the real answer, but don't know how to make it right. fr...
Python 3 I think I have a type mismatch but can't find it
I'm using Python 3.1 to write a simple game involving naming state capitols. I think I have some kind of type mismatch but I don't know what it is. I think it's when I compare the player's answer to the real answer, but don't know how to make it right. from random import * states = {} print ("Guess State Capitols") ...
[ "You can use two \"prints\" to debug it:\nprint(playerguess)\nprint(states[guess])\n\nthis should give you the hint. \nI would say that when you got your capitol from your csv file you didnt take out the newline.\nSo maybe this will work:\nfor line in statefile:\n (state, capitol) = line.strip().split(\",\")\n ...
[ 2, 0 ]
[]
[]
[ "file_io", "python", "string" ]
stackoverflow_0003665538_file_io_python_string.txt
Q: How is Ruby more object-oriented than Python? Matz, who invented Ruby, said that he designed the language to be more object-oriented than Python. How is Ruby more object-oriented than Python? A: If you take the Python from 1993 and compare it with Ruby then the latter is more object oriented. However, after the ...
How is Ruby more object-oriented than Python?
Matz, who invented Ruby, said that he designed the language to be more object-oriented than Python. How is Ruby more object-oriented than Python?
[ "If you take the Python from 1993 and compare it with Ruby then the latter is more object oriented. However, after the overhaul in Python 2.2 this is no longer true. I'd say that modern Python is as object oriented as it gets.\n", "One example that's commonly given is len, which in Python is a built-in function. ...
[ 23, 17, 12 ]
[ "It's simple, nearly everything in Ruby (including numbers) is an object; there are no scalar values. \n" ]
[ -2 ]
[ "oop", "python", "ruby" ]
stackoverflow_0003665656_oop_python_ruby.txt
Q: How to create a simple mesh in Blender 2.50 via the Python API I would like to create a simple mesh in Blender (2.50) via the Python API but the examples from the API documentation don't work yet. I tried the following but it's from API 2.49 from Blender import * import bpy editmode = Window.EditMode() ...
How to create a simple mesh in Blender 2.50 via the Python API
I would like to create a simple mesh in Blender (2.50) via the Python API but the examples from the API documentation don't work yet. I tried the following but it's from API 2.49 from Blender import * import bpy editmode = Window.EditMode() # are we in edit mode? If so ... if editmode: Window.EditMode...
[ "Try this documentation for the 2.5x API. I understand that despite the big warnings at the top, the most used sections are fairly stable now. I've not tried it yet.\nEDIT:\nI think the relevant bit is this section - it seems you create a list of vertices faces etc. and pass it to this. This seems to have change...
[ 3, 1 ]
[]
[]
[ "blender", "blender_2.50", "python" ]
stackoverflow_0003657120_blender_blender_2.50_python.txt
Q: How to uniqufy the tuple element? i have a result tuple of dictionaries. result = ({'name': 'xxx', 'score': 120L }, {'name': 'xxx', 'score': 100L}, {'name': 'yyy', 'score': 10L}) I want to uniqify it. After uniqify operation result = ({'name': 'xxx', 'score': 120L }, {'name': 'yyy', 'score': 10L}) The result cont...
How to uniqufy the tuple element?
i have a result tuple of dictionaries. result = ({'name': 'xxx', 'score': 120L }, {'name': 'xxx', 'score': 100L}, {'name': 'yyy', 'score': 10L}) I want to uniqify it. After uniqify operation result = ({'name': 'xxx', 'score': 120L }, {'name': 'yyy', 'score': 10L}) The result contain only one dictionary of each name an...
[ "from operator import itemgetter\n\nnames = set(d['name'] for d in result)\nuniq = []\nfor name in names:\n scores = [res for res in result if res['name'] == name]\n uniq.append(max(scores, key=itemgetter('score')))\n\nI'm sure there is a shorter solution, but you won't be able to avoid filtering the scores b...
[ 2, 2, 1, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003665414_algorithm_python.txt
Q: Separating URL from http request I am studying Python language. I want to know about splitting HTTP request GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1 Host: www.explainth.at User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11 Accept: text/xml,text/htm...
Separating URL from http request
I am studying Python language. I want to know about splitting HTTP request GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1 Host: www.explainth.at User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11 Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*...
[ "It's not clear why you want to do this, what the context or goal is, or how this data is arriving in your program. However, Python supports a number of useful string operations on its string type. So if you have a string containing all of this text, then you may find the splitlines method useful, along with some...
[ 1, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003666610_python_twisted.txt
Q: What is the best way to implement web services in Python? What is the best way to implement web services in Python? A: There are two main flavors of web services: RESTful SOAP based (old article) I suggest you look into the RESTful stuff first. IMO, it is generally simpler to produce and/or consume a RESTful s...
What is the best way to implement web services in Python?
What is the best way to implement web services in Python?
[ "There are two main flavors of web services:\n\nRESTful\nSOAP based (old article)\n\nI suggest you look into the RESTful stuff first. IMO, it is generally simpler to produce and/or consume a RESTful service, than it is to use SOAP.\n" ]
[ 1 ]
[]
[]
[ "python", "rest", "soap", "web_services" ]
stackoverflow_0003666854_python_rest_soap_web_services.txt
Q: Python: Testing if a value is present in a defaultdict list I want test whether a string is present within any of the list values in a defaultdict. For instance: from collections import defaultdict animals = defaultdict(list) animals['farm']=['cow', 'pig', 'chicken'] animals['house']=['cat', 'rat'] I want t...
Python: Testing if a value is present in a defaultdict list
I want test whether a string is present within any of the list values in a defaultdict. For instance: from collections import defaultdict animals = defaultdict(list) animals['farm']=['cow', 'pig', 'chicken'] animals['house']=['cat', 'rat'] I want to know if 'cow' occurs in any of the lists within animals. 'cow' ...
[ "defaultdict is no different from a regular dict in this case. You need to iterate over the values in the dictionary:\nany('cow' in v for v in animals.values())\n\nor more procedurally:\ndef in_values(s, d):\n \"\"\"Does `s` appear in any of the values in `d`?\"\"\"\n for v in d.values():\n if s in v:...
[ 12, 0 ]
[ "This example will flatten the list, checking each element and will return True or False as follows:\n>>> from collections import defaultdict \n>>> animals = defaultdict(list) \n>>> animals['farm']=['cow', 'pig', 'chicken'] \n>>> animals['house']=['cat', 'rat']\n\n>>> 'cow' in [x for y in animals.values() for x ...
[ -1 ]
[ "collections", "dictionary", "list", "python" ]
stackoverflow_0003667411_collections_dictionary_list_python.txt
Q: how to write regex starts and ends with particular string? How to write regex for this paricular situation. Here letters in [] is not fixed but letters without [] is fixed. http://www.abc.com/fixed/[any small letters]/[anyletters]/fixed.html A: http://www.abc.com/fixed/[a-z]+/[a-zA-Z]+/fixed.html Possibly chan...
how to write regex starts and ends with particular string?
How to write regex for this paricular situation. Here letters in [] is not fixed but letters without [] is fixed. http://www.abc.com/fixed/[any small letters]/[anyletters]/fixed.html
[ "http://www.abc.com/fixed/[a-z]+/[a-zA-Z]+/fixed.html\n\nPossibly change to a more forgiving:\nhttp://www.abc.com/fixed/[a-z]+/[^/]+/fixed.html\n\n", "You can use lookarounds for that. One problem may be that they are not available in every language. For instance Javascript has only positive lookahead.\nOh, you m...
[ 4, 0 ]
[]
[]
[ "mysql", "python", "regex" ]
stackoverflow_0003667599_mysql_python_regex.txt
Q: Appengine retrieve data related to user form submission I had read the docs for Appengine to know how to retrieve data from Models. But i´m missing something.. My models are user and student, where student is a reference property from user. Users login, fill form with some values and save the data with put(). If ...
Appengine retrieve data related to user form submission
I had read the docs for Appengine to know how to retrieve data from Models. But i´m missing something.. My models are user and student, where student is a reference property from user. Users login, fill form with some values and save the data with put(). If you login with test@example.com you get your data or if you l...
[ "If your Student model looks like this:\nclass Student(db.Model):\n user = db.UserProperty()\n name = db.StringProperty()\n address = db.StringProperty()\n\nThen you probably want something like this:\nuser = users.get_current_user() \nif user: \n student = models.Student.all().filter('user =', user).ge...
[ 3 ]
[]
[]
[ "bigtable", "google_app_engine", "python", "reportlab" ]
stackoverflow_0003667332_bigtable_google_app_engine_python_reportlab.txt
Q: Converting from list of tuples to list of lists of tuples Possible Duplicate: How do you split a list into evenly sized chunks in Python? I have list of tuples, each tuple has two items (the amount of tuples may vary). [(a, b), (c, d)...)] I want to convert the list to a nested list of tuples so that each neste...
Converting from list of tuples to list of lists of tuples
Possible Duplicate: How do you split a list into evenly sized chunks in Python? I have list of tuples, each tuple has two items (the amount of tuples may vary). [(a, b), (c, d)...)] I want to convert the list to a nested list of tuples so that each nested list contains 4 tuples, if the original list of tuples has q...
[ ">>> lst = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12), (13, 14), (15, 16), (17, 18)]\n>>> [lst[i:i+4] for i in xrange(0, len(lst), 4)]\n[[(1, 2), (3, 4), (5, 6), (7, 8)], [(9, 10), (11, 12), (13, 14), (15, 16)], [(17, 18)]]\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003667581_python.txt
Q: What's the correct way to store an object in a Model property? I need to store a Django template object in a Model property. My solution so far has been to pickle the object before assigning it to a BlobProperty : entity.template_blob = pickle.dumps(template) entity.put() And then after a fetch from the datastore...
What's the correct way to store an object in a Model property?
I need to store a Django template object in a Model property. My solution so far has been to pickle the object before assigning it to a BlobProperty : entity.template_blob = pickle.dumps(template) entity.put() And then after a fetch from the datastore, I do : template = pickle.loads(entity.template_blob) Am I doing t...
[ "You've got it right. Pickling to a blob is the standard solution for this problem.\nThere isn't a built-in property that automatically handles the serialization / deserialization, but the PickleProperty in aetycoon will do this for you.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003666680_google_app_engine_google_cloud_datastore_python.txt
Q: Removing non-ascii characters from any given stringtype in Python >>> teststring = 'aõ' >>> type(teststring) <type 'str'> >>> teststring 'a\xf5' >>> print teststring aõ >>> teststring.decode("ascii", "ignore") u'a' >>> teststring.decode("ascii", "ignore").encode("ascii") 'a' which is what i really wanted it to st...
Removing non-ascii characters from any given stringtype in Python
>>> teststring = 'aõ' >>> type(teststring) <type 'str'> >>> teststring 'a\xf5' >>> print teststring aõ >>> teststring.decode("ascii", "ignore") u'a' >>> teststring.decode("ascii", "ignore").encode("ascii") 'a' which is what i really wanted it to store internally as i remove non-ascii characters. Why did the decode("as...
[ "\nWhy did the decode(\"ascii\") give out a unicode string?\n\nBecause that's what decode is for: it decodes byte strings like your ASCII one into unicode.\nIn your second example, you're trying to \"decode\" a string which is already unicode, which has no effect. To print it to your terminal, though, Python must e...
[ 4, 4 ]
[]
[]
[ "non_ascii_characters", "python", "replace", "string", "unicode" ]
stackoverflow_0003667875_non_ascii_characters_python_replace_string_unicode.txt
Q: Are order of keys() and values() in python dictionary guaranteed to be the same? Does native built-in python dict guarantee that the keys() and values() lists are ordered in the same way? d = {'A':1, 'B':2, 'C':3, 'D':4 } # or any other content otherd = dict(zip(d.keys(), d.values())) Do I always have d == otherd...
Are order of keys() and values() in python dictionary guaranteed to be the same?
Does native built-in python dict guarantee that the keys() and values() lists are ordered in the same way? d = {'A':1, 'B':2, 'C':3, 'D':4 } # or any other content otherd = dict(zip(d.keys(), d.values())) Do I always have d == otherd ? Either it's true or false, I'm interested in any reference pointer on the subject. ...
[ "\nKeys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, ...
[ 30, 4 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003666237_dictionary_python.txt
Q: Python smtp connection is always failed in a VMware Windows machine I m trying to use smtp class from Python 2.6.4 to send smtp email from a WinXP VMware machine. After the send method is called, I always got this error: socket.error: [Errno 10061] No connection could be made because the target machine actively re...
Python smtp connection is always failed in a VMware Windows machine
I m trying to use smtp class from Python 2.6.4 to send smtp email from a WinXP VMware machine. After the send method is called, I always got this error: socket.error: [Errno 10061] No connection could be made because the target machine actively refused it. Few stuff I noticed: The same code works in the physical WinXP...
[ "The phrase \"...because the target machine actively refused it\" usually means there's a firewall that drops any unauthorized connections. Is there a firewall service on the SMTP server that's blocking the WinXP VM's IP address?\nOr, more likely: Is the SMTP server not configured to accept relays from the WinXP VM...
[ 2 ]
[]
[]
[ "email", "python", "smtp", "vmware" ]
stackoverflow_0003664438_email_python_smtp_vmware.txt
Q: earliest commonly used version of Python Is there an officially updated recommendation indicating which versions of Python should be supported by released modules? Or perhaps a page giving a survey of production usage of various versions? It's difficult to know how much use to make of newish features like contex...
earliest commonly used version of Python
Is there an officially updated recommendation indicating which versions of Python should be supported by released modules? Or perhaps a page giving a survey of production usage of various versions? It's difficult to know how much use to make of newish features like context managers, class decorators, etc. when writin...
[ "I'm not aware of any single resource keeping an up-to-date summary of production usage of different Python versions, but a good start would probably be to check which Python versions that are distributed with various Linux distributions. Here's a sample for some of the most used server distributions (taken from D...
[ 6, 0 ]
[]
[]
[ "backwards_compatibility", "python", "version" ]
stackoverflow_0003666750_backwards_compatibility_python_version.txt
Q: Python decorator to refresh cursor instance I have a method to save data in DB, and a decorator to manage the connection, but I can't figure out how to make it work. method to save: class DA_Row(DABase): @DABase.connectAndDisconnect def save(self): """ Guarda el spin en la base de datos ...
Python decorator to refresh cursor instance
I have a method to save data in DB, and a decorator to manage the connection, but I can't figure out how to make it work. method to save: class DA_Row(DABase): @DABase.connectAndDisconnect def save(self): """ Guarda el spin en la base de datos """ self.__cursor.callproc('sp_inse...
[ "self is just a name like everything else, it does not magically appear like Java's this. You need to add it to your decorator. Try this:\n @staticmethod\n def connectAndDisconnect(func):\n # deco will be a method, so it needs self (ie a DA_Row instance)\n def deco(self, *args):\n ret...
[ 4, 2 ]
[]
[]
[ "connection", "decorator", "python" ]
stackoverflow_0003668254_connection_decorator_python.txt
Q: Sorting a sublist within a Python list of integers I have an unsorted list of integers in a Python list. I want to sort the elements in a subset of the full list, not the full list itself. I also want to sort the list in-place so as to not create new lists (I'm doing this very frequently). I initially tried p[i:j]...
Sorting a sublist within a Python list of integers
I have an unsorted list of integers in a Python list. I want to sort the elements in a subset of the full list, not the full list itself. I also want to sort the list in-place so as to not create new lists (I'm doing this very frequently). I initially tried p[i:j].sort() but this didn't change the contents of p presum...
[ "You can write p[i:j] = sorted(p[i:j])\n", "This is because p[i:j] returns a new list. I can think of this immediate solution:\nl = p[i:j]\nl.sort()\na = 0\nfor x in range(i, j):\n p[x] = l[a]\n a += 1\n\n" ]
[ 28, 0 ]
[ "\"in place\" doesn't mean much. You want this.\np[i:j] = list( sorted( p[i:j] ) ) \n\n" ]
[ -6 ]
[ "python" ]
stackoverflow_0003668930_python.txt
Q: Dropping a file onto a script to run as argument causes exception in Vista edit:OK, I could swear that the way I'd tested it showed that the getcwd was also causing the exception, but now it appears it's just the file creation. When I move the try-except blocks to their it actually does catch it like you'd think ...
Dropping a file onto a script to run as argument causes exception in Vista
edit:OK, I could swear that the way I'd tested it showed that the getcwd was also causing the exception, but now it appears it's just the file creation. When I move the try-except blocks to their it actually does catch it like you'd think it would. So chalk that up to user error. Original Question: I have a script I'...
[ "Seeing as this is probably not Python related, but a Windows problem (I for one could not reproduce the error given your code), I'd suggest attaching a debugger to the Python interpreter when it is started. Since you start the interpreter implicitly by a drag&drop action, you need to configure Windows to auto-atta...
[ 1, 1 ]
[]
[]
[ "arguments", "drag_and_drop", "exception_handling", "python", "windows_vista" ]
stackoverflow_0003661948_arguments_drag_and_drop_exception_handling_python_windows_vista.txt
Q: Python Regular Expressions - Complete Match for my CGI application I'm writing a function to get the browser's preferred language (supplied in the HTTP_ACCEPT_LANGUAGE variable). I want to find all language tags in this variable with regular expressions (The general pattern of a language tag is defined in RFC1766)...
Python Regular Expressions - Complete Match
for my CGI application I'm writing a function to get the browser's preferred language (supplied in the HTTP_ACCEPT_LANGUAGE variable). I want to find all language tags in this variable with regular expressions (The general pattern of a language tag is defined in RFC1766). EBNF from RFC1766 ('1*8ALPHA' means one to eigh...
[ "You can use the ?: operator to prevent the regex engine from saving bracketed subpatterns:\n((?:[a-z]{1,8})(?:-[a-z]{1,8})*)\n\nThis gives the output:\nre.findall(\"((?:[a-z]{1,8})(?:-[a-z]{1,8})*)\", \"x-pig-latin en-us de-de en\", re.IGNORECASE)\n['x-pig-latin', 'en-us', 'de-de', 'en']\n\nTo answer your question...
[ 4, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003669236_python_regex.txt
Q: Problem with deepcopy(ing) a TypedList class inheriting from list and overriding append I don't understand why the new instance of the TypeList class does not have a my_type attribute. Here is my code: import copy class TypedList(list): def __init__(self, typeof, iterable=''): """ Initialize t...
Problem with deepcopy(ing) a TypedList class inheriting from list and overriding append
I don't understand why the new instance of the TypeList class does not have a my_type attribute. Here is my code: import copy class TypedList(list): def __init__(self, typeof, iterable=''): """ Initialize the typed list. Examples: tmp = TypedList(str, 'foobar') # OK tmp = T...
[ "I just tested your script with Python 2.5 and Python 2.7 and it works:\nimport copy\n\nclass TypedList(list):\n\n def __init__(self, typeof, iterable=''):\n \"\"\" Initialize the typed list.\n\n Examples:\n tmp = TypedList(str, 'foobar') # OK\n tmp = TypedList('str', 'foobar') # FAIL!\n \"\"\"\n ...
[ 0 ]
[]
[]
[ "deep_copy", "python" ]
stackoverflow_0003669396_deep_copy_python.txt
Q: Converting Unicode objects with non-ASCII symbols in them into strings objects (in Python) I want to send Chinese characters to be translated by an online service, and have the resulting English string returned. I'm using simple JSON and urllib for this. And yes, I am declaring. # -*- coding: utf-8 -*- on top of...
Converting Unicode objects with non-ASCII symbols in them into strings objects (in Python)
I want to send Chinese characters to be translated by an online service, and have the resulting English string returned. I'm using simple JSON and urllib for this. And yes, I am declaring. # -*- coding: utf-8 -*- on top of my code. Now everything works fine if I feed urllib a string type object, even if that object c...
[ "When you get a unicode object and want to return a UTF-8 encoded byte string from it, use theobject.encode('utf8').\nIt seems strange that you don't know whether the incoming object is a str or unicode -- surely you do control the call sites to that function, too?! But if that is indeed the case, for whatever wei...
[ 8 ]
[]
[]
[ "python", "string", "unicode", "unicode_string", "urllib" ]
stackoverflow_0003669436_python_string_unicode_unicode_string_urllib.txt
Q: Are there existing python modules for dealing with / normalizing units of time represented as strings? I am new to python and am doing an export and import to a new db. I have a column on my export (to be imported) of strings for units of time, "20 minutes" "1.5 hours" "2 1/2 hours", etc. I tried googling but cou...
Are there existing python modules for dealing with / normalizing units of time represented as strings?
I am new to python and am doing an export and import to a new db. I have a column on my export (to be imported) of strings for units of time, "20 minutes" "1.5 hours" "2 1/2 hours", etc. I tried googling but couldn't really find any good phrases and kept coming up with information more related to datetime units rather...
[ "For the first two formats it looks like you can use the excellent 3rd-party module dateutil, e.g.:\n>>> from dateutil import parser\n>>> dt = parser.parse('1.5 hours') # returns `datetime` object\n>>> t = dt.time()\n>>> t\ndatetime.time(1, 30)\n\nThis doesn't appear to work for \"2 1/2 hours\", however.\n" ]
[ 1 ]
[]
[]
[ "normalization", "python", "time" ]
stackoverflow_0003669635_normalization_python_time.txt
Q: Imaging library that supports 16bit tiffs I had been using using PIL but I just found out that it doesn't support 16bit tiffs. I need a library that can do: 1)Image conversion -->16bit tiff to jpeg 2)Image resize and crop and of jpegs A: ImageMagick supports 16bit Tiffs, and they have a wrapper for Python calle...
Imaging library that supports 16bit tiffs
I had been using using PIL but I just found out that it doesn't support 16bit tiffs. I need a library that can do: 1)Image conversion -->16bit tiff to jpeg 2)Image resize and crop and of jpegs
[ "ImageMagick supports 16bit Tiffs, and they have a wrapper for Python called PythonMagick.\n" ]
[ 2 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0003669746_image_processing_python.txt
Q: I have text files in multiple languages. How to selectively delete one language in NLTK? Maybe this is just impossible and I should give up all hope. Or maybe there's a really clever way to do it that I haven't thought of. Here's two examples of what I've got: يَبِسَ - يَيْبَسُ (yabisa, yaybasu)[y-b-s][ي-ب-س] (...
I have text files in multiple languages. How to selectively delete one language in NLTK?
Maybe this is just impossible and I should give up all hope. Or maybe there's a really clever way to do it that I haven't thought of. Here's two examples of what I've got: يَبِسَ - يَيْبَسُ (yabisa, yaybasu)[y-b-s][ي-ب-س] (To become dry, stiff, rigid) 20:77 yabasan = dry. يَسَّرَ - يُيَسِّرُ (yassara, yuyassir...
[ "You can use nltk.NaiveBayesClassifier to do the job exactly as you said above.\nThe following link should help:\nhttp://nltk.googlecode.com/svn/trunk/doc/book/ch06.html\nIt has an example of using nltk.NaiveBayesClassifier for gender identification. you use the same for language identification.\nThe first example ...
[ 2 ]
[]
[]
[ "localization", "nlp", "nltk", "python" ]
stackoverflow_0003570939_localization_nlp_nltk_python.txt
Q: python distutils, writing c extentions with generated source code I have written a Python extension library in C and I am currently using distutils to build it. I also have a Python script that generates a .h file, which I would like to include with my extension. Is it possible to setup a dependency like this with...
python distutils, writing c extentions with generated source code
I have written a Python extension library in C and I am currently using distutils to build it. I also have a Python script that generates a .h file, which I would like to include with my extension. Is it possible to setup a dependency like this with distutils? Will it be able to notice when my script changes, regenerat...
[ "You can do this by overrinding build_ext command from distutils.\nfrom distutils.core import setup, Extension\nfrom distutils.command.build_ext import build_ext as _build_ext\n\nmodule=Extension(....) # The way to build your extension\n\nclass build_ext(_build_ext):\n description = \"Custom Build Process\"\n\n ...
[ 0 ]
[]
[]
[ "c", "distutils", "python" ]
stackoverflow_0003517301_c_distutils_python.txt
Q: Accessing variables by their names in a tuple I need to access variables given their names, in the following way: a = numpy.array([1,2,3]) b = numpy.array([4,5,6]) names = ('a', 'b') Then, I pass the variable names to a function, say numpy.hstack() to obtain the same result as with numpy.hstack((a,b)). What is th...
Accessing variables by their names in a tuple
I need to access variables given their names, in the following way: a = numpy.array([1,2,3]) b = numpy.array([4,5,6]) names = ('a', 'b') Then, I pass the variable names to a function, say numpy.hstack() to obtain the same result as with numpy.hstack((a,b)). What is the best pythonic way to do so? And what is the purpo...
[ "You can use the built-in function locals, which returns a dictionary representing the local namespace:\n>>> a = 1\n>>> locals()['a']\n1\n\n>>> a = 1; b = 2; c = 3\n>>> [locals()[x] for x in ('a','b','c')]\n[1, 2, 3]\n\nYou could also simply store your arrays in your own dictionary, or in a module.\n", "If i unde...
[ 2, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003669651_python.txt
Q: Quick test if web-page offer asynchronous HTTP? I am fetching current data from another company's web feed. It is a simple fetch of an XML file over HTTP. They haven't provided me with much documentation - just a URL. Because I need to know as soon as possible when the data changes on their site, I need to poll fr...
Quick test if web-page offer asynchronous HTTP?
I am fetching current data from another company's web feed. It is a simple fetch of an XML file over HTTP. They haven't provided me with much documentation - just a URL. Because I need to know as soon as possible when the data changes on their site, I need to poll frequently, which isn't a satisfactory solution for eit...
[ "I suggest you read this Wikipedia article on the subject. What you want is certainly possible, however it may not be supported by all browsers.\nThat said... I generally recommend against push technologies on the web, as they sap the resources of a server much faster than a request/response paradigm. \nPerhaps the...
[ 1, 1, 1, 1 ]
[]
[]
[ "asynchronous", "http", "python", "xmlhttprequest" ]
stackoverflow_0003668827_asynchronous_http_python_xmlhttprequest.txt
Q: Skip python "import" statements in exuberant ctags if I have two files file a.py: class A(): pass file b.py: from a import A b = A() When I use ctags and press Ctrl+] in vim, it redirects me to import statement, not to class definition. In this code all is ok: file a.py: class A(): pass file b.py: from ...
Skip python "import" statements in exuberant ctags
if I have two files file a.py: class A(): pass file b.py: from a import A b = A() When I use ctags and press Ctrl+] in vim, it redirects me to import statement, not to class definition. In this code all is ok: file a.py: class A(): pass file b.py: from a import * b = A()
[ "You can add the following line to your ~/.ctags file.\n\n--python-kinds=-i\n\nto have ctags skip indexing import statements. To see what else you can enable/disable:\n\nctags --list-kinds=python\n\n", "I use a mapping similar to the following which allows me to choose when there are multiple matches for a given ...
[ 57, 1 ]
[]
[]
[ "exuberant_ctags", "python", "vim" ]
stackoverflow_0003609433_exuberant_ctags_python_vim.txt
Q: python multi threading/ multiprocess code In the code below, I am considering using mutli-threading or multi-process for fetching from url. I think pools would be ideal, Can anyone help suggest solution.. Idea: pool thread/process, collect data... my preference is process over thread, but not sure. import urlli...
python multi threading/ multiprocess code
In the code below, I am considering using mutli-threading or multi-process for fetching from url. I think pools would be ideal, Can anyone help suggest solution.. Idea: pool thread/process, collect data... my preference is process over thread, but not sure. import urllib URL = "http://download.finance.yahoo.com/d/q...
[ "So here's a very simple example. It iterates over symbols passing one at a time to fetch_quote.\nimport urllib\nimport multiprocessing\n\nURL = \"http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv\"\nsymbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')\n#symbols = ('GGP')\n\ndef fet...
[ 1, 1, 0 ]
[ "As you would know multi-threading in Python is not actually multi-threading due to GIL. Essentially it's a single thread that's running at a given time. So in your program if you want multiple urls to be fetched at any given time, multi-threading might not be the way to go. Also after the crawl you store the data ...
[ -1 ]
[ "multiprocess", "multithreading", "python" ]
stackoverflow_0003669791_multiprocess_multithreading_python.txt
Q: Pymedia installation on Windows with Python 2.6 I am trying to install latest version of Pymedia from sources. I have Python2.6 and there is no binary available. Started with: python setup.py build and got the following messages: Using WINDOWS configuration... Path for OGG not found. Path for VORBIS not found...
Pymedia installation on Windows with Python 2.6
I am trying to install latest version of Pymedia from sources. I have Python2.6 and there is no binary available. Started with: python setup.py build and got the following messages: Using WINDOWS configuration... Path for OGG not found. Path for VORBIS not found. Path for FAAD not found. Path for MP3LAME not fou...
[ "Somebody has done it, if you're just after pymedia for python2.6 on windows:\nHave a look here:\nhttp://www.lfd.uci.edu/~gohlke/pythonlibs/\nThere's also a version for python2.7\n", "You need to install all of those modules separately, in a similar fashion (python setup.py install).\nThose other modules are just...
[ 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002141701_python.txt
Q: Using Windows 7 taskbar features in PyQt I am looking for information on the integration of some of the new Windows 7 taskbar features into my PyQt applications. Specifically if there already exists the possibility to use the new progress indicator (see here) and the quick links (www.petri.co.il/wp-content/uploads...
Using Windows 7 taskbar features in PyQt
I am looking for information on the integration of some of the new Windows 7 taskbar features into my PyQt applications. Specifically if there already exists the possibility to use the new progress indicator (see here) and the quick links (www.petri.co.il/wp-content/uploads/new_win7_taskbar_features_8.gif). If anyone c...
[ "As quark said, the functionality is not in Qt 4.5, but you can call the windows API directly from Qt. Its a little bit of work though.\n\nThe new taskbar API is exposed through COM, so you can't use ctypes.windll . You need to create a .tlb file to access the functions. Get the interface definition for ITaskbarLis...
[ 23, 5, 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "taskbar", "windows_7" ]
stackoverflow_0001736394_pyqt_pyqt4_python_taskbar_windows_7.txt
Q: Python - Make Script to Manipulate Windows File Paths but running on Linux I have this script which processes lines containing windows file paths. However the script is running on Linux. Is there a way to change the os library to do Windows file path handling while running on linux? I was thinking something like...
Python - Make Script to Manipulate Windows File Paths but running on Linux
I have this script which processes lines containing windows file paths. However the script is running on Linux. Is there a way to change the os library to do Windows file path handling while running on linux? I was thinking something like: import os os.pathsep = '\\' (which doesn't work since os.pathsep is ; for som...
[ "Look at the ntpath module\nOn Linux, I did:\n>> import ntpath \n>> ntpath.split(\"c:\\windows\\i\\love\\you.txt\")\n('c:\\\\windows\\\\i\\\\love', 'you.txt')\n>> ntpath.splitext(\"c:\\windows\\i\\love\\you.txt\")\n('c:\\\\windows\\\\i\\\\love\\\\you', '.txt')\n>> ntpath.basename(\"c:\\windows\\i\\love\\you.tx...
[ 7, 3, 1 ]
[]
[]
[ "filesystems", "linux", "python", "windows" ]
stackoverflow_0003670673_filesystems_linux_python_windows.txt
Q: Django ORM, filtering objects by type with model inheritence So I have two models... Parent and Child. Child extends Parent. When I do Parent.objects.all(), I get both the Parents and the Children. I only want Parents Is there a Parent.objects.filter() argument I can use to only get the Parent objects instead of t...
Django ORM, filtering objects by type with model inheritence
So I have two models... Parent and Child. Child extends Parent. When I do Parent.objects.all(), I get both the Parents and the Children. I only want Parents Is there a Parent.objects.filter() argument I can use to only get the Parent objects instead of the objects that extend parent?
[ "I've found a better way to solve this, using the django ORM and without the need for any changes to your models (such as an ABC):\n\nclass Parent(models.Model):\n field1 = models.IntegerField()\n field2 = models.IntegerField()\n\nclass Child(Parent):\n field3 = models.IntegerField()\n\n#Return all Parent ...
[ 13, 4, 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001447742_django_django_models_python.txt
Q: Parsing FLV header (duration) of remote file in Java I'm looking for an example of parsing an FLV header for duration specifically in Java. Given the URL of an FLV file I want to download the header only and parse out the duration. I have the FLV spec but I want an example. Python or PHP would be OK too but Java i...
Parsing FLV header (duration) of remote file in Java
I'm looking for an example of parsing an FLV header for duration specifically in Java. Given the URL of an FLV file I want to download the header only and parse out the duration. I have the FLV spec but I want an example. Python or PHP would be OK too but Java is preferred.
[ "Do you have problems downloading the header or parsing it? if it's downloading then use this code:\nURL url = new URL(fileUrl);\nInputStream dis = url.openStream();\nbyte[] header = new byte[HEADER_SIZE];\ndis.read(header);\n\nYou can wrap InputStream with DataInputStream if you want to read int's rather than byte...
[ 1, 0 ]
[]
[]
[ "flash", "flv", "java", "python" ]
stackoverflow_0001313640_flash_flv_java_python.txt
Q: how to select a long list of id's in sql using python I have a very large db that I am working with, and I need to know how to select a large set of id's which doesn't have any real pattern to them. This is segment of code I have so far: longIdList = [1, 3, 5 ,8 ....................................] for id in long...
how to select a long list of id's in sql using python
I have a very large db that I am working with, and I need to know how to select a large set of id's which doesn't have any real pattern to them. This is segment of code I have so far: longIdList = [1, 3, 5 ,8 ....................................] for id in longIdList sql = "select * from Table where id = %s" %id ...
[ "Yes, you can use SQL's IN() predicate to compare a column to a set of values. This is standard SQL and it's supported by every SQL database.\nThere may be a practical limit to the number of values you can put in an IN() predicate before it becomes too inefficient or simply exceeds a length limit on SQL queries. ...
[ 6, 4, 3 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0003670961_python_sql.txt
Q: Working around Python bug in different versions I've come across a bug in Python (at least in 2.6.1) for the bytearray.fromhex function. This is what happens if you try the example from the docstring: >>> bytearray.fromhex('B9 01EF') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeErro...
Working around Python bug in different versions
I've come across a bug in Python (at least in 2.6.1) for the bytearray.fromhex function. This is what happens if you try the example from the docstring: >>> bytearray.fromhex('B9 01EF') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: fromhex() argument 1 must be unicode, not str Thi...
[ "For cases like this it's good to remember that a try block is very cheap if no exception is thrown. So I'd use:\ntry:\n x = bytearray.fromhex(some_str)\nexcept TypeError:\n # Work-around for Python 2.6 bug \n x = bytearray.fromhex(unicode(some_str))\n\nThis lets Python 2.6 work with a small performance hi...
[ 8, 3 ]
[]
[]
[ "python", "python_2.6", "python_2.7" ]
stackoverflow_0003670816_python_python_2.6_python_2.7.txt
Q: How, to prevent image cache by browser? in my Pylons app i write a script to autogenerate thumbnail, from image geting by url. To generate thumbnail i use PIL(python) W wont to prevent image cache by browser. I can't use after src ?[random_number] because the site, where i past this image must be static. I try t...
How, to prevent image cache by browser?
in my Pylons app i write a script to autogenerate thumbnail, from image geting by url. To generate thumbnail i use PIL(python) W wont to prevent image cache by browser. I can't use after src ?[random_number] because the site, where i past this image must be static. I try to send headers response.headers['Cache-Contr...
[ "Traditionally, you need additional headers to catch most browsers, and even then some will still cache it. Even browsers that support the Cache-Control header (which is part of HTTP 1.1) may be connecting through an HTTP 1.0 proxy that strips out nonstandard headers. I'd try also adding an explicit Expires header ...
[ 0 ]
[]
[]
[ "caching", "image", "python", "python_imaging_library" ]
stackoverflow_0003671321_caching_image_python_python_imaging_library.txt
Q: BeautifulSoup chokes on paths with back slashes I wrote a script to automate the process of creating an image gallery. I used os.path.join() for creating paths to new image directories. I only relized after creating all the galleries that using os.path.join() was not such a good idea as it creates paths with \ (on...
BeautifulSoup chokes on paths with back slashes
I wrote a script to automate the process of creating an image gallery. I used os.path.join() for creating paths to new image directories. I only relized after creating all the galleries that using os.path.join() was not such a good idea as it creates paths with \ (on windows) which causes problems with firefox (it does...
[ "In this case, per the comments, it appears that the problem can be solved with a\nglobal substitution of / for \\:\nimport fileinput\nimport sys\nfor line in fileinput.input(['test.html'], inplace=True, backup='.bak'):\n sys.stdout.write(line.replace('\\\\','/'))\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "path", "python" ]
stackoverflow_0003662213_beautifulsoup_path_python.txt
Q: Problems accessing a variable which is casted into pointer to array of int with ctypes in python I have C code which uses a variable data, which is a large 2d array created with malloc with variable size. Now I have to write an interface, so that the C functions can be called from within Python. I use ctypes for t...
Problems accessing a variable which is casted into pointer to array of int with ctypes in python
I have C code which uses a variable data, which is a large 2d array created with malloc with variable size. Now I have to write an interface, so that the C functions can be called from within Python. I use ctypes for that. C code: FOO* pytrain(float **data){ FOO *foo = foo_autoTrain((float (*)[])data); return f...
[ "It looks to me like the issue is a miscomprehension of how multidimensional arrays work in C. An expression like a[r][c] can mean one of two things depending on the type of a. If the type of a were float **, then the expression would mean a double pointer-offset dereference, something like this if done out long-...
[ 0 ]
[]
[]
[ "casting", "ctypes", "multidimensional_array", "pointers", "python" ]
stackoverflow_0003523250_casting_ctypes_multidimensional_array_pointers_python.txt
Q: Why Django's ModelAdmin uses lists over tuples and vice-versa From the Django intro tutorial, in \mysite\polls\admin.py: from django.contrib import admin #... class PollAdmin(admin.ModelAdmin): #... inlines = [ChoiceInline] list_display = ('question', 'pub_date', 'was_published_today') list_filter = ['pub_...
Why Django's ModelAdmin uses lists over tuples and vice-versa
From the Django intro tutorial, in \mysite\polls\admin.py: from django.contrib import admin #... class PollAdmin(admin.ModelAdmin): #... inlines = [ChoiceInline] list_display = ('question', 'pub_date', 'was_published_today') list_filter = ['pub_date'] admin.site.register(Poll, PollAdmin) Why do inlines and li...
[ "It doesn't matter which you use because Django (and you) will never change them during runtime. All that's important is that the value be an iterable of strings. I often use foo = [\"something\"] when there is only one element because I've gotten nailed so often when I accidentally say foo = (\"somthing\") instead...
[ 8 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003671437_django_python.txt
Q: Setup Python variable environment on ubuntu how to set or create new environment variables in ubuntu(10.04, 64bits), for a python library. I have to configure PYTHONPATH library_HOME library_data A: In bash, you can use export: export PYTHONPATH=/path/to/library export library_HOME=/path/to/library_HOME etc. ...
Setup Python variable environment on ubuntu
how to set or create new environment variables in ubuntu(10.04, 64bits), for a python library. I have to configure PYTHONPATH library_HOME library_data
[ "In bash, you can use export:\nexport PYTHONPATH=/path/to/library\nexport library_HOME=/path/to/library_HOME\netc.\n\nYou can put these lines in your ~/.bashrc or ~/.bash_profile to have them loaded every time you start a login shell.\n" ]
[ 3 ]
[]
[]
[ "python", "ubuntu_10.04" ]
stackoverflow_0003671837_python_ubuntu_10.04.txt
Q: python problems with integer comparision I'm using a function in a card game, to check the value of each card, and see if it is higher than the last card played. def Valid(card): prev=pile[len(pile)-1] cardValue=0 prevValue=0 if card[0]=="J": cardValue=11 elif card[0]=="Q": cardValue=12 elif card[0]=="K": ...
python problems with integer comparision
I'm using a function in a card game, to check the value of each card, and see if it is higher than the last card played. def Valid(card): prev=pile[len(pile)-1] cardValue=0 prevValue=0 if card[0]=="J": cardValue=11 elif card[0]=="Q": cardValue=12 elif card[0]=="K": cardValue=13 elif card[0]=="A": cardVa...
[ "I think what you meant is that it is saying that \"2\" > 13 which is true. You need to change \ncardValue=card[0]\n\nto\ncardValue=int(card[0])\n\n", "Why not use a dictionary instead of a big cascade of if/else blocks?\ncards = dict(zip((str(x) for x in range(1, 11)), range(1, 11)))\ncards['J'] = 11\ncards['Q']...
[ 11, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003671936_python.txt
Q: How to deploy this "Python+twill+mechanize" combination to "Google App Engine"? I've been trying to pass my login and password from Python script to the eBay sign-in page. Later I want this script to be run from "Google App Engine" I was suggested to use "mechanize". Unfortunately, it didn't work for me: IDLE 1....
How to deploy this "Python+twill+mechanize" combination to "Google App Engine"?
I've been trying to pass my login and password from Python script to the eBay sign-in page. Later I want this script to be run from "Google App Engine" I was suggested to use "mechanize". Unfortunately, it didn't work for me: IDLE 1.2.4 >>> import re >>> import mechanize >>> br = mechanize.Browser() >>> br.open...
[ "The error message is indicating that mechanize is obeying the site's robots.txt file for you.\nYou should use eBay's API if you want to access their site in an automated way. If you don't, and build your own solution that ignores robots.txt, don't be surprised when they block you, and complain to Google about aut...
[ 2, 2 ]
[]
[]
[ "deployment", "google_app_engine", "mechanize", "python", "twill" ]
stackoverflow_0003670701_deployment_google_app_engine_mechanize_python_twill.txt
Q: Django / Python, Using Radio Button for boolean field in Modelform? I'm trying to use a radio button in my modelform but its just outputting nothing when I do an override this way (it just prints the label in my form, not the radio buttosn, if I don't do the override it does a standard checkbox) My modelfield is d...
Django / Python, Using Radio Button for boolean field in Modelform?
I'm trying to use a radio button in my modelform but its just outputting nothing when I do an override this way (it just prints the label in my form, not the radio buttosn, if I don't do the override it does a standard checkbox) My modelfield is defined as: Class Mymodelname (models.Model): fieldname = models.Boole...
[ "Does this work?\nclass createdbentry(forms.ModelForm):\n\n choices = ( (1,'Yes'),\n (0,'No'),\n )\n\n class Meta:\n model = Mymodelname\n\n def __init__(self, *args, **kwargs):\n super(createdbentry, self).__init__(*args, **kwargs)\n\n BinaryFieldsList = ['...
[ 3 ]
[]
[]
[ "django", "django_forms", "forms", "python", "radio_button" ]
stackoverflow_0003672221_django_django_forms_forms_python_radio_button.txt
Q: HtmlWindow doesn't display page in wxpython notebook layout I have a project set up as a notebook layout using wxpython. I am trying to create a help panel. The HtmlWindow object doesn't display the html page on the panel. No errors are displayed and a call to HtmlWindow.GetOpenedPage() returns the page name. i...
HtmlWindow doesn't display page in wxpython notebook layout
I have a project set up as a notebook layout using wxpython. I am trying to create a help panel. The HtmlWindow object doesn't display the html page on the panel. No errors are displayed and a call to HtmlWindow.GetOpenedPage() returns the page name. import wx import wx.html as html class HelpPanel(wx.Panel): d...
[ "I think the problem may be how your adding your HtmlWindow object to your sizer, try and setting the EXPAND flag and the proportion to 1.\nself.sizer.Add(self.help, 1, wx.EXPAND)\n\n" ]
[ 0 ]
[]
[]
[ "python", "wxhtmlwindow", "wxpython" ]
stackoverflow_0003672459_python_wxhtmlwindow_wxpython.txt
Q: How to accomplish this in python? Given the following input file: a = 2 b = 3 c = a * b d = c + 4 I want to run the above input file through a python program that produces the following output: a = 2 b = 3 c = a * b = 6 d = c + 4 = 10 The input file is a legal python program, but the output is python with extra ...
How to accomplish this in python?
Given the following input file: a = 2 b = 3 c = a * b d = c + 4 I want to run the above input file through a python program that produces the following output: a = 2 b = 3 c = a * b = 6 d = c + 4 = 10 The input file is a legal python program, but the output is python with extra output that prints the value of each va...
[ "Something like the following is a good start. It's not very Pythonic, but it is pretty close. It doesn't distinguish between newly added variables and modified ones.\n#! /usr/bin/env python\nimport sys\nlocals = dict()\nfor line in sys.stdin:\n saved = locals.copy()\n stmt = compile(line, '<stdin>', 'singl...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003672789_python.txt
Q: How to embed Evince? I'm trying to make embed Evince (libevview-2.30) in a Python and a C program, but it doesn't work. I'm using Ubuntu Lucid. Here is my C code: #include <gtk/gtk.h> #include <evince/2.30/evince-view.h> #include <evince/2.30/evince-document.h> int main(int argc, char *argv[]){ GtkWidget *win...
How to embed Evince?
I'm trying to make embed Evince (libevview-2.30) in a Python and a C program, but it doesn't work. I'm using Ubuntu Lucid. Here is my C code: #include <gtk/gtk.h> #include <evince/2.30/evince-view.h> #include <evince/2.30/evince-document.h> int main(int argc, char *argv[]){ GtkWidget *window; EvDocument *docum...
[ "I've figured it out. You need to put EvView widget inside a ScrolledWindow widget.\n" ]
[ 2 ]
[]
[]
[ "c", "gnome", "python" ]
stackoverflow_0003672847_c_gnome_python.txt
Q: List of months in Django I'm trying to have a select form with a list of months but I can't seem to get it to post correctly. form: class MonthForm(forms.Form): months = [('January','January'), ('February','February'), ('March','March'), ('April','Ap...
List of months in Django
I'm trying to have a select form with a list of months but I can't seem to get it to post correctly. form: class MonthForm(forms.Form): months = [('January','January'), ('February','February'), ('March','March'), ('April','April'), ('May...
[ "The cleaned_data attribute is present only after the form has been validated with is_valid().\nJust change your code to \ndef table_view(request):\n if request.method == 'POST':\n form = MonthForm(request.POST)\n if form.is_valid():\n print form.cleaned_data['month']\n\n\nInternally, if...
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003672959_django_python.txt
Q: python asyncore or threadpool for web crawler? It seem what i can do fast crawler with python in two ways: thread pool with block sockets non block sockets select,asyncore,etc.. i thnk where is no real need in thread here, and solution #2 better. which is better and why? A: Twisted is usually preferred to asy...
python asyncore or threadpool for web crawler?
It seem what i can do fast crawler with python in two ways: thread pool with block sockets non block sockets select,asyncore,etc.. i thnk where is no real need in thread here, and solution #2 better. which is better and why?
[ "Twisted is usually preferred to asyncore. It is an asynchronous I/O framework that can also work with thread pools.\nIn Python, you should prefer asynchronous IO to threads, simply because threads are a second class citizen in its canonical implementation (CPython) due to GIL.\n" ]
[ 3 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0003673111_python_web_crawler.txt
Q: Python: find most frequent bytes? I'm looking for a (preferably simple) way to find and order the most common bytes in a python stream element. e.g. >>> freq_bytes(b'hello world') b'lohe wrd' or even >>> freq_bytes(b'hello world') [108,111,104,101,32,119,114,100] I currently have a function that returns a list ...
Python: find most frequent bytes?
I'm looking for a (preferably simple) way to find and order the most common bytes in a python stream element. e.g. >>> freq_bytes(b'hello world') b'lohe wrd' or even >>> freq_bytes(b'hello world') [108,111,104,101,32,119,114,100] I currently have a function that returns a list in the form list[97] == occurrences of ...
[ "Try the Counter class in the collections module.\nfrom collections import Counter\n\nstring = \"hello world\"\nprint ''.join(char[0] for char in Counter(string).most_common())\n\nNote you need Python 2.7 or later.\nEdit: Forgot the most_common() method returned a list of value/count tuples, and used a list compreh...
[ 6, 3 ]
[]
[]
[ "byte", "frequency", "python" ]
stackoverflow_0003673175_byte_frequency_python.txt
Q: gtk: label which goes multi-line instead of expanding horizontally I have a VBox which looks like this: ImportantWidget HSeparator Label I want this window to be only as wide as ImportantWidget needs to be, and no wider. However, the Label can sometimes grow to be very long. I want the following logic: if L...
gtk: label which goes multi-line instead of expanding horizontally
I have a VBox which looks like this: ImportantWidget HSeparator Label I want this window to be only as wide as ImportantWidget needs to be, and no wider. However, the Label can sometimes grow to be very long. I want the following logic: if Label can fit all its text without expanding the VBox horizontally (after...
[ "Ah yes this shows how to do it:\nl = gtk.Label(\"Painfully long text\" * 30)\nl.set_line_wrap(True)\n\n", "EDIT:\nexample of a dynamic label who works in multi-line according to the size of the window and text:\nimport gtk\n\nclass DynamicLabel(gtk.Window):\n def __init__(self):\n gtk.Window.__init__(s...
[ 1, 1, 1 ]
[]
[]
[ "gtk", "pygtk", "python", "user_interface" ]
stackoverflow_0003516235_gtk_pygtk_python_user_interface.txt
Q: Constructing python function callable from C , with input parameter having *output* semantics The use case is the following: Given a (fixed, not changeable) DLL implemented in C Wanted: a wrapper to this DLL implemented in python (chosen method: ctypes) Some of the functions in the DLL need synchronization primi...
Constructing python function callable from C , with input parameter having *output* semantics
The use case is the following: Given a (fixed, not changeable) DLL implemented in C Wanted: a wrapper to this DLL implemented in python (chosen method: ctypes) Some of the functions in the DLL need synchronization primitives. To aim for maximum flexibility, the designers of the DLL completely rely on client-provided ...
[ "You appear to be incorrectly defining the return type. It looks like your C callback returns an int, while the Python one you are declaring as return c_int, yet not explicitly returning anything (thus actually returning None). If you \"return 0\" it might stop crashing. You should do that or change the callback...
[ 0, 0 ]
[]
[]
[ "callback", "ctypes", "python", "void_pointers" ]
stackoverflow_0001891021_callback_ctypes_python_void_pointers.txt
Q: What is the most 'pythonic' way to logically combine a list of booleans? I have a list of booleans I'd like to logically combine using and/or. The expanded operations would be: vals = [True, False, True, True, True, False] # And-ing them together result = True for item in vals: result = result and item # Or...
What is the most 'pythonic' way to logically combine a list of booleans?
I have a list of booleans I'd like to logically combine using and/or. The expanded operations would be: vals = [True, False, True, True, True, False] # And-ing them together result = True for item in vals: result = result and item # Or-ing them together result = False for item in vals: result = result or ite...
[ "See all(iterable) :\n\nReturn True if all elements of the\n iterable are true (or if the iterable\n is empty).\n\nAnd any(iterable) :\n\nReturn True if any element of the\n iterable is true. If the iterable is empty, return False.\n\n", "The best way to do it is with the any() and all() functions.\nvals = [Tr...
[ 123, 15 ]
[]
[]
[ "boolean", "list", "python" ]
stackoverflow_0003673337_boolean_list_python.txt
Q: What module is PYSIGNAL defined in PyQt4 All of the examples I read online use from PyQt4 import * or some variant of that, importing everything. I don't want to do this, but I can't find where PYSIGNAL is defined! A: I think you want: PyQt4.Qt.SIGNAL This is the same as: PyQt4.QtCore.SIGNAL
What module is PYSIGNAL defined in PyQt4
All of the examples I read online use from PyQt4 import * or some variant of that, importing everything. I don't want to do this, but I can't find where PYSIGNAL is defined!
[ "I think you want:\nPyQt4.Qt.SIGNAL\n\nThis is the same as:\nPyQt4.QtCore.SIGNAL\n\n" ]
[ 1 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0003673553_pyqt_python.txt
Q: python: replacing regex with BNF or pyparsing I am parsing a relatively simple text, where each line describes a game unit. I have little knowledge of parsing techniques, so I used the following ad hoc solution: class Unit: # rules is an ordered dictionary of tagged regex that is intended to be applied in the ...
python: replacing regex with BNF or pyparsing
I am parsing a relatively simple text, where each line describes a game unit. I have little knowledge of parsing techniques, so I used the following ad hoc solution: class Unit: # rules is an ordered dictionary of tagged regex that is intended to be applied in the given order # the group named V would correspon...
[ "I started to write up a coaching guide for pyparsing, but looking at your rules, they translate pretty easily into pyparsing elements themselves, without dealing with EBNF, so I just cooked up a quick sample:\nfrom pyparsing import Word, nums, oneOf, Group, OneOrMore, Regex, Optional\n\ninteger = Word(nums)\nlevel...
[ 4 ]
[]
[]
[ "ebnf", "pyparsing", "python", "regex" ]
stackoverflow_0003673388_ebnf_pyparsing_python_regex.txt
Q: What is a 'good practice' way to write a Python GTK+ application? I'm currently writing a PyGTK application and I'd like some advice as to the best way to structure my application. Basically the application will read a specific file specification and present it in a GUI for editing. Currently I have a parser.py wh...
What is a 'good practice' way to write a Python GTK+ application?
I'm currently writing a PyGTK application and I'd like some advice as to the best way to structure my application. Basically the application will read a specific file specification and present it in a GUI for editing. Currently I have a parser.py which handles all the low level file IO and parsing of the file. I'm disp...
[ "You should take a look at the tutorial \"Sub-classing GObject in Python\". This goes through using GObject's type system to create signals and properties, which allow you to model underlying behavior in a way that is easy to integrate with typical PyGTK semantics (connecting to signals, waiting for property notifi...
[ 5 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003673340_pygtk_python.txt
Q: AppEngine Python - updating entity properties without twenty elif statements Suppose I have an AppEngine model defined with twenty different StringProperty properties. And then I have a web form, which POSTs updated values for an entity of this model. I end up with something like this after reading in the form d...
AppEngine Python - updating entity properties without twenty elif statements
Suppose I have an AppEngine model defined with twenty different StringProperty properties. And then I have a web form, which POSTs updated values for an entity of this model. I end up with something like this after reading in the form data: entity_key['name'] = 'new_name' entity_key['city'] = 'new_city' entity_key['s...
[ "The same effect as for your if / elif tree could be obtained by a single statement:\nsetattr(entity, property, entity_key[property])\n\nThis is just elementary Python, working the same way in every Python version since 1.5.2 (and perhaps earlier -- I wasn't using Python that many years ago!-), and has nothing spec...
[ 2, 0 ]
[]
[]
[ "djangoappengine", "python" ]
stackoverflow_0003664719_djangoappengine_python.txt
Q: TypedChoiceField or ChoiceField in Django When should you use TypedChoiceField with a coerce function over a ChoiceField with a clean method on the form for the field? In other words why would you use MyForm over MyForm2 or vice versa. Is this simply a matter of preference? from django import forms CHOICES = (('...
TypedChoiceField or ChoiceField in Django
When should you use TypedChoiceField with a coerce function over a ChoiceField with a clean method on the form for the field? In other words why would you use MyForm over MyForm2 or vice versa. Is this simply a matter of preference? from django import forms CHOICES = (('1', 'A'), ('2', 'B'), ('3', 'C')) class MyForm...
[ "I would use a clean_field method for doing \"heavy lifting\". For instance if your field requires non-trivial, custom cleaning and/or type conversion etc. If on the other hand the requirement is straightforward such as coercing to int then the clean_field is probably an overkill. TypedChoiceField would be the way ...
[ 13 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003673833_django_django_forms_python.txt
Q: Why don't you need a powerful ide for writing Python? I have heard before that many Python developers don't use an IDE like Eclipse because it is unnecessary with a language like Python. What are the reasons people use to justify this claim? A: I'd say the main reason is because Python isn't horribly verbose li...
Why don't you need a powerful ide for writing Python?
I have heard before that many Python developers don't use an IDE like Eclipse because it is unnecessary with a language like Python. What are the reasons people use to justify this claim?
[ "I'd say the main reason is because Python isn't horribly verbose like, e.g., Java. You don't need an IDE to generate 100s of lines of boilerplate because you don't need 100s of lines of boilerplate in Python. You tend to automate stuff within the language instead of further up the toolchain.\nA second reason is ...
[ 15, 9, 6, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003673487_python.txt
Q: Best way to find max and min of two values I have a function that is passed two values and then iterates over the range of those values. The values can be passed in any order, so I need to find which one is the lowest first. I had the function written like this: def myFunc(x, y): if x > y: min_val, ma...
Best way to find max and min of two values
I have a function that is passed two values and then iterates over the range of those values. The values can be passed in any order, so I need to find which one is the lowest first. I had the function written like this: def myFunc(x, y): if x > y: min_val, max_val = y, x else: min_val, max_val ...
[ "min and max are your friends.\ndef myFunc(x, y):\n min_val, max_val = min(x, y), max(x, y)\n\n\nEdit. Benchmarked min-max version againt a simple if. Due to the function call overhead, min-max takes 2.5x longer that the simple if; see http://gist.github.com/571049\n", "Since the OP's question was posed using ...
[ 16, 6, 4, 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003672599_python.txt
Q: Write a regex for a pattern? a + (ab or cd ) + g is my expression. How can I write a regex in Python to match these? A: To search this regex in a string, say re.search("a\\+((ab)|(cd))\\+g", your_string) To extract matches, use re.findall etc. No need to copy&paste the docs here. :) EDIT: Updated after OP chang...
Write a regex for a pattern?
a + (ab or cd ) + g is my expression. How can I write a regex in Python to match these?
[ "To search this regex in a string, say\nre.search(\"a\\\\+((ab)|(cd))\\\\+g\", your_string)\n\nTo extract matches, use re.findall etc. No need to copy&paste the docs here. :)\nEDIT: Updated after OP changed the regex.\nIf you want it to match whitespace in between, things get pretty ugly ...\nre.search(\"a\\W*\\\\+...
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003674403_python_regex.txt
Q: regex regarding symbols in urls I want to replace consecutive symbols just one such as; this is a dog??? to this is a dog? I'm using str = re.sub("([^\s\w])(\s*\1)+", "\\1",str) however I notice that this might replace symbols in urls that might happen in my text. like http://example.com/this--is-a-page.html...
regex regarding symbols in urls
I want to replace consecutive symbols just one such as; this is a dog??? to this is a dog? I'm using str = re.sub("([^\s\w])(\s*\1)+", "\\1",str) however I notice that this might replace symbols in urls that might happen in my text. like http://example.com/this--is-a-page.html Can someone give me some advice how ...
[ "So you want to unleash the power of regular expressions on an irregular language like HTML. First of all, search SO for \"parse HTML with regex\" to find out why that might not be such a good idea.\nThen consider the following: You want to replace duplicate symbols in (probably user-entered) text. You don't want t...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003674116_python_regex.txt
Q: compile python script in linux So I have a python script that relies on a couple modules. Specifically pexpect and pyinoitify. I know you can compile a python script into a .exe in windows, but is there something relatively equivalent in linux? I don't care about it being a binary, I'd just like to be able to dist...
compile python script in linux
So I have a python script that relies on a couple modules. Specifically pexpect and pyinoitify. I know you can compile a python script into a .exe in windows, but is there something relatively equivalent in linux? I don't care about it being a binary, I'd just like to be able to distribute my script without requiring t...
[ "cx_Freeze is a cross-platform way to \"freeze\" a Python script into standalone binary form. According to their site:\n\ncx_Freeze is a set of scripts and\n modules for freezing Python scripts\n into executables in much the same way\n that py2exe and py2app do. Unlike\n these two tools, cx_Freeze is cross\n p...
[ 7, 0, 0 ]
[]
[]
[ "binary", "compilation", "linux", "python" ]
stackoverflow_0003671466_binary_compilation_linux_python.txt
Q: Communicating end of Queue I'm learning to use the Queue module, and am a bit confused about how a queue consumer thread can be made to know that the queue is complete. Ideally I'd like to use get() from within the consumer thread and have it throw an exception if the queue has been marked "done". Is there a bet...
Communicating end of Queue
I'm learning to use the Queue module, and am a bit confused about how a queue consumer thread can be made to know that the queue is complete. Ideally I'd like to use get() from within the consumer thread and have it throw an exception if the queue has been marked "done". Is there a better way to communicate this than...
[ "original (most of this has changed; see updates below)\nBased on some of the suggestions (thanks!) of Glenn Maynard and others, I decided to roll up a descendant of Queue.Queue that implements a close method. It's available in the form of a primitive (unpackaged) module. I'll clean this up a bit and package it p...
[ 12, 9, 8, 2, 0 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0003605188_multithreading_python_queue.txt
Q: python2.5 multiprocessing Pool I have python2.5 and multiprocessoring (get from http://code.google.com/p/python-multiprocessing/) This simple code (get from docs), works very strange from time to time, sometimes it ok, but sometimes it throw timeout ex or hang my Windows (Vista), only reset helps :) Why this can h...
python2.5 multiprocessing Pool
I have python2.5 and multiprocessoring (get from http://code.google.com/p/python-multiprocessing/) This simple code (get from docs), works very strange from time to time, sometimes it ok, but sometimes it throw timeout ex or hang my Windows (Vista), only reset helps :) Why this can happen? from multiprocessing import P...
[ "This is just a wild guess, but have you tried to move the Pool creation into the if block? I suspect that otherwise it might spawn an unlimited number of new processes, causing the freeze.\n" ]
[ 4 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0003674746_multiprocessing_python.txt
Q: Remove class attribute in inherited class Python Consider such code: class A (): name = 7 description = 8 color = 9 class B(A): pass Class B now has (inherits) all attributes of class A. For some reason I want B not to inherit attribute 'color'. Is there a possibility to do this? Yes, I know, that I ...
Remove class attribute in inherited class Python
Consider such code: class A (): name = 7 description = 8 color = 9 class B(A): pass Class B now has (inherits) all attributes of class A. For some reason I want B not to inherit attribute 'color'. Is there a possibility to do this? Yes, I know, that I can first create class B with attributes 'name' and 'd...
[ "I think the best solution would be to change your class hierarchy so you can get the classes you want without any fancy tricks. \nHowever, if you have a really good reason not to do this you could hide the color attribute using a Descriptor. You'll need to be using new style classes for this to work.\nclass A(ob...
[ 9, 8 ]
[]
[]
[ "class_attributes", "inheritance", "python" ]
stackoverflow_0003674597_class_attributes_inheritance_python.txt
Q: How do I tell which widget triggered an event in Tkinter? I have several widgets bound to the same function call. How do I tell which one triggered that call? A: The event has a widget field that may help you to distinguish which widget is the source: from Tkinter import * class MyObj: def callback(self, e...
How do I tell which widget triggered an event in Tkinter?
I have several widgets bound to the same function call. How do I tell which one triggered that call?
[ "The event has a widget field that may help you to distinguish which widget is the source:\nfrom Tkinter import *\n\nclass MyObj:\n def callback(self, event):\n print event.widget.message\n\nobj = MyObj()\nroot = Tk()\nbtn=Button(root, text=\"Click\")\nbtn.bind('<Button-1>', obj.callback)\nbtn.pack()\nbtn...
[ 6 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003674916_python_tkinter.txt
Q: Multiple Web Development Environments on Windows Beginner here, stuck wondering what I need to do to learn development in different web environments. Say, for instance I want to play around in PHP & MySQL. But I also want to try things with Ruby on Rails and maybe even server things with Python. Do I need a dif...
Multiple Web Development Environments on Windows
Beginner here, stuck wondering what I need to do to learn development in different web environments. Say, for instance I want to play around in PHP & MySQL. But I also want to try things with Ruby on Rails and maybe even server things with Python. Do I need a different environment for each platform? Am I required t...
[ "I started off with php and mysql, it's a lower-level then the rest of the environments like Django and Ruby on Rails; so it's much easier to understand what is really happening. \nIf you want to get into web development, php is a solid foundation and has easy bundle installers such as WAMP, and has a massive commu...
[ 1, 0, 0 ]
[]
[]
[ "mysql", "php", "python", "ruby_on_rails" ]
stackoverflow_0003674568_mysql_php_python_ruby_on_rails.txt
Q: going through a dictionary and printing its values in sequence def display_hand(hand): for letter in hand.keys(): for j in range(hand[letter]): print letter, Will return something like: b e h q u w x. This is the desired output. How can I modify this code to get the output only when the f...
going through a dictionary and printing its values in sequence
def display_hand(hand): for letter in hand.keys(): for j in range(hand[letter]): print letter, Will return something like: b e h q u w x. This is the desired output. How can I modify this code to get the output only when the function has finished its loops? Something like below code causes me ...
[ "You can do this in one line by combining a couple of list comprehensions:\nprint ' '.join(letter for letter, count in hand.iteritems() for i in range(count))\n\nLet's break that down piece by piece. I'll use a sample dictionary that has a couple of counts greater than 1, to show the repetition part working.\n>>> h...
[ 3, 1, 1, 0 ]
[]
[]
[ "dictionary", "key", "printing", "python", "sequence" ]
stackoverflow_0003669986_dictionary_key_printing_python_sequence.txt
Q: why is python inconsistent when interpreting a subtraction when making a list? I am making a small program and at some point from each row of a matrix I need to subtract the average of the row itself. Quite a standard renormalization procedure. Note in the code def subtractaverage(data): datanormalized=[] ...
why is python inconsistent when interpreting a subtraction when making a list?
I am making a small program and at some point from each row of a matrix I need to subtract the average of the row itself. Quite a standard renormalization procedure. Note in the code def subtractaverage(data): datanormalized=[] for row in data: average_row=sum(row)/len(row) print "average=",aver...
[ "I guess the problem is the integer division (if row consists of integers only)\naverage_row=sum(row)/len(row)\n\nwhich will give you an average of 0 if the length of the row is greater than the sum. Try\naverage_row=sum(row)/float(len(row))\n\ninstead.\n" ]
[ 2 ]
[]
[]
[ "list", "python", "subtraction" ]
stackoverflow_0003675148_list_python_subtraction.txt
Q: Find subsequences of strings within strings I want to make a function which checks a string for occurrences of other strings within them. However, the sub-strings which are being checked may be interrupted within the main string by other letters. For instance: a = 'abcde' b = 'ace' c = 'acb' The function in q...
Find subsequences of strings within strings
I want to make a function which checks a string for occurrences of other strings within them. However, the sub-strings which are being checked may be interrupted within the main string by other letters. For instance: a = 'abcde' b = 'ace' c = 'acb' The function in question should return as b being in a, but not c....
[ "You can turn your expected sequence into a regex:\nimport re\n\ndef sequence_in(s1, s2):\n \"\"\"Does `s1` appear in sequence in `s2`?\"\"\"\n pat = \".*\".join(s1)\n if re.search(pat, s2):\n return True\n return False\n\n# or, more compactly:\ndef sequence_in(s1, s2):\n \"\"\"Does `s1` appea...
[ 11, 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003673434_python.txt
Q: how to get results from exec() in python 3.1? how to get results from exec() in python 3.1? #!/usr/bin/python import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) host = socket.gethostname() port = 1234 sock.bind((host,port)) ret_str = "executed" while True: cmd, addr = sock.recvfrom(1024) ...
how to get results from exec() in python 3.1?
how to get results from exec() in python 3.1? #!/usr/bin/python import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) host = socket.gethostname() port = 1234 sock.bind((host,port)) ret_str = "executed" while True: cmd, addr = sock.recvfrom(1024) if len(cmd) > 0: print("Received ", cmd...
[ "exec expression don't return a value use eval function insted.\nprint \"result:\", eval(cmd)\n\nUpdate: If you still need this I came up with this hack when creating JSON-RPC python interpreter http://trypython.jcubic.pl\nimport sys\nfrom StringIO import StringIO\n__stdout = sys.stdout\nsys.stdout = StringIO()\ntr...
[ 2 ]
[]
[]
[ "exec", "python", "sockets" ]
stackoverflow_0003675512_exec_python_sockets.txt
Q: Get warning for python string literals not prefixed with 'u' To follow best practices for Unicode in python, you should prefix all string literals of characters with 'u'. Is there any tool available (preferably PyDev compatible) that warns if you forget it? A: you should prefix all string literals with 'u' No, ...
Get warning for python string literals not prefixed with 'u'
To follow best practices for Unicode in python, you should prefix all string literals of characters with 'u'. Is there any tool available (preferably PyDev compatible) that warns if you forget it?
[ "\nyou should prefix all string literals with 'u'\n\nNo, not really.\nYou should prefix literals for strings of characters with u. But not all strings are strings of characters. When you are talking to components that are byte based, like network services, or binary files, you need to be using byte strings.\neg. Wa...
[ 4, 2, 1 ]
[]
[]
[ "pydev", "python", "unicode" ]
stackoverflow_0003674631_pydev_python_unicode.txt
Q: How to add python "libraries" to Eclypse and pydev I am trying to learn how to use Abaqus Scripting. I just downloaded Eclipse and added the pydev plugin. Everything seems to work fine. What I want to do now is to add all the built-in Abaqus libraries or modules. I would like, for example, the IDE to display the ...
How to add python "libraries" to Eclypse and pydev
I am trying to learn how to use Abaqus Scripting. I just downloaded Eclipse and added the pydev plugin. Everything seems to work fine. What I want to do now is to add all the built-in Abaqus libraries or modules. I would like, for example, the IDE to display the class members and methods when I press the ".". I would ...
[ "You can add these libraries to the settings to get the effect you want. This can be done in the Libraries setting accessed through Window > Preferences > PyDev > Interpreter - Python > Libraries. Add the .egg or source folder of the libraries you want to add and click Apply followed by OK.\n" ]
[ 7 ]
[]
[]
[ "eclipse", "ide", "pydev", "python" ]
stackoverflow_0003675585_eclipse_ide_pydev_python.txt
Q: Can the formatter class be used without relying on an intermediate stream/file? import formatter # a long string I want to format s="""When running behind a load balancer like nginx, it is recommended to pass xheaders=True to the HTTPServer constructor. This will tell Tornado to use headers like X-Real-IP to get ...
Can the formatter class be used without relying on an intermediate stream/file?
import formatter # a long string I want to format s="""When running behind a load balancer like nginx, it is recommended to pass xheaders=True to the HTTPServer constructor. This will tell Tornado to use headers like X-Real-IP to get the user's IP address instead of attributing all traffic to the balancer's IP address...
[ "You could use StringIO.\n>>> import StringIO\n>>> fh = StringIO.StringIO()\n>>> f.send_flowing_data(s)\n>>> print(fh.getvalue())\nWhen running behind a load balancer like nginx, it is recommended to\npass xheaders=True to the HTTPServer constructor. This will tell Tornado\nto use headers like X-Real-IP to get the ...
[ 2 ]
[]
[]
[ "formatting", "python" ]
stackoverflow_0003675875_formatting_python.txt
Q: Best interface paradigm for time interval selection? I'm working on a small project that involves selecting time intervals and then using them for my nefarious purposes (which basically boils down to making a robot voice shout things at me). However, I can't decide on a proper paradigm for choosing these interval...
Best interface paradigm for time interval selection?
I'm working on a small project that involves selecting time intervals and then using them for my nefarious purposes (which basically boils down to making a robot voice shout things at me). However, I can't decide on a proper paradigm for choosing these intervals. The required data is as follows: Action (Text) Startin...
[ "I'm no GUI expert, but, personally, I love interfaces that give me three ways to choose an interval: \"starting at\", \"ending at\", and \"duration\". Of course, when I advance (say) the duration, it's crucial to have the \"ending at\" advance in tandem (I find it more intuitive to have the \"starting at\" interv...
[ 3, 3, 3 ]
[]
[]
[ "forms", "python", "user_interface", "wxpython" ]
stackoverflow_0003673227_forms_python_user_interface_wxpython.txt
Q: Howto change Pythonpath in Python 3 I am trying to switch from using Python 2.6.5 to using Python 3.2a2. I am using OSX 10.6.4. However, when I open Idle in the Python 3.2a2 folder it cannot import any of the modules I installed to Python 2.6.5. Is there a way that I can share the same folders on Python 3.2a2 ? A...
Howto change Pythonpath in Python 3
I am trying to switch from using Python 2.6.5 to using Python 3.2a2. I am using OSX 10.6.4. However, when I open Idle in the Python 3.2a2 folder it cannot import any of the modules I installed to Python 2.6.5. Is there a way that I can share the same folders on Python 3.2a2 ?
[ "Python 2 and Python 3 are sufficiently different that you cannot in general share modules between them. You will need new, Python-3-compatible modules instead of re-using the Python 2 ones.\n(It's possible with a great deal of care to make scripts that will work in both, but it's not usually the done thing. Python...
[ 2 ]
[]
[]
[ "osx_snow_leopard", "python", "python_3.x", "pythonpath", "upgrade" ]
stackoverflow_0003675999_osx_snow_leopard_python_python_3.x_pythonpath_upgrade.txt
Q: How to execute another python script from your script and be able to debug? You have wrapper python script that is calling another python script, currently using os.system('python another.py some-params'). You want to be able to debug both scripts and if you use os.system() you'll loose the debugger, so it does ma...
How to execute another python script from your script and be able to debug?
You have wrapper python script that is calling another python script, currently using os.system('python another.py some-params'). You want to be able to debug both scripts and if you use os.system() you'll loose the debugger, so it does make sense to load the second script using the same interpretor instead of starting...
[ "So far I found a solution that works only with Python 2.7+ (runpy.run_path() was introduced in Python 2.7). \nIf you can find one that works with 2.6 (or even 2.5) you are welcome to post it.\nimport runpy, sys\nsaved_argv = sys.argv\n... # patch sys.argv[1:] and load new command line parameters\n# run_path() does...
[ 10, 2, 2, 1 ]
[]
[]
[ "command_line", "debugging", "python", "runpy" ]
stackoverflow_0003657955_command_line_debugging_python_runpy.txt
Q: Python + GStreamer - Won't connect I'm having trouble combining audio and video into one file. The Python code looks like this; filmPipe = gst.Pipeline("filmPipe") filmSrc = gst.element_factory_make("multifilesrc", "filmSrc") filmSrc.set_property("location", "pictures/%d.png") ...
Python + GStreamer - Won't connect
I'm having trouble combining audio and video into one file. The Python code looks like this; filmPipe = gst.Pipeline("filmPipe") filmSrc = gst.element_factory_make("multifilesrc", "filmSrc") filmSrc.set_property("location", "pictures/%d.png") filmFilt1 = gst.element_facto...
[ "You are linking 2 times filmOggmux to filmFilesink: this is not allowed, only one link is possible.\nTry removing filmFilesink in the second gst.element_link_many().\n" ]
[ 1 ]
[]
[]
[ "gstreamer", "python" ]
stackoverflow_0003484953_gstreamer_python.txt
Q: Is it possible to check if an email contains an attachement just from the e-mail header? I am developing an email client in Python. Is it possible to check if an email contains an attachement just from the e-mail header without downloading the whole E-Mail? A: Try IMAP4.fetch(message_set, "BODYSTRUCTURE") Read t...
Is it possible to check if an email contains an attachement just from the e-mail header?
I am developing an email client in Python. Is it possible to check if an email contains an attachement just from the e-mail header without downloading the whole E-Mail?
[ "Try IMAP4.fetch(message_set, \"BODYSTRUCTURE\")\nRead the RFC3501 for details about the FETCH BODYSTRUCTURE response.\n", "\"attachment\" is quite a broad term. Is an image for HTML message an attachment? \nIn general, you can try analyzing content-type header. If it's multipart/mixed, most likely the message co...
[ 7, 5 ]
[]
[]
[ "email", "imap", "imaplib", "python" ]
stackoverflow_0003676344_email_imap_imaplib_python.txt
Q: Google App Engine many-to-many to self I'm trying to convert a django project for GAE, and I've stumbled upon this: (relational-databse) class Clan(models.Model): wars = models.ManyToManyField('self') How can I do this in a non-relational database(i.e. gae datastore)? A: If you don't expect more than, say,...
Google App Engine many-to-many to self
I'm trying to convert a django project for GAE, and I've stumbled upon this: (relational-databse) class Clan(models.Model): wars = models.ManyToManyField('self') How can I do this in a non-relational database(i.e. gae datastore)?
[ "If you don't expect more than, say, a couple of hundred keys in the list of related entities, you could use a db.ListProperty(db.Key), containing the keys of the referenced entities.\n" ]
[ 1 ]
[]
[]
[ "django", "google_app_engine", "non_relational_database", "nosql", "python" ]
stackoverflow_0003674632_django_google_app_engine_non_relational_database_nosql_python.txt
Q: best way to compare sequence of letters inside file? I have a file, that have lots of sequences of letters. Some of these sequences might be equal, so I would like to compare them, all to all. I'm doing something like this but this isn't exactly want I wanted: for line in fl: line = line.split() for elem in line...
best way to compare sequence of letters inside file?
I have a file, that have lots of sequences of letters. Some of these sequences might be equal, so I would like to compare them, all to all. I'm doing something like this but this isn't exactly want I wanted: for line in fl: line = line.split() for elem in line: if '>' in elem: pass else: for e...
[ "If the goal is to simply group like sequences together, then simply sorting the data will do the trick. Here is a solution that uses BioPython to parse the input FASTA file, sorts the collection of sequences, uses the standard Python itertools.groupby function to merge ids for equal sequences, and outputs a new F...
[ 8, 2, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003675895_python.txt
Q: Installing VPython in Snow Leopard? So, i've just startet university, and we have to install python. Thats fine, cause it's build-in to OSX (Snow Leopard). I have installed matplotlib, numpy and scipy using this : http://stronginference.com/scipy-superpack/ It works perfectly, and i don't have to install the pytho...
Installing VPython in Snow Leopard?
So, i've just startet university, and we have to install python. Thats fine, cause it's build-in to OSX (Snow Leopard). I have installed matplotlib, numpy and scipy using this : http://stronginference.com/scipy-superpack/ It works perfectly, and i don't have to install the python.org version. But, now we have to instal...
[ "This is a complicated software with a complicated build process, so first and foremost I'd advice you to save yourself some trouble and compile your own Python 2.7 and install it as a user somewhere under your home directory / install the MacOS X binary of 2.7 (probably also as a user under your home directory, bu...
[ 0, 0 ]
[]
[]
[ "macos", "osx_snow_leopard", "python", "vpython" ]
stackoverflow_0003676184_macos_osx_snow_leopard_python_vpython.txt
Q: Question regarding regex and tokenizing I need to make a tokenizer that is able to English words. Currently, I'm stuck with characters where they can be part of of a url expression. For instance, if the characters ':','?','=' are part of a url, i shouldn't really segment them. My qns is, can this be expressed in r...
Question regarding regex and tokenizing
I need to make a tokenizer that is able to English words. Currently, I'm stuck with characters where they can be part of of a url expression. For instance, if the characters ':','?','=' are part of a url, i shouldn't really segment them. My qns is, can this be expressed in regex? I have the regex \b(?:(?:https?|ftp|fil...
[ "I would approach this problem by doing a sweep with a different regexp, putting hits into an array, removing those hits from the string, and then doing your tokenizer as normal.\n" ]
[ 0 ]
[]
[]
[ "python", "regex", "tokenize" ]
stackoverflow_0003676628_python_regex_tokenize.txt
Q: python multidimensional list.. how to grab one dimension? my question is, is I have a list like the following: someList = [[0,1,2],[3,4,5],[6,7,8]] how would I get the first entry of each sublist? I know I could do this: newList = [] for entry in someList: newList.append(entry[0]) where newList would be: [0...
python multidimensional list.. how to grab one dimension?
my question is, is I have a list like the following: someList = [[0,1,2],[3,4,5],[6,7,8]] how would I get the first entry of each sublist? I know I could do this: newList = [] for entry in someList: newList.append(entry[0]) where newList would be: [0, 3, 6] But is there a way to do something like: newList = som...
[ "EDIT: Here's some actual numbers! The izip, list comprehension, and numpy ways of doing this are all about the same speed.\n# zip\n>>> timeit.timeit( \"newlist = zip(*someList)[0]\", setup = \"someList = [range(1000000), range(1000000), range(1000000)]\", number = 10 )\n1.4984046398561759\n\n# izip\n>>> timeit.tim...
[ 16, 10, 8 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003676805_list_python.txt
Q: Terminating a wxPython app cleanly I'm working on a wxPython app which has multiple frames and a serial connection. I need to be able to exit the app cleanly, closing the serial connection as the app terminates. What is the best way to do this? Should this be handled by a subclass of wxApp? Thanks, Josh A: Not t...
Terminating a wxPython app cleanly
I'm working on a wxPython app which has multiple frames and a serial connection. I need to be able to exit the app cleanly, closing the serial connection as the app terminates. What is the best way to do this? Should this be handled by a subclass of wxApp? Thanks, Josh
[ "Not totally sure what you're having trouble with here, but I'll take a shot in the dark and assume this is a program organization/design question.\nThere may be better ways that I'm unfamiliar with, but this is what I'd try to do: create a \"parent\" object (doesn't have to have any particular type) that keeps ref...
[ 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003673418_python_wxpython.txt
Q: binding events with wxpython I have the wxPyhon following code self.button1 = wx.Button(self, id=-1, label='Button1',pos=(8, 8), size=(175, 28)) self.button2 = wx.Button(self, id=-1, label='Button2',pos=(16, 8), size=(175, 28)) self.button1.Bind(wx.EVT_BUTTON, self.onButton) self.button1.Bind(wx.EVT_BUTTON, se...
binding events with wxpython
I have the wxPyhon following code self.button1 = wx.Button(self, id=-1, label='Button1',pos=(8, 8), size=(175, 28)) self.button2 = wx.Button(self, id=-1, label='Button2',pos=(16, 8), size=(175, 28)) self.button1.Bind(wx.EVT_BUTTON, self.onButton) self.button1.Bind(wx.EVT_BUTTON, self.onButton) and I need to proces...
[ "One option is to use the label (or ID...but that's usually more troublesome) to key off of, such as:\n def onButton(self, event):\n label = event.GetEventObject().GetLabel()\n if label == \"foo\":\n ...\n elif label == \"bar\":\n ....\n\nOften times, I wish that it has a call back mechanis...
[ 3, 1, 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003672255_python_wxpython.txt
Q: How to convert unicode string like u'\\u4f60\\u4f60' to u'\u4f60\u4f60' in Python? I capture the string from a html source file using regex: f = open(rrfile, 'r') p = re.compile(r'"name":"([^"]+)","head":"([^"]+)"') match = re.findall(p, f.read()) And I've tried: >>> u'\\u4f60\\u4f60'.replace('\\u', '\u') u'\...
How to convert unicode string like u'\\u4f60\\u4f60' to u'\u4f60\u4f60' in Python?
I capture the string from a html source file using regex: f = open(rrfile, 'r') p = re.compile(r'"name":"([^"]+)","head":"([^"]+)"') match = re.findall(p, f.read()) And I've tried: >>> u'\\u4f60\\u4f60'.replace('\\u', '\u') u'\\u4f60\\u4f60' >>> u'\\u4f60\\u4f60'.replace(u'\\u', '\u') u'\\u4f60\\u4f60' >>> u...
[ ">>> u'\\\\u4f60\\\\u4f60'.decode('unicode_escape')\nu'\\u4f60\\u4f60'\n\n" ]
[ 7 ]
[]
[]
[ "python", "replace", "unicode" ]
stackoverflow_0003677213_python_replace_unicode.txt
Q: send an email with python Possible Duplicate: Receive and send emails in python I tried searching but couldn't find a simple way to send an email. I'm looking for something like this: from:"Test1@test.com"#email sender To:"test2@test.com"# my email content:open('x.txt','r') Everything I've found is complicated ...
send an email with python
Possible Duplicate: Receive and send emails in python I tried searching but couldn't find a simple way to send an email. I'm looking for something like this: from:"Test1@test.com"#email sender To:"test2@test.com"# my email content:open('x.txt','r') Everything I've found is complicated really: my project doesn't nee...
[ "The docs are pretty straitforward:\n# Import smtplib for the actual sending function\nimport smtplib\n\n# Import the email modules we'll need\nfrom email.mime.text import MIMEText\n\n# Open a plain text file for reading. For this example, assume that\n# the text file contains only ASCII characters.\nfp = open(tex...
[ 8, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003677067_python.txt
Q: get_current_session returns None I've been using geasessions for a while, been working great. It's simple and fast. But today I started a new project (GAE v1.3.7) and can't get it to work, get_current_session() just returns None I've split the code in to a new project that's just using gaesessions: from google.ap...
get_current_session returns None
I've been using geasessions for a while, been working great. It's simple and fast. But today I started a new project (GAE v1.3.7) and can't get it to work, get_current_session() just returns None I've split the code in to a new project that's just using gaesessions: from google.appengine.ext import webapp from google....
[ "I think you have missed something in the installation process.\nAnyway, if you scroll down the source code you will notice also this part of code that actually valorize the _current_session variable.\ndef __call__(self, environ, start_response):\n # initialize a session for the current user\n global ...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "session" ]
stackoverflow_0003677611_google_app_engine_python_session.txt
Q: Multiprocess conditional/named Lock In a multiprocess program I want to lock certain function based on arguments e.g. def calculate(spreadsheet): _do_calc(spreadsheet) Now what I want to do is based on spreadsheet, lock the function so that multiple spreadsheets can be worked on concurrently but two calls on ...
Multiprocess conditional/named Lock
In a multiprocess program I want to lock certain function based on arguments e.g. def calculate(spreadsheet): _do_calc(spreadsheet) Now what I want to do is based on spreadsheet, lock the function so that multiple spreadsheets can be worked on concurrently but two calls on same spreadsheet will lock e.g. def calcu...
[ "Why not give each spreadsheet a Lock as an instance attribute?\nclass Spreadsheet(...):\n def __init__(self, ...):\n self.lock = multiprocessing.Lock()\n\n ...\n\nand then\ndef calculate(spreadsheet):\n with spreadsheet.lock:\n ...\n\n", "You might be able to improve on simple file opening...
[ 2, 2 ]
[]
[]
[ "locking", "mutex", "python" ]
stackoverflow_0003676732_locking_mutex_python.txt