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: Python Regex on File Read Input So im reading from a file like so. f = open("log.txt", 'w+r') f.read() So f now has a bunch of lines, but im mainly concerned with it having a number, and then a specific string (For example "COMPLETE" would be the string) How...exactly would you go about checking this? I thought i...
Python Regex on File Read Input
So im reading from a file like so. f = open("log.txt", 'w+r') f.read() So f now has a bunch of lines, but im mainly concerned with it having a number, and then a specific string (For example "COMPLETE" would be the string) How...exactly would you go about checking this? I thought it'd be something like: r.search(['[0-...
[ "Regular expressions are overkill here if you're just looking for \"200 COMPLETE\". Just do this:\nif \"200 COMPLETE\" in log:\n # Do something\n\n", "It should be something like \nm = r.search('[0-9]+\\s+COMPLETE',line)\n\n", "You should use Rafe's answer instead of regex to search for \"200 COMPLETE\" in t...
[ 5, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006048039_python_regex.txt
Q: Django, Python: Is there a simple way to convert PHP-style bracketed POST keys to multidimensional dict? Specifically, I got a form that calls a Django service (written using Piston, but I don't think that's relevant), sending via POST something like this: edu_type[3][name] => a edu_type[3][spec] => b edu_type[3][...
Django, Python: Is there a simple way to convert PHP-style bracketed POST keys to multidimensional dict?
Specifically, I got a form that calls a Django service (written using Piston, but I don't think that's relevant), sending via POST something like this: edu_type[3][name] => a edu_type[3][spec] => b edu_type[3][start_year] => c edu_type[3][end_year] => d edu_type[4][0][name] => Cisco edu_type[4][0][spec] => CCNA edu_typ...
[ "I made a little parser in python to handle multidimensional dicts, you can find it at https://github.com/bernii/querystring-parser\n", "Dottedish does something like what you want. http://pypi.python.org/pypi/dottedish. It doesn't really have a homepage but you can install it from pypi or download the source fro...
[ 4, 1, 0, 0 ]
[]
[]
[ "django", "http", "php", "post", "python" ]
stackoverflow_0001890013_django_http_php_post_python.txt
Q: ordering a list of dictionaries by date I have the following list: l = [{datetime.date(2011, 4, 30): "Carrot"}, {datetime.date(2009, 4, 12): "Banana"}, {datetime.date(2012, 1, 1): "Corn"}] I want a new list with the dictionaries ordered by date (earliest first): l = [{datetime.date(2009, 4, 12): "Banan...
ordering a list of dictionaries by date
I have the following list: l = [{datetime.date(2011, 4, 30): "Carrot"}, {datetime.date(2009, 4, 12): "Banana"}, {datetime.date(2012, 1, 1): "Corn"}] I want a new list with the dictionaries ordered by date (earliest first): l = [{datetime.date(2009, 4, 12): "Banana"}, {datetime.date(2011, 4, 30): "Carro...
[ "Use the key of your inner dictionary as sort key. You can do this by passing a key getter function to sorted which pulls out the date key from your dictionary.\nsorted(l, key=lambda v: v.keys()[0])\n\n", "print sorted(l) \n\n[{datetime.date(2009, 4, 12): 'Banana'}, {datetime.date(2011, 4, 30): 'Carrot'}, {dateti...
[ 6, 3, 1 ]
[]
[]
[ "date", "dictionary", "python", "sorting" ]
stackoverflow_0006048596_date_dictionary_python_sorting.txt
Q: Python tkinter: How do I 'send' to a tkname that has spaces in it I'm trying to send() a tk message to an existing tcl/tk compatible running program. Problem is that this running program has a space in its tk name. Think "bob #2". For the life of me I can't figure out how to send() to "bob #2" and have it work. T...
Python tkinter: How do I 'send' to a tkname that has spaces in it
I'm trying to send() a tk message to an existing tcl/tk compatible running program. Problem is that this running program has a space in its tk name. Think "bob #2". For the life of me I can't figure out how to send() to "bob #2" and have it work. This is the most common error I get: _tkinter.TclError: Wrong number of ...
[ "Note: completely untested!\nHave you tried\ntname = '{bob #2}'\nmw.send(tName, \"MyCmd\")\n\nYou shouldn't have to do that if the send method had been written properly. The curly braces would be Tcl solution to the problem (of a badly written send method). Another possible solution might be:\ntname = 'bob\\ #2'\...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004261856_python_tkinter.txt
Q: In Django, how can I reuse settings.py in a new app outside of the project I have a new Django application I am working on. I have the following directory structure. Django/ appc project1 appA appB I would like to use the settings.py from project1 in appc. I have added the appc application to the INS...
In Django, how can I reuse settings.py in a new app outside of the project
I have a new Django application I am working on. I have the following directory structure. Django/ appc project1 appA appB I would like to use the settings.py from project1 in appc. I have added the appc application to the INSTALLED_APPS under project1. I am using WSGI so I added the Django/appc directory...
[ "Django apps that require access to the project settings should import and use django.conf.settings.\n" ]
[ 3 ]
[]
[]
[ "django", "django_settings", "python" ]
stackoverflow_0006048393_django_django_settings_python.txt
Q: Why doesn't this simple Python program print out? from urllib import urlopen import re p = re.compile('<h2><a .*?><a .*? href="(.*?)">(.*?)</a>') text = urlopen('http://python.org/community/jobs').read() for url, name in p.findall(text): print '%s (%s)' % (name, url) A: Your regex isn't what you want. Try th...
Why doesn't this simple Python program print out?
from urllib import urlopen import re p = re.compile('<h2><a .*?><a .*? href="(.*?)">(.*?)</a>') text = urlopen('http://python.org/community/jobs').read() for url, name in p.findall(text): print '%s (%s)' % (name, url)
[ "Your regex isn't what you want. Try this instead:\nfrom urllib import urlopen\nimport re\np = re.compile(r'<h2><a\\s.*?href=\"(.*?)\">(.*?)</a>')\ntext = urlopen('http://python.org/community/jobs').read()\nprint text\nfor url, name in p.findall(text):\n print '%s (%s)' % (name, url)\n\nAlso, your way of going a...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0006048737_python.txt
Q: Why does my script stop executing commands after calling an .EXE? Here is the relevant code from a Python script where a few commands are executed to copy an executable file and then execute it: exe_file_path = os.getcwd() + r'\name_of_executable.exe' temp_loc = os.environ['temp'] subprocess.Popen(r'copy %s %s' %...
Why does my script stop executing commands after calling an .EXE?
Here is the relevant code from a Python script where a few commands are executed to copy an executable file and then execute it: exe_file_path = os.getcwd() + r'\name_of_executable.exe' temp_loc = os.environ['temp'] subprocess.Popen(r'copy %s %s' % (exe_file_path, temp_loc), shell=True) exe_file_path = os.environ['tem...
[ "All programs will be immediately started one after another. Call communicate on each Popen object to wait for program termination.\nAdditionally, your use of format strings is unnecessarily dangerous. ['copy', exe_file_path, temp_loc] automatically escapes any strange characters in exe_file_path and temp_loc (and...
[ 6 ]
[]
[]
[ "executable", "python" ]
stackoverflow_0006048805_executable_python.txt
Q: Python code checker for comparing a function as an attribute I occasionally spend a considerable amount of time tracking down brainfarts in my code... while I normally run pylint against it, there are some things that slip past pylint. The easiest problem for me to overlook is this... # normally, variable is popu...
Python code checker for comparing a function as an attribute
I occasionally spend a considerable amount of time tracking down brainfarts in my code... while I normally run pylint against it, there are some things that slip past pylint. The easiest problem for me to overlook is this... # normally, variable is populated from parsed text, so it's not predictable variable = 'fOoBaR...
[ "@Mike Pennington I just want to first say that I also run into this a lot -.-\n@eyquem 'lower()' is a function. 'lower' is a function pointer (if I'm not mistaken). Python will let you attempt to run this code, but it will not invoke the function.\nI think the reason this is hard to catch is that you don't always ...
[ 0, 0, 0 ]
[]
[]
[ "lint", "python", "static_analysis" ]
stackoverflow_0005463296_lint_python_static_analysis.txt
Q: My first game: Python using pygame vs. Java using lwjgl? My game would be a simple 2D tower defense type game. It should have some animations and sounds. I've only learned Java so this seems like a huge plus for choosing that option. But I'm fairly new to programming so i suppose it wont be a huge problem to switc...
My first game: Python using pygame vs. Java using lwjgl?
My game would be a simple 2D tower defense type game. It should have some animations and sounds. I've only learned Java so this seems like a huge plus for choosing that option. But I'm fairly new to programming so i suppose it wont be a huge problem to switch. From my limited research, either Python using pygame or Ja...
[ "Java + LWJGL is very low level and you'll have to write a lot of the sound and animation code yourself. A better choice would be Java + Slick2D (a 2d library on top of LWJGL). You can find it at http://slick.cokeandcode.com\n", "A benefit from Pygame for the kind of game you want to do is the Python Pygame Tower...
[ 5, 5 ]
[]
[]
[ "java", "lwjgl", "pygame", "python" ]
stackoverflow_0006048528_java_lwjgl_pygame_python.txt
Q: PyQt4 can't import Qsci I'm installing PyQt4 on an old Linux system (CentOS 4.4) that can't be upgraded for hardware compatibility reasons. I've got Python 2.6, QT4 and SIP installed, and the installation of PyQt4 didn't give me any errors. When I run Python, this happens: Python 2.6.2 (r262:71600, May 11 2011, 14...
PyQt4 can't import Qsci
I'm installing PyQt4 on an old Linux system (CentOS 4.4) that can't be upgraded for hardware compatibility reasons. I've got Python 2.6, QT4 and SIP installed, and the installation of PyQt4 didn't give me any errors. When I run Python, this happens: Python 2.6.2 (r262:71600, May 11 2011, 14:18:37) [GCC 3.4.6 20060404 ...
[ "You need to install qscintilla separately. If PyQt is already installed, then you should just have to install the qscintilla python bindings. Hopefully this fixes your issue!\n" ]
[ 7 ]
[]
[]
[ "linux", "pyqt", "python", "qscintilla", "qt" ]
stackoverflow_0006046432_linux_pyqt_python_qscintilla_qt.txt
Q: generating chart using python or google charts i would like be able to input a dataset and get SMOOTH graph. for example i have the following graph how would i smooth this out: A: Take a look at the Google Charts API. You can use it to generate a URL that represents your graph. Simply download the image associat...
generating chart using python or google charts
i would like be able to input a dataset and get SMOOTH graph. for example i have the following graph how would i smooth this out:
[ "Take a look at the Google Charts API. You can use it to generate a URL that represents your graph. Simply download the image associated with that URL and you have your chart.\n" ]
[ 2 ]
[]
[]
[ "charts", "google_visualization", "graph", "python" ]
stackoverflow_0006049282_charts_google_visualization_graph_python.txt
Q: When programming a GUI, is it possible to have a loop running in the background all the time? I am self teaching myself some python OOP, and I have created a simple GUI that starts a number of scripts in the background using Popen. I need to determine at all times whether these scripts are active or not, which I ...
When programming a GUI, is it possible to have a loop running in the background all the time?
I am self teaching myself some python OOP, and I have created a simple GUI that starts a number of scripts in the background using Popen. I need to determine at all times whether these scripts are active or not, which I was going to use a loop for. But how can I have a loop running in the background at all times, with...
[ "You must run a thread in the background. A thread is simply a set of code that runs at the same time as anyother thread. A python program for example is one thread, only one action can occur at any one time, which is why you will see a lag with a infinite loop and a gui. If you create a new thread though the gui w...
[ 5, 3, 2 ]
[]
[]
[ "background", "loops", "python", "subprocess" ]
stackoverflow_0006049328_background_loops_python_subprocess.txt
Q: Python importing issue I have a module(Executive.py) that I am trying to import into another module I am working on (ExecutiveTest.py). The directory structure is like so: src/ common/ python/ Executive.py tests/ ExecutiveTest.py In ExecutiveTest.py, I have the ...
Python importing issue
I have a module(Executive.py) that I am trying to import into another module I am working on (ExecutiveTest.py). The directory structure is like so: src/ common/ python/ Executive.py tests/ ExecutiveTest.py In ExecutiveTest.py, I have the following line: from common....
[ "You have to have an __init__.py file in the root of your package (it can be empty). Also, your module hierarchy has to reflect the directory structure, so python and tests should be part of the import as well.\n", "I found a similar post here. it looks like you can define the path that python refers to when look...
[ 2, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0006050284_import_python.txt
Q: Python: Inheriting builtin types dict and list I have always been confused and falling over the minute details while inheriting the builtin types in Python e.g. list and dict. Can you please point to the tutorials and docs which give a comprehensive details about the internals and the syntax involved. A: Python ...
Python: Inheriting builtin types dict and list
I have always been confused and falling over the minute details while inheriting the builtin types in Python e.g. list and dict. Can you please point to the tutorials and docs which give a comprehensive details about the internals and the syntax involved.
[ "Python Language Reference, §3.4.6, \"Emulating container types\"\n", "this is for Dict:\nhttp://docs.python.org/library/userdict.html\nEdit\nupdate userdict docs link:\nhttps://docs.python.org/2/library/userdict.html\n", "Take a look at the custom trackingdict class in my answer to a different Stack Overflow q...
[ 3, 0, 0 ]
[]
[]
[ "built_in", "built_in_types", "inheritance", "python" ]
stackoverflow_0006049533_built_in_built_in_types_inheritance_python.txt
Q: Write to file descriptor 3 of a Python subprocess.Popen object How do I write to file descriptor 3 of a subprocess.Popen object? I'm trying to accomplish the redirection in the following shell command with Python (without using named pipes): $ gpg --passphrase-fd 3 -c 3<passphrase.txt < filename.txt > filename.gpg...
Write to file descriptor 3 of a Python subprocess.Popen object
How do I write to file descriptor 3 of a subprocess.Popen object? I'm trying to accomplish the redirection in the following shell command with Python (without using named pipes): $ gpg --passphrase-fd 3 -c 3<passphrase.txt < filename.txt > filename.gpg
[ "The subprocess proc inherits file descriptors opened in the parent process.\nSo you can use os.open to open passphrase.txt and obtain its associated file descriptor. You can then construct a command which uses that file descriptor:\nimport subprocess\nimport shlex\nimport os\n\nfd=os.open('passphrase.txt',os.O_RDO...
[ 7 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0006050187_python_subprocess.txt
Q: wxpython, find control based on its name I was wondering if it is possible (I'm sure it is) to get a reference to a control based on the name of the control. Something like control = findcontrol("btnProduct"+buttonNumber) You probably catch my drift... (and yes, I am a newby in wxPython) Regards, Dennis A: You c...
wxpython, find control based on its name
I was wondering if it is possible (I'm sure it is) to get a reference to a control based on the name of the control. Something like control = findcontrol("btnProduct"+buttonNumber) You probably catch my drift... (and yes, I am a newby in wxPython) Regards, Dennis
[ "You can use the frame instance's FindWindowByName() method, assuming you passed a unique name parameter to the widget or you might be able to use the frame instance's FindWindowByLabel() method. You can also find by id, but I don't really recommend that since it's better not to manage the ids yourself.\n", "In t...
[ 3, 2, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006049481_python_wxpython.txt
Q: from import ... in __init__.py makes module name visible? Take the following code example: File package1/__init__.py: from moduleB import foo print moduleB.__name__ File package1/moduleB.py: def foo(): pass Then from the current directory: >>> import package1 package1.moduleB This code works in CPython. What s...
from import ... in __init__.py makes module name visible?
Take the following code example: File package1/__init__.py: from moduleB import foo print moduleB.__name__ File package1/moduleB.py: def foo(): pass Then from the current directory: >>> import package1 package1.moduleB This code works in CPython. What surprises me about it is that the from ... import in __init__.py ...
[ "The documentation misled you as it is written to describe the more common case of importing a module from outside of the parent package containing it.\nFor example, using \"from example import submodule\" in my own code, where \"example\" is some third party library completely unconnected to my own code, does not ...
[ 6, 0 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0006048786_python_python_import.txt
Q: getting odd error when calling python script within another python script I am getting an IOError when calling a python script(script2) within another python script(script1). Script 2 runs fine if called stand alone, however, if I call it from within script one, i get the following error. C:\>C:\Python32\python.ex...
getting odd error when calling python script within another python script
I am getting an IOError when calling a python script(script2) within another python script(script1). Script 2 runs fine if called stand alone, however, if I call it from within script one, i get the following error. C:\>C:\Python32\python.exe R:\Scripts\BatchAging.py Traceback (most recent call last): File "R:\Script...
[ "Cleaner is to import the script and run its main method:\nimport DeleteAgingFiles\nDeleteAgingFiles.main()\n\nAdding a main method to your script:\ndef main():\n # the main code goes here\n\nif __name__ == \"__main__\":\n main()\n\n", "The best solution to this problem, is, I would think, don't use call to...
[ 1, 0 ]
[]
[]
[ "invalid_argument", "ioerror", "logging", "python" ]
stackoverflow_0006051051_invalid_argument_ioerror_logging_python.txt
Q: re.compile(pattern, file) calls causes the system to crash I have a file I need to parse. The parsing is built incrementally, such that on each iteration the expressions becomes more case specific. The code segment which overloads the system looks roughly like this: for item in ret: pat = r'a\sstyle="....
re.compile(pattern, file) calls causes the system to crash
I have a file I need to parse. The parsing is built incrementally, such that on each iteration the expressions becomes more case specific. The code segment which overloads the system looks roughly like this: for item in ret: pat = r'a\sstyle=".+class="VEAPI_Pushpin"\sid="msftve(.+?)".+>%s<'%item[1] ...
[ "My only guess is that you are getting too many matches and running out of memory. Though this doesn't seem very reasonable, it might be the case. Try using finditer instead of findall to get one match at a time without creating a monster list of matches. If that doesn't fix your problem, you might have stumbled...
[ 0 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0006051157_parsing_python_regex.txt
Q: Speeding up loops over a Numpy array In my code I have for loop that indexes over a multidimensional numpy array and does some operation using the sub-array that is obtained at each iteration. It looks like this for sub in Arr: #do stuff using sub Now the stuff that is done using sub is fully vectorized, so it ...
Speeding up loops over a Numpy array
In my code I have for loop that indexes over a multidimensional numpy array and does some operation using the sub-array that is obtained at each iteration. It looks like this for sub in Arr: #do stuff using sub Now the stuff that is done using sub is fully vectorized, so it should be efficient. On the other hand thi...
[ "If you can't 'vectorize' the entire operation and looping is indeed the bottleneck, then I highly recommend using Cython. I've been dabbling around with it recently and it is straightforward to work with and has a decent interface with numpy. For something like a langevin integrator I saw a 115x speedup over a dec...
[ 6, 2, 1 ]
[]
[]
[ "for_loop", "numpy", "python" ]
stackoverflow_0005972976_for_loop_numpy_python.txt
Q: Iterator value not retained after 'any()' call I have the following snippet of code. I'm basically trying to get the index/iterator of a particular string in a list (aside from just knowing whether it is present). Is this possible at all, or should I be using a loop-with-an-if? bucket = ["alpha", "beta", "gamma"] ...
Iterator value not retained after 'any()' call
I have the following snippet of code. I'm basically trying to get the index/iterator of a particular string in a list (aside from just knowing whether it is present). Is this possible at all, or should I be using a loop-with-an-if? bucket = ["alpha", "beta", "gamma"] content = "" if any(content == "beta" for content in...
[ "You are creating a generator for searching within the any call. That generator as you have left it is a temporary. That is, it exists only within the call to any so you will not be able to look at it afterwards. If you want it to come out to the location of the index then do this:\nitem = [x for x in enumerate(...
[ 1, 1 ]
[]
[]
[ "iterator", "python", "scope" ]
stackoverflow_0006051570_iterator_python_scope.txt
Q: Saving text file contents to DB: "Incorrect string value: '\xEF\xBB\xBF# W...' for column 'contents' at row 1" In my Django app, I'm uploading a text file, using file.read() to get the contents of the file, and then saving to the database (using Django's .save() method). I'm getting the following error: Environmen...
Saving text file contents to DB: "Incorrect string value: '\xEF\xBB\xBF# W...' for column 'contents' at row 1"
In my Django app, I'm uploading a text file, using file.read() to get the contents of the file, and then saving to the database (using Django's .save() method). I'm getting the following error: Environment: Request Method: POST Request URL: http://localhost:8000/ Django Version: 1.2.5 Python Version: 2.7.1 Installed A...
[ "You're on the right path. Check the charset of your database (is it utf-8?). If it isn't and you want to use UTF-8, change the charset by using this SQL command\nalter table yourTableName DEFAULT CHARACTER SET utf8;\n\nAnd read this great tutorial on using UTF-8 in Python if you want to convert your UTF-8 string b...
[ 2, 0 ]
[]
[]
[ "character_encoding", "django", "file", "mysql", "python" ]
stackoverflow_0006051732_character_encoding_django_file_mysql_python.txt
Q: Django with system timezone setting vs user's individual timezones How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like this sc...
Django with system timezone setting vs user's individual timezones
How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE="UTC") so all datetimes were stored in the database as UTC. Stuff like this scares me which is why I prefer UTC everywhere. But how hard will it be to...
[ "Update, January 2013: Django 1.4 now has time zone support!!\n\nOld answer for historical reasons:\nI'm going to be working on this problem myself for my application. My first approach to this problem would be to go with django core developer Malcom Tredinnick's advice in this django-user's post. You'll want to st...
[ 7, 4, 3, 2, 1, 1 ]
[]
[]
[ "django", "python", "timezone" ]
stackoverflow_0001061911_django_python_timezone.txt
Q: python print string on multiple lines I have a function that can only accept strings. (it creates the image with the string, but the string has little formatting and no word wrapping, so a long string will just bleed right through the edge of the image and keep going into the abyss, when in reality I would have li...
python print string on multiple lines
I have a function that can only accept strings. (it creates the image with the string, but the string has little formatting and no word wrapping, so a long string will just bleed right through the edge of the image and keep going into the abyss, when in reality I would have liked it to create a paragraph, instead of a ...
[ "Use inputFiles.read() which creates a string. Does that help?\n", "The 'join' should have worked. Your problem may be that the writing of the string ignores newline characters. You could maybe try '\\r\\n'.join(...)\n" ]
[ 4, 2 ]
[]
[]
[ "file", "io", "python", "string" ]
stackoverflow_0006052049_file_io_python_string.txt
Q: Determine if a line segment intersects a polygon If I have a vector (a line consisting of 2 points) on a 2D plane how can I determine if it has passed through a polygon? I know I can take each line which makes up the polygon and see if any intersect but is there a better way? I've read this one post How can I dete...
Determine if a line segment intersects a polygon
If I have a vector (a line consisting of 2 points) on a 2D plane how can I determine if it has passed through a polygon? I know I can take each line which makes up the polygon and see if any intersect but is there a better way? I've read this one post How can I determine whether a 2D Point is within a Polygon? which gi...
[ "If you want a python library for geometric operations, have a look at shapely. It makes this as simple as someline.intersects(somepolygon).\nHere's a quick example of intersections, buffer, and clipping (with a nice plot... I'm using descartes to easily convert shapely polygons into matplotlib patches.). \nimpor...
[ 21, 2, 1, 0 ]
[]
[]
[ "geometry", "polygon", "python" ]
stackoverflow_0006050392_geometry_polygon_python.txt
Q: Python eigenvalue computations run much slower than those of MATLAB on my computer. Why? I would like to compute the eigenvalues of large-ish matrices (about 1000x1000) using Python 2.6.5. I have been unable to do so quickly. I have not found any other threads addressing this question. When I run a = rand(1000,10...
Python eigenvalue computations run much slower than those of MATLAB on my computer. Why?
I would like to compute the eigenvalues of large-ish matrices (about 1000x1000) using Python 2.6.5. I have been unable to do so quickly. I have not found any other threads addressing this question. When I run a = rand(1000,1000); tic; for i =1:10 eig(a); end toc; in MATLAB it takes about 30 seconds. A similar tes...
[ "I think what you're seeing is the difference between the Intel Math Kernel Library (MKL) that's being used by Matlab and whatever LAPACK implementation you have on your system (ATLAS, maybe?) that scipy is linked against. You can see how much faster the MKL is in these benchmarks.\nI imagine that you would get mu...
[ 15, 3 ]
[]
[]
[ "eigenvalue", "matlab", "numpy", "python" ]
stackoverflow_0006051678_eigenvalue_matlab_numpy_python.txt
Q: formencode nesting custom validators within schema I want to nest my custom validators within my schema, like this: MySchema(Schema): class MyValidator(validators.FancyValidator): def _to_python(self, value, state): ... class MyOtherValidator(validators.FancyValidator): def _to_...
formencode nesting custom validators within schema
I want to nest my custom validators within my schema, like this: MySchema(Schema): class MyValidator(validators.FancyValidator): def _to_python(self, value, state): ... class MyOtherValidator(validators.FancyValidator): def _to_python(self, value, state): ... field_f...
[ "My advice is: you should move the FancyValidator subclass definitions to global scope, either (1) in the same module just before the definition of the Schema in which they're used, or (2) in a separate module for greater reuse. Unless there is a specific reason why nesting is required, a few extra class names in ...
[ 2, 0 ]
[]
[]
[ "formencode", "python" ]
stackoverflow_0005919318_formencode_python.txt
Q: pytz: Why do these different methods give different UTC offsets? When creating a datetime object in a specific time zone using pytz I get a different UTC offset depending on whether I use datetime.datetime() or datetime.datetime.now(). now() seems to give the correct UTC offset for the time zone, datetime() gives ...
pytz: Why do these different methods give different UTC offsets?
When creating a datetime object in a specific time zone using pytz I get a different UTC offset depending on whether I use datetime.datetime() or datetime.datetime.now(). now() seems to give the correct UTC offset for the time zone, datetime() gives an offset that I don't recognise. Why are they different? What is the...
[ "It seems that datetime() will use the first recorded timezone for the region by default, and in many cases (like in La Paz) this is old and no longer valid.\nThe datetime must instead be created naive and then localised like so:\nb = la_paz.localize(datetime.datetime(2011, 03, 22, 5, 30))\nprint b, b.utcoffset()\n...
[ 2, 2 ]
[]
[]
[ "python", "pytz", "timezone" ]
stackoverflow_0005389506_python_pytz_timezone.txt
Q: How to finish running the code even after handling exceptions in python I'm do some calculations and append them to a list. However there are calculations that will cause a division by zero error. If that happens, I want to just append the word "error" in the list. A sample code: try: for i in [1,2,3]...
How to finish running the code even after handling exceptions in python
I'm do some calculations and append them to a list. However there are calculations that will cause a division by zero error. If that happens, I want to just append the word "error" in the list. A sample code: try: for i in [1,2,3]: z.append(i/(i-1)) except ZeroDivisionError: z.appen...
[ "for i in [1,2,3]:\n try:\n z.append(i/(i-1))\n except ZeroDivisionError:\n z.append(\"error\")\n\n" ]
[ 7 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0006052333_exception_handling_python.txt
Q: break with multiple loops python - specific question My question is about the second break statement: if x == xstart and y == ystart: break So this break statement breaks out of the while true loop correct? But then does it go back to the next closest loop (namely the while board[x][y] = Other...
break with multiple loops python - specific question
My question is about the second break statement: if x == xstart and y == ystart: break So this break statement breaks out of the while true loop correct? But then does it go back to the next closest loop (namely the while board[x][y] = OtherTile:) But because this condition is not met, it goes bac...
[ "It will only break the while True loop. The loop will continue forever until x == xstart and y == ystart.\nOnce that condition is met, it will continue on in the that outer for loop.\n" ]
[ 2 ]
[]
[]
[ "break", "loops", "python" ]
stackoverflow_0006052418_break_loops_python.txt
Q: python: exception within a comprehension: can I get retrieve values of the loop variables? Suppose I am parsing a fixed-width file: file_format = {'year' : (0, 3, int), 'price' : (4, 10, float)} for lineno, line in enumerate(input_file): try: fields = {k : v[2](line[v[0]:v[1]]) for k, v in file_format....
python: exception within a comprehension: can I get retrieve values of the loop variables?
Suppose I am parsing a fixed-width file: file_format = {'year' : (0, 3, int), 'price' : (4, 10, float)} for lineno, line in enumerate(input_file): try: fields = {k : v[2](line[v[0]:v[1]]) for k, v in file_format.items()} except ValueError: print("cannot parse line {}".format(lineno)) I would li...
[ "You could shift the problematic part into a function\nfile_format = {'year' : (0, 3, int), 'price' : (4, 10, float)}\n\ndef build_value(v):\n try:\n return v[2](line[v[0]:v[1]])\n except ValueError:\n print(\"cannot parse line {}\".format(lineno))\n\nfor lineno, line in enumerate(input_file):\n...
[ 4, 0 ]
[]
[]
[ "exception", "list_comprehension", "python", "python_3.x" ]
stackoverflow_0006052280_exception_list_comprehension_python_python_3.x.txt
Q: Using Python 3.1 and 2.5 together I'm currently working the final project for my programming class. We're writing it in Python 3.1, and I'm doing the GUI. My team's leader wants to do the whole project in 3.1, but most pyGame addons (like pyConsole) are giving me compatibility issues. So, my question is, can I wr...
Using Python 3.1 and 2.5 together
I'm currently working the final project for my programming class. We're writing it in Python 3.1, and I'm doing the GUI. My team's leader wants to do the whole project in 3.1, but most pyGame addons (like pyConsole) are giving me compatibility issues. So, my question is, can I write my frontend in 2.5 and then hook it...
[ "To be honest, that's probably more trouble than it's worth.\nYour best bet is to get together and make a list of the addons you guys want to use and whether or not they're compatible with 3.1. Then decide if you can live without the incompatible ones. If you can't, do the project in 2.5, otherwise go with 3.1 an...
[ 6, 3 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0006052379_pygame_python_python_3.x.txt
Q: File handle leaking (maybe) in a C library makes trouble with NFS (+python, but that's incidental) here is a quite cool problem. I have a python script (main) that calls a python module (foo.py) which in turns calls another python module (barwrapper.py) uses LoadLibrary to dynamically open and access a libbar.so l...
File handle leaking (maybe) in a C library makes trouble with NFS (+python, but that's incidental)
here is a quite cool problem. I have a python script (main) that calls a python module (foo.py) which in turns calls another python module (barwrapper.py) uses LoadLibrary to dynamically open and access a libbar.so library. libbar and the whole rest of the chain open and create files to perform their task. The problem...
[ "The kernel keeps track of file descriptors, so even if you got python to unload the .so and release the memory, it would not know to close the leaked file descriptors. The only thing that comes to mind is importing the .so after forking, and only cleaning up after the forked child process has exited (and the file ...
[ 2, 1 ]
[]
[]
[ "file", "nfs", "python", "resource_leak" ]
stackoverflow_0006048046_file_nfs_python_resource_leak.txt
Q: Make random subset of white pixels black in pygame surface I have a pygame surface (some text created by font.render) that is mostly transparent except some pixels are white. I'd like to change half of these white pixels black. I know I could iterate through each pixel, checking whether it is white by get_at() and...
Make random subset of white pixels black in pygame surface
I have a pygame surface (some text created by font.render) that is mostly transparent except some pixels are white. I'd like to change half of these white pixels black. I know I could iterate through each pixel, checking whether it is white by get_at() and changing its color using set_at(), but it strikes me that there...
[ "I think you'll need to iterate through all the pixels to check if they're white. Once you have the list of whites, do something like:\nfor px in random.sample(whites,len(whites)/2):\n Surface.set_at((px.x,px.y),'black')\n\nPython Documentation - random\n" ]
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0006051317_pygame_python.txt
Q: How to remove a range from start to end enclusive from a list def remove_section(alist, start, end): """ Return a copy of alist removing the section from start to end inclusive >>> inlist = [8,7,6,5,4,3,2,1] >>> remove_section(inlist, 2, 5) [8, 7, 2, 1] >>> inlist == [8,7,6,5,4,3,2,1] ...
How to remove a range from start to end enclusive from a list
def remove_section(alist, start, end): """ Return a copy of alist removing the section from start to end inclusive >>> inlist = [8,7,6,5,4,3,2,1] >>> remove_section(inlist, 2, 5) [8, 7, 2, 1] >>> inlist == [8,7,6,5,4,3,2,1] True >>> inlist = ["bob","sue","jim","mary","tony"] >>> rem...
[ "Simply\ndel alist[start:end+1]\n\nshould be enough.\n", "This should do what you want:\ndef remove_section(alist, start, end):\n return alist[:start] + alist[end+1:]\n\n", "You could copy the list and delete the parts you don't want\nnewlist = alist[:]\ndel newlist[start:end]\n\nOr you could combine two sli...
[ 3, 3, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006052635_list_python.txt
Q: Avoiding unncessary use of lambda for calls to object methods Consider the following code, which simply calls a method on each member of a list: class Demo: def make_change(self): pass foo = [Demo(), Demo(), Demo()] map(lambda x: x.make_change(), foo) Is there a way to accomplish this without the lon...
Avoiding unncessary use of lambda for calls to object methods
Consider the following code, which simply calls a method on each member of a list: class Demo: def make_change(self): pass foo = [Demo(), Demo(), Demo()] map(lambda x: x.make_change(), foo) Is there a way to accomplish this without the long-winded lambda syntax? For example, in Scala, something similar to...
[ "It's not very pythonic to use map just for side-effects\nso why not\nfor item in foo:\n item.make_change()\n\nThis will run faster than using map\nyou can put it on one line if you insist, but I wouldn't\nfor item in foo:item.make_change()\n\n", "operator.methodcaller('make_change')\n\n", "I'm with gnibbler...
[ 6, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006052380_python.txt
Q: Difference between calling a python script by terminal and by PHP? Where is the Error? I have a PHP script, that calls a python script by $call_python = "python ../python/lp_3.py ".$author; $python_output = Null; $mystring = exec($call_python, $output_python); This produces me an error in the log: $ vi logs/error...
Difference between calling a python script by terminal and by PHP? Where is the Error?
I have a PHP script, that calls a python script by $call_python = "python ../python/lp_3.py ".$author; $python_output = Null; $mystring = exec($call_python, $output_python); This produces me an error in the log: $ vi logs/error_log shows .... Traceback (most recent call last): File "../python/lp_3.py", line 14, in...
[ "In your PHP code, you're just calling \"python\", and letting PHP decide which version of Python to use. Use an explicit path to a specific Python binary, (e.g. /usr/bin/python2.6).\nYou need to know the exact path to the version of Python that has MySQLdb installed.\n", "$call_python = \"/opt/local/bin/python2....
[ 4, 0 ]
[]
[]
[ "exec", "import", "php", "python", "terminal" ]
stackoverflow_0006051693_exec_import_php_python_terminal.txt
Q: wxPython Crashing randomly at THIThemeTextInfoPublic::GetOptions() const + 9 I'm writing an application for a uni project, and after about 5 minutes it just crashes. I'm on a MacBook Pro running Snow Leopard, with python 2.6, and wxPython 2.8.12, and according to the crash log i am using libwx_macud-2.8.0.dylib, I...
wxPython Crashing randomly at THIThemeTextInfoPublic::GetOptions() const + 9
I'm writing an application for a uni project, and after about 5 minutes it just crashes. I'm on a MacBook Pro running Snow Leopard, with python 2.6, and wxPython 2.8.12, and according to the crash log i am using libwx_macud-2.8.0.dylib, I'm not a C or a C++ programmer and it is infuriating me. The copy of the crash log...
[ "From the crash log, it appears that you are using OS X's system python. I believe this defaults to 64-bit, which isn't compatible with wxPython based on this SO answer, this blog post, and from the wxPython download website, which states:\n\nSince they use the Carbon API they are limited to running in 32-bit mode....
[ 1 ]
[]
[]
[ "macos", "python", "wxpython" ]
stackoverflow_0006052701_macos_python_wxpython.txt
Q: Outputting new lines to txt files. (Python 3.2) all. I'm having trouble outputting new lines to a txt file. The output is good but it's all in one line. Any ideas on how to work around? #Double numberer end=100 count=0 count=int(input("What number would you like to start?")) end=int(input("What number would you l...
Outputting new lines to txt files. (Python 3.2)
all. I'm having trouble outputting new lines to a txt file. The output is good but it's all in one line. Any ideas on how to work around? #Double numberer end=100 count=0 count=int(input("What number would you like to start?")) end=int(input("What number would you like to end?")) biglist = [] logfile=open("output.txt...
[ "To concatenate the new lines to the string, use a + symbol:\nlogfile.write(str(count) + \"\\n\")\nlogfile.write(str(count) + \"\\n\")\n\nAlso, be aware that your while loop incrementing count each time is unnecessary in Python. You could just do this:\nfor x in range(0, end + 1):\n logfile.write((str(x) + \"\\n...
[ 3, 1 ]
[]
[]
[ "python", "text" ]
stackoverflow_0006052836_python_text.txt
Q: Problem using decimal and money in sqlite3 with adapters Using sqlite3 as the database, I want to keep a couple of decimal.Decimal values, one a percentage the other a dollar amount. However I saw problems when using sum(amount) on over 20,000 entries. It was several dollars off. I thought of using an adapter to...
Problem using decimal and money in sqlite3 with adapters
Using sqlite3 as the database, I want to keep a couple of decimal.Decimal values, one a percentage the other a dollar amount. However I saw problems when using sum(amount) on over 20,000 entries. It was several dollars off. I thought of using an adapter to save the number of cents and then aggregates should work. sq...
[ "There are two simple solutions, and I hope someone has something more direct:\n1. convert to a string and store the string in the DB\n2. multiply by 100 and store as an integer for money values\nBoth of these will require a conversion back to decimal.Decimal when the values are read from the DB.\n", "The problem...
[ 2, 0 ]
[]
[]
[ "currency", "decimal", "python", "sqlite" ]
stackoverflow_0006047192_currency_decimal_python_sqlite.txt
Q: How to generically apply an override of a function to mutiple classes in python? I am working on a Django application but this seems like it is just a python question, with nothing necessarily specific to Django. I'm pretty new to python, and its hard to describe what I am trying to do, but easier to show so here...
How to generically apply an override of a function to mutiple classes in python?
I am working on a Django application but this seems like it is just a python question, with nothing necessarily specific to Django. I'm pretty new to python, and its hard to describe what I am trying to do, but easier to show so here goes: I have one class: class SlideForm(ModelForm): class Meta: model = ...
[ "One option is to use a Mixin class; example: \nFirst, the common behavior goes in the mixin:\nclass SomeMixin(object):\n def __init__(self, *args, **kwargs):\n super(SomeMixin, self).__init__(*args, **kwargs)\n for name, field in self.fields.iteritems():\n field.widget = field.hidden_w...
[ 4, 0 ]
[]
[]
[ "decorator", "django", "inheritance", "python" ]
stackoverflow_0006052710_decorator_django_inheritance_python.txt
Q: How do I check if cartesian coordinates make up a rectangle efficiently? The situation is as follows: There are N arrays. In each array (0..N-1) there are (x,y) tuples (cartesian coordinates) stored The length of each array can be different I want to extract the subset of coordinate combinations which make up a ...
How do I check if cartesian coordinates make up a rectangle efficiently?
The situation is as follows: There are N arrays. In each array (0..N-1) there are (x,y) tuples (cartesian coordinates) stored The length of each array can be different I want to extract the subset of coordinate combinations which make up a complete retangle of size N. In other words; all the cartesian coordinates are...
[ "You can use hashing to great effect:\nhash each point (keeping track of which list it is in)\nfor each pair of points (a,b) and (c,d):\n if (a,d) exists in another list, and (c,b) exists in yet another list:\n yield rectangle(...)\n\nWhen I say exists, I mean do something like:\nhashesToPoints = {}\nfor ...
[ 5, 0 ]
[]
[]
[ "algorithm", "coordinates", "geometry", "optimization", "python" ]
stackoverflow_0006043831_algorithm_coordinates_geometry_optimization_python.txt
Q: press more than one Tkinter button Hi i was wondering if you could make it so you could have more that one button pressed at a time? Like: from Tkinter import * tkwin = Tk() def delayedDoSomethings(): for i in range(1,10000000): print 'hi',i def delayedDoSomething(): for i in range(1,10000000): ...
press more than one Tkinter button
Hi i was wondering if you could make it so you could have more that one button pressed at a time? Like: from Tkinter import * tkwin = Tk() def delayedDoSomethings(): for i in range(1,10000000): print 'hi',i def delayedDoSomething(): for i in range(1,10000000): print i a = Button(tkwin, te...
[ "What you want here is to use threads. Threads allow you to have multiple pieces of code executing at the same time (or they will at least appear to be executing simultaneously)\nInside of delayedDoSomethings(), you'll want to spawn a new thread that does the actual work, so that you can return control to Tkinter i...
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006053208_python_tkinter.txt
Q: Loading Magnet LINK using Rasterbar libtorrent in Python How would one load a Magnet link via rasterbar libtorrent python binding? A: import libtorrent as lt import time ses = lt.session() params = { 'save_path': '/home/downloads/'} link = "magnet:?xt=urn:btih:4MR6HU7SIHXAXQQFXFJTNLTYSREDR5EI&tr=http://tracker....
Loading Magnet LINK using Rasterbar libtorrent in Python
How would one load a Magnet link via rasterbar libtorrent python binding?
[ "import libtorrent as lt\nimport time\n\nses = lt.session()\nparams = { 'save_path': '/home/downloads/'}\nlink = \"magnet:?xt=urn:btih:4MR6HU7SIHXAXQQFXFJTNLTYSREDR5EI&tr=http://tracker.vodo.net:6970/announce\"\nhandle = lt.add_magnet_uri(ses, link, params)\n\nprint 'downloading metadata...'\nwhile (not handle.has_...
[ 18 ]
[]
[]
[ "bittorrent", "magnet_uri", "python" ]
stackoverflow_0006051877_bittorrent_magnet_uri_python.txt
Q: Spatial index/query (finding k nearest points) I have +10k points (latitude, longitude) and I'm building an app that shows you the k nearest points to a user's location. I think this is a very common problem and I don't want to reinvent the wheel. I'm learning about Quadtrees. It seems to be a good approach to so...
Spatial index/query (finding k nearest points)
I have +10k points (latitude, longitude) and I'm building an app that shows you the k nearest points to a user's location. I think this is a very common problem and I don't want to reinvent the wheel. I'm learning about Quadtrees. It seems to be a good approach to solve this spatial problem. I'm using these tools: Py...
[ "MongoDB has support for spatial indexes built-in, so all you'd need to do is load your points using the correct format, create the spatial index, and then run your queries.\nFor a quick example, I loaded the center points for all 50 states in the mongo shell:\n> db.places.ensureIndex({loc: \"2d\"})\n> db.places.sa...
[ 7, 2, 1 ]
[]
[]
[ "geospatial", "python", "spatial", "spatial_index", "spatial_query" ]
stackoverflow_0006025991_geospatial_python_spatial_spatial_index_spatial_query.txt
Q: Block Keyboard but get global Hotkeys XLib [SOLVED - Provided example contains the answer!] I am trying to implement a program which is started in fullscreen and does not allow any userinput (wether mouse nor keyboard) because it just reacts on UDEV-Signals, when a usb-stick or cd is inserted. I want to prevent, ...
Block Keyboard but get global Hotkeys XLib
[SOLVED - Provided example contains the answer!] I am trying to implement a program which is started in fullscreen and does not allow any userinput (wether mouse nor keyboard) because it just reacts on UDEV-Signals, when a usb-stick or cd is inserted. I want to prevent, that a user puts in a keyboard / mouse and does ...
[ "Did you flush the calls to the X server? Xlib is asynchronous and buffers all requests until you fill the buffer, make a call that needs a response from the server, or call XFlush (the C API interface, not sure the python binding name).\n" ]
[ 2 ]
[]
[]
[ "python", "xlib" ]
stackoverflow_0006029949_python_xlib.txt
Q: Simple way to display results of a sql query using web.py Using web.py, I'm creating a handful of result sets by using web.database.query() And I'd like to display the query results on an html template. Does web.py have any built-in facility for doing this? I didn't see any going through the doc and code samples....
Simple way to display results of a sql query using web.py
Using web.py, I'm creating a handful of result sets by using web.database.query() And I'd like to display the query results on an html template. Does web.py have any built-in facility for doing this? I didn't see any going through the doc and code samples. I'd also appreciate any pointers to other modules that will co...
[ "Check out the docs for web.py's built-in templating system. There are also cookbook examples for hooking in 3rd party template engines like Mako, Cheetah and Jinja2.\nIn order to convert the data to be displayed by Javascript you could use one of the JSON modules for Python: the standard json module (2.6+), simpl...
[ 2 ]
[]
[]
[ "python", "web.py", "web_frameworks" ]
stackoverflow_0006053219_python_web.py_web_frameworks.txt
Q: How does popular mail websites handle server side scripting? I was wondering how do popular mail websites handle / call the serverside scripts. How do they do it differently in a way that users are not easily able to decipher which file they are calling to invoke say login authentication. For eg: from yahoo websit...
How does popular mail websites handle server side scripting?
I was wondering how do popular mail websites handle / call the serverside scripts. How do they do it differently in a way that users are not easily able to decipher which file they are calling to invoke say login authentication. For eg: from yahoo website i did view source on login page and saw <form method="post" a...
[ "Are you merely confused about the URL https://login.yahoo.com/config/login??\nConsider: A web server does not need to work with files at all. Having a URL like http://example.com/login.php is merely an extremely lazy way to map to a file on disk. Internally, the web server will receive the request as /login.php an...
[ 1, 1 ]
[]
[]
[ "cgi", "css", "javascript", "jsp", "python" ]
stackoverflow_0006053587_cgi_css_javascript_jsp_python.txt
Q: how to assign an sql value to this python variable ok i got this as simple as i can, everythings working and i need one last thing before I'm done with this issue i am using sqlite3 module in python i also have very limited sql expierance the problem- i need to take the only value out of an sql table; the tablenam...
how to assign an sql value to this python variable
ok i got this as simple as i can, everythings working and i need one last thing before I'm done with this issue i am using sqlite3 module in python i also have very limited sql expierance the problem- i need to take the only value out of an sql table; the tablename is saves and the row id is 0 the name of the row is lv...
[ "SELECT 0 FROM saves is not sensible (or valid) SQL, you probably want to do something like SELECT * FROM saves WHERE lvl = 0\nI suggest reading some sql tutorial\n" ]
[ 0 ]
[]
[]
[ "database", "python", "sqlite" ]
stackoverflow_0006053897_database_python_sqlite.txt
Q: Putting Webkit onto the Nautilus desktop (on Ubuntu Maverick) with PyGTK I can get what I think is the Nautilus desktop window by using this code: screen = wnck.screen_get_default() while gtk.events_pending(): gtk.main_iteration() for window in screen.get_windows(): if window.get_name() == 'x-nautilus-desk...
Putting Webkit onto the Nautilus desktop (on Ubuntu Maverick) with PyGTK
I can get what I think is the Nautilus desktop window by using this code: screen = wnck.screen_get_default() while gtk.events_pending(): gtk.main_iteration() for window in screen.get_windows(): if window.get_name() == 'x-nautilus-desktop': xid = window.get_xid() wrapped_window = gtk.gdk.window_f...
[ "You're mixing up gtk.Window and gtk.gdk.Window. They are not the same. The former is a toplevel desktop window and functions as a container for GTK widgets; the latter is an abstraction of an area of the screen which can be drawn on top of, and is not a container.\nYou can't get an application's GTK widgets using ...
[ 0 ]
[]
[]
[ "desktop", "gtk", "nautilus", "pygtk", "python" ]
stackoverflow_0006039680_desktop_gtk_nautilus_pygtk_python.txt
Q: Loop through Registry Python I am trying to write a small application that checks each value in the Windows Registry for valid file paths, provided it is a REG_SZ. I need to be able to loop through all of the keys and subkeys reading each value as I go. I looked in to _winreg, but couldn't find any clear examples ...
Loop through Registry Python
I am trying to write a small application that checks each value in the Windows Registry for valid file paths, provided it is a REG_SZ. I need to be able to loop through all of the keys and subkeys reading each value as I go. I looked in to _winreg, but couldn't find any clear examples for this task. Any help would be g...
[ "_winreg.OpenKey to open a given registry key.\n_winreg.EnumKey to enumerate the sub-keys of a given registry key.\nAnd you have the _winreg.HKEY_CLASSES_ROOT and friends key constants.\nWhat else do you need?\n" ]
[ 2 ]
[]
[]
[ "loops", "python", "registry", "windows" ]
stackoverflow_0006053867_loops_python_registry_windows.txt
Q: google api and calendar selection I have a problem with google calendar api. How can you select which calendar to add an event? It add always to default calendar? thanks A: You can list the calendars using the GetOwnCalendarsFeed() and GetAllCalendarsFeed() calls. This will return a list of entries, each of whic...
google api and calendar selection
I have a problem with google calendar api. How can you select which calendar to add an event? It add always to default calendar? thanks
[ "You can list the calendars using the GetOwnCalendarsFeed() and GetAllCalendarsFeed() calls. This will return a list of entries, each of which holds attributes for a given calendar. You need to obtain the calendar's url from the entry.content.src attribute, and use this on your InsertEntry call:\nclient = calendar....
[ 1 ]
[]
[]
[ "calendar", "google_api", "python" ]
stackoverflow_0006009862_calendar_google_api_python.txt
Q: ftp read() Memory Error in python i get an error 'Memory Error' when it open and reads a file larger than 500mb. if its less than 500mb it works perfectly.. im using the size for my progress bar's maxvalue self.ftp = FTP(hostname) self.ftp.login(user, password) self.f = open(self.filename,'rb') wi...
ftp read() Memory Error in python
i get an error 'Memory Error' when it open and reads a file larger than 500mb. if its less than 500mb it works perfectly.. im using the size for my progress bar's maxvalue self.ftp = FTP(hostname) self.ftp.login(user, password) self.f = open(self.filename,'rb') with open(self.filename,'rb') as filein: ...
[ "So, filein.read() actually reads (i.e. downloads) the file and is consuming your memory.\nYou can instead use\nself.size = self.ftp.size(self.filename)\n\n", "Don't use the read() method since it reads the whole file into a string. You should use the os.stat() function to get the the file metadata, which returns...
[ 1, 0 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0006054022_ftp_ftplib_python.txt
Q: python cherrypy - how to add header How can I add retry-header in cherrypy? import cherrypy import os class Root: def index(self): cherrypy.response.headers['Retry-After'] = 60 cherrypy.request.headers["Age"]= 20 cherrypy.config.update({'Retry-After': '60'}) raise cherrypy.HTTP...
python cherrypy - how to add header
How can I add retry-header in cherrypy? import cherrypy import os class Root: def index(self): cherrypy.response.headers['Retry-After'] = 60 cherrypy.request.headers["Age"]= 20 cherrypy.config.update({'Retry-After': '60'}) raise cherrypy.HTTPError(503, 'Service Unavailable') ind...
[ "When you set a status code by raising HTTPError, the headers in cherrypy.response.headers are ignored. Set the HTTP status by setting cherrypy.response.status instead:\nimport cherrypy\n\nclass Root:\n def index(self):\n cherrypy.response.headers['Retry-After'] = 60\n cherrypy.response.status = 5...
[ 24 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0006054473_cherrypy_python.txt
Q: Split PDF after RegEx: Where should I start? I am trying to split gargantuan PDFs based on a RegEx of the sort [A-Z][a-z]+(\s–\s)[A-Z][a-z]+ Because after every instance of this begins a new 'section' that I need to be split into its own document. I have no idea where to begin, or what language to look at first. A...
Split PDF after RegEx: Where should I start?
I am trying to split gargantuan PDFs based on a RegEx of the sort [A-Z][a-z]+(\s–\s)[A-Z][a-z]+ Because after every instance of this begins a new 'section' that I need to be split into its own document. I have no idea where to begin, or what language to look at first. Any help would be appreciated.
[ "Splitting a PDF at the byte stream level will not result in a valid PDF.\nNow that we've got that out of the way, you'll need a library (Apache PDFBox in java, pyPDF in python) that can parse PDFs and let you iterate over the text, applying your regexp. Once you've found the text you use the library to extract the...
[ 1, 1, 0 ]
[]
[]
[ "java", "pdf", "php", "python", "regex" ]
stackoverflow_0006051378_java_pdf_php_python_regex.txt
Q: Django: How to carry model form data from one page to another, and back, without commiting to the DB? [Preamble: Whereas I realize there may be simpler ways to do this (i.e., just use Django built-in Admin, or use inlines to do all editing on one page, etc.), unfortunately, I am not in control of the designs, so I...
Django: How to carry model form data from one page to another, and back, without commiting to the DB?
[Preamble: Whereas I realize there may be simpler ways to do this (i.e., just use Django built-in Admin, or use inlines to do all editing on one page, etc.), unfortunately, I am not in control of the designs, so I'm seeking help on how to work with what I've been tasked with implementing.] I have 2 models, Deck and Sl...
[ "Idea A: Store the uncommitted data in the session until everything is ready for commit. Each form/roundtrip to the client just adds/updates the accumulating data. If they abandon it you only have crap lying around until the session is destroyed. You can save pretty much anything to the session.\nIdea B: Add a bo...
[ 3, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0006054124_django_django_forms_django_models_python.txt
Q: Python- Replace all occurrences of letter at specific position on a string Trying to create the TV game-show "Lingo" in Python. In the game, players are trying to guess a five letter word. They start off my randomly guessing a five letter word. The game board then will light up showing how the word they guessed ...
Python- Replace all occurrences of letter at specific position on a string
Trying to create the TV game-show "Lingo" in Python. In the game, players are trying to guess a five letter word. They start off my randomly guessing a five letter word. The game board then will light up showing how the word they guessed matches up with the actual word. For example, if the real word is "gorge" and ...
[ "To find common letters regardless of position:\nIn [1]: set('harpy') & set('happy')\nOut[1]: set(['a', 'h', 'p', 'y'])\n\nTo get a boolean flag indicating whether each letter of 'harpy' is present in 'happy' at any position:\nIn [17]: [l in 'happy' for l in 'harpy']\nOut[17]: [True, True, False, True, True]\n\nIn ...
[ 5 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006054856_python_string.txt
Q: django virtualenv I have a few questions regarding virtualenv in general. I have found some documentation online about virtualenv, although I don't think my setup is installing something correctly. Basically I am looking at seperating my applications into their own directories and I want to start upgrading django ...
django virtualenv
I have a few questions regarding virtualenv in general. I have found some documentation online about virtualenv, although I don't think my setup is installing something correctly. Basically I am looking at seperating my applications into their own directories and I want to start upgrading django and certain other featu...
[ "Are you using a yolk installed in your virtualenv or the global yolk installation? \nflaper87@BigMac:/tmp$ virtualenv test3 --no-site-packages\nNew python executable in test3/bin/python\nInstalling setuptools............done.\nInstalling pip...............done.\nflaper87@BigMac:/tmp$ source test3/bin/activate\n(te...
[ 1 ]
[]
[]
[ "django", "python", "virtualenv" ]
stackoverflow_0006054816_django_python_virtualenv.txt
Q: Python set not empty but pop returns empty? I saw a similar problem with multithreading but this isn't even multithreading, it's just straight up populating a set and then popping. I print out the set and then immediately after, try to print out the pop of the set. but it says the set is empty when i see something...
Python set not empty but pop returns empty?
I saw a similar problem with multithreading but this isn't even multithreading, it's just straight up populating a set and then popping. I print out the set and then immediately after, try to print out the pop of the set. but it says the set is empty when i see something like this for the set print out: set(['', 'asdf'...
[ "pop(...)\n Remove and return an arbitrary set element.\n Raises KeyError if the set is empty.\n\nSince you have an empty string in your set, it is highly possible that a foo.pop() returns this empty string and printing an empty string gives you nothing.\n" ]
[ 3 ]
[]
[]
[ "python", "set" ]
stackoverflow_0006055097_python_set.txt
Q: Attach text on path in GIMP I'm discovering the gimp API for few days now (using python-fu) and I actually enjoy it. However there is something I can't manage to do : attach a text on a path. Using the user interface to perform it is quite easy (create a path > create a text > click on text along path in toolbox)....
Attach text on path in GIMP
I'm discovering the gimp API for few days now (using python-fu) and I actually enjoy it. However there is something I can't manage to do : attach a text on a path. Using the user interface to perform it is quite easy (create a path > create a text > click on text along path in toolbox)... but, as you might expect, I ai...
[ "After hours and hours of research on the right side of Internet (the one with no naked people on it) I haven't found so much about my question. That's why I decided to look at Gimp source code in order to know how the magical \"text along path\" actually works... and it seems nothing has been made to make this act...
[ 4 ]
[]
[]
[ "gimp", "python", "script_fu" ]
stackoverflow_0006041091_gimp_python_script_fu.txt
Q: how to create log files for test execution I am trying to create a testcontroller and wants the execution of tests to be collected a a file. i know using, tee and redirecting the test script execution to a certain file, but I am interested to do it with python over linux. So, in this case whenever a test is execu...
how to create log files for test execution
I am trying to create a testcontroller and wants the execution of tests to be collected a a file. i know using, tee and redirecting the test script execution to a certain file, but I am interested to do it with python over linux. So, in this case whenever a test is executed the log file should get created, and all the...
[ "There are several good logging modules, starting with the built-in logging, here is the official cookbook. Among the more interesting 3rd party libraries is Logbook, here is a pretty bare example just scratching the surface of its very cool features:\nimport logbook\n\ndef f(i,j):\n return i+j\n\nlogger = logbo...
[ 5, 3, 2, 2, 0 ]
[]
[]
[ "automation", "logging", "python" ]
stackoverflow_0006053985_automation_logging_python.txt
Q: input() vs sys.stdin.read() import sys s1 = input() s2 = sys.stdin.read(1) #type "s" for example s1 == "s" #False s2 == "s" #True Why? How can I make input() to work properly? I tried to encode/decode s1, but it doesn't work. Thank you. A: If you're on Windows, you'll notice that the result of input() when yo...
input() vs sys.stdin.read()
import sys s1 = input() s2 = sys.stdin.read(1) #type "s" for example s1 == "s" #False s2 == "s" #True Why? How can I make input() to work properly? I tried to encode/decode s1, but it doesn't work. Thank you.
[ "If you're on Windows, you'll notice that the result of input() when you type an 's' and Enter is \"s\\r\". Strip all trailing whitespace from the result and you'll be fine.\n", "You didn't say which version of Python you are using, so I'm going to guess you were using Python 3.2 running on Microsoft Windows.\nTh...
[ 7, 6, 0 ]
[]
[]
[ "input", "python", "python_3.2", "python_3.x" ]
stackoverflow_0006055659_input_python_python_3.2_python_3.x.txt
Q: How to add a space for user? If i had a word that had space, like abc def for user to guess, and i want to input the space, so user don't have to guess the space. Beacuse i had a code like this: if len(letter)==1 and letter.isalpha(): if letters_tried.find(letter) != -1: Befor user gusee is: _ _ _ _ _...
How to add a space for user?
If i had a word that had space, like abc def for user to guess, and i want to input the space, so user don't have to guess the space. Beacuse i had a code like this: if len(letter)==1 and letter.isalpha(): if letters_tried.find(letter) != -1: Befor user gusee is: _ _ _ _ _ _ _ If guess the letter: abc_def...
[ "Maybe you are looking for next:\ninputs = [\"abc def\", ...]\ninputs_map = zip(inputs, [i.replace(' ', '') for i in inputs])\n\nuser_input = get_user_input()\n\nuser_input = inputs_map.get(user_input, user_input)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006055752_python.txt
Q: How to connect to an access point using python? I would create a simple program(Linux) that connects to my WIFI, is there a Wireless module in Python Thank you A: Sounds to me like you really want wicd. No need to "re-invent the wheel". that's a network connection manager that works especially with wifi. It's wr...
How to connect to an access point using python?
I would create a simple program(Linux) that connects to my WIFI, is there a Wireless module in Python Thank you
[ "Sounds to me like you really want wicd. No need to \"re-invent the wheel\". that's a network connection manager that works especially with wifi. It's written in Python.\n" ]
[ 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0006056039_linux_python.txt
Q: Error when using GeoDjango with SpatiaLite on Ubuntu I'm trying to get GeoDjango running on SpatiaLite on Ubuntu 11.04, and even with a very minimal setup, I'm hitting a strange error. Saving an instance of a model with geo-fields works, but loading it again fails with an exception: Error encountered checking Geom...
Error when using GeoDjango with SpatiaLite on Ubuntu
I'm trying to get GeoDjango running on SpatiaLite on Ubuntu 11.04, and even with a very minimal setup, I'm hitting a strange error. Saving an instance of a model with geo-fields works, but loading it again fails with an exception: Error encountered checking Geometry returned from GEOS C function "GEOSWKBReader_read_r"....
[ "OK, I found the problem myself: I forgot to use models.GeoManager as the default manager. This fixes my problem:\nclass TestModel(models.Model):\n name = models.CharField(max_length=10)\n location = models.PointField()\n\n objects = models.GeoManager()\n\n" ]
[ 5 ]
[]
[]
[ "django", "geodjango", "python", "spatialite" ]
stackoverflow_0006055726_django_geodjango_python_spatialite.txt
Q: Python: list to JSON I am trying to use Django with jquery UI autocomplete but having trouble sending response. Here is my code: def ajax_tags_autocomplete(request): """ Autocomplete for tag list """ beginning_of_title = request.GET.get('term', '') tags_found = Tag.objects.values_list('title', flat=Tru...
Python: list to JSON
I am trying to use Django with jquery UI autocomplete but having trouble sending response. Here is my code: def ajax_tags_autocomplete(request): """ Autocomplete for tag list """ beginning_of_title = request.GET.get('term', '') tags_found = Tag.objects.values_list('title', flat=True).filter(title__startswit...
[ "Are you sure it's actually a list containing unicode objects and not a list containing some database objects? The u\"php\" might just be the repr() of the object.\nTry json.dumps([unicode(t) for t in tags_found]) or json.dumps(map(unicode, tags_found))\n" ]
[ 9 ]
[]
[]
[ "django", "jquery_ui_autocomplete", "python" ]
stackoverflow_0006056418_django_jquery_ui_autocomplete_python.txt
Q: What is the proper way of using Python record arrays I would like to combine several lists or arrays into a single record array. In the following code I want to created a record array with two colums: "a" and "b". The first column will contain letters from "a" to "j", the second one will contain numbers from 0 to ...
What is the proper way of using Python record arrays
I would like to combine several lists or arrays into a single record array. In the following code I want to created a record array with two colums: "a" and "b". The first column will contain letters from "a" to "j", the second one will contain numbers from 0 to 9 In [22]: a = list('abcdefghij'); b = range(10); c = nump...
[ "There are different ways to achieve your result. One simple option is\na = list('abcdefghij'); b = range(10)\ndesc = {'names': ('a', 'b'), 'formats': ('S4', 'f4')}\nd = numpy.array(zip(a, b), dtype=desc)\n\n", "Following from your comment on Sven's answer, if you don't have a and b, then do the following and po...
[ 3, 1 ]
[]
[]
[ "numpy", "python", "record" ]
stackoverflow_0006055407_numpy_python_record.txt
Q: Why does this instruction not work? Hi I'm trying to count using keys only and get an error message when using this line self.response.out.write(A.all(keys_only=True).count(100000000)) The error message I get is TypeError: all() got an unexpected keyword argument 'keys_only' Isn't it supposed to work this way? Wha...
Why does this instruction not work?
Hi I'm trying to count using keys only and get an error message when using this line self.response.out.write(A.all(keys_only=True).count(100000000)) The error message I get is TypeError: all() got an unexpected keyword argument 'keys_only' Isn't it supposed to work this way? What am I doing wrong? Thanks ` UPDA...
[ "There is problem with SearchableModel and keys_only. you can do some think like this.\nquery = A.all()\nquery._keys_only = True \n\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006055710_google_app_engine_python.txt
Q: Plone 4.0.5 unified installer failing on Ubuntu 11.04 (natty) with zip/zlib error I am a Plone newbie and am trying to install Plone 4.0.5 on Ubuntu 11.04 Natty using the Unified Installer. I unpack the installer and run the ./install.sh zeo as root and I get the following error: ZEO Cluster Install selected Det...
Plone 4.0.5 unified installer failing on Ubuntu 11.04 (natty) with zip/zlib error
I am a Plone newbie and am trying to install Plone 4.0.5 on Ubuntu 11.04 Natty using the Unified Installer. I unpack the installer and run the ./install.sh zeo as root and I get the following error: ZEO Cluster Install selected Detailed installation log being written to /tmp/Plone-4.0.5-UnifiedInstaller/install.log ...
[ "Its an issue with the Python disutils and the new multilib setup of natty. I ran into the same issue trying to get sqlite support in Python built from source.\nYou can hack around it in the detect modules section of the setup.py\nhttp://bugs.python.org/issue9762\nEdit:\nTo work around it, change lib_dirs in the p...
[ 9, 2, 2, 1, 0 ]
[]
[]
[ "plone", "python", "ubuntu", "zlib" ]
stackoverflow_0006030876_plone_python_ubuntu_zlib.txt
Q: Python-twitter API help I have just started using the python-twitter API and it requires me to register the app for the authorization using OAuth. But when i register with twitter it asks for a Application website. Now the app I am creating is very basic I don't wish to share as I am doing this just for learning p...
Python-twitter API help
I have just started using the python-twitter API and it requires me to register the app for the authorization using OAuth. But when i register with twitter it asks for a Application website. Now the app I am creating is very basic I don't wish to share as I am doing this just for learning purposes and I don't have webs...
[ "Have you already read this?\nTwitter REST API Method: oauth authorize\nand from there this:\nAuthentication\n\nDesktop Clients\nThe traditional OAuth flow for desktop\n clients can be cumbersome. We've\n created a PIN-based experience for\n destkop clients that use the following\n flow:\n\nThe application uses...
[ 1 ]
[]
[]
[ "python", "python_twitter", "twitter", "twitter_oauth" ]
stackoverflow_0006056765_python_python_twitter_twitter_twitter_oauth.txt
Q: Finding a Python Library to Mock a Database I am about to finish a university project that involves Python, and my team has a test case shortage. We need more, and specifically, we need some test cases for the database. This is where mocking comes in, however. We need a Python-specific library that can be used to ...
Finding a Python Library to Mock a Database
I am about to finish a university project that involves Python, and my team has a test case shortage. We need more, and specifically, we need some test cases for the database. This is where mocking comes in, however. We need a Python-specific library that can be used to mock a database, so the test cases do not use SQL...
[ "If you absolutely must use mocks rather than the Django stuff others have mentioned, I'd recommend either Fudge or Mock.\n", "If you are using django, fixtures can solve your problem. I don't really know what you mean by mocking library, but they allow you to fill your db with test data. Which you can then int...
[ 6, 5, 2, 1, 0 ]
[]
[]
[ "database", "django", "mocking", "python", "testing" ]
stackoverflow_0005955032_database_django_mocking_python_testing.txt
Q: return outside function Hii I am getting the following error in Biopython: 'return' outside function (filename.. line 26) Below is the code of myfile PLEASE HELP # File Name RandonProteinSequences.py # standard library import os import random # biopython from Bio.Seq import Seq from Bio.Alphabet import IUPAC from...
return outside function
Hii I am getting the following error in Biopython: 'return' outside function (filename.. line 26) Below is the code of myfile PLEASE HELP # File Name RandonProteinSequences.py # standard library import os import random # biopython from Bio.Seq import Seq from Bio.Alphabet import IUPAC from Bio.SeqRecord import SeqReco...
[ "Python is sensitive to indentation. If your code is badly indented, it won't work.\nMy amazing googling powers tell me you've taken your code from this page, where unfortunately the code isn't properly formatted either. \nBut here, I took the effort. I'm not responsible if this will fail miserably though, because...
[ 8, 5, 2 ]
[]
[]
[ "biopython", "python" ]
stackoverflow_0006056675_biopython_python.txt
Q: How to display multiple placemarks and paths? I'm using PyKml module in order to form kml inside my Python script. I want to display path which consists of array of coordinates and also display all points as placemarks. Currently, I'm trying (without success) to do it following way doc = K.kml( K.Document...
How to display multiple placemarks and paths?
I'm using PyKml module in order to form kml inside my Python script. I want to display path which consists of array of coordinates and also display all points as placemarks. Currently, I'm trying (without success) to do it following way doc = K.kml( K.Document( K.Placemark( K.Point...
[ "This should let you iterate over the objects and associate each point with the lines it terminates:\nfrom pykml.factory import KML_ElementMaker as K\nfrom lxml import etree\n\n#line_points here comes from a geojson object\ndata = json.loads(open('tib.json').read())\nline_points = data['features'][0]['geometry']['c...
[ 1 ]
[]
[]
[ "google_maps", "kml", "metaprogramming", "pykml", "python" ]
stackoverflow_0006056434_google_maps_kml_metaprogramming_pykml_python.txt
Q: What is the pythonic/faster way to check if the "key" argument of a custom __getitem__ method is a slice? I have a custom Sequence type. It is essentially a wrapper for a list plus a boolean flag and I wanted it to emulate usual immutable sequence behavior. My issue is with slicing. I understand that in Python 3 t...
What is the pythonic/faster way to check if the "key" argument of a custom __getitem__ method is a slice?
I have a custom Sequence type. It is essentially a wrapper for a list plus a boolean flag and I wanted it to emulate usual immutable sequence behavior. My issue is with slicing. I understand that in Python 3 the way to implement it is to have a __getitem__(key) method that returns an item if %key is a single index and ...
[ "You could have a look through the standard library and copy what is done there. For example, calendar.py has:\ndef __getitem__(self, i):\n funcs = self._months[i]\n if isinstance(i, slice):\n return [f(self.format) for f in funcs]\n else:\n return funcs(self.format)\n\nwhich shows both expli...
[ 12, 2 ]
[]
[]
[ "magic_methods", "python", "slice", "typechecking" ]
stackoverflow_0006056898_magic_methods_python_slice_typechecking.txt
Q: Many to One relationship with SQLAlchemy in the same table I have a table of 'Clients' where a client can be a child of another client. Here's the table definition. [ClientID] [int] IDENTITY(1,1) NOT NULL, [name] [varchar](50) NOT NULL, [VPFSID] [varchar](50) NOT NULL, [Type] [varchar](25) NULL, [ROHostID] [varcha...
Many to One relationship with SQLAlchemy in the same table
I have a table of 'Clients' where a client can be a child of another client. Here's the table definition. [ClientID] [int] IDENTITY(1,1) NOT NULL, [name] [varchar](50) NOT NULL, [VPFSID] [varchar](50) NOT NULL, [Type] [varchar](25) NULL, [ROHostID] [varchar](60) NOT NULL, [RWHostID] [varchar](60) NOT NULL, [ParentClien...
[ "class Client(Base):\n ...<snip>...\n parent = relation('Client', remote_side=[client_id])\n\nDocs here: orm/self_referential.html\n" ]
[ 18 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0005649385_python_sql_sqlalchemy.txt
Q: Is there a standard way to sort by a non-english alphabet? For example, the romanian alphabet is "a ă â b c..." Possible Duplicate: How do I sort unicode strings alphabetically in Python? As a citizen of the Rest-of-the-World, I'm really annoyed by the fact that computers aren't adapted by default to deal with i...
Is there a standard way to sort by a non-english alphabet? For example, the romanian alphabet is "a ă â b c..."
Possible Duplicate: How do I sort unicode strings alphabetically in Python? As a citizen of the Rest-of-the-World, I'm really annoyed by the fact that computers aren't adapted by default to deal with international issues. Many sites still don't use Unicode and PHP is still in the Dark Ages. When I want to sort a lis...
[ "In Python, you can always use sorted function with a key parameter. For example, in Turkish, we have letters like 'ç','ı','ş' etc. If I want to sort according to that letter, I would use a key string which letters is sorted, and sort the string according to this, like this:\n>>> letters=\"abcçdefgğhıijklmnoöprsştu...
[ 8, 4 ]
[]
[]
[ "alphabetical", "non_english", "python", "sorting", "standards" ]
stackoverflow_0006056842_alphabetical_non_english_python_sorting_standards.txt
Q: Searching for £ sign with lxml I'm struggling with encodings and lxml. I'm reading in some html from a website and would like to search for a tag that includes a £ in its text using lxml. I can search the the tag(h3) and get the contents to print fine but if I try to search for the £ sign within the text I get a U...
Searching for £ sign with lxml
I'm struggling with encodings and lxml. I'm reading in some html from a website and would like to search for a tag that includes a £ in its text using lxml. I can search the the tag(h3) and get the contents to print fine but if I try to search for the £ sign within the text I get a UnicodeDecodeError. I need to do the ...
[ "I'm not experienced with neither python nor lxml, but the problem could be that the 'h3' string isn't a unicode string and that the byte a3 isn't a unicode code point by itself. You could try to replace:\n'h3:contains(u\"\\xa3\")'\n\nwith:\nu'h3:contains(\"\\u00a3\")'\n\n" ]
[ 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0006057319_lxml_python.txt
Q: Check the email message size limit with Python Can someone tell me, how could I check the size limit of an email message. So, if all attachements together exceeded the limit, I could send them in more messages. And lets say that each attachement is smaller than limit size. Im using python 2.7 (email, smtplib modul...
Check the email message size limit with Python
Can someone tell me, how could I check the size limit of an email message. So, if all attachements together exceeded the limit, I could send them in more messages. And lets say that each attachement is smaller than limit size. Im using python 2.7 (email, smtplib modules). Any suggestions, samples, links.. would be appr...
[ "Ok, I found that out :)\nimport smtplib \nsmtp = smtplib.SMTP('server.name') \nsmtp.ehlo() \nmax_limit_in_bytes = int( smtp.esmtp_features['size'] )\n\nThis returns size limit (in bytes) of entire email (with header, subject, message text...).\n" ]
[ 11 ]
[]
[]
[ "email", "limit", "python", "size" ]
stackoverflow_0006040906_email_limit_python_size.txt
Q: Python super() - should be working but isn't? As far as I can tell, and everything I've been finding online, this should work (but it doesn't, which is why I'm asking here ;) ) class Tigon(Crossbreeds, Predator, Lion): def __init__(self): super().__init__() def printSize(self): print("Huge...
Python super() - should be working but isn't?
As far as I can tell, and everything I've been finding online, this should work (but it doesn't, which is why I'm asking here ;) ) class Tigon(Crossbreeds, Predator, Lion): def __init__(self): super().__init__() def printSize(self): print("Huge") Both "Crossbreeds" and "Predator" inherit from ...
[ "Short answer: Don't inherit the same base class directly and indirectly, but inheriting directly after indirectly should work. So don't inherit Predator or inherit it after Lion.\nWell, the C3 MRO seems to not be able to find any order consistent with all constraints. The constraints are that:\n\neach class must c...
[ 7, 0, 0 ]
[]
[]
[ "multiple_inheritance", "python" ]
stackoverflow_0006057540_multiple_inheritance_python.txt
Q: ttk tkinter multiple frames/windows The following application I have created is used to demonstrate multiple windows in tkinter. The main problem is that none of the Entry controls, neither in the bmi-calculator or the converter, accept the values in the entry boxes - they get a ValueError when I do a calculation....
ttk tkinter multiple frames/windows
The following application I have created is used to demonstrate multiple windows in tkinter. The main problem is that none of the Entry controls, neither in the bmi-calculator or the converter, accept the values in the entry boxes - they get a ValueError when I do a calculation. from tkinter import * from tkinter impor...
[ "You have to convert the StringVar() to an integer/float or use IntVar() or DoubleVar()\nThere are other problems as well. Statements like the following return \"None\" since it is a grid() object and not a Label() object:\nself.label1 = ttk.Label(self, text=\"Enter your weight:\").grid(row=0, column=0, sticky=W) ...
[ 12, 9 ]
[]
[]
[ "python", "python_3.x", "tkinter", "ttk", "user_interface" ]
stackoverflow_0006035101_python_python_3.x_tkinter_ttk_user_interface.txt
Q: mining a database to extract text fields in python I have a database from which I am trying to extract certain information. The logical structure goes like this: gc; QUERY ft; NAME (need this field) fd; SEQUENCE (need this field) fd; SEQUENCE ... (more "fd;" fields) ft; NAME (need this field) fd; SEQUENCE (need o...
mining a database to extract text fields in python
I have a database from which I am trying to extract certain information. The logical structure goes like this: gc; QUERY ft; NAME (need this field) fd; SEQUENCE (need this field) fd; SEQUENCE ... (more "fd;" fields) ft; NAME (need this field) fd; SEQUENCE (need only first fd) ... (more fd; fields) ft; NAME (need this ...
[ "In the 6th line of code, flag == 1 should only have 1 equals sign. Otherwise, it's never being set to 1, which then fails your other checks. Additionally, unless there's more code below that which is cut off off, you don't need any of those continues - it will automatically go to the next iteration of the loop.\...
[ 1 ]
[]
[]
[ "python", "text_extraction" ]
stackoverflow_0006057381_python_text_extraction.txt
Q: Digital image correlation libraries for a mac I'm working on a project to develop a Digital Image Correlation tool for measuring surface strains. Does anyone know of any Mac compatible libraries that I can use to do the DIC processing. I was thinking that this might be something where there is a Python library but...
Digital image correlation libraries for a mac
I'm working on a project to develop a Digital Image Correlation tool for measuring surface strains. Does anyone know of any Mac compatible libraries that I can use to do the DIC processing. I was thinking that this might be something where there is a Python library but I have not yet managed to find one.
[ "Have a look at this thread Image Processing, In Python?\nThen there is the OpenCV with Python interface\nDon't know about the MAC-part though...\n" ]
[ 1 ]
[]
[]
[ "image_processing", "macos", "python" ]
stackoverflow_0006057876_image_processing_macos_python.txt
Q: Python: Rearranging csv lines with conditions If I have few csv files as follows: a,1,2,3 type, max, min, avg b,4,5,6 <empty line> c,6,7,8 xxx,4,3,2 d,5,6,7 after reading the above csv file using csv reader, how do i dump the data to a new xls file using xlwt module but in an arranged manner, so that it: - writes...
Python: Rearranging csv lines with conditions
If I have few csv files as follows: a,1,2,3 type, max, min, avg b,4,5,6 <empty line> c,6,7,8 xxx,4,3,2 d,5,6,7 after reading the above csv file using csv reader, how do i dump the data to a new xls file using xlwt module but in an arranged manner, so that it: - writes the header as 1st line (this line always has 'type...
[ "If a line were empty, I don't think this would be true:\nrow[0] == ' ' # A space?\n\nI would expect row to be an empty list, but perhaps there's something in your data that I don't know about.\nAlso, instead of sorting out the logic to keep track of row_count and then subtracting pass_count, why not keep things s...
[ 3, 3 ]
[]
[]
[ "csv", "python", "xlwt" ]
stackoverflow_0006057527_csv_python_xlwt.txt
Q: What package should I use to query Mysql Databases in Python? I need to query a Mysql database with Python. I have virtual env installed and also PIP, I have tried to install this package, http://pypi.python.org/pypi/MySQL-python/#downloads but without success. I have parformed the command: sudo pip install http:/...
What package should I use to query Mysql Databases in Python?
I need to query a Mysql database with Python. I have virtual env installed and also PIP, I have tried to install this package, http://pypi.python.org/pypi/MySQL-python/#downloads but without success. I have parformed the command: sudo pip install http://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.3....
[ "The error message is self-speaking\nsh: mysql_config: not found\n\nmysql_config is part of the MySQL installation is either not installed nor not available\nfrom the $PATH. This is the problem to be solved - not the question about binding alternatives.\n", "The error message shows you are missing mysql_config (a...
[ 4, 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006058076_mysql_python.txt
Q: Using a Django variable in a CSS file I am trying to create a dynamic CSS file using the Django templating engine or any other means. Currently, I have a CSS rule that looks like this: background-image: url('http://static.example.com/example.png'); Where http://static.example.com corresponds to the STATIC_URL var...
Using a Django variable in a CSS file
I am trying to create a dynamic CSS file using the Django templating engine or any other means. Currently, I have a CSS rule that looks like this: background-image: url('http://static.example.com/example.png'); Where http://static.example.com corresponds to the STATIC_URL variable in Python. Using the Django templatin...
[ "A very good solution here is to use django-compressor. Firstly, if you are serving more than one CSS file, compressor is going to help improve page load times by dropping the number of requests. \nA side effect of compressing / concatenating files is that compressor rewrites urls in the css file, so relatively ref...
[ 14, 11 ]
[]
[]
[ "css", "django", "django_templates", "python", "templates" ]
stackoverflow_0006052341_css_django_django_templates_python_templates.txt
Q: use python twisted framework to connect to multiple serial sockets I currently use twisted to connect to a serial device I have, using code like the following. from twisted.internet import reactor SerialPort(Handler(), "/dev/ttyACM1", reactor, baudrate='9600') reactor.run() However, I know need to extend the appl...
use python twisted framework to connect to multiple serial sockets
I currently use twisted to connect to a serial device I have, using code like the following. from twisted.internet import reactor SerialPort(Handler(), "/dev/ttyACM1", reactor, baudrate='9600') reactor.run() However, I know need to extend the application to monitor for new serial devices being added (and removed). I ...
[ "Any time you want to use a Twisted API but your code isn't running in the same thread as the reactor, you can use reactor.callFromThread to have the reactor call some of your code in its thread. So, for example, you could do something like this:\ndef process_IN_CREATE(self, event):\n reactor.callFromThread(\n ...
[ 7 ]
[]
[]
[ "python", "serial_port", "twisted" ]
stackoverflow_0006057485_python_serial_port_twisted.txt
Q: Efficient way to find the token (word) index after a regular expression string search I need to perform a regular expression search for a string x in another string y, but I then need to know the token (word) index of the first character of the hit after tokenizing (splitting) string y using some other regular ex...
Efficient way to find the token (word) index after a regular expression string search
I need to perform a regular expression search for a string x in another string y, but I then need to know the token (word) index of the first character of the hit after tokenizing (splitting) string y using some other regular expression (e.g. white space). The first regular expression might find a substring, so I cann...
[ "According to your updates:\n#!/usr/bin/perl -l\nuse strict;\nuse warnings;\n\nmy $string = \"The moon is made of cheese\";\nmy $search = 'de of ch';\nmy $pos = index($string, $search);\nif ($pos != -1) {\n my $substr = substr($string, 0, $pos);\n my @words = split /\\s+/, $substr;\n print \"found in word ...
[ 1, 1 ]
[]
[]
[ "perl", "python", "regex", "string" ]
stackoverflow_0006056236_perl_python_regex_string.txt
Q: Is it safe to write your own table creation SQL for use with Django, when the generated tables are not enough? I need to have some references in my table and a bunch of "deferrable initially deferred" modifiers, but I can't find a way to make this work in the default generated Django code. Is it safe to create the...
Is it safe to write your own table creation SQL for use with Django, when the generated tables are not enough?
I need to have some references in my table and a bunch of "deferrable initially deferred" modifiers, but I can't find a way to make this work in the default generated Django code. Is it safe to create the table manually and still use Django models?
[ "Yes. \nI don't see why not, but that would be most unconventional and breaking convention usually leads to complications down the track.\nDescribe the problem you think it will solve and perhaps someone can offer a more conventional solution.\n", "Yep! Django is super flexible in this regard. It even has a reall...
[ 2, 0, 0 ]
[]
[]
[ "django", "postgresql", "python", "sql" ]
stackoverflow_0006053426_django_postgresql_python_sql.txt
Q: Django: how to give mp3 file correctly The problem is I can't change playing position by clicking on a timeline in google Chrome (it always plays from start to end) If Nginx gives mp3 file to the client everything is OK and I can change playing position. In my script I give mp3 this way: from django.core.server...
Django: how to give mp3 file correctly
The problem is I can't change playing position by clicking on a timeline in google Chrome (it always plays from start to end) If Nginx gives mp3 file to the client everything is OK and I can change playing position. In my script I give mp3 this way: from django.core.servers.basehttp import FileWrapper wrapper = File...
[ "This is because the headers should handle additiona headers (like Accept-Ranges), and it should handle partial file requests\nDoing this kind of things inside Django itself is a mess (I tried it some time ago), but then I ended up using Apache for serving files (this way you just don't waste resources)\nYou can co...
[ 5 ]
[]
[]
[ "django", "http_headers", "mp3", "python" ]
stackoverflow_0006057215_django_http_headers_mp3_python.txt
Q: Python module problem I have two .py files called "notepad.py" & "pycolour.py". First is in the parent folder, second is in "subdir" folder. First file: #notepad.py from Tkinter import * from subdir import pycolour class SimpleNotepad(object): def __init__(self): self.frame = Frame(root, bg='#707070'...
Python module problem
I have two .py files called "notepad.py" & "pycolour.py". First is in the parent folder, second is in "subdir" folder. First file: #notepad.py from Tkinter import * from subdir import pycolour class SimpleNotepad(object): def __init__(self): self.frame = Frame(root, bg='#707070', bd=1) self.text_f...
[ "PyColour is a class. In order to take advantage of what it does you must either create an instance of it (eg self.text_field = PyColour(...)) or create your own class that subclasses the PyColour class (eg class MyPyColour(PyColour): ...; self.text_field = MyPyColour(...))\n", "PyColour is not a utility class bu...
[ 1, 0 ]
[]
[]
[ "module", "python", "tkinter" ]
stackoverflow_0006031785_module_python_tkinter.txt
Q: Storing user and password in a database I am creating a software with user + password. After autentification, the user can access some semi public services, but also encrypt some files that only the user can access. The user must be stored as is, without modification, if possible. After auth, the user and the pass...
Storing user and password in a database
I am creating a software with user + password. After autentification, the user can access some semi public services, but also encrypt some files that only the user can access. The user must be stored as is, without modification, if possible. After auth, the user and the password are kept in memory as long as the softwa...
[ "Crypto is hard to get right, it's good that you're asking questions.\nStoring passwords: Passwords should be hashed using a key stretching algorithm. Typically, you want to use a library rather than implement it yourself. Key stretching algorithms are designed to chew up processor cycles, so it's nice to evaluat...
[ 10, 2 ]
[]
[]
[ "passwords", "python", "security" ]
stackoverflow_0006058019_passwords_python_security.txt
Q: Python UTF-8 conversion problem In my database, I have stored some UTF-8 characters. E.g. 'α' in the "name" field Via Django ORM, when I read this out, I get something like >>> p.name u'\xce\xb1' >>> print p.name α I was hoping for 'α'. After some digging, I think if I did >>> a = 'α' >>> a '\xce\xb1' So when P...
Python UTF-8 conversion problem
In my database, I have stored some UTF-8 characters. E.g. 'α' in the "name" field Via Django ORM, when I read this out, I get something like >>> p.name u'\xce\xb1' >>> print p.name α I was hoping for 'α'. After some digging, I think if I did >>> a = 'α' >>> a '\xce\xb1' So when Python is trying to display '\xce\xb1'...
[ "Try to put the unicode signature u before your string, e.g. u'YOUR_ALFA_CHAR' and revise your database encoding, because Django always supports UTF-8 .\n", "What you seem to have is the individual bytes of a UTF-8 encoded string interpreted as unicode codepoints. You can \"decode\" your string out of this strang...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "django", "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0006050719_django_encoding_python_unicode_utf_8.txt
Q: Fuse-Python: Unable to run example I'm tinkering around with the fuse-python bindings and I can't seem to grasp how to run the example xmp.py from the library package (xmp.py is located here). Looking at a lecture slide from MIT (located here), on slide 33, it shows the command line invoking of xmp.py: ./xmp.py --...
Fuse-Python: Unable to run example
I'm tinkering around with the fuse-python bindings and I can't seem to grasp how to run the example xmp.py from the library package (xmp.py is located here). Looking at a lecture slide from MIT (located here), on slide 33, it shows the command line invoking of xmp.py: ./xmp.py --o root=/mit/sipb/ /tmp/mntdir (I do pyt...
[ "I tried your script, and on my ubuntu box, with this command line :\npython xmp.py -o root=/home/chris /tmp/fs\n\nit works !\nWith a --o option, it never works ;)\n" ]
[ 4 ]
[]
[]
[ "fuse", "python", "xmp" ]
stackoverflow_0006058780_fuse_python_xmp.txt
Q: How to better visualizing data while working with MySQL Database? To double check if my code does the right thing (python and php querying a huge dMySQL dabase) I do ssh to my server and fireup mysql. Then I start querying... and querying... and querying... And the querys sometimes are really long. That is trouble...
How to better visualizing data while working with MySQL Database?
To double check if my code does the right thing (python and php querying a huge dMySQL dabase) I do ssh to my server and fireup mysql. Then I start querying... and querying... and querying... And the querys sometimes are really long. That is troublesome. :-) Because I have to double check a lot of times if my code doe...
[ "Have you tried using something like Querious for the mac or Mysql Query browser for most platforms ?\n", "I personally use Navicat and I love it. Check out Toad for MySQL for a free tool.\n", "To see the changes in the database you have no other than to connect to the db and see the results. Best idea is to us...
[ 3, 0, 0 ]
[]
[]
[ "mysql", "php", "python", "visualization" ]
stackoverflow_0006058958_mysql_php_python_visualization.txt
Q: Evaluating a list of python lambda functions only evaluates the last list element I have a list of lambda functions I want to evaluate in order. I'm not sure why, but only the last function gets evaluated. Example below: >>> def f(x,z): ... print "x=",x,", z=",z ... >>> >>> g = lambda x : f(x,13) ...
Evaluating a list of python lambda functions only evaluates the last list element
I have a list of lambda functions I want to evaluate in order. I'm not sure why, but only the last function gets evaluated. Example below: >>> def f(x,z): ... print "x=",x,", z=",z ... >>> >>> g = lambda x : f(x,13) >>> g(2) x= 2 , z= 13 # As expected >>> >>> lst=[] >>> >>> for i in ran...
[ "The lambda is just looking up the global value of 'i'.\nTry the following instead:\nfor i in range(0,5):\n lst.append(lambda x, z=i: f(x,z))\n\n", "try using partial, works for me:\nfrom functools import partial\n\ndef f(x,z):\n print \"x=\",x,\", z=\",z\n\nlst = [ partial(f,z=i) for i in range(5) ]\n\nfor f...
[ 18, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006059205_python.txt
Q: I want to extract a .tgz file and extract any subdirectories that have files that are .tgz and .tar I'm using the code below to extract .tgz files. The type of log files (.tgz) that I need to extract have sub-directories that have other .tgz files and .tar files inside them. I want to extract those too. Ultimately...
I want to extract a .tgz file and extract any subdirectories that have files that are .tgz and .tar
I'm using the code below to extract .tgz files. The type of log files (.tgz) that I need to extract have sub-directories that have other .tgz files and .tar files inside them. I want to extract those too. Ultimately, I'm trying to search for certain strings in all .log files and .txt files that may appear in a .tgz fil...
[ "This should give you the desired result:\nimport os, sys, tarfile\n\ndef extract(tar_url, extract_path='.'):\n print tar_url\n tar = tarfile.open(tar_url, 'r')\n for item in tar:\n tar.extract(item, extract_path)\n if item.name.find(\".tgz\") != -1 or item.name.find(\".tar\") != -1:\n ...
[ 13 ]
[]
[]
[ "compression", "gzip", "python", "tar" ]
stackoverflow_0006058786_compression_gzip_python_tar.txt
Q: What is the pythonic/faster way to declare module-level constants with computed values? I'm writing a utility module for easy handling of data text files. I have declared some module-level constants to provide default values to my methods arguments since for now I only use these values but I want my code to be eas...
What is the pythonic/faster way to declare module-level constants with computed values?
I'm writing a utility module for easy handling of data text files. I have declared some module-level constants to provide default values to my methods arguments since for now I only use these values but I want my code to be easily adaptable. But some constants aren't easily hard-coded. For example re's pattern objects ...
[ "Yes, this is fine. It will be executed on import. If you have a significant amount of computation to do (which re.compile isn't), it will slow down the import -- but this is as it should be, since you need the constants to do your work anyway.\nWhy are you using double-underscore names? If the constants are meant ...
[ 6, 2, 1 ]
[]
[]
[ "module", "python" ]
stackoverflow_0006059519_module_python.txt
Q: python parse plain text file with ^M carriage returns Possible Duplicate: Make the readline method of Python recognize both end-of-line variations? Hello, I have a plain text file that uses ^M as carriage returns. In my OSX text editors it appears well formatted with spaces, but in vi it shows as one line with ^...
python parse plain text file with ^M carriage returns
Possible Duplicate: Make the readline method of Python recognize both end-of-line variations? Hello, I have a plain text file that uses ^M as carriage returns. In my OSX text editors it appears well formatted with spaces, but in vi it shows as one line with ^M interspaced throughout the file. Python also only sees t...
[ "They can be safely removed. If you're using vi you can remove all extraneous visible ^M characters by issuing the following command (in command mode of course):\n%s[enter]\n\n(Actually hit the enter key, don't type that in!)\n" ]
[ 0 ]
[]
[]
[ "carriage_return", "file", "parsing", "python" ]
stackoverflow_0006059626_carriage_return_file_parsing_python.txt
Q: GAE/Django TemplateError I have a google app engine app that is using Django templates. I am trying to do this: {% if person.age >= 4 %} <p style="color:White">Hello</p> {% else %} <p style="color:Black">Hello</p> {% endif %} This doesn't work, I get: "TemplateSyntaxError: 'if' statement improperly fo...
GAE/Django TemplateError
I have a google app engine app that is using Django templates. I am trying to do this: {% if person.age >= 4 %} <p style="color:White">Hello</p> {% else %} <p style="color:Black">Hello</p> {% endif %} This doesn't work, I get: "TemplateSyntaxError: 'if' statement improperly formatted". Meanwhile (because s...
[ "Do if person.age and person.age >= 4\nThat way, if person.age is None, it will fail the first check and not throw the syntax error on the second one.\n", "What Django version are you using?\nThe default version on App Engine is 0.96, and the >= operator was not supported until 1.2.\nYou can switch to 1.2 by addi...
[ 2, 2, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0006054194_django_templates_google_app_engine_python.txt
Q: Robust way to put contents of any arbitrary text file in the database (using Django/Python)? As part of my Django app, I have to get the contents of a text file which a user uploads (which could be any charset) and save it to my DB. I keep running into issues (like having to remove UTF8's BOM manually, or having t...
Robust way to put contents of any arbitrary text file in the database (using Django/Python)?
As part of my Django app, I have to get the contents of a text file which a user uploads (which could be any charset) and save it to my DB. I keep running into issues (like having to remove UTF8's BOM manually, or having to figure out how to account for non-printable characters, or having to figure out how to make all ...
[ "Causes some overhead, but you could base64 encode the entire string before persisting to the db. Then no escaping is required.\n", "If you want to explicitly steer away from any issues with encoding and just see files as bunches of binary data (not strings of text in a specific encoding) you might want to use yo...
[ 1, 0 ]
[]
[]
[ "django", "file_upload", "python", "text", "unicode" ]
stackoverflow_0006059382_django_file_upload_python_text_unicode.txt