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: html/javascript automaticly getting link from submit button (maybe automating with python?) I have a website where I have to click a submit button on a form. This gives me a link. I know the link is made up with the paramter that is passed through a hidden value. I was wondering if I could make a python script or ...
html/javascript automaticly getting link from submit button (maybe automating with python?)
I have a website where I have to click a submit button on a form. This gives me a link. I know the link is made up with the paramter that is passed through a hidden value. I was wondering if I could make a python script or something else that would go to the website and click some buttons returning the link that the su...
[ "If it is python you're looking for then give the Mechanize library a shot. If you are just extracting small but unique elements of the HTML document then you may as well use regex's with python. To work with the HTML document more pragmatically then BeautifulSoup may be more beneficial, which you can combine with ...
[ 1, 1, 1 ]
[]
[]
[ "automation", "html", "javascript", "python", "webforms" ]
stackoverflow_0002648738_automation_html_javascript_python_webforms.txt
Q: error in a pygame code # INTIALISATION import pygame, math, sys from pygame.locals import * screen = pygame.display.set_mode((1024, 768)) car = pygame.image.load('car.png') clock = pygame.time.Clock() k_up = k_down = k_left = k_right = 0 speed = direction = 0 position = (100, 100) TURN_SPEED = 5 ACCELERATION = 2 M...
error in a pygame code
# INTIALISATION import pygame, math, sys from pygame.locals import * screen = pygame.display.set_mode((1024, 768)) car = pygame.image.load('car.png') clock = pygame.time.Clock() k_up = k_down = k_left = k_right = 0 speed = direction = 0 position = (100, 100) TURN_SPEED = 5 ACCELERATION = 2 MAX_FORWARD_SPEED = 10 MAX_RE...
[ "You have a non-ASCII character on line 13. Python doesn't accept UTF-8 in source files unless you put a special comment at the top of your file:\n# encoding: UTF-8\n\n", "As Greg says, you have a non-ascii character in your code - what looks like a minus sign in front of the 5 on line 13. It is called 'soft hyph...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002648800_python.txt
Q: Is django orm & templates thread safe? I'm using django orm and templates to create a background service that is ran as management command. Do you know if django is thread safe? I'd like to use threads to speed up processing. The processing is blocked by I/O not CPU so I don't care about performance hit caused by...
Is django orm & templates thread safe?
I'm using django orm and templates to create a background service that is ran as management command. Do you know if django is thread safe? I'd like to use threads to speed up processing. The processing is blocked by I/O not CPU so I don't care about performance hit caused by GIL.
[ "If you need run jobs in background, you should use celery\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002645953_django_django_models_python.txt
Q: SVG to black-and-white I would like to be able to convert SVG documents to black and white. My try is the following Makefile script using 'sed' : %.bw.svg: %.svg sed '/stroke:none/!s/stroke:[^;\"]*/stroke:black/g' $< > $@ This works for lines etc but not for fillings. Basically if the stroke is not invisible ...
SVG to black-and-white
I would like to be able to convert SVG documents to black and white. My try is the following Makefile script using 'sed' : %.bw.svg: %.svg sed '/stroke:none/!s/stroke:[^;\"]*/stroke:black/g' $< > $@ This works for lines etc but not for fillings. Basically if the stroke is not invisible (none), then I convert it to...
[ "Two options that I would try:\n1- Inkscape appears to be able to do it - Inkscape Convert\n2- SVG supports a ColorProfile attribute on the SVG element that can reference an ICC Color Profile. I would try to reference a GrayScale color profile there and see what happens. Looks like there is one available here.\n"...
[ 5, 0, 0, 0 ]
[]
[]
[ "awk", "python", "sed", "svg", "xslt" ]
stackoverflow_0002203241_awk_python_sed_svg_xslt.txt
Q: Long-running stats process - thoughts on language choice? I am on a LAMP stack for a website I am managing. There is a need to roll up usage statistics (a variety of things related to our desktop product). I initially tackled the problem with PHP (being that I had a bunch of classes to work with the data already)....
Long-running stats process - thoughts on language choice?
I am on a LAMP stack for a website I am managing. There is a need to roll up usage statistics (a variety of things related to our desktop product). I initially tackled the problem with PHP (being that I had a bunch of classes to work with the data already). All worked well on my dev box which was using 5.3. Long story ...
[ "I have worked on a project to do a similar thing in the past, so I have actual experience with performance. You would be hard pressed to beat the performance of \"INSERT ... SELECT\" (not \"INSERT...VALUES (SELECT ...)\". Please see http://dev.mysql.com/doc/refman/5.1/en/insert-select.html\nThe advantage is that i...
[ 1, 1, 0 ]
[]
[]
[ "java", "long_running_processes", "php", "python", "statistics" ]
stackoverflow_0002647905_java_long_running_processes_php_python_statistics.txt
Q: I need to speed up a function. Should I use cython, ctypes, or something else? I'm having a lot of fun learning Python by writing a genetic programming type of application. I've had some great advice from Torsten Marek, Paul Hankin and Alex Martelli on this site. The program has 4 main functions: generate (rando...
I need to speed up a function. Should I use cython, ctypes, or something else?
I'm having a lot of fun learning Python by writing a genetic programming type of application. I've had some great advice from Torsten Marek, Paul Hankin and Alex Martelli on this site. The program has 4 main functions: generate (randomly) an expression tree. evaluate the fitness of the tree crossbreed mutate As all ...
[ "Ignore everyone elses' answer for now. The first thing you should learn to use is the profiler. Python comes with a profile/cProfile; you should learn how to read the results and analyze where the real bottlenecks is. The goal of optimization is three-fold: reduce the time spent on each call, reduce the number of ...
[ 14, 3, 0, 0 ]
[]
[]
[ "ctypes", "cython", "python" ]
stackoverflow_0002647105_ctypes_cython_python.txt
Q: Python: how to design a container with elements that must reference their container (The title is admittedly not that great. Please forgive my English, this is the best I could think of.) I'm writing a python script that will manage email domains and their accounts, and I'm also a newby at OOP design. My two (rela...
Python: how to design a container with elements that must reference their container
(The title is admittedly not that great. Please forgive my English, this is the best I could think of.) I'm writing a python script that will manage email domains and their accounts, and I'm also a newby at OOP design. My two (related?) issues are: the Domain class must do special work to add and remove accounts, like...
[ "For the operations you've outlined, it's not clear that you need Account at all. The only information it holds that is not already duplicated in Domain is the password. You could just have Domain.accounts being a lookup of username: password instead.\nDon't multiply identity-bearing classes until you need to.\nFor...
[ 2, 1, 1, 0 ]
[]
[]
[ "design_patterns", "oop", "python" ]
stackoverflow_0002646744_design_patterns_oop_python.txt
Q: delta-dictionary/dictionary with revision awareness in python? I am looking to create a dictionary with 'roll-back' capabilities in python. The dictionary would start with a revision number of 0, and the revision would be bumped up only by explicit method call. I do not need to delete keys, only add and update key...
delta-dictionary/dictionary with revision awareness in python?
I am looking to create a dictionary with 'roll-back' capabilities in python. The dictionary would start with a revision number of 0, and the revision would be bumped up only by explicit method call. I do not need to delete keys, only add and update key,value pairs, and then roll back. I will never need to 'roll forward...
[ "Have just one dictionary, mapping from the key to a list of (revision_number, actual_value) tuples. Current value is the_dict[akey][-1][1]. Rollback merely involves popping the appropriate entries off the end of each list.\nUpdate: examples of rollback\nkey1 -> [(10, 'v1-10'), (20, 'v1-20')]\nScenario 1: current r...
[ 2, 2 ]
[]
[]
[ "data_structures", "dictionary", "persistence", "python", "revision" ]
stackoverflow_0002649221_data_structures_dictionary_persistence_python_revision.txt
Q: google app engine persistent globals I'm looking for a way to keep the equivalent of persistent global variables in app engine (python). What I'm doing is creating a global kind that I initialize once (i.e. when I reset all my database objects when I'm testing). I have things in there like global counters, or th...
google app engine persistent globals
I'm looking for a way to keep the equivalent of persistent global variables in app engine (python). What I'm doing is creating a global kind that I initialize once (i.e. when I reset all my database objects when I'm testing). I have things in there like global counters, or the next id to assign certain kinds I create...
[ "The datastore is the only place you can have guaranteed-persistent data that are also modifiable. So you can have a single large object, or several smaller ones (with a name attribute and others), depending on your desired access patterns -- but live in the datastore it must. You can use memcache for faster cach...
[ 6 ]
[]
[]
[ "database", "global", "google_app_engine", "python" ]
stackoverflow_0002650014_database_global_google_app_engine_python.txt
Q: Can a native-looking GUI be made with Python I haven't gotten far enough into Python to make GUIs yet, so I thought I'd ask here. Can a python app be made with the windows default style GUI, or will it have its own style? The only screenshots I've seen of a python app running with a GUI had this ugly win95 look to...
Can a native-looking GUI be made with Python
I haven't gotten far enough into Python to make GUIs yet, so I thought I'd ask here. Can a python app be made with the windows default style GUI, or will it have its own style? The only screenshots I've seen of a python app running with a GUI had this ugly win95 look to it.
[ "The \"ugly\" Windows 95 look is determined by the version of the Common Dialog library.\nSupplying a manifest file with the executable (probably your Python implementation) makes Windows use of visual styles, instead of the \"ugly\" look.\nRead more here: http://msdn.microsoft.com/en-us/library/ms997646.aspx\n", ...
[ 10, 8, 6, 3, 3 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0002649882_python_user_interface.txt
Q: python interactive web data/forms/interface communicating with remote server What's an efficient method (preferably simple as well) for communicating with a remote server and allowing the user to 'interact' with it (IE submit commands, user interface) via the web browser (IE a text box to input commands, and an te...
python interactive web data/forms/interface communicating with remote server
What's an efficient method (preferably simple as well) for communicating with a remote server and allowing the user to 'interact' with it (IE submit commands, user interface) via the web browser (IE a text box to input commands, and an text area for output, or various command-less abstracted interfaces)? I have the 's...
[ "Probably the most efficient would be to set up REST as fmsf said. In general, each command would correspond to an URL with other variables attached:\nhttp://example.com/nuclear_warhead/activate/1\nhttp://example.com/nuclear_warhead/activate/2\nhttp://example.com/nuclear_warhead/activate/3\nhttp://example.com/nucle...
[ 2, 1, 1 ]
[]
[]
[ "django", "javascript", "network_programming", "python" ]
stackoverflow_0002647685_django_javascript_network_programming_python.txt
Q: python remove everything between <div class="comment> .. any... how do you use python 2.6 to remove everything including the <div class="comment"> ....remove all ....</div> i tried various way using re.sub without any success Thank you A: This can be done easily and reliably using an HTML parser like BeautifulS...
python remove everything between <div class="comment> .. any...
how do you use python 2.6 to remove everything including the <div class="comment"> ....remove all ....</div> i tried various way using re.sub without any success Thank you
[ "This can be done easily and reliably using an HTML parser like BeautifulSoup:\n>>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup('<body><div>1</div><div class=\"comment\"><strong>2</strong></div></body>')\n>>> for div in soup.findAll('div', 'comment'):\n... div.extract()\n... \n<div class=\"c...
[ 18, 3, 2, 0, 0, 0 ]
[]
[]
[ "class", "html", "python" ]
stackoverflow_0002649751_class_html_python.txt
Q: Lightweight cryptography toolkit(s) for C++ and Python I'm looking to do some basic encryption of server messages which would be encrypted with C++ and decrypted using Python server side. I was wondering if anyone knew if there were good solutions that were simpler or more lightweight than Keyczar. I see that su...
Lightweight cryptography toolkit(s) for C++ and Python
I'm looking to do some basic encryption of server messages which would be encrypted with C++ and decrypted using Python server side. I was wondering if anyone knew if there were good solutions that were simpler or more lightweight than Keyczar. I see that supports both C++ and python, but would using Crypto++ and PyC...
[ "The C++ libraries seem to have dependencies to hundreds of files.\nI don't know much about Python, but that is absolutely normal for C++. I'd recommend Crypto++ -- it's a great easy to use library, and it's public domain, meaning you won't have any license problems with it.\nEDIT: Keep in mind a large library with...
[ 2 ]
[]
[]
[ "c++", "cryptography", "encryption", "python" ]
stackoverflow_0002650073_c++_cryptography_encryption_python.txt
Q: How do Ruby and Python implement their interactive consoles? When implementing the interpreter for my programming language I first thought of a simple console window which allows the user to enter some code which is then executed as a standalone program as a shell. But there are severe problems: If every line of c...
How do Ruby and Python implement their interactive consoles?
When implementing the interpreter for my programming language I first thought of a simple console window which allows the user to enter some code which is then executed as a standalone program as a shell. But there are severe problems: If every line of code the user enters is handled as a standalone program, it has to ...
[ "For Python, an expression isn't complete until all parentheses, brackets, etc. match up. This is fairly easy to detect. A function/class definition isn't complete until a completely blank line is entered. The compiler then compiles the entered expression or definition, and runs it.\nMuch like a normal function, cl...
[ 4, 3, 3 ]
[]
[]
[ "command_line_interface", "interactive", "interpreter", "python", "ruby" ]
stackoverflow_0002649250_command_line_interface_interactive_interpreter_python_ruby.txt
Q: How would I merged nested dictionaries in a list in python? for example if i had the result [{'Germany': {"Luge - Men's Singles": 'Gold'}}, {'Germany': {"Luge - Men's Singles": 'Silver'}}, {'Italy': {"Luge - Men's Singles": 'Bronze'}}] [{'Germany': {"Luge - Women's Singles": 'Gold'}}, {'Austria': {"Luge - Women'...
How would I merged nested dictionaries in a list in python?
for example if i had the result [{'Germany': {"Luge - Men's Singles": 'Gold'}}, {'Germany': {"Luge - Men's Singles": 'Silver'}}, {'Italy': {"Luge - Men's Singles": 'Bronze'}}] [{'Germany': {"Luge - Women's Singles": 'Gold'}}, {'Austria': {"Luge - Women's Singles": 'Silver'}}, {'Germany': {"Luge - Women's Singles": 'B...
[ "import collections\n\nmerged_result = collections.defaultdict(list)\n\nfor L in listoflistsofdicts:\n for d in L:\n for k in d:\n merged_result[k].append(d[k])\n\nor if you just have a list of dicts instead of a list of lists of dicts (hard to say from your Q!-), then just the\n for d in listofdicts:\n ...
[ 4, 1 ]
[]
[]
[ "add", "dictionary", "merge", "python" ]
stackoverflow_0002646480_add_dictionary_merge_python.txt
Q: Simple non-network concurrency with Twisted I have a problem with using Twisted for simple concurrency in python. The problem is - I don't know how to do it and all online resources are about Twisted networking abilities. So I am turning to SO-gurus for some guidance. Python 2.5 is used. Simplified version of my p...
Simple non-network concurrency with Twisted
I have a problem with using Twisted for simple concurrency in python. The problem is - I don't know how to do it and all online resources are about Twisted networking abilities. So I am turning to SO-gurus for some guidance. Python 2.5 is used. Simplified version of my problem runs as follows: A bunch of scientific da...
[ "As Jean-Paul said, Twisted is great for coordinating multiple processes. However, unless you need to use Twisted, and simply need a distributed processing pool, there are possibly better suited tools out there.\nOne I can think of which hasn't been mentioned is celery. Celery is a distributed task queue - you set ...
[ 4, 3, 2, 1 ]
[]
[]
[ "concurrency", "python", "twisted" ]
stackoverflow_0002539599_concurrency_python_twisted.txt
Q: Using the Queue class in Python 2.6 Let's assume I'm stuck using Python 2.6, and can't upgrade (even if that would help). I've written a program that uses the Queue class. My producer is a simple directory listing. My consumer threads pull a file from the queue, and do stuff with it. If the file has already be...
Using the Queue class in Python 2.6
Let's assume I'm stuck using Python 2.6, and can't upgrade (even if that would help). I've written a program that uses the Queue class. My producer is a simple directory listing. My consumer threads pull a file from the queue, and do stuff with it. If the file has already been processed, I skip it. The processed li...
[ "I tried running your code, and did not see the behavior you describe. However, the program never exits. I recommend changing the .get() call as follows:\n try:\n file = dirlist.get(True, 1)\n except Queue.Empty:\n return\n\nIf you want to know which thread is currently executing, you can impo...
[ 2, 1 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0002650057_multithreading_python_queue.txt
Q: How to replace by regular expression to lowercase in python I want to search key words (keys would be dynamic) and replace them in a certain format. For example: these data keys = ["cat", "dog", "mouse"] text = "Cat dog cat cloud miracle DOG MouSE" had to be converted to converted_text = "[Cat](cat) [dog](dog) [c...
How to replace by regular expression to lowercase in python
I want to search key words (keys would be dynamic) and replace them in a certain format. For example: these data keys = ["cat", "dog", "mouse"] text = "Cat dog cat cloud miracle DOG MouSE" had to be converted to converted_text = "[Cat](cat) [dog](dog) [cat](cat) cloud miracle [DOG](dog) [MouSE](mouse)" Here is my cod...
[ "You can use a function to do the replacing:\npattern = re.compile('|'.join(map(re.escape, keys)), re.IGNORECASE)\ndef format_term(term):\n return '[%s](%s)' % (term, term.lower())\n\nconverted_text = pattern.sub(lambda m: format_term(m.group(0)), text)\n\n", "no need to use regex\n>>> keys = [\"cat\", \"dog\"...
[ 11, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002643737_python_regex.txt
Q: How to give an error when no options are given with optparse I'm try to work out how to use optparse, but I've come to a problem. My script (represented by this simplified example) takes a file, and does different things to it depending on options that are parsed to it. If no options are parsed nothing is done. It...
How to give an error when no options are given with optparse
I'm try to work out how to use optparse, but I've come to a problem. My script (represented by this simplified example) takes a file, and does different things to it depending on options that are parsed to it. If no options are parsed nothing is done. It makes sense to me that because of this, an error should be given ...
[ "The required argument to a program is usually given without a flag, i.e.:\nmunch <filename>\n\nAnd not:\nmunch --name <filename>\n\nThis custom makes sure the user realizes that <filename> is mandatory and not optional. parse_args returns the options object and a list of leftover arguments - those without flags. I...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002650612_python.txt
Q: python interval i've dev code for wifi scanning in python, now i trying to modify my code so it will scan wifi at specific interval, how this can be done thanks A: You generally have two solutions: schedule to run the python script which refreshes WIFI info at various interval, using crontab or similar exter...
python interval
i've dev code for wifi scanning in python, now i trying to modify my code so it will scan wifi at specific interval, how this can be done thanks
[ "You generally have two solutions: \n\nschedule to run the python script which refreshes WIFI info at various interval, using crontab or similar external device.\nkeep the [python] program running and use threading.timer to schedule calls to the WIFI checking routine at desired intervals.\n\n", "If you want it al...
[ 4, 3 ]
[]
[]
[ "intervals", "python" ]
stackoverflow_0002650477_intervals_python.txt
Q: How do I redirect stdin/stdout when I have a sequence of commands in Bash? I've currently got a Bash command being executed (via Python's subprocess.Popen) which is reading from stdin, doing something and outputing to stdout. Something along the lines of: pid = subprocess.Popen( ["-c", "cmd1 | cmd2"], ...
How do I redirect stdin/stdout when I have a sequence of commands in Bash?
I've currently got a Bash command being executed (via Python's subprocess.Popen) which is reading from stdin, doing something and outputing to stdout. Something along the lines of: pid = subprocess.Popen( ["-c", "cmd1 | cmd2"], stdin = subprocess.PIPE, stdout = subprocess...
[ "execute cmd0 and cmd1 in a subshell and redirect /dev/null as stdin for cmd0:\n(cmd0 </dev/null; cmd1) | cmd2\n\n", "I don't think you should have to do anything special. If cmd0 doesn't touch stdin, it'll be intact for cmd1. Try for yourself:\nls | ( echo \"foo\"; sed 's/^/input: /')\n\n(Using ls as an arbitrar...
[ 4, 1, 0 ]
[]
[]
[ "bash", "pipe", "python", "subprocess" ]
stackoverflow_0002650759_bash_pipe_python_subprocess.txt
Q: Basic anydbm example generates 'AttributeError: iteritems' I'm attempting a pretty cut & dry example of anydbm: #!/usr/bin/python import anydbm # Open database, creating it if necessary. db = anydbm.open('cache',...
Basic anydbm example generates 'AttributeError: iteritems'
I'm attempting a pretty cut & dry example of anydbm: #!/usr/bin/python import anydbm # Open database, creating it if necessary. db = anydbm.open('cache', 'c') # Record some values ...
[ "It appears the Apple-supplied Pythons are not built with any third-party database libraries so anydbm results in the use of the default portable dumbdbm implementation which lacks an iteritems method.\n$ /usr/bin/python2.5\nPython 2.5.4 (r254:67916, Feb 11 2010, 00:50:55) \n[GCC 4.2.1 (Apple Inc. build 5646)] on d...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002650914_python.txt
Q: How can I start using twill? I am sorry I have already asked this question on "Superuser", but nobody answers there, so I deleted it from "Superuser" and decided to post it here. Hope it's not a big crime, especially given the fact that I was firstly advised to use twill here on "StackOverflow" (not on "SuperUser"...
How can I start using twill?
I am sorry I have already asked this question on "Superuser", but nobody answers there, so I deleted it from "Superuser" and decided to post it here. Hope it's not a big crime, especially given the fact that I was firstly advised to use twill here on "StackOverflow" (not on "SuperUser") How do I start using twill? I h...
[ "You cannot just double click setup.py\nYou need to open command prompt or shell and go to that folder\nand need to do\npython setup.py build\npython setup.py install\n\ninstall step should automatically do build normally, so only last one will work\n\nEdit: ok, here is superuser way of installation steps\n\nI have...
[ 10 ]
[]
[]
[ "installation", "python", "twill" ]
stackoverflow_0002651334_installation_python_twill.txt
Q: how to call a c++ file from python without using any of the spam bindings? i have this encryption algorithm written in C++ , but the values that has to be encrypted are being taken input and stored in a file by a python program . Thus how can i call this c++ program from python? A: Look for the subprocess module...
how to call a c++ file from python without using any of the spam bindings?
i have this encryption algorithm written in C++ , but the values that has to be encrypted are being taken input and stored in a file by a python program . Thus how can i call this c++ program from python?
[ "Look for the subprocess module. It is the recommended way to invoke processes from within Python. The os.system function is a viable alternative sometimes, if your needs are very simple (no pipes, simple arguments, etc.)\n", "The os.system function will invoke an arbitrary command-line from python.\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002651466_python.txt
Q: Django database caching I have a Django form that uses an integer field to lookup a model object by its primary key. The form has a save() method that uses the model object referred to by the integer field. The model's manager's get() method is called twice, once in the clean method and once in the save() method...
Django database caching
I have a Django form that uses an integer field to lookup a model object by its primary key. The form has a save() method that uses the model object referred to by the integer field. The model's manager's get() method is called twice, once in the clean method and once in the save() method: class MyForm(forms.Form): ...
[ "No, the value wouldn't be cached. Your second example is the right way to go. \n(The first snippet actually contains an error, in that nothing is returned from the clean method, so the id_a attribute would end up empty.)\n", "This query is not cached. get() calls never are. QuerySets on the other hand, are (some...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002651193_django_django_models_python.txt
Q: How to use Python list comprehension (or such) for retrieving rows when using MySQLdb? I use MySQLdb a lot when dealing with my webserver. I often find myself repeating the lines: row = cursor.fetchone() while row: do_processing(row) row = cursor.fetchone() Somehow this strikes me as somewhat un-pythonic...
How to use Python list comprehension (or such) for retrieving rows when using MySQLdb?
I use MySQLdb a lot when dealing with my webserver. I often find myself repeating the lines: row = cursor.fetchone() while row: do_processing(row) row = cursor.fetchone() Somehow this strikes me as somewhat un-pythonic. Is there a better, one-line way to accomplish the same thing, along the lines of inline as...
[ "There isn't really a way to get list comprehensions involved in this. You need a loop that terminates when a sentinel value is returned. Fortunately, Python does provide this:\nfor row in iter(cursor.fetchone, None):\n process(row)\n\nThe two-argument iter() takes a callable, and a sentinel value that will term...
[ 3, 2, 0, 0 ]
[]
[]
[ "coding_style", "mysql", "python" ]
stackoverflow_0002649484_coding_style_mysql_python.txt
Q: What are the most frustrating Python hacks to unwind, rewrite, etc.? My impression of Python from the short time I've been developing with it is that it's incredible powerful and flexible, but I can't help but feel like "with great power comes great responsibility." So while I've read numerous blog posts about si...
What are the most frustrating Python hacks to unwind, rewrite, etc.?
My impression of Python from the short time I've been developing with it is that it's incredible powerful and flexible, but I can't help but feel like "with great power comes great responsibility." So while I've read numerous blog posts about simple and elegant Python snippets that solve a problems, I wonder if there ...
[ "Magic that works but not always. For example, when metaclasses are abused to create a DSL. Such DSL could be suitable for most tasks but breaks horribly on a complex (unexpected by author) one.\n", "Using eval or exec on user input may be the most common abuse of Python features. \n", "Excessive usage of from ...
[ 4, 4, 4, 3, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002647288_python.txt
Q: Self Authenticating Links in Django In my web app I would like to be able to email self-authenticating links to users. These links will contain a unique token (uuid). When they click the link the token being present in the query string will be enough to authenticate them and they won't have to enter their username...
Self Authenticating Links in Django
In my web app I would like to be able to email self-authenticating links to users. These links will contain a unique token (uuid). When they click the link the token being present in the query string will be enough to authenticate them and they won't have to enter their username and password. What's the best way to do ...
[ "That's quite common task if you properly expire your links :) You'll need to implement your own authentication backend. Instead of checking username and password parameters you'll check for auth_link.\nclass AuthLinkBackend(object):\n def authenticate(auth_link = None):\n if auth_link:\n # validate and ex...
[ 3, 0, 0 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0002650189_authentication_django_python.txt
Q: fft and array-to-image / image-to-array-conversion I want to make a fourier-transformation of an image. But how can I change the picture to an array? And after this I think I should use numpy.fft.rfft2 for the transformation. And how to change back from the array to the image? Thanks in advance. A: You can use t...
fft and array-to-image / image-to-array-conversion
I want to make a fourier-transformation of an image. But how can I change the picture to an array? And after this I think I should use numpy.fft.rfft2 for the transformation. And how to change back from the array to the image? Thanks in advance.
[ "You can use the PIL library to load/save images and convert to/from numpy arrays.\nimport Image, numpy\ni = Image.open('img.png')\ni = i.convert('L') #convert to grayscale\na = numpy.asarray(i) # a is readonly\n\nb = abs(numpy.fft.rfft2(a))\n\nj = Image.fromarray(b)\nj.save('img2.png')\n\nI used abs above becau...
[ 12 ]
[]
[]
[ "fft", "image_processing", "python" ]
stackoverflow_0002652415_fft_image_processing_python.txt
Q: matplotlib equivalent for MATLABs truesize() I am new to matplotlib and python and would like to display an image so that 1 pixel of the image is actually represented by 1 pixel in the figure. In MATLAB, this is achieved with the command truesize(). How can I do this in Python? I tried playing around with the imsh...
matplotlib equivalent for MATLABs truesize()
I am new to matplotlib and python and would like to display an image so that 1 pixel of the image is actually represented by 1 pixel in the figure. In MATLAB, this is achieved with the command truesize(). How can I do this in Python? I tried playing around with the imshow() arguments as well as set_dpi() and set_figwid...
[ "If you want to create images right down to the pixel level, why not use PIL in the first place? That way you wouldn't have to programatically calculate your true drawing area by substracting margins, labels and axis widths from the figure extend.\n", "This hack does what I wanted to do, though it's still not per...
[ 1, 0 ]
[]
[]
[ "matlab", "matplotlib", "python" ]
stackoverflow_0002645049_matlab_matplotlib_python.txt
Q: Can't iterate over a list class in Python I'm trying to write a simple GUI front end for Plurk using pyplurk. I have successfully got it to create the API connection, log in, and retrieve and display a list of friends. Now I'm trying to retrieve and display a list of Plurks. pyplurk provides a GetNewPlurks functi...
Can't iterate over a list class in Python
I'm trying to write a simple GUI front end for Plurk using pyplurk. I have successfully got it to create the API connection, log in, and retrieve and display a list of friends. Now I'm trying to retrieve and display a list of Plurks. pyplurk provides a GetNewPlurks function as follows: def GetNewPlurks(self, since):...
[ "When you define your own __iter__ method, you should realize that that __iter__ method should return an iterator, not an iterable. You are returning a list, not an iterator to a list, so it fails. You can fix it by doing return iter(self._plurks), for example.\nIf you wanted to do something a little more complex, ...
[ 14, 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002652761_python.txt
Q: Create matplotlib legend out of the figure I added the legend this way: leg = fig.legend((l0,l1,l2,l3,l4,l5,l6), ('0 Cl : r2, slope, origin', '1 Cl :'+str(r1b)+' , '+str(m1)+' , '+str(b1), '2 Cl :'+str(r2b)+' , '+str(m2)+' , '+str(b2), '3 Cl :'+str(r3b)+' , '+str(m3)+' , '+str(b3), '4 Cl...
Create matplotlib legend out of the figure
I added the legend this way: leg = fig.legend((l0,l1,l2,l3,l4,l5,l6), ('0 Cl : r2, slope, origin', '1 Cl :'+str(r1b)+' , '+str(m1)+' , '+str(b1), '2 Cl :'+str(r2b)+' , '+str(m2)+' , '+str(b2), '3 Cl :'+str(r3b)+' , '+str(m3)+' , '+str(b3), '4 Cl :'+str(r4b)+' , '+str(m4)+' , '+str(b4), ...
[ "did you try:\nfig.legend((plot1,plot2), (lab1,lab2), 'right')\n\n'right' shows the legend at the right of the axes\nas for the second question (help for a command) you could look at the matplotlib demos (for example http://matplotlib.sourceforge.net/examples/api/legend_demo.html and API (for example, http://matplo...
[ 3 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0002652624_matplotlib_numpy_python.txt
Q: How to convert SVG images for use with Pisa / XHTML2PDF? I'm using Pisa/XHTML2PDF to generate PDFs on the fly in Django. Unfortunately, I need to include SVG images as well, which I don't believe is an easy task. What's the best way to go about either a) converting the SVGs to PNG / JPG (in Python) or b) including...
How to convert SVG images for use with Pisa / XHTML2PDF?
I'm using Pisa/XHTML2PDF to generate PDFs on the fly in Django. Unfortunately, I need to include SVG images as well, which I don't believe is an easy task. What's the best way to go about either a) converting the SVGs to PNG / JPG (in Python) or b) including SVGs in the PDF export from Pisa?
[ "There's the Java based Apache Batik SVG toolkit.\nIn a similar question regarding C# it was proposed using the command line version of Inkscape for this.\nFor Python, here's a useful suggestion from this discussion thread:\nimport rsvg\nfrom gtk import gdk\nh = rsvg.Handle('svg-file.svg')\npixbuf = h.get_pixbuf()\...
[ 2, 1 ]
[]
[]
[ "pdf", "pdf_generation", "pisa", "python", "svg" ]
stackoverflow_0000787287_pdf_pdf_generation_pisa_python_svg.txt
Q: Python Tkinter comparing PhotoImage objects In a simple LightsOut game, when I click on a light I need to toggle the image on a button. I'm doing this with Tkinter, so I thought I'd just check and see what image is currently on the button (either 'on.gif' or 'off.gif') and set it to the other one, like this: def c...
Python Tkinter comparing PhotoImage objects
In a simple LightsOut game, when I click on a light I need to toggle the image on a button. I'm doing this with Tkinter, so I thought I'd just check and see what image is currently on the button (either 'on.gif' or 'off.gif') and set it to the other one, like this: def click(self,x,y): if self.buttons[x][y].image =...
[ "Pointers\n\nself.buttons[x][y].image == self.off, are you sure you want \"==\" instead of \"=\"\nComparing images to get what state you are in is not a good way, instead use a variable e.g self._isLightOn and toggle it when you change states, based on this variable set correct images, or text or whatever.\n\n" ]
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0002653119_python_tkinter.txt
Q: Is there an equivalent in Scala to Python's more general map function? I know that Scala's Lists have a map implementation with signature (f: (A) => B):List[B] and a foreach implementation with signature (f: (A) => Unit):Unit but I'm looking for something that accepts multiple iterables the same way that the Pytho...
Is there an equivalent in Scala to Python's more general map function?
I know that Scala's Lists have a map implementation with signature (f: (A) => B):List[B] and a foreach implementation with signature (f: (A) => Unit):Unit but I'm looking for something that accepts multiple iterables the same way that the Python map accepts multiple iterables. I'm looking for something with a signature...
[ "In scala 2.8, there is a method called zipped in Tuple2 & Tuple3 which avoid to create temporary collection.\nHere is some sample use case:\nWelcome to Scala version 2.8.0.r21561-b20100414020114 (Java HotSpot(TM) Client VM, Java 1.6.0_18).\nType in expressions to have them evaluated.\nType :help for more informati...
[ 12, 11, 3, 2 ]
[]
[]
[ "applicative", "iterable", "python", "scala" ]
stackoverflow_0002650156_applicative_iterable_python_scala.txt
Q: Inexpensive ways to add seek to a filetype object PdfFileReader reads the content from a pdf file to create an object. I am querying the pdf from a cdn via urllib.urlopen(), this provides me a file like object, which has no seek. PdfFileReader, however uses seek. What is the simple way to create a PdfFileReader ob...
Inexpensive ways to add seek to a filetype object
PdfFileReader reads the content from a pdf file to create an object. I am querying the pdf from a cdn via urllib.urlopen(), this provides me a file like object, which has no seek. PdfFileReader, however uses seek. What is the simple way to create a PdfFileReader object from a pdf downloaded via url. Now, what can I do ...
[ "You could use the .read() method to read in the entire data of the file, and then create your own File-like object (most likely via StringIO) to provide access to it.\n", "There isn't really an inexpensive, ready-to-use way to do this. The simplest way is to read all data and put it into a StringIO object. That ...
[ 1, 1, 1 ]
[]
[]
[ "file", "file_type", "python", "urllib" ]
stackoverflow_0002653079_file_file_type_python_urllib.txt
Q: Cython code doesn't work I wrote some Python code and it worked fine when using the "python". I then converted it to C using "Cython" and used distutils to compile it to a shared library. I then changed some of the code to Cython so it would run faster. But when I imported the .so module and tried to use the comma...
Cython code doesn't work
I wrote some Python code and it worked fine when using the "python". I then converted it to C using "Cython" and used distutils to compile it to a shared library. I then changed some of the code to Cython so it would run faster. But when I imported the .so module and tried to use the command I had "cdef"ed it said that...
[ "cdef functions are not exposed to Python. cpdef is provided to provide a Python wrapper to a C function defined in Cython.\nAlso, you're probably better off using timeit than bothering with implementing this.\n" ]
[ 2 ]
[]
[]
[ "cython", "function", "python" ]
stackoverflow_0002653712_cython_function_python.txt
Q: Importing a submodule given a module object I am given a module as an object, and I need to import a submodule from it. Like this: import logging x = logging Now I want to import logging.handlers using only x and not the name "logging". (This is because I am doing some dynamic imports and won't know the name of t...
Importing a submodule given a module object
I am given a module as an object, and I need to import a submodule from it. Like this: import logging x = logging Now I want to import logging.handlers using only x and not the name "logging". (This is because I am doing some dynamic imports and won't know the name of the module.) How do I do this? If I do import x.ha...
[ "Try:\n__import__('%s.handlers' % x.__name__)\n\nNote that this will return a reference to logging, which you probably won't care about. It will create x.handlers though.\n", "You can use built-in function __import__:\nhttp://docs.python.org/library/functions.html#import\n" ]
[ 5, 0 ]
[]
[]
[ "dynamic", "import", "python" ]
stackoverflow_0002654046_dynamic_import_python.txt
Q: Double linking array in Python Since I'm pretty new this question'll certainly sound stupid but I have no idea about how to approach this. I'm trying take a list of nodes and for each of the nodes I want to create an array of predecessors and successors in the ordered array of all nodes. Currently my code looks li...
Double linking array in Python
Since I'm pretty new this question'll certainly sound stupid but I have no idea about how to approach this. I'm trying take a list of nodes and for each of the nodes I want to create an array of predecessors and successors in the ordered array of all nodes. Currently my code looks like this: nodes = self.peers.keys...
[ "I would almost bet that when the error occurs, the values in nodes have duplicates, which would cause your dictionary in peers to get mixed up. Your code assumes the values in nodes are unique.\n" ]
[ 2 ]
[]
[]
[ "arrays", "indexing", "overlay", "p2p", "python" ]
stackoverflow_0002653702_arrays_indexing_overlay_p2p_python.txt
Q: Error on windows using session from appengine-utilities I ran across an odd problem while trying to transfer a project to a windows machine. In my project I use a session handler (http://gaeutilities.appspot.com/session) it works fine on my mac but on windows I get: Traceback (most recent call last): File "C:\Pro...
Error on windows using session from appengine-utilities
I ran across an odd problem while trying to transfer a project to a windows machine. In my project I use a session handler (http://gaeutilities.appspot.com/session) it works fine on my mac but on windows I get: Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext...
[ "The bug is pretty clear by glancing at the sources, although perfectly OS-independent. In sessions.py lines 544-547:\n string_cookie = os.environ.get(u\"HTTP_COOKIE\", u\"\")\n self.cookie = Cookie.SimpleCookie()\n self.output_cookie = Cookie.SimpleCookie()\n self.cookie.load(string_cookie)\n\nlines 5...
[ 11, 1 ]
[]
[]
[ "google_app_engine", "python", "session" ]
stackoverflow_0002652820_google_app_engine_python_session.txt
Q: access variables of other functions in python, how can i access the variables of one function into another function, is it possible, i tried the global variable method but that doesn't work for me. can someone help me, how to access the variables from one function to another function. A: If you want to share dat...
access variables of other functions
in python, how can i access the variables of one function into another function, is it possible, i tried the global variable method but that doesn't work for me. can someone help me, how to access the variables from one function to another function.
[ "If you want to share data between functions then create a class and turn the functions into methods on the class. \n", "Don't try to do this. Explicit is better than implicit - if your function needs access to certain variables, pass them in. If it needs to change a value in the calling function, return the new...
[ 1, 0 ]
[]
[]
[ "function", "global_variables", "python", "variables" ]
stackoverflow_0002654484_function_global_variables_python_variables.txt
Q: Is there a production ready web application framework in Python? I heard lots of good opinions about Python language. They say it's mature, expressive etc... I'm looking for production-ready enterprise application frameworks in Python. By "production ready" I mean : supports objective-relational mapping with cach...
Is there a production ready web application framework in Python?
I heard lots of good opinions about Python language. They say it's mature, expressive etc... I'm looking for production-ready enterprise application frameworks in Python. By "production ready" I mean : supports objective-relational mapping with caching and declarative desciption (like JPA, Hibernate etc..) controls or...
[ "Django seems like the obvious choice. It is by far the most stable and developed framework, used by several large corporations.\nBecause it is a Python framework, it can generally use any Python module, as well as the many modules that have been made for Django.\nIt should fulfill all of your needs, and is not ter...
[ 27, 15, 5, 4, 1, 1 ]
[]
[]
[ "python", "web_applications" ]
stackoverflow_0002643321_python_web_applications.txt
Q: Is Django a good choice for a security critical application? Is Django a good choice for a security critical application? I am asking this because most of the online banking software is built using Java. Is there any real reason for this? A: Actually, the security in Java and Python is the same. Digest-only pas...
Is Django a good choice for a security critical application?
Is Django a good choice for a security critical application? I am asking this because most of the online banking software is built using Java. Is there any real reason for this?
[ "Actually, the security in Java and Python is the same. Digest-only password handling, cookies that timeout rapidly, careful deletion of sessions, multi-factor authentication. None of this is unique to a Java framework or a Python framework like Django.\nDjango, indeed, has a security backend architecture that al...
[ 30, 17, 8, 4, 1, 1, 0 ]
[]
[]
[ "django", "python", "security" ]
stackoverflow_0000498630_django_python_security.txt
Q: Does sending a dictionary through a multiprocessing.queue mutate it somehow? I have a setup where I send a dictionary through a multiprocessing.queue and do some stuff with it. I was getting an odd "dictionary size changed while iterating over it" error when I wasn't changing anything in the dictionary. Here's t...
Does sending a dictionary through a multiprocessing.queue mutate it somehow?
I have a setup where I send a dictionary through a multiprocessing.queue and do some stuff with it. I was getting an odd "dictionary size changed while iterating over it" error when I wasn't changing anything in the dictionary. Here's the traceback, although it's not terribly helpful: Traceback (most recent call last...
[ "There was a bug fixed quite recently where a garbage collection could change the size of a dictionary that contained weak references and that could trigger the \"dictionary changed size during iteration\" error. I don't know if that is your problem but the multiprocessing package does use weak references.\nSee htt...
[ 2 ]
[]
[]
[ "dictionary", "multiprocessing", "python", "queue" ]
stackoverflow_0002653698_dictionary_multiprocessing_python_queue.txt
Q: Python: Convert format string to regular expression The users of my app can configure the layout of certain files via a format string. For example, the config value the user specifies might be: layout = '%(group)s/foo-%(locale)s/file.txt' I now need to find all such files that already exist. This seems easy enoug...
Python: Convert format string to regular expression
The users of my app can configure the layout of certain files via a format string. For example, the config value the user specifies might be: layout = '%(group)s/foo-%(locale)s/file.txt' I now need to find all such files that already exist. This seems easy enough using the glob module: glob_pattern = layout % {'group'...
[ "Since you are using named placeholders, I'd use named groups. This seems to work:\nimport re\nUNIQ='_UNIQUE_STRING_'\nclass MarkPlaceholders(dict):\n def __getitem__(self, key):\n return UNIQ+('(?P<%s>.*?)'%key)+UNIQ\n\ndef format_to_re(format):\n parts = (format % MarkPlaceholders()).split(UNIQ)\n ...
[ 2, 1 ]
[]
[]
[ "formatting", "python", "regex" ]
stackoverflow_0002654856_formatting_python_regex.txt
Q: What's the equivalent of Ruby's class @@variable in Python? In Ruby 1.9, I can use its class variable like the following: class Sample @@count = 0 def initialize @@count += 1 end def count @@count end end sample = Sample.new puts sample.count # Output: 1 sample2 = Sample.new puts sample2....
What's the equivalent of Ruby's class @@variable in Python?
In Ruby 1.9, I can use its class variable like the following: class Sample @@count = 0 def initialize @@count += 1 end def count @@count end end sample = Sample.new puts sample.count # Output: 1 sample2 = Sample.new puts sample2.count # Output: 2 How can I achieve the above in Python 2.5+ ...
[ "class Sample(object):\n _count = 0\n\n def __init__(self):\n Sample._count += 1\n\n @property\n def count(self):\n return Sample._count\n\nThe use is a bit different from Ruby; e.g. if you have this code in module a.py,\n>>> import a\n>>> x = a.Sample()\n>>> print x.count\n1\n>>> y = a.Sample()\n>>> prin...
[ 6 ]
[]
[]
[ "class_variables", "python", "ruby" ]
stackoverflow_0002655104_class_variables_python_ruby.txt
Q: django link format words joined with hypens href="http://www.torontolife.com/daily/daily-dish/restauranto/2010/03/10/best-new-restaurants-2010-james-chatto-names-five-honourable-mentions/">Best new restaurants 2010: honourable mentions does django have built in mechanism to format links above i mean words joined w...
django link format words joined with hypens
href="http://www.torontolife.com/daily/daily-dish/restauranto/2010/03/10/best-new-restaurants-2010-james-chatto-names-five-honourable-mentions/">Best new restaurants 2010: honourable mentions does django have built in mechanism to format links above i mean words joined with hypens how can i achieve this ?
[ "At a lower level, Django provides a function to transform an arbitrary string into a slug:\n>>> from django.template.defaultfilters import slugify\n>>> print slugify('Hello, World!')\nhello-world\n\nAnd because slugify is a default template filter, you can always use this in your templates like so:\n{{ foo.name|sl...
[ 4, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002655086_django_python.txt
Q: Stop execution of python script when parent Bash shell script is killed I'm working on a Bash shell script that runs several Python scripts like so: cd ${SCRIPT_PATH} python -u ${SCRIPT_NAME} ${SCRIPT_ARGS} >> $JOBLOG 2>&1 At one point, I killed the shell script (using kill PID), but the Python script continued r...
Stop execution of python script when parent Bash shell script is killed
I'm working on a Bash shell script that runs several Python scripts like so: cd ${SCRIPT_PATH} python -u ${SCRIPT_NAME} ${SCRIPT_ARGS} >> $JOBLOG 2>&1 At one point, I killed the shell script (using kill PID), but the Python script continued running, even after the script terminated. I thought these would die as soon a...
[ "You need to install a signal handler to take care of your child processes:\ntrap \"echo killing childs; pkill -P $$\" EXIT\n\n", "Children should be sent SIGHUP when the parent process dies - however:\na) The child process can ignore SIGHUP, or handle it a non-fatal manner.\nb) The Child could disassociate itse...
[ 2, 1 ]
[]
[]
[ "bash", "python", "shell" ]
stackoverflow_0002655403_bash_python_shell.txt
Q: Is it approproate it use django signals within the same app Trying to add email notification to my app in the cleanest way possible. When certain fields of a model change, app should send a notification to a user. Here's my old solution: from django.contrib.auth import User class MyModel(models.Model): user...
Is it approproate it use django signals within the same app
Trying to add email notification to my app in the cleanest way possible. When certain fields of a model change, app should send a notification to a user. Here's my old solution: from django.contrib.auth import User class MyModel(models.Model): user = models.ForeignKey(User) field_a = models.CharField() f...
[ "I think it's a good idea. The \"Custom Signals for Uncoupled Design\" talk from the most recent DjangoCon is a great resource of what is possible and appropriate with signals in Django. \n", "I think using signals here is a good design decision. The notification isn't part of the save, it's a consequence of the ...
[ 4, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002655226_django_python.txt
Q: Writing a DBMS in Python I'm working on a basic DBMS as a pet project and planning to prototype in Python. I figure there's a reason there are only a few Python databases, and my gut agrees that my favorite language will be too slow to act as an honest performing database, but I'm looking forward to using it to le...
Writing a DBMS in Python
I'm working on a basic DBMS as a pet project and planning to prototype in Python. I figure there's a reason there are only a few Python databases, and my gut agrees that my favorite language will be too slow to act as an honest performing database, but I'm looking forward to using it to learn what I need quickly. Would...
[ "It's doubtful that anything you create as a pet project is going to turn out to be popular. Presumably you are mostly doing this as a learning experience and for fun.\nGiven these facts, there's no reason to stop yourself so early just because you think there might be performance problems. Just do it and have fun...
[ 4, 1 ]
[]
[]
[ "database", "performance", "prototype", "python" ]
stackoverflow_0002655748_database_performance_prototype_python.txt
Q: Accessing data entered into multiple Django forms and generating them onto a new URL I have a projects page where users can start up new projects. Each project has two forms. The two forms are: class ProjectForm(forms.Form): Title = forms.CharField(max_length=100, widget=_hfill) class SsdForm(forms.Form): Status ...
Accessing data entered into multiple Django forms and generating them onto a new URL
I have a projects page where users can start up new projects. Each project has two forms. The two forms are: class ProjectForm(forms.Form): Title = forms.CharField(max_length=100, widget=_hfill) class SsdForm(forms.Form): Status = forms.ModelChoiceField(queryset=P.ProjectStatus.objects.all()) With their respective mo...
[ "You don't seem to have any relationship between Project and SSD. Without that, there's no way of telling that any particular SSD object is a member of a particular project. I presume that there are other fields on these models, otherwise there's no point in having SSD as a separate model - status should just be a ...
[ 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0002655537_django_mysql_python.txt
Q: Identifying that a variable is a new-style class in Python? I'm using Python 2.x and I'm wondering if there's a way to tell if a variable is a new-style class? I know that if it's an old-style class that I can do the following to find out. import types class oldclass: pass def test(): o = oldclass() if typ...
Identifying that a variable is a new-style class in Python?
I'm using Python 2.x and I'm wondering if there's a way to tell if a variable is a new-style class? I know that if it's an old-style class that I can do the following to find out. import types class oldclass: pass def test(): o = oldclass() if type(o) is types.InstanceType: print 'Is old-style' else: ...
[ "I think what you are asking is: \"Can I test if a class was defined in Python code as a new-style class?\". Technically simple types such as int are new-style classes, but it is still possible to distinguish classes written in Python from the built-in types.\nHere's something that works, although it's a bit of a ...
[ 7, 2, 1 ]
[ "Checking for old-style classes is really easy. Just check type(cls) is types.ClassType. Checking for new-style classes is also easy, isinstance(cls, type). Note that the built-in types are also new-style classes.\nThere seems to be no trivial way to distinguish built-ins from classes written in Python. New-style c...
[ -1 ]
[ "class", "python", "python_2.x" ]
stackoverflow_0002654622_class_python_python_2.x.txt
Q: Error with python decorator I get this error object has no attribute 'im_func' with this class Test(object): def __init__(self, f): self.func = f def __call__( self, *args ): return self.func(*args) pylons code: class TestController(BaseController): @Test def index(self): ...
Error with python decorator
I get this error object has no attribute 'im_func' with this class Test(object): def __init__(self, f): self.func = f def __call__( self, *args ): return self.func(*args) pylons code: class TestController(BaseController): @Test def index(self): return 'hello world' full erro...
[ "TestController.index ends up an instance of Test, with no access to the TestController object. Also, only user defined methods (which must be functions, not objects) have an im_func attribute. You'll need to instantiate Test and have its __call__ method return a function so that it can be passed the TestController...
[ 4, 1, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002655383_decorator_python.txt
Q: filtering elements from list of lists in Python? I want to filter elements from a list of lists, and iterate over the elements of each element using a lambda. For example, given the list: a = [[1,2,3],[4,5,6]] suppose that I want to keep only elements where the sum of the list is greater than N. I tried writing:...
filtering elements from list of lists in Python?
I want to filter elements from a list of lists, and iterate over the elements of each element using a lambda. For example, given the list: a = [[1,2,3],[4,5,6]] suppose that I want to keep only elements where the sum of the list is greater than N. I tried writing: filter(lambda x, y, z: x + y + z >= N, a) but I get ...
[ "Using lambda with filter is sort of silly when we have other techniques available.\nIn this case I would probably solve the specific problem this way (or using the equivalent generator expression)\n>>> a = [[1, 2, 3], [4, 5, 6]]\n>>> [item for item in a if sum(item) > 10]\n[[4, 5, 6]]\n\nor, if I needed to unpack,...
[ 40, 11, 1, 1, 0, 0, 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0002655956_list_list_comprehension_python.txt
Q: Python Qlistview output dir i wish make little gui with pyqt4 that show the output of "dir c:\windows\" line by line I'm looking for QlistView but i don't understand how do it. Can anyone help me? A: import os for root, dirs, files in os.walk(r'C:\windows'): //add your QlistView add codes here A: Try QList...
Python Qlistview output dir
i wish make little gui with pyqt4 that show the output of "dir c:\windows\" line by line I'm looking for QlistView but i don't understand how do it. Can anyone help me?
[ "import os\nfor root, dirs, files in os.walk(r'C:\\windows'):\n //add your QlistView add codes here\n\n", "Try QListWidget instead of QListView. QListWidget extends QListView and adds some very helpful methods like addItems.\nI'm going to assume you know how to create the GUI part of the application using Des...
[ 1, 0 ]
[]
[]
[ "pyqt4", "python", "qlistview" ]
stackoverflow_0002653898_pyqt4_python_qlistview.txt
Q: Adding a font for use in ReportLab I'm trying to add a font to the python ReportLab so that I can use it for a function. The function is using canvas.Canvas to draw a bunch of text in a PDF, nothing complicated, but I need to add a fixed width font for layout issues. When I tried to register a font using what lit...
Adding a font for use in ReportLab
I'm trying to add a font to the python ReportLab so that I can use it for a function. The function is using canvas.Canvas to draw a bunch of text in a PDF, nothing complicated, but I need to add a fixed width font for layout issues. When I tried to register a font using what little info I could find, that seemed to wo...
[ "c.setFont('TestFont')\nc.drawString(1,1,'test data here')\n\nsetFont to set the font name you're going to use, and drawString.\nReportLab will automatically embed the font if you use it in the document, you don't have to manually add it after you've registered the font globally under a name.\n" ]
[ 8 ]
[]
[]
[ "fonts", "python", "reportlab" ]
stackoverflow_0002656145_fonts_python_reportlab.txt
Q: Django, How authenticate user with first name and last name? i want to authenticate users using firstname and lastname This is the code i am using user = auth.authenticate(first_name=firstname,last_name=lastname,password=password) it keep coming up with NoneType: None i have checked the firstname and lastname plu...
Django, How authenticate user with first name and last name?
i want to authenticate users using firstname and lastname This is the code i am using user = auth.authenticate(first_name=firstname,last_name=lastname,password=password) it keep coming up with NoneType: None i have checked the firstname and lastname plus password seen to be correct? what i am doing wrong? thanks
[ "The difficulty here is that normally you'd handle this by creating a custom authentication backend that implements authenticate and get_user. However, the function signature for authenticate is:\ndef authenticate(self, username=None, password=None):\n\nEverywhere in Django that would be calling this will be passi...
[ 3, 2, 2, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0002650106_django_django_admin_django_models_python.txt
Q: Cleaner way to get user name in pylons with repoze.name in mako template, i use this ${request.environ['repoze.who.identity']['user']} and the render in controller: render('file.html') can i write this better without passing in parameter everytime? A: Well, you can auto add the varible in the base controller i...
Cleaner way to get user name in pylons with repoze.name
in mako template, i use this ${request.environ['repoze.who.identity']['user']} and the render in controller: render('file.html') can i write this better without passing in parameter everytime?
[ "Well, you can auto add the varible in the base controller in /lib/base.py. This will add it to every controller in your pylons application automatically. I'm using repoze.what and what I do is in base.py I put:\n# if there's no user set, just setup a blank instance\nc.current_user = auth.get_user(User()) \n\nAnd t...
[ 2 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002656066_pylons_python.txt
Q: Handle incorrect user/password repoze.who gracefully in Python/Pylons im using FriendlyFormPlugin, but would like to retrieve the username that was input as part of the request.params, but its no longer there when i check. this way i can set the default for username if the password is incorrect. thanks A: I th...
Handle incorrect user/password repoze.who gracefully in Python/Pylons
im using FriendlyFormPlugin, but would like to retrieve the username that was input as part of the request.params, but its no longer there when i check. this way i can set the default for username if the password is incorrect. thanks
[ "I think what you need to do is to setup a post login handler action when you setup the middleware. In that action you can then check params, set a session var, etc. I had to hook into here in order to create a message to the user that their login had failed. I check for a 'login_failed' param on the login form. \...
[ 3 ]
[]
[]
[ "pylons", "python", "repoze.who" ]
stackoverflow_0002656374_pylons_python_repoze.who.txt
Q: Preserve time stamp when shrinking an image My digital camera takes pictures with a very high resolution, and I have a PIL script to shrink them to 800x600 (or 600x800). However, it would be nice for the resultant file to retain the original timestamp. I noticed in the docs that I can use a File object instead of ...
Preserve time stamp when shrinking an image
My digital camera takes pictures with a very high resolution, and I have a PIL script to shrink them to 800x600 (or 600x800). However, it would be nice for the resultant file to retain the original timestamp. I noticed in the docs that I can use a File object instead of a name in PIL's image save method, but I don't kn...
[ "Use shutil.copystat\nIt appears that PIL does not save EXIF metadata.\nTo copy the EXIF data using Python you could use\npyexiv2. This is how Phatch, a batch photo resizer program written in Python, deals with EXIF data, for example.\nI'm not sure if you're using Ubuntu, but if so, installation is easy since pyexi...
[ 5 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0002656900_python_python_imaging_library.txt
Q: python os.execvp() trying to display mysql tables gives 1049 error - Unknown database error I have a question related to MySQL and Python. This command works on the shell, but not when I use os.execvp. $./mysql -D test -e "show tables" +----------------+ | Tables_in_test | +----------------+ | sample | +...
python os.execvp() trying to display mysql tables gives 1049 error - Unknown database error
I have a question related to MySQL and Python. This command works on the shell, but not when I use os.execvp. $./mysql -D test -e "show tables" +----------------+ | Tables_in_test | +----------------+ | sample | +----------------+ The corresponding piece of code in python would be def execute(): args = [...
[ "Each of your separate parameters needs to be a separate element in the list of parameters.\nargs.extend([MYSQL, '-D test', '-e \"show tables\"'])\n\n", "Try:\nargs.extend([MYSQL, '-D', 'test', '-e', 'show tables'])\n\nYou might also be interested in the subprocess module if you weren't aware of it:\n>>> import s...
[ 0, 0 ]
[]
[]
[ "mysql", "mysql_error_1049", "python" ]
stackoverflow_0002654148_mysql_mysql_error_1049_python.txt
Q: Attribute References in Python I do Java programming and recently started learning Python via the official documentation. I see that we can dynamically add data attributes to an instance object unlike in Java: class House: pass my_house = House() my_house.number = 40 my_house.rooms = 8 my_house.garden = 1 My ...
Attribute References in Python
I do Java programming and recently started learning Python via the official documentation. I see that we can dynamically add data attributes to an instance object unlike in Java: class House: pass my_house = House() my_house.number = 40 my_house.rooms = 8 my_house.garden = 1 My question is, in what situations is t...
[ "It can also be used when dynamically creating classes; see for instance this tutorial:\nhttp://onlamp.com/pub/a/python/2003/04/17/metaclasses.html?page=1\nor this one on Mix-ins, a programming technique that uses this capability to provide better encapsulation and modularity to object oriented code: \nhttp://www.l...
[ 2, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002656922_oop_python.txt
Q: Python Expand Tabs Length Calculation I'm confused by how the length of a string is calculated when expandtabs is used. I thought expandtabs replaces tabs with the appropriate number of spaces (with the default number of spaces per tab being 8). However, when I ran the commands using strings of varying lengths and...
Python Expand Tabs Length Calculation
I'm confused by how the length of a string is calculated when expandtabs is used. I thought expandtabs replaces tabs with the appropriate number of spaces (with the default number of spaces per tab being 8). However, when I ran the commands using strings of varying lengths and varying numbers of tabs, the length calcul...
[ "Like when you are entering tabs in a text-editor, the tab character increases the length to the next multiple of 8.\nSo:\n\n'\\t' by itself is 8, obviously.\n'\\t\\t' is 16.\n'abc\\tabc' starts at 3 characters, then a tab pushes it up to 8, and then the last 'abc' pushes it from 8 to 11...\n'abc\\tabc\\tabc' likew...
[ 9, 6 ]
[]
[]
[ "python", "tabs" ]
stackoverflow_0002656997_python_tabs.txt
Q: How do I automatically rebuild the Sphinx index under django-sphinx? I just setup django-sphinx, and it is working beautifully. I am now able to search my model and get amazing results. The one problem is that I have to build the index by hand using the indexer command. That means every time I add new content, I h...
How do I automatically rebuild the Sphinx index under django-sphinx?
I just setup django-sphinx, and it is working beautifully. I am now able to search my model and get amazing results. The one problem is that I have to build the index by hand using the indexer command. That means every time I add new content, I have to manually hit the command line to rebuild the search index. That is ...
[ "There are basically two primary strategies for building search indexes:\n\nIndexer internal to a database server, which indexes on the fly as records are inserted or deleted.\nIndexer external to the database (which may or may not be a RDMS which is why I leave off the word server), which indexes periodically.\n\n...
[ 5, 0 ]
[]
[]
[ "django", "django_sphinx", "python", "search", "sphinx" ]
stackoverflow_0001653071_django_django_sphinx_python_search_sphinx.txt
Q: What is the advantage of using Python Virtualbox API? what is the advantage of using a python virtualbox API instead of using XPCOM? A: The advantage is that pyvb is lot easier to work with. On the contrary the documentation for the python API of XPCOM doesn't exist, and the API is not pythonic at all. You can'...
What is the advantage of using Python Virtualbox API?
what is the advantage of using a python virtualbox API instead of using XPCOM?
[ "The advantage is that pyvb is lot easier to work with.\nOn the contrary the documentation for the python API of XPCOM doesn't exist, and the API is not pythonic at all. You can't do introspection to find methods/attributes of an object, etc. So you have to check the C++ source to find how it works or some python s...
[ 8, 5, 1 ]
[]
[]
[ "python", "virtualbox", "xpcom" ]
stackoverflow_0002652146_python_virtualbox_xpcom.txt
Q: Indexing CSV file contents in Python I have a very large CSV file contaning only two fields (id,url). I want to do some indexing on the url field with python, I know that there are some tools like Whoosh or Pylucene. but I can't get the examples to work. can someone help me with this? A: PyLucene is very easy to...
Indexing CSV file contents in Python
I have a very large CSV file contaning only two fields (id,url). I want to do some indexing on the url field with python, I know that there are some tools like Whoosh or Pylucene. but I can't get the examples to work. can someone help me with this?
[ "PyLucene is very easy to work with, but as you haven't posted your example i am not sure what problem you are facing.\nAlternatively when you have only key:value type of data, may be better than Pylucene would be DB like Berkeley DB(python bindings pybsddb). It will work like python dictionary and should be more ...
[ 1, 0 ]
[]
[]
[ "full_text_indexing", "indexing", "python", "whoosh" ]
stackoverflow_0002656607_full_text_indexing_indexing_python_whoosh.txt
Q: How to fix this python program? import math def p(n): return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factorial(n) print p(3) When I run it, I get the following error message: Traceback (most recent call last): File "poisson.py", line 6, in <module> print p(3) File "poisson.py", ...
How to fix this python program?
import math def p(n): return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factorial(n) print p(3) When I run it, I get the following error message: Traceback (most recent call last): File "poisson.py", line 6, in <module> print p(3) File "poisson.py", line 4, in p return 393000*((2882...
[ "Replace ^ with ** in \n(288200/393000)^n\n\nBear in mind that \n288200/393000\n\nReturns 0 \nMaybe you should try using decimal numbers:\nimport math\n\ndef p(n):\n a = 393000.0 # <-- notice the .0 \n b = 288200.0\n c = b / a\n return a * ( c**n * math.exp(-c) )/ math.factorial(n)\n\nprint p(3)\n\nRetu...
[ 5, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002657319_python.txt
Q: jar to python module I am using an API which provides a Java version but not a Python version. I can switch to Java as right now I am only prototyping. but is there a quick way to convert the functionality of API packaged in a jar to a python module? A: Did you look into Jython?
jar to python module
I am using an API which provides a Java version but not a Python version. I can switch to Java as right now I am only prototyping. but is there a quick way to convert the functionality of API packaged in a jar to a python module?
[ "Did you look into Jython?\n" ]
[ 3 ]
[]
[]
[ "jar", "java", "port", "python" ]
stackoverflow_0002657882_jar_java_port_python.txt
Q: Django - how to write users and profiles handling in best way? I am writing simple site that requires users and profiles to be handled. The first initial thought is to use django's build in user handling, but then the user model is too narrow and does not contain fields that I need. The documentation mentions user...
Django - how to write users and profiles handling in best way?
I am writing simple site that requires users and profiles to be handled. The first initial thought is to use django's build in user handling, but then the user model is too narrow and does not contain fields that I need. The documentation mentions user profiles, but user profiles section has been removed from djangoboo...
[ "\nusers should be able to register and authenticate\n\ndjango.contrib.auth is the module you want. Be sure to check the docs for custom login forms.\n\nevery user should have profile (or model with all required fields)\n\nYou need to set settings.AUTH_PROFILE_MODULE, as noted by others.\nInformation about setting...
[ 12, 2, 0, 0 ]
[]
[]
[ "django", "profiles", "python" ]
stackoverflow_0002654689_django_profiles_python.txt
Q: How can I detect if the caller passed any variables to my function in Python? I guess the subject sounds pretty stupid, so I'll show some code: def foo(**kwargs): # How can you detect the difference between (**{}) and ()? pass foo(**{}) foo() Is there any way to detect inside of foo, how the method was ca...
How can I detect if the caller passed any variables to my function in Python?
I guess the subject sounds pretty stupid, so I'll show some code: def foo(**kwargs): # How can you detect the difference between (**{}) and ()? pass foo(**{}) foo() Is there any way to detect inside of foo, how the method was called? Update 1 Because there were some comments why you possible want to do somethi...
[ "This hack only works with CPython. \nimport traceback\n\ndef foo(**kwargs):\n # stack is a list of 4-tuples: (filename, line number, function name, text)\n # see http://docs.python.org/library/traceback.html#module-traceback\n\n (filename,line_number,function_name,text)=traceback.extract_stack()[-2]\n ...
[ 0, 0, 0 ]
[]
[]
[ "inspect", "python" ]
stackoverflow_0002529491_inspect_python.txt
Q: Qt: How to autoexpand parents of a new QTreeView item when using a QSortFilterProxyModel I'm making an app wherein the user can add new data to a QTreeModel at any time. The parent under which it gets placed is automatically expanded to show the new item: self.tree = DiceModel(headers) self.treeView.setModel(self....
Qt: How to autoexpand parents of a new QTreeView item when using a QSortFilterProxyModel
I'm making an app wherein the user can add new data to a QTreeModel at any time. The parent under which it gets placed is automatically expanded to show the new item: self.tree = DiceModel(headers) self.treeView.setModel(self.tree) expand_node = self.tree.addRoll() #addRoll makes a node, adds it, and returns the (paren...
[ "I believe you should map your expanding item index into the proxy model item index before calling expand for it. QSortFilterProxyModel::mapFromSource method should do what you need. Please check if an example below would work for you (it's c++, let me know if you're having troubles converting it to python): \n// c...
[ 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0002657380_pyqt_pyqt4_python_qt.txt
Q: python django automated data addition I have a script which reads data from a csv file. I need to store the data into a database which has already been created as $ python manage.py syncdb so, that automated data entry is possible in an easier manner, as available in the django shell. A: You have to set up a dj...
python django automated data addition
I have a script which reads data from a csv file. I need to store the data into a database which has already been created as $ python manage.py syncdb so, that automated data entry is possible in an easier manner, as available in the django shell.
[ "You have to set up a django environment to use in your script, afterwards your python script can work with django models just as in the 'real' site:\nThe easiest way to do this: set the DJANGO_SETTINGS_MODULE environment variable (e.g. export DJANGO_SETTINGS_MODULE=mysite.settings ). Then your script can do thing...
[ 1 ]
[]
[]
[ "automation", "database", "django", "python" ]
stackoverflow_0002658527_automation_database_django_python.txt
Q: execute python file from another file I have a python file that has functions and classes. now I am writting another program (in another file). and I want to start the new file with running the old file (with the function and classes). I have tried using exec(path_2_oldFile.pyw) but it didn't work. thanks for any ...
execute python file from another file
I have a python file that has functions and classes. now I am writting another program (in another file). and I want to start the new file with running the old file (with the function and classes). I have tried using exec(path_2_oldFile.pyw) but it didn't work. thanks for any help Ariel
[ "Ideally you should try and import the first file into the new as a module using the import statement:\nhttp://effbot.org/zone/import-confusion.htm\nYou'll need to make sure that your original module is on the python path somewhere. If it is in the same directory as the new file this should just work.\n" ]
[ 1 ]
[]
[]
[ "exec", "import", "python" ]
stackoverflow_0002658612_exec_import_python.txt
Q: write in file is not complete without quitting the IDLE(Python GUI) I want to write something in a file. for example, fo=open('C:\\Python\\readline_test.txt','a') for i in range(3): st='abc'+'\n' fo.write(st) fo.close then I open this python file in IDLE, and click "Run Module". There is no error message but I ...
write in file is not complete without quitting the IDLE(Python GUI)
I want to write something in a file. for example, fo=open('C:\\Python\\readline_test.txt','a') for i in range(3): st='abc'+'\n' fo.write(st) fo.close then I open this python file in IDLE, and click "Run Module". There is no error message but I find the writing is not complete if I didn't quit IDLE. How can I complet...
[ "Maybe a typo, but it should be:\nfo.close()\n\nThen it should work.\nAlternative you can use the with statement syntax (better example):\nwith open('C:\\\\Python\\\\readline_test.txt','a') as fo:\n for i in range(3):\n fo.write('abc'+'\\n')\n\nThe file is automatically closed when leaving the with block....
[ 8, 0 ]
[]
[]
[ "file", "python", "python_idle" ]
stackoverflow_0002658707_file_python_python_idle.txt
Q: Passing sql results to views hard-codes views to database column names I just realized that i may not be following best practices in regards to the MVC pattern. My issue is that my views "know" information about my database Here's my situation in psuedo code... My controller invokes a method from my model and pass...
Passing sql results to views hard-codes views to database column names
I just realized that i may not be following best practices in regards to the MVC pattern. My issue is that my views "know" information about my database Here's my situation in psuedo code... My controller invokes a method from my model and passes it directly to the view view.records = tableGateway.getRecords() // gets ...
[ "I'd say it's not bad to have such info hardcoded if you need to have it quick and dirty.\nBut consider having generic class for views with method that takes your data from db and some array describing which columns to use. Then in the children classes (UserView, PostView, WhateverTableNameView) you could call this...
[ 1, 1 ]
[]
[]
[ "model_view_controller", "php", "python" ]
stackoverflow_0002657336_model_view_controller_php_python.txt
Q: Regexp for extracting data in parenthesis and commas So, i have this : "( ABC,2004 )" And I would need to extract ABC in a variable and 2004 in another. So what I have for now is this: In: re.compile(r'([^)]*,').findall("( ABC,2004 )") Out: ['( ABC,'] A: If your inputs are always like that (begin with "( ", e...
Regexp for extracting data in parenthesis and commas
So, i have this : "( ABC,2004 )" And I would need to extract ABC in a variable and 2004 in another. So what I have for now is this: In: re.compile(r'([^)]*,').findall("( ABC,2004 )") Out: ['( ABC,']
[ "If your inputs are always like that (begin with \"( \", end with \" )\"), you can have your values as:\ninput_text.strip(\" ()\").split(\",\")\n\n>>> \"( ABC,2004 )\".strip(\" ()\").split(\",\")\n['ABC', '2004']\n\nThis will consume any parentheses at the edges inside the outer parentheses.\nAlso, if the commas ca...
[ 5, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002658622_python_regex.txt
Q: News feed APIs for general news I'm building a database + tool that scours news feeds for a certain term. For example "food poisoning from nuts". I want to scour social media sites, news sites, major news aggregators, etc... for that term. Question 1: What are some of the news aggregator APIs out there? Question ...
News feed APIs for general news
I'm building a database + tool that scours news feeds for a certain term. For example "food poisoning from nuts". I want to scour social media sites, news sites, major news aggregators, etc... for that term. Question 1: What are some of the news aggregator APIs out there? Question 2: How Would you go about coding and ...
[ "Do you know Yahoo! Pipes? It's a very flexible feed aggregator, and you can manipulate it using YQL, which is quite powerful and has a Python librabry, python-yql :). YQL also has specific \"tables\" for Twitter and other services and news sources, so, depending on what you want, you might not even need Pipes.\nTh...
[ 4, 1, 0, 0 ]
[]
[]
[ "c++", "feed", "postgresql", "python" ]
stackoverflow_0002652692_c++_feed_postgresql_python.txt
Q: In my virtualenv, I need to use sudo for all commands I set up a virtualenv, which is working, but for some reason I need to use sudo for commands as simple as mkdir. Obviously I did something incorrectly. Any idea what it might be? Thanks A: Check the directory permissions and owner and give: $ sudo chown -R me...
In my virtualenv, I need to use sudo for all commands
I set up a virtualenv, which is working, but for some reason I need to use sudo for commands as simple as mkdir. Obviously I did something incorrectly. Any idea what it might be? Thanks
[ "Check the directory permissions and owner and give:\n$ sudo chown -R me:me virtualenvdir\n$ sudo chmod -R a+rX virtualenvdir\n\nchange me with your username, typically $USER, and virtualenvdir with your virtualenv's work directory.\n", "The commands\ncd test\nsudo virtualenv python\n\ncreates a directory called ...
[ 15, 4 ]
[]
[]
[ "python", "sudo", "virtualenv" ]
stackoverflow_0002658902_python_sudo_virtualenv.txt
Q: My QFileSystemModel doesn't work as expected in PyQt EDIT2: model.hasChildren(parentIndex) returns True, but model.rowCount(parentIndex) returns 0. Is QFileSystemModel just fubar in PyQt? EDIT: With a bit of adaptation this all works exactly as it should if I use QDirModel. This is deprecated, but maybe QFileSyste...
My QFileSystemModel doesn't work as expected in PyQt
EDIT2: model.hasChildren(parentIndex) returns True, but model.rowCount(parentIndex) returns 0. Is QFileSystemModel just fubar in PyQt? EDIT: With a bit of adaptation this all works exactly as it should if I use QDirModel. This is deprecated, but maybe QFileSystemModel hasn't been fully implemented in PyQt? I'm learnin...
[ "I've solved it.\nThe reason to use QFileSystemModel as opposed to QDirModel is because QFileSystemModel loads the data from the filesystem in a separate thread. The problem with that is that if you try to print the number of children just after it's been constructed is that it won't have loaded the children yet. T...
[ 2, 1 ]
[]
[]
[ "pyqt", "python", "qfilesystemmodel", "qt" ]
stackoverflow_0002658467_pyqt_python_qfilesystemmodel_qt.txt
Q: Get localized language name from locale code How can I get localized language name by specified locale code in python? For example: >> get_language_name('ja') >> ('Japanese', u'日本語') A: The Babel package can help: >>> from babel import Locale >>> locale = Locale('ja', 'JP') >>> print locale.display_name 日本語 (日本)...
Get localized language name from locale code
How can I get localized language name by specified locale code in python? For example: >> get_language_name('ja') >> ('Japanese', u'日本語')
[ "The Babel package can help:\n>>> from babel import Locale\n>>> locale = Locale('ja', 'JP')\n>>> print locale.display_name\n日本語 (日本)\n\nThere is also PyICU, a Python wrapper for the ICU library.\n" ]
[ 13 ]
[]
[]
[ "locale", "python" ]
stackoverflow_0002657787_locale_python.txt
Q: Generate and merge data with python multiprocessing I have a list of starting data. I want to apply a function to the starting data that creates a few pieces of new data for each element in the starting data. Some pieces of the new data are the same and I want to remove them. The sequential version is essentially...
Generate and merge data with python multiprocessing
I have a list of starting data. I want to apply a function to the starting data that creates a few pieces of new data for each element in the starting data. Some pieces of the new data are the same and I want to remove them. The sequential version is essentially: def create_new_data_for(datum): """make a list of n...
[ "I would use a multiprocessing Lock (similar to a threading lock) which is provided in the std lib.\nHere's an example from the standard documentation.\nfrom multiprocessing import Process, Lock\n\ndef f(l, i):\n l.acquire()\n print 'hello world', i\n l.release()\n\nif __name__ == '__main__':\n lock = L...
[ 1 ]
[]
[]
[ "multiprocessing", "parallel_processing", "python" ]
stackoverflow_0002659588_multiprocessing_parallel_processing_python.txt
Q: Call to MATLAB function in a Python program Possible Duplicate: Calling MATLAB functions from python I wrote MATLAB code (that easily could be implemented as a function) that convert a series of BMP files to AVI files. I want a Python program to call to this program/function. How do I do it? A: Take a look at ...
Call to MATLAB function in a Python program
Possible Duplicate: Calling MATLAB functions from python I wrote MATLAB code (that easily could be implemented as a function) that convert a series of BMP files to AVI files. I want a Python program to call to this program/function. How do I do it?
[ "Take a look at mlabwrap. Mlabwrap is a high-level Python-to-MATLAB® bridge that lets MATLAB look like a normal Python library.\n" ]
[ 2 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0002659661_matlab_python.txt
Q: efficiently list items in tuples starting at end I'd like to list the items in a tuple in Python starting with the back and go to front. Similar to: foo_t = tuple(int(f) for f in foo) print foo, foo_t[len(foo_t)-1] ... I believe this should be possible without Try ...-4, except ...-3. Thoughts? suggestions? A: ...
efficiently list items in tuples starting at end
I'd like to list the items in a tuple in Python starting with the back and go to front. Similar to: foo_t = tuple(int(f) for f in foo) print foo, foo_t[len(foo_t)-1] ... I believe this should be possible without Try ...-4, except ...-3. Thoughts? suggestions?
[ "You can print tuple(reversed(foo_t)), or use list in lieu of tuple, or \nprint ' '.join(str(x) for x in reversed(foo_t))\n\nand many variants. You could also use foo_t[::-1], but I think the reversed builtin is more readable.\n", "First, a general tip: in Python you never need to write foo_t[len(foo_t)-1]. You...
[ 6, 2 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002659556_python_tuples.txt
Q: Idiomatic Python: 'times' loop Say I have a function foo that I want to call n times. In Ruby, I would write: n.times { foo } In Python, I could write: for _ in xrange(n): foo() But that seems like a hacky way of doing things. My question: Is there an idiomatic way of doing this in Python? A: You've already sh...
Idiomatic Python: 'times' loop
Say I have a function foo that I want to call n times. In Ruby, I would write: n.times { foo } In Python, I could write: for _ in xrange(n): foo() But that seems like a hacky way of doing things. My question: Is there an idiomatic way of doing this in Python?
[ "You've already shown the idiomatic way:\nfor _ in range(n): # or xrange if you are on 2.X\n foo()\n\nNot sure what is \"hackish\" about this. If you have a more specific use case in mind, please provide more details, and there might be something better suited to what you are doing.\n", "If you want the time...
[ 44, 17, 16, 10 ]
[]
[]
[ "idioms", "loops", "python" ]
stackoverflow_0002657068_idioms_loops_python.txt
Q: django filebrowser extensions problem I've set django filebrowser's debug to True and wrote the extension restrictions in the model. pdf = FileBrowseField("PDF", max_length=200, directory="documents/", extensions=['.pdf', '.doc', '.txt'], format='Document', blank=True, null=True) In django admin it shows correctly...
django filebrowser extensions problem
I've set django filebrowser's debug to True and wrote the extension restrictions in the model. pdf = FileBrowseField("PDF", max_length=200, directory="documents/", extensions=['.pdf', '.doc', '.txt'], format='Document', blank=True, null=True) In django admin it shows correctly with debug info. Directory documents/ Exte...
[ "In filebrowser/fb_seettings define them as a dictionary called EXTENSIONS.\nEXTENSIONS = {\n 'Folder':[''],\n 'Image':['.jpg', '.jpeg', '.gif','.png','.tif','.tiff'],\n 'Zip':['.zip', '.rar'],\n 'Video':['.mov','.wmv','.mpeg','.mpg','.avi','.rm'],\n 'Document':['.pdf','.doc','.rtf','.txt','.xls','.c...
[ 1 ]
[]
[]
[ "django", "django_filebrowser", "python", "uploadify" ]
stackoverflow_0002659787_django_django_filebrowser_python_uploadify.txt
Q: Can't parse a 1904 date in ARPA format (email date) I'm processing an IMAP mailbox and running into trouble parsing the dates using the mxDateTime package. In particular, early dates like "Fri, 1 Jan 1904 00:43:25 -0400" is causing trouble: >>> import mx.DateTime >>> import mx.DateTime.ARPA >>> mx.DateTime.ARPA.Pa...
Can't parse a 1904 date in ARPA format (email date)
I'm processing an IMAP mailbox and running into trouble parsing the dates using the mxDateTime package. In particular, early dates like "Fri, 1 Jan 1904 00:43:25 -0400" is causing trouble: >>> import mx.DateTime >>> import mx.DateTime.ARPA >>> mx.DateTime.ARPA.ParseDateTimeUTC("Fri, 1 Jan 1904 00:43:25 -0400").gmtoffse...
[ "Is it possible that the mxDateTime object only handles datetimes which fall after the Unix Epoch?\n", "Figured it out with the help of the eGenix folks. It is an Epoch problem, but you can work around it by manually extracting the timezone offset and then re-applying explicitly:\n>>> s = \"Wed, 1 Jan 1969 00:43:...
[ 2, 0 ]
[]
[]
[ "datetime", "email", "parsing", "python" ]
stackoverflow_0002648992_datetime_email_parsing_python.txt
Q: pylibmc: undefined symbol: memcached_server_list There is a problem when I used the pylibmc. When I "import pylibmc", then I'll get some error following: ImportError: /usr/local/python2.6/lib/python2.6/site-packages/_pylibmc.so: undefined symbol: memcached_server_list. My enviroment are Python 2.6.5, libmemcached ...
pylibmc: undefined symbol: memcached_server_list
There is a problem when I used the pylibmc. When I "import pylibmc", then I'll get some error following: ImportError: /usr/local/python2.6/lib/python2.6/site-packages/_pylibmc.so: undefined symbol: memcached_server_list. My enviroment are Python 2.6.5, libmemcached 0.39, memcached 1.4.5 So, how can I solve it? Thanks v...
[ "There appears to be some confusion about the symbol memcached_server_list: libmemcached 0.38 exposes it, but 0.39 does not. The symbol has even been removed from the documentation. pylibmc relies on memcached_server_list for its get_stats() method. I suspect pylibmc should be using memcached_server_cursor inste...
[ 1, 0, 0 ]
[]
[]
[ "memcached", "python" ]
stackoverflow_0002612515_memcached_python.txt
Q: In python, how do I drag and drop 1 or more files onto my script as arguments with absolute path? (for windows, linux, and mac) I am writing a simple Python script with no GUI. I want to be able to drag and drop multiple files onto my python script and have access to their absolute paths inside of the script. How ...
In python, how do I drag and drop 1 or more files onto my script as arguments with absolute path? (for windows, linux, and mac)
I am writing a simple Python script with no GUI. I want to be able to drag and drop multiple files onto my python script and have access to their absolute paths inside of the script. How do I do this in Mac, Linux, and windows? For times sake, just Mac will be fine for now. I've googled this question and only found one...
[ "For OS X, the most straightforward way is to have your script run as part of an application bundle (.app). You can use something like py2app to build a python application. Another approach might be to use Automator or AppleScript to create an app that takes the input parameters and passes them to the python scri...
[ 3, 1, 1 ]
[]
[]
[ "arguments", "drag_and_drop", "python", "scripting" ]
stackoverflow_0002660291_arguments_drag_and_drop_python_scripting.txt
Q: How do I view this in an easy format to read? (JSON) https://search.twitter.com/search.json?q=doug How do I read this like VIEW SOURCE, so that I know what I'm looking at? Is there a website that can prettify it for me? BTW, I use python A: Parse it, then use pprint: data = json.load(...) pprint.pprint(data) A:...
How do I view this in an easy format to read? (JSON)
https://search.twitter.com/search.json?q=doug How do I read this like VIEW SOURCE, so that I know what I'm looking at? Is there a website that can prettify it for me? BTW, I use python
[ "Parse it, then use pprint:\ndata = json.load(...)\npprint.pprint(data)\n\n", "You can also use something like http://hurl.it.\n", "Personally, I use JSONView for Firefox, which does a good job formatting and colour-highlighting JSON.\n" ]
[ 2, 1, 1 ]
[ "Insert a carriage return after every comma with your favorite search and replace utility. If you know Python then you shouldn't have any trouble getting it even prettier than that. \n" ]
[ -1 ]
[ "http", "json", "python", "twitter", "xml" ]
stackoverflow_0002576265_http_json_python_twitter_xml.txt
Q: Why do socket.makefile objects fail after the first read for UDP sockets? I'm using the socket.makefile method to create a file-like object on a UDP socket for the purposes of reading. When I receive a UDP packet, I can read the entire contents of the packet all at once by using the read method, but if I try to s...
Why do socket.makefile objects fail after the first read for UDP sockets?
I'm using the socket.makefile method to create a file-like object on a UDP socket for the purposes of reading. When I receive a UDP packet, I can read the entire contents of the packet all at once by using the read method, but if I try to split it up into multiple reads, my program hangs. Here's a program which demons...
[ "You're sending 1 packet, but call read twice. The 2. read will not read anything as there's no new packets to read/receive. read on a udp socket reads one packet and discards the rest of the data if you didn't read all of the bytes. UDP is not stream oriented, it is message/datagram oriented.\nUDP does not map to ...
[ 2 ]
[]
[]
[ "python", "sockets", "udp" ]
stackoverflow_0002660389_python_sockets_udp.txt
Q: django select max field from mysql when column is varchar Using Django 1.1, I am trying to select the maximum value from a varchar column (in MySQL.) The data stored in the column looks like: 9001 9002 9017 9624 10104 11823 (In reality, the numbers are much bigger than this.) This worked until the numbers incre...
django select max field from mysql when column is varchar
Using Django 1.1, I am trying to select the maximum value from a varchar column (in MySQL.) The data stored in the column looks like: 9001 9002 9017 9624 10104 11823 (In reality, the numbers are much bigger than this.) This worked until the numbers incremented above 10000: Feedback.objects.filter(est__pk=est_id).agg...
[ "In the spirit of \"any help would be much appreciated\", you should figure out why it stopped working inside Django (but apparently not inside MySQL) - at 10,000.\nWhat is the query that is being generated? See this question for how to find that out.\nI suspect it is because you're adding the +0 to make the sort n...
[ 1 ]
[]
[]
[ "django", "max", "mysql", "python", "varchar" ]
stackoverflow_0002660489_django_max_mysql_python_varchar.txt
Q: reuse generators I want to check the central limit with dices. Roll D dices. Sum the results. Repeat the same thing for N times. Change D and repeat. There's no need to store random values so I want to use only generators. The problem is that the generators are consumed; I can't reuse them many times. Now my code ...
reuse generators
I want to check the central limit with dices. Roll D dices. Sum the results. Repeat the same thing for N times. Change D and repeat. There's no need to store random values so I want to use only generators. The problem is that the generators are consumed; I can't reuse them many times. Now my code uses explicit for and ...
[ "You could do it like this:\nfor r in repetitions:\n make_rools_generator = lambda: (random.randint(1,6) for _ in range(dice_number))\n sum_generator = (sum(make_rools_generator()) for _ in range(r))\n\nThis creates a function called make_rools_generator that, when called, creates a new generator that supplie...
[ 5, 2, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0002660350_generator_python.txt
Q: Adding a method to a function object at runtime I read a question earlier asking if there was a times method in Python, that would allow a function to be called n times in a row. Everyone suggested for _ in range(n): foo() but I wanted to try and code a different solution using a function decorator. Here's what I ...
Adding a method to a function object at runtime
I read a question earlier asking if there was a times method in Python, that would allow a function to be called n times in a row. Everyone suggested for _ in range(n): foo() but I wanted to try and code a different solution using a function decorator. Here's what I have: def times(self, n, *args, **kwargs): for _ ...
[ "Your decorator should return the function object:\ndef repeatable(func):\n func.times = new.instancemethod(times, func, func.__class__)\n return func\n\nNow it returns nothing, so you actually change threeArgs in a None\nThis is because this:\n@decorator\ndef func(...):\n ...\n\nis more or less the same a...
[ 3, 1, 0 ]
[]
[]
[ "decorator", "function", "python" ]
stackoverflow_0002660093_decorator_function_python.txt
Q: Django: Named URLs / Same Template, Different Named URL I have a webapp that lists all of my artists, albums and songs when the appropriate link is clicked. I make extensive use of generic views (object_list/detail) and named urls but I am coming across an annoyance. I have three templates that pretty much outpu...
Django: Named URLs / Same Template, Different Named URL
I have a webapp that lists all of my artists, albums and songs when the appropriate link is clicked. I make extensive use of generic views (object_list/detail) and named urls but I am coming across an annoyance. I have three templates that pretty much output the exact same html that look just like this: {% extends "b...
[ "You could define url patterns for a generic object_type instead of individually for artists, albums and songs:\nurlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views',\n # (r'^$', index),\n url(r'^(?P<object_type>\\w+)/$', music_object_list, name='music_object_list'),\n url(r'^(?P<object_type>\\w+)/(?...
[ 3 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002660404_django_django_templates_python.txt
Q: Optimizing Python code with many attribute and dictionary lookups I have written a program in Python which spends a large amount of time looking up attributes of objects and values from dictionary keys. I would like to know if there's any way I can optimize these lookup times, potentially with a C extension, to re...
Optimizing Python code with many attribute and dictionary lookups
I have written a program in Python which spends a large amount of time looking up attributes of objects and values from dictionary keys. I would like to know if there's any way I can optimize these lookup times, potentially with a C extension, to reduce the time of execution, or if I need to simply re-implement the pro...
[ "How about keeping the iteration order of interaction_graph.neighbors_iter(node) sorted (or partially sorted using collections.heapq)? Since you're just trying to find the max value, you can iterate node_neighbors in descending order, the first node that is in selected_node must be the max in selected_node.\nSecond...
[ 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "optimization", "profiling", "python" ]
stackoverflow_0002580158_dictionary_optimization_profiling_python.txt
Q: pdftotext can't find any of the files to convert when called within a python script i have a python script which keeps crashing on: subprocess.call(["pdftotext", pdf_filename]) the error being: OSError: [Errno 2] No such file or directory the absolute path to the filename (which i am storing in a log file as i d...
pdftotext can't find any of the files to convert when called within a python script
i have a python script which keeps crashing on: subprocess.call(["pdftotext", pdf_filename]) the error being: OSError: [Errno 2] No such file or directory the absolute path to the filename (which i am storing in a log file as i debug) is fine; on the command line, if i type pdftotext <pdf_filename_goes_here> it works...
[ "You'll also get that error if it can't find the executable on path...try using a full path to pdftotext as well, and look at how the $PATH for subprocess.call is set.\n" ]
[ 1 ]
[]
[]
[ "pdftotext", "python" ]
stackoverflow_0002660803_pdftotext_python.txt
Q: Tkinter layout question Tricky to explain with words so I'll use a picture. A: row 0, column 0 B: row 0, column 1 C: row 1, column 0, span 2 A: Try: A: row 0, column 0, sticky=W B: row 0, column 1, sticky=W C: row 1, column 0, span 3 grid_columnconfigure(2, weight=4) A: What you can't see in that picture is t...
Tkinter layout question
Tricky to explain with words so I'll use a picture. A: row 0, column 0 B: row 0, column 1 C: row 1, column 0, span 2
[ "Try:\nA: row 0, column 0, sticky=W\nB: row 0, column 1, sticky=W\nC: row 1, column 0, span 3\ngrid_columnconfigure(2, weight=4)\n\n", "What you can't see in that picture is the big element D in the third slot of the 3-element hbox that's in the first slot of the 2-element vbox.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0002660895_python_tkinter.txt
Q: Unexplained Django error. Diagnosis anyone? I have a django project I keep on github. It worked perfectly fine on my laptop. I downloaded it on my desktop and tried to "python manage.py runserver" or even "python manage.py shell" I get a Error: No module named messages No other messages, no stack trace, nothing....
Unexplained Django error. Diagnosis anyone?
I have a django project I keep on github. It worked perfectly fine on my laptop. I downloaded it on my desktop and tried to "python manage.py runserver" or even "python manage.py shell" I get a Error: No module named messages No other messages, no stack trace, nothing..Anyone have any idea whats going on? Thanks.
[ "I have come across similar errors a number of times. They have been the result of python not being able to find the django or project files in the path. This is exceptionally annoying when django gets installed or referenced to one version of python when you have multiple python installs on the machine. It may hel...
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002661015_django_python.txt
Q: How to access external object within event handler? As the title says, I'm grabbing the cursor location within a motion triggered event handler in Tkinter. I'd like to update an existing label widget with the location. However, I cannot for the life of me figure out how to edit the Label text field (or any extern...
How to access external object within event handler?
As the title says, I'm grabbing the cursor location within a motion triggered event handler in Tkinter. I'd like to update an existing label widget with the location. However, I cannot for the life of me figure out how to edit the Label text field (or any external object for that matter) within the event handler. From...
[ "Tkinter won't pass around objects in event handler, and anyway how it would know in which object you are interested in? \nInstead it is your responsibility to access the objects you wish to update from event handler, e.g. your event handler could be simple function and it could access global object, or it can be a...
[ 3 ]
[]
[]
[ "events", "handler", "python", "tkinter", "user_interface" ]
stackoverflow_0002660881_events_handler_python_tkinter_user_interface.txt
Q: AJAX based remote Online text editor I'm looking to install an online text editor on my server, that I can link to svn. I would like to have some form of syntax highlighting, keyboard shortcuts, and perhaps some text complete. Languages, python, php, sql, and C++ are a minimum ... any suggestions? A: you should ...
AJAX based remote Online text editor
I'm looking to install an online text editor on my server, that I can link to svn. I would like to have some form of syntax highlighting, keyboard shortcuts, and perhaps some text complete. Languages, python, php, sql, and C++ are a minimum ... any suggestions?
[ "you should have a look at https://mozillalabs.com/bespin/ \nI've tried it and decided not to use it, but only because it's web-based, the same reason why I use googledocs only when I really need to. \nIf you don't want to build a public service, you may use the approach I like. That is to install your favourite ed...
[ 2, 1 ]
[]
[]
[ "ide", "python", "text_editor" ]
stackoverflow_0002660886_ide_python_text_editor.txt