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: Which of these scripting languages is more appropriate for pen-testing? First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. If, for example, I se...
Which of these scripting languages is more appropriate for pen-testing?
First of all, I want to avoid a flame-war on languages. The languages to choose from are Perl, Python and Ruby . I want to mention that I'm comfortable with all of them, but the problem is that I can't focus just on one. If, for example, I see a cool Perl module, I have to try it out. If I see a nice Python app, I hav...
[ "You probably want Ruby, because it's the native language for Metasploit, which is the de facto standard open source penetration testing framework. Ruby's going to give you:\n\nMetasploit's framework, opcode and shellcode databases\nMetasploit's Ruby lorcon bindings for raw 802.11 work.\nMetasploit's KARMA bindings...
[ 28, 8, 4, 3, 3, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "penetration_testing", "perl", "python", "ruby", "security" ]
stackoverflow_0000076408_penetration_testing_perl_python_ruby_security.txt
Q: Channels and TaskQueues in Google App Engine (client debugging) I'm trying to build and debug my first GAE application and have already benefited from the awesome support of Stackoverflowers to get where I am in having tasks being processed on the default queue. Thanks! However, I wanted to use Queues to demonstra...
Channels and TaskQueues in Google App Engine (client debugging)
I'm trying to build and debug my first GAE application and have already benefited from the awesome support of Stackoverflowers to get where I am in having tasks being processed on the default queue. Thanks! However, I wanted to use Queues to demonstrate how you would do some 'long' work in the background. My idea was: ...
[ "Yes, the App Engine dev_appserver is single-threaded, and only processes a single request at a time. Your user-facing request should return before it begins processing the task queue request, however.\n" ]
[ 2 ]
[]
[]
[ "channel_api", "google_app_engine", "python", "task_queue" ]
stackoverflow_0004918359_channel_api_google_app_engine_python_task_queue.txt
Q: What can be done to speed up this memoization decorator? What I want is a memoization decorator that: can memoize instance methods with both arguments and keyword arguments has a cache that can be cleared (globally) with one call (vs. this one that uses a per-function cache: python resettable instance method me...
What can be done to speed up this memoization decorator?
What I want is a memoization decorator that: can memoize instance methods with both arguments and keyword arguments has a cache that can be cleared (globally) with one call (vs. this one that uses a per-function cache: python resettable instance method memoization decorator) is reasonably efficient I've tweaked an...
[ "You're not actually caching any data, because each time you set a new cached value you overwrite the previous:\nMemoized.__cache[self.key] = {args : value}\n\neg.\nimport functools\n\nclass Memoized(object):\n \"\"\"Decorator that caches a function's return value each time it is called.\n If called later wit...
[ 13, 2 ]
[]
[]
[ "memoization", "python" ]
stackoverflow_0004927323_memoization_python.txt
Q: Error while running a python file I am getting a error while running it. The Error is : File "binary_Light.py", model_url^=project page Traceback (most recent call last): File "binary_light.py", line 8, in <module> from brisa.upnp.device import Device, Service File "/usr/local/lib/python2.6...
Error while running a python file
I am getting a error while running it. The Error is : File "binary_Light.py", model_url^=project page Traceback (most recent call last): File "binary_light.py", line 8, in <module> from brisa.upnp.device import Device, Service File "/usr/local/lib/python2.6/dist-packages/brisa/upnp/device/__init...
[ "There is a comma missing at the end of model_number = '1.0'.\nmodel_name = 'Binary Light Device',\nmodel_description = 'Test Device',\nmodel_number = '1.0' <-\nmodel_url= project_page)\n\n", "You are missing a comma:\nmodel_description = 'Test Device',\nmodel_number = '1.0', # <- here\nmodel_url=...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004927894_python.txt
Q: Python - Fetching data from two serial ports in realtime My project is a directional antenna which is mounted on a self-stabilizing base. The language I wish to use is python, but changing this to a more suited language, is a possibility, if needed. Problem 1: How would you go about taking in serial data in real...
Python - Fetching data from two serial ports in realtime
My project is a directional antenna which is mounted on a self-stabilizing base. The language I wish to use is python, but changing this to a more suited language, is a possibility, if needed. Problem 1: How would you go about taking in serial data in real-time[1], and then parse the data in python? Problem 2: How ca...
[ "You can use the pyserial module to read serial port data with Python. See: http://pyserial.sourceforge.net/shortintro.html\nHere's a short usage example from the docs:\n>>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)\n>>> x = ser.read() # read one byte\n>>> s = ser.read(10) # read up to t...
[ 2 ]
[]
[]
[ "gps", "math", "parsing", "python", "real_time" ]
stackoverflow_0004928108_gps_math_parsing_python_real_time.txt
Q: How to handle time zones in a CMS? I'm storing MySQL DateTimes in UTC, and let the user select their time zone, storing that information. However, I want to to some queries that uses group by a date. Is it better to store that datetime information in UTC (and do the calculation every time) or is it better to save...
How to handle time zones in a CMS?
I'm storing MySQL DateTimes in UTC, and let the user select their time zone, storing that information. However, I want to to some queries that uses group by a date. Is it better to store that datetime information in UTC (and do the calculation every time) or is it better to save it in the timezone given? Since time z...
[ "Generally always store in UTC and convert for display, it's the only sane way to do time differences etc. Or when somebody next year decides to change the summer time dates.\n", "It's almost always better to save the time information in UTC, and convert it to local time when needed for presentation and display.\...
[ 3, 1 ]
[]
[]
[ "mysql", "python", "timezone" ]
stackoverflow_0004928220_mysql_python_timezone.txt
Q: all permutations of a binary sequence x bits long I would like to find a clean and clever way (in python) to find all permutations of strings of 1s and 0s x chars long. Ideally this would be fast and not require doing too many iterations... So, for x = 1 I want: ['0','1'] x =2 ['00','01','10','11'] etc.. Right now...
all permutations of a binary sequence x bits long
I would like to find a clean and clever way (in python) to find all permutations of strings of 1s and 0s x chars long. Ideally this would be fast and not require doing too many iterations... So, for x = 1 I want: ['0','1'] x =2 ['00','01','10','11'] etc.. Right now I have this, which is slow and seems inelegant: se...
[ "itertools.product is made for this:\n>>> import itertools\n>>> [\"\".join(seq) for seq in itertools.product(\"01\", repeat=2)]\n['00', '01', '10', '11']\n>>> [\"\".join(seq) for seq in itertools.product(\"01\", repeat=3)]\n['000', '001', '010', '011', '100', '101', '110', '111']\n\n", "There's no need to be over...
[ 73, 9, 7, 6, 3 ]
[]
[]
[ "algorithm", "combinatorics", "python" ]
stackoverflow_0004928297_algorithm_combinatorics_python.txt
Q: What is causing this massive discrepancy on the timing of these method calls? Using the accepted answer (with the doctests) for the Memoized decorator from here: What can be done to speed up this memoization decorator? and the following code (fib.py): class O(object): def nfib(self,n): # non-memoized fib fn ...
What is causing this massive discrepancy on the timing of these method calls?
Using the accepted answer (with the doctests) for the Memoized decorator from here: What can be done to speed up this memoization decorator? and the following code (fib.py): class O(object): def nfib(self,n): # non-memoized fib fn if n in (0, 1): return n return self.nfib(n-1) + self.nfib(n-2) ...
[ "The call tree for a naive fibonacci function isn't linear or triangular, it's multidimensional pyramidal. By memoizing even a single time you trim vast amounts of calls from the tree, turning the pyramid into a mostly linear structure.\n", "The third loop is resetting after calculating each final result - howeve...
[ 6, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004928507_python.txt
Q: WxPython: Create Resizable Columns I just recently started using Wxpython and I am coding something for a friend that requires a UI that has adjustable columns (you can change the width). Any help would be appreciated. A: wx.ListCtrl
WxPython: Create Resizable Columns
I just recently started using Wxpython and I am coding something for a friend that requires a UI that has adjustable columns (you can change the width). Any help would be appreciated.
[ "wx.ListCtrl\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004927735_python_wxpython.txt
Q: Python, pythonic expression Is there pythonic expression for this snippet? # linux.cmd is a dict cmd = linux.cmd.get(k, k) if not cmd: cmd = k The value of linux.cmd.get[k] could be False. A: All you need is the first line, sice the second paramter to dict.get() is the default value anyway. That construct r...
Python, pythonic expression
Is there pythonic expression for this snippet? # linux.cmd is a dict cmd = linux.cmd.get(k, k) if not cmd: cmd = k The value of linux.cmd.get[k] could be False.
[ "All you need is the first line, sice the second paramter to dict.get() is the default value anyway. That construct returns k if k is not in dict. IF dict can return a value that evaluates to false add a \" or k\" to the end of the first line.\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0004928857_python.txt
Q: Google App Engine unique=True? Possible Duplicate: How do I define a unique property for a Model in Google App Engine? I can't seems to find a way to work the unique property for a model. I followed How do I define a unique property for a Model in Google App Engine? and a couple other tutorials, but none seems t...
Google App Engine unique=True?
Possible Duplicate: How do I define a unique property for a Model in Google App Engine? I can't seems to find a way to work the unique property for a model. I followed How do I define a unique property for a Model in Google App Engine? and a couple other tutorials, but none seems to work? What's the easiest way to m...
[ "The easiest way is to find a different way to do what you want. Google AppEngine does not natively support unique properties, and all of the ways that I have seen to implement them involve either pain or subverting the performance and scalability that are why you should be using it in the first place.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004928731_google_app_engine_google_cloud_datastore_python.txt
Q: Is it possible to turn this code snippet in a list comprehension? How? a = 0 b = {'a': [(1, 'a'), (2, 'b'), (3, 'c')], 'b': [(4, 'd'), (5, 'e')]} for c, d in b.iteritems(): for e, f in d: a += e // now a = 15 Tried several ways. I want to know a way (if possible) to simplify this sum with a list com...
Is it possible to turn this code snippet in a list comprehension? How?
a = 0 b = {'a': [(1, 'a'), (2, 'b'), (3, 'c')], 'b': [(4, 'd'), (5, 'e')]} for c, d in b.iteritems(): for e, f in d: a += e // now a = 15 Tried several ways. I want to know a way (if possible) to simplify this sum with a list comprehension: a = sum(...) Thank you in advance, pf.me
[ "a = sum(e for d in b.itervalues() for e, _ in d) works in Python 2.7.\na = sum([e for d in b.itervalues() for e, _ in d]) works in Python 2.3.\nI haven't tried it, but a = sum(e for d in b.values() for e, _ in d) should be the Python 3.0 equivalent.\n", "sum(j for _,i in b.iteritems() for j,_ in i) will do it.\n...
[ 6, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0004929075_list_comprehension_python.txt
Q: Python csv write module, need output into different rows instead of columns I am trying to get a list of files for a certain path in a csv file. I get the desired results but they are in a single row. How can the output appear in different rows. My code is follows: import csv import os path = raw_input("Enter ...
Python csv write module, need output into different rows instead of columns
I am trying to get a list of files for a certain path in a csv file. I get the desired results but they are in a single row. How can the output appear in different rows. My code is follows: import csv import os path = raw_input("Enter Path:") dirList=os.listdir(path) csvOut=open('outputnew.csv','w') w = csv.w...
[ "Call writerow multiple times to put the list into different rows.\nfor directory in dirList:\n w.writerow([directory])\n\n(But in this case I don't see the need of using CSV...)\n" ]
[ 2 ]
[]
[]
[ "csv", "file", "list", "python" ]
stackoverflow_0004929128_csv_file_list_python.txt
Q: Is it possible to use Django 1.2 on Google App Engine? I want to use the in operator in my Google App Engine project which was introduced in Django 1.2: {% if "bc" in "abcdef" %} This appears since "bc" is a substring of "abcdef" {% endif %} I found out that is possible to use version 1.0 or 1.1on GAE, but noth...
Is it possible to use Django 1.2 on Google App Engine?
I want to use the in operator in my Google App Engine project which was introduced in Django 1.2: {% if "bc" in "abcdef" %} This appears since "bc" is a substring of "abcdef" {% endif %} I found out that is possible to use version 1.0 or 1.1on GAE, but nothing for 1.2. Is it possible?
[ "It appears so, I found this - http://www.deck.cc/django_1.2_on_google_app_engine.html\n", "You can bundle any version of Django with your application and deploy it.\nDjango 1.2.4 will almost certainly be included in the next release of App Engine; it's in the pre-release SDK 1.4.2 that was put out late last week...
[ 3, 2, 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0004927626_django_google_app_engine_python.txt
Q: KeyError while building multidimensional dictionary in Python I am trying to build a dictionary with two keys but am getting a KeyError when assigning items. I don't get the error when using each of the keys separately, and the syntax seems pretty straightforward so I'm stumped. searchIndices = ['Books', 'DVD'] a...
KeyError while building multidimensional dictionary in Python
I am trying to build a dictionary with two keys but am getting a KeyError when assigning items. I don't get the error when using each of the keys separately, and the syntax seems pretty straightforward so I'm stumped. searchIndices = ['Books', 'DVD'] allProducts = {} for index in searchIndices: res = amazon.ItemSe...
[ "In order to assign to allProducts[index][x], first a lookup is done on allProducts[index] to get a dict, then the value you're assigning is stored at index x in that dict.\nHowever, the first time through the loop, allProducts[index] doesn't exist yet. Try this:\nfor x in range(10):\n if index not in allProduct...
[ 6, 3, 1, 0, 0 ]
[]
[]
[ "dictionary", "multidimensional_array", "python" ]
stackoverflow_0004926721_dictionary_multidimensional_array_python.txt
Q: Python C API: PyEval_CallFunction? I've discovered a function in the Python C API named PyEval_CallFunction which seems to be useful. It allows you to invoke a Python callable by saying something like: PyEval_CallFunction(obj, "OOO", a, b, c); However, I can't find any official documentation on this function. A...
Python C API: PyEval_CallFunction?
I've discovered a function in the Python C API named PyEval_CallFunction which seems to be useful. It allows you to invoke a Python callable by saying something like: PyEval_CallFunction(obj, "OOO", a, b, c); However, I can't find any official documentation on this function. A google search brings up various unoffic...
[ "I couldn't find many references to it either, but the tutorial you linked to mentions this:\n\nThe string format and the following\n arguments are as for Py_BuildValue\n (XXX so i really should have described\n that by now!). A call such as\nPyEval_CallFunction(obj, \"iii\", a, b, c);\n\nis equivalent to\nPyEva...
[ 5, 5 ]
[]
[]
[ "c", "python", "python_c_api" ]
stackoverflow_0004922365_c_python_python_c_api.txt
Q: Python override __getattr__ for nested assignment, but not for referencing? Here's the behavior I'm looking for: >>> o = SomeClass() >>> # Works: >>> o.foo.bar = 'bar' >>> print o.foo.bar 'bar' >>> # The in-between object would be of type SomeClass as well: >>> print o.foo >>> <__main__.SomeClass object at 0x7f...
Python override __getattr__ for nested assignment, but not for referencing?
Here's the behavior I'm looking for: >>> o = SomeClass() >>> # Works: >>> o.foo.bar = 'bar' >>> print o.foo.bar 'bar' >>> # The in-between object would be of type SomeClass as well: >>> print o.foo >>> <__main__.SomeClass object at 0x7fea2f0ef810> >>> # I want referencing an unassigned attribute to fail: >>> print...
[ "This is impossible in Python.\nWhat you're asking is for this:\n>>> o = SomeClass()\n>>> o.foo.bar = 'bar' \n>>> print o.foo.bar\n'bar'\n>>> a = o.baz\nraises AttributeError\n\nThis can't be done. There's no way to distinguish\n>>> o.foo.bar = 'bar' \n\nfrom\n>>> temp = o.foo\n>>> temp.bar = 'bar' \n\nThey're log...
[ 6, 2, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004928419_python.txt
Q: ctags never stops when I try to build a tag file for all python libraries I used to use ctags to generate a tags file for all installed python libraries by this command: C:\Windows\System32>ctags -R -f d:\home\vimfiles\python.ctags d:\Python26 But this morning, after I upgraded to Python 2.6.7, that command only ...
ctags never stops when I try to build a tag file for all python libraries
I used to use ctags to generate a tags file for all installed python libraries by this command: C:\Windows\System32>ctags -R -f d:\home\vimfiles\python.ctags d:\Python26 But this morning, after I upgraded to Python 2.6.7, that command only generates the following output and never finishes its job. The size of the tag...
[ "@Gintautas You are genius. \nI found ctags was stopped by this file : \nD:\\Python26\\Lib\\site-packages\\ipython-0.10-py2.6.egg\\share\\doc\\ipython\\manual\\html\\searchindex.js\n\nExclude it by set the following ctags option could resolve the problem.\n--exclude=searchindex.js\n\nI guess it's a bug of ctags.\n...
[ 4 ]
[]
[]
[ "ctags", "python" ]
stackoverflow_0004924289_ctags_python.txt
Q: Sharing data between two lists First let me say that I thought that the way data storage worked in python is that everything is an object so there is no need for such things as pointers. If you pass an piece of data into a function then that function has the real piece of data. When you exit out of that function...
Sharing data between two lists
First let me say that I thought that the way data storage worked in python is that everything is an object so there is no need for such things as pointers. If you pass an piece of data into a function then that function has the real piece of data. When you exit out of that function it the data passed in could have be...
[ "First of all, integers (really, number objects) are immutable. There is no \"modifying\" this \"data\".\nSecond of all, there is also in Python the notion of name binding. When you do:\np = 9\n\nTwo things happen: first, a number object (9) is created; second, it is then bound to the name p.\nWhen you later do:\np...
[ 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004929716_list_python.txt
Q: Installing/compiling pylzma (lzma python binding) I've already posted this question on the authors website, but I thought I might ask here as well. I've been trying to install pylzma with this setup: Windows 7 x64 Python 2.6.6 x64 the amd64 compiler coming from windows server 2003 sdk cloned the git repo git://gi...
Installing/compiling pylzma (lzma python binding)
I've already posted this question on the authors website, but I thought I might ask here as well. I've been trying to install pylzma with this setup: Windows 7 x64 Python 2.6.6 x64 the amd64 compiler coming from windows server 2003 sdk cloned the git repo git://github.com/fancycode/pylzma.git With a simple easy_insta...
[ "I have installed pylzma to try this out myself. For python 2.6 it builds fine with mingw, but msvc compiler chokes for python2.4-2.7. Let's see errors first:\n\nsrc/pylzma/pylzma.c(102) : error\n C2275: 'CSha256' : illegal use of this\n type as an expression\n c:\\users\\xavier.lapointe\\appdata\\local\\temp\\e...
[ 2 ]
[]
[]
[ "c", "compiler_construction", "lzma", "python", "visual_c++" ]
stackoverflow_0004764972_c_compiler_construction_lzma_python_visual_c++.txt
Q: Problem with web.py + mod_wsgi file upload I'm working on a web.py app for uploading files and im having real problems with my deployment. Basically I want to give the user a 'percentage uploaded' but this seems to be messing up severely when deployed on mod_wsgi. The main upload works like this: out = open(path, ...
Problem with web.py + mod_wsgi file upload
I'm working on a web.py app for uploading files and im having real problems with my deployment. Basically I want to give the user a 'percentage uploaded' but this seems to be messing up severely when deployed on mod_wsgi. The main upload works like this: out = open(path, 'wb', 1000) while (True): packet =...
[ "You can't just use a global dictionary for this. It is in fact very likely that the webserver is using a separate thread to serve the following requests, and there is no guarantee that the session dictionary is the same. Try using the session object which is part of web.py. It uses either a db or a file to stor...
[ 2 ]
[]
[]
[ "io", "mod_wsgi", "python", "web.py" ]
stackoverflow_0004929233_io_mod_wsgi_python_web.py.txt
Q: Python lib to make nice command line scripts with options etc I remember coming reading about a python module/lib that helped make nice command line scripts that takes in options. My python script (1 file) does many things, and currently I comment out/uncomment the function I want run in my main section. I was hop...
Python lib to make nice command line scripts with options etc
I remember coming reading about a python module/lib that helped make nice command line scripts that takes in options. My python script (1 file) does many things, and currently I comment out/uncomment the function I want run in my main section. I was hoping someone knows the lib I'm talking about that would help me orga...
[ "there is an optparse module. in newer variants of python, argparse is preferred.\noptparse: http://docs.python.org/library/optparse.html\nargparse: http://docs.python.org/library/argparse.html\nuse optparse in <= 2.7, argparse in > 2.7\n", "Python’s optparse for human beings\n" ]
[ 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004929851_python.txt
Q: Assign a value to class variable is assiging it for all instances of that object I have a class with a dictionary. I create n number instances of the class. When I += values on a key in that dictionary it is reflected in every single object I have instantiated from that object. How do I make that dictionary unique...
Assign a value to class variable is assiging it for all instances of that object
I have a class with a dictionary. I create n number instances of the class. When I += values on a key in that dictionary it is reflected in every single object I have instantiated from that object. How do I make that dictionary unique to every instantiation of that class? Here is how I create the Object: for num in ran...
[ "You've created shipNamesandNumber as a class attribute since it's contained directly within the class. Each mutation, even via self, mutates the same dictionary. If you want to prevent this then you must create an instance attribute, usually in __init__():\nclass Fleet:\n def __init__(self):\n self.shipNamesan...
[ 4 ]
[]
[]
[ "dictionary", "global", "object", "python" ]
stackoverflow_0004929969_dictionary_global_object_python.txt
Q: Problems with gtk text itters I have an app that I'm writing in python using gtk and I want it to automatically close parenthesis' and place the cursor between them The problem is I'm randomly getting the following error and having the program crash: ./mbc.py:266: GtkWarning: Invalid text buffer iterator: eith...
Problems with gtk text itters
I have an app that I'm writing in python using gtk and I want it to automatically close parenthesis' and place the cursor between them The problem is I'm randomly getting the following error and having the program crash: ./mbc.py:266: GtkWarning: Invalid text buffer iterator: either the iterator is uninitialized, ...
[ "The insert_at_cursor call invalidates the iterator passed in to your function. When you refer back to that iterator on the last line, GTK+ shows a warning. This behaviour is explained in the GTK+ Text Widget Overview.\nFixing this is a matter of not re-using the iterator, for example:\nbuff.insert_at_cursor(')') ...
[ 2 ]
[]
[]
[ "gtk", "gtk_textbuffer", "pygtk", "python" ]
stackoverflow_0004928308_gtk_gtk_textbuffer_pygtk_python.txt
Q: Python Script to search for a file i was going through one of the python scripts that Searches for Files and lists their permissions. Im still a learner in python, and while studying this code, i encountered the following questions: In the lines below, what is the implication of the line "mode=stat.SIMODE(os.lstat...
Python Script to search for a file
i was going through one of the python scripts that Searches for Files and lists their permissions. Im still a learner in python, and while studying this code, i encountered the following questions: In the lines below, what is the implication of the line "mode=stat.SIMODE(os.lstat(file)[stat.ST_MODE])" ? what is the val...
[ "The interactive Python interpreter shell is a good place to play around with snippets of Python code in order to understand them. For instance, to get the mode thing in your script:\n>>> import os, stat\n>>> os.lstat(\"path/to/some/file\")\nposix.stat_result(st_mode=33188, st_ino=834121L, st_dev=2049L, ...\n>>> st...
[ 1 ]
[]
[]
[ "file", "permissions", "python", "search" ]
stackoverflow_0004930179_file_permissions_python_search.txt
Q: Overriding the default field type in Django models.py class Job(db.Model): title = db.StringProperty(verbose_name='Project Title:') description = db.StringProperty(multiline=True, verbose_name='Description:') created_at = db.DateTimeProperty(auto_now_add=True) updated_at = db.DateTimeProperty(auto_now=True) bu...
Overriding the default field type in Django
models.py class Job(db.Model): title = db.StringProperty(verbose_name='Project Title:') description = db.StringProperty(multiline=True, verbose_name='Description:') created_at = db.DateTimeProperty(auto_now_add=True) updated_at = db.DateTimeProperty(auto_now=True) budget = db.IntegerProperty() max_project_duration ...
[ "Here's how I would do it in Django 1.2:\nfrom django.forms import ModelForm\nfrom django.forms.widgets import Textarea, TextInput\n\nfrom my_project.models import Job\n\nclass JobForm(ModelForm):\n\n class Meta:\n model = Job\n widgets = {\n 'description': Textarea(attrs={'rows': '2', 'co...
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0004930327_django_django_forms_python.txt
Q: Keeping concurrency in web.py applications on mod_wsgi Sorry if this makes no sense. Please comment if clarification is needed. I'm writing a small file upload app in web.py which I am deploying using mod_wsgi + apache. I have been having a problem with my session management and would like clarification on how the...
Keeping concurrency in web.py applications on mod_wsgi
Sorry if this makes no sense. Please comment if clarification is needed. I'm writing a small file upload app in web.py which I am deploying using mod_wsgi + apache. I have been having a problem with my session management and would like clarification on how the threading works in web.py. Essentially I embed a code in a ...
[ "Apache/mod_wsgi can run in multiprocess configurations and possible your requests aren't even being serviced by the same process and never will if for that multiprocess configuration each process is single thread because while the upload is occuring no other requests can be handled by that same process. Read:\nhtt...
[ 1, 0 ]
[]
[]
[ "concurrency", "mod_wsgi", "python", "web.py" ]
stackoverflow_0004927727_concurrency_mod_wsgi_python_web.py.txt
Q: Better python datetime display? I'm using babel and pytz to get the time zones. However, for most of America, it maps to something not as helpful in a dropdown box: "America/New_York" displays "Eastern Time", "America/Nipigon" also displays "Eastern Time". Is there some way to do this conversion to add city info?...
Better python datetime display?
I'm using babel and pytz to get the time zones. However, for most of America, it maps to something not as helpful in a dropdown box: "America/New_York" displays "Eastern Time", "America/Nipigon" also displays "Eastern Time". Is there some way to do this conversion to add city info? other timezones seems okay, like "A...
[ "Works for me with Babel 0.9.5 and pytz 2010b.\npy.tz\n#!/usr/bin/env python\n\nimport pytz\nimport babel.dates\n\ntz = pytz.timezone('America/New_York')\nprint babel.dates.get_timezone_location(tz)\n\noutput\n$ python tz.py \nUnited States (New York) Time\n\nHow are you running it? What versions?\n\nIf you are st...
[ 2 ]
[]
[]
[ "python", "python_babel", "pytz", "timezone" ]
stackoverflow_0004930233_python_python_babel_pytz_timezone.txt
Q: Change Bluetooth name Python I'm using PyBluez on Ubuntu 10.10. I would like to know how is possible to change the bluetooth name of the local device in software. I couldn't find any command related.. A: Invoke org.bluez.Adapter.SetProperty(u'Name', u'New name here') in the /org/bluez/<pid>/<device> object path ...
Change Bluetooth name Python
I'm using PyBluez on Ubuntu 10.10. I would like to know how is possible to change the bluetooth name of the local device in software. I couldn't find any command related..
[ "Invoke org.bluez.Adapter.SetProperty(u'Name', u'New name here') in the /org/bluez/<pid>/<device> object path on the org.bluez D-Bus bus.\n" ]
[ 1 ]
[]
[]
[ "bluetooth", "python", "ubuntu_10.10" ]
stackoverflow_0004931244_bluetooth_python_ubuntu_10.10.txt
Q: How do I set a forms.CharField text programmatically? Basically I'm trying to create some sort of dynamic form and I'm trying to change the value of a CharField via a post request. Simply, I have the following field in my form: choice = forms.CharField(max_length=50) In the init of the form I have something like ...
How do I set a forms.CharField text programmatically?
Basically I'm trying to create some sort of dynamic form and I'm trying to change the value of a CharField via a post request. Simply, I have the following field in my form: choice = forms.CharField(max_length=50) In the init of the form I have something like this: for key, value in request.post.items(): if key ==...
[ "It depends on what you mean by the 'value' of the field.\nIf you're trying to change what is shown when the form is displayed initially, you need to pass an initial dictionary with a key corresponding to the field name:\nself.initial['choice'] = 'myvalue'\n\nIf you're trying to change what gets passed into validat...
[ 3, 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0004930013_django_django_forms_python.txt
Q: How to import python module with same filename that is already imported? I have a problem with python module import. I installed django (this can be any other module). I use this module: from django.template import Context # other imports # use Context I have a folder in my application named "utilities". In this ...
How to import python module with same filename that is already imported?
I have a problem with python module import. I installed django (this can be any other module). I use this module: from django.template import Context # other imports # use Context I have a folder in my application named "utilities". In this folder I created a file "django.py" - this file contains some functions to wor...
[ "You will have to enable absolute imports at the top of the file:\nfrom __future__ import absolute_import\n\nYou will then have to convert the imports in the module into absolute or relative imports as appropriate.\n", "Use namepaces, create a __init__.py in your utilities directory, so that it is package and the...
[ 11, 0 ]
[]
[]
[ "django", "import", "module", "python" ]
stackoverflow_0004931487_django_import_module_python.txt
Q: ZSH & Python: python as shell environment variable? I've been researching setting up ZSH. I've wiped my machine (Mac OS X), installed XCode (Python), ran chsh -s zsh, and installed oh-my-zsh. The masses seem to rave about Steve Losh's "Prose" theme and his tutorial he wrote in making it. I've been able to incorpor...
ZSH & Python: python as shell environment variable?
I've been researching setting up ZSH. I've wiped my machine (Mac OS X), installed XCode (Python), ran chsh -s zsh, and installed oh-my-zsh. The masses seem to rave about Steve Losh's "Prose" theme and his tutorial he wrote in making it. I've been able to incorporate everything relevant to me in it, except for the Batte...
[ "Because earlier in the file you're supposed to assign the location of the script to the environment variable (or omit the environment variable altogether and use the script location directly).\n" ]
[ 1 ]
[]
[]
[ "python", "zsh", "zshrc" ]
stackoverflow_0004931655_python_zsh_zshrc.txt
Q: Programmatically preventing exhaustion of allocated Google App Engine Quotas Am working on a gae app using python. The app involves some crowd-sourced data collection system and data used in the app is submitted by users all-over the country. Now, am using the default quotas (Free) but am faced with a problem of e...
Programmatically preventing exhaustion of allocated Google App Engine Quotas
Am working on a gae app using python. The app involves some crowd-sourced data collection system and data used in the app is submitted by users all-over the country. Now, am using the default quotas (Free) but am faced with a problem of ensuring at least 99% up-time for my app. The challenge is that Google blocks any f...
[ "One common solution of this problem is to delegate the tasks to a rate limited taskqueue. \nFor example:\nqueue:\n- name: mail-throttle\n rate: 2000/d\n bucket_size: 10\n- name: background-processing-throttle\n rate: 5/s\n\nIn this way you can control the usage of all the parts of your application forcing them...
[ 5 ]
[]
[]
[ "gae_quotas", "google_app_engine", "python" ]
stackoverflow_0004931348_gae_quotas_google_app_engine_python.txt
Q: Change string in python using a dictionary I currently have a dictionary of morse code letters, and i want to be able to change a user input string into corresponding morse code characters. Is there any easy way to accomplish this in python? A: morse = {"A": ".-", "B": "-...", "C": "-.-."} #etc. text = "ABC" out...
Change string in python using a dictionary
I currently have a dictionary of morse code letters, and i want to be able to change a user input string into corresponding morse code characters. Is there any easy way to accomplish this in python?
[ "morse = {\"A\": \".-\", \"B\": \"-...\", \"C\": \"-.-.\"} #etc.\ntext = \"ABC\"\noutput = \" \".join(morse[letter] for letter in text)\n\nYou might want to use letter.upper() if input can also be lowercased. And if you don't have all morse characters in your table, you might want to compensate for that, too (credi...
[ 6, 2, 0, 0 ]
[]
[]
[ "dictionary", "python", "string" ]
stackoverflow_0004931939_dictionary_python_string.txt
Q: How to restrict amount of requests? Django How to restrict amount of requests for certain view and user? Suppose to be a build-in way... A: try to look at django-piston. it is a REST API framework for django. there is a throtling decorator. it should be feasible to steal it (get inspired) for your project. http...
How to restrict amount of requests? Django
How to restrict amount of requests for certain view and user? Suppose to be a build-in way...
[ "try to look at django-piston. it is a REST API framework for django.\nthere is a throtling decorator. it should be feasible to steal it (get inspired)\nfor your project.\nhttps://bitbucket.org/jespern/django-piston/wiki/Documentation#throttling\nhope it helps.\n", "I don't know if your need is related to authent...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004927096_django_python.txt
Q: Python and Unicode Blocks for regex Coming from the land of Perl, I can do something like the following to test the membership of a string in a particular unicode block: # test if string has any katakana script characters my $japanese = "カタカナ"; if ($japanese =~ /\p{InKatakana}/) { print "string has katakana" } ...
Python and Unicode Blocks for regex
Coming from the land of Perl, I can do something like the following to test the membership of a string in a particular unicode block: # test if string has any katakana script characters my $japanese = "カタカナ"; if ($japanese =~ /\p{InKatakana}/) { print "string has katakana" } I've read that Python does not support u...
[ ">>> re.search(u'[\\u30a0-\\u30ff]', u'カタカナ')\n<_sre.SRE_Match object at 0x7fa0dbb62578>\n\n", "As Ignacio said, the re expression is very useful. Don't forget the import first. This search only finds full-width katakana. \nimport re \nre.search(u'[\\u30a0-\\u30ff]', u'カタカナ') \n\nOr you might already have a ...
[ 7, 2 ]
[]
[]
[ "python", "regex", "unicode" ]
stackoverflow_0003145232_python_regex_unicode.txt
Q: Django - why is this hitting the database twice I have a property in my model: def _get_image(self): return Media.objects.get_for_object(self) image = property(_get_image) It calls the following function on my Media model: def get_for_object(self, obj): ctype = ContentType.objects.get_for_model(obj) ...
Django - why is this hitting the database twice
I have a property in my model: def _get_image(self): return Media.objects.get_for_object(self) image = property(_get_image) It calls the following function on my Media model: def get_for_object(self, obj): ctype = ContentType.objects.get_for_model(obj) return self.filter(items__content_type__pk=ct...
[ "\"or something\"?\nWhy should it store the results? You've explicitly written the _get_image function so that it queries the database each time. If you want it to store the results, you need to tell it to do it.\nProbably the simplest way would be to just get it once in the template:\n{% with entry.image as images...
[ 6, 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004932476_django_django_models_python.txt
Q: How to provide SVN username/password to easy_install? I'm trying to install Python EGG with easy_install, providing a URL of Subversion repository, where sources are hosted: $ easy_install svn://user:secret@svn.example.com/repo/trunk/my-egg Authentication realm: <svn://svn.example.com:3690> repo Password for 'me':...
How to provide SVN username/password to easy_install?
I'm trying to install Python EGG with easy_install, providing a URL of Subversion repository, where sources are hosted: $ easy_install svn://user:secret@svn.example.com/repo/trunk/my-egg Authentication realm: <svn://svn.example.com:3690> repo Password for 'me': The problem is that the repository is password protected....
[ "I reported a bug for Python team: http://bugs.python.org/setuptools/issue121\n" ]
[ 1 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0004921253_easy_install_python.txt
Q: python: Is there a way to get the code inside the with statement I was hoping this would work: class A: def __enter__(self, code): print code def __exit__(..): pass and then: with A(): f() g() would print: f() g() Specifically, my intention is to take this code and create a function...
python: Is there a way to get the code inside the with statement
I was hoping this would work: class A: def __enter__(self, code): print code def __exit__(..): pass and then: with A(): f() g() would print: f() g() Specifically, my intention is to take this code and create a function out of it. So I can do: with runInThreads() or with runManyTimesTillS...
[ "In a portable, language defined way, no. However, the withhacks module provides several examples of CPython specific hackery that lets you do all sorts of creative things.\nThat's more for playing around, though - functions and generators are still the only official ways of playing with reusable code blocks in Pyt...
[ 6, 3, 1, 0 ]
[]
[]
[ "python", "with_statement" ]
stackoverflow_0004930386_python_with_statement.txt
Q: how to lengthen the pause between the words with text-to-speech (pyTTS or SAPI5) Is it possible to extend the gap between spoken words when using text to speech with SAPI5 ? The problem is that esp. with some voices, the words are almost connected to each other, which makes the speech more difficult to understand....
how to lengthen the pause between the words with text-to-speech (pyTTS or SAPI5)
Is it possible to extend the gap between spoken words when using text to speech with SAPI5 ? The problem is that esp. with some voices, the words are almost connected to each other, which makes the speech more difficult to understand. I'm using python and pyTTS module (on windows, since it's using SAPI) I tried to hook...
[ "I don't have any great solutions here. But:\nPyTTS last release was in 2007, and there seems to be no documentation. The same people now maintains a cross-platform library, called pyttsx, which also supports SAPI. It has a words per minute setting, but no setting to increase the pause between the words. This is mo...
[ 2, 2, 0 ]
[]
[]
[ "accessibility", "python", "sapi", "text_to_speech" ]
stackoverflow_0004172541_accessibility_python_sapi_text_to_speech.txt
Q: Where can I find documentation for calling the various types in Python's types module? While working on some custom serialization, I've been using the types module a lot. One thing that really frustrates me is that the documentation says nothing at all on how to actually call the types. An example: types.CodeType ...
Where can I find documentation for calling the various types in Python's types module?
While working on some custom serialization, I've been using the types module a lot. One thing that really frustrates me is that the documentation says nothing at all on how to actually call the types. An example: types.CodeType - The type for code objects such as returned by compile(). Yeah sure, what about the 12 argu...
[ "It's generally not very useful to actually instantiate the types in the types module. Their purpose is to be used in isinstance() calls, and some of them can't be instantiated at all (for example types.GeneratorType).\nIf it's just curiosity, have a look at the documentation available in the interactive interpret...
[ 2 ]
[]
[]
[ "documentation", "python" ]
stackoverflow_0004933325_documentation_python.txt
Q: How can I introspect properties and model fields in Django? I am trying to get a list of all existing model fields and properties for a given object. Is there a clean way to instrospect an object so that I can get a dict of fields and properties. class MyModel(Model) url = models.TextField() def _get_loca...
How can I introspect properties and model fields in Django?
I am trying to get a list of all existing model fields and properties for a given object. Is there a clean way to instrospect an object so that I can get a dict of fields and properties. class MyModel(Model) url = models.TextField() def _get_location(self): return "%s/jobs/%d"%(url, self.id) locat...
[ "If you strictly want just the model fields and properties (those declared using property) then:\ndef get_fields_and_properties(model, instance):\n field_names = [f.name for f in model._meta.fields]\n property_names = [name for name in dir(model) if isinstance(getattr(model, name), property)]\n return dict...
[ 16, 1, 0, 0 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0004930414_django_models_python.txt
Q: Working with databases in Python without an ORM What is the standard/recommended way to work with a database (MySQL, mostly) in Python? I don't want an ORM, and the lighter the better. I don't mind writing my own SELECTs but I'd like something that maps a dictionary, for example, to do INSERTs and UPDATEs. I'm mos...
Working with databases in Python without an ORM
What is the standard/recommended way to work with a database (MySQL, mostly) in Python? I don't want an ORM, and the lighter the better. I don't mind writing my own SELECTs but I'd like something that maps a dictionary, for example, to do INSERTs and UPDATEs. I'm mostly a PHP programmer and I'm used to do something lik...
[ "To use a dict for inserts, you are looking for a DB driver that supports the \"named\" (placeholder) paramstyle (in the link, search for \"paramstyle\"):\nFrom the sqlite3 docs:\nimport sqlite3\ncon = sqlite3.connect(\"mydb\") \ncur = con.cursor()\n\nwho = \"Yeltsin\"\nage = 72\n\ncur.execute(\"select name_last...
[ 5, 0 ]
[]
[]
[ "database", "python" ]
stackoverflow_0004933355_database_python.txt
Q: whats the easiest way of converting a character into its ascii equivalent in python? Possible Duplicate: ASCII value of a character in python The method I have applied is mapping the characters in an array . Is there a library for it ? A: ord() — or are you asking for something entirely different? Given a str...
whats the easiest way of converting a character into its ascii equivalent in python?
Possible Duplicate: ASCII value of a character in python The method I have applied is mapping the characters in an array . Is there a library for it ?
[ "ord() — or are you asking for something entirely different?\n\nGiven a string of length one, return\n an integer representing the Unicode\n code point of the character when the\n argument is a unicode object, or the\n value of the byte when the argument is\n an 8-bit string. … This is the\n inverse of chr() ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004933634_python.txt
Q: Loading a pickled list just once - Django\Python I have a pickle file that contains a list of compiled regexes and other data. It takes about 1-1.5 seconds to load. What could a good way of using this list into my views, but have pickle work on the file just once? Edit: would importing into settings.py be consider...
Loading a pickled list just once - Django\Python
I have a pickle file that contains a list of compiled regexes and other data. It takes about 1-1.5 seconds to load. What could a good way of using this list into my views, but have pickle work on the file just once? Edit: would importing into settings.py be considered ok? Any ideas?
[ "How you can do it\nCreate a module called cache.py, then:\nimport cache\ndata = getattr(cache, 'data', '') or get_my_data()\n\nThis will reload the data only once by server process (which will depend on your setup, your web server and wherever you use WSGI or CGI). In the dev web server (./manage.py runserver), ev...
[ 3, 2, 1 ]
[]
[]
[ "django", "django_views", "pickle", "python" ]
stackoverflow_0004933190_django_django_views_pickle_python.txt
Q: Django: ForeignKey to_field and db_column doesn't seem to work I'm trying to get the field value for select widget using to_field or db_column arguments, but they doesn't seem to work. Here is the model: class Employer(models.Model): e_name = models.CharField( max_length ...
Django: ForeignKey to_field and db_column doesn't seem to work
I'm trying to get the field value for select widget using to_field or db_column arguments, but they doesn't seem to work. Here is the model: class Employer(models.Model): e_name = models.CharField( max_length = 40, verbose_name = 'Name') ...
[ "If all you need is all available Position's to choose from in a html select widget, you can get those like this:\np_names = (p.name for p in Position.objects.all())\n\nBut how do you generate the html? If you are using forms.Form you can use\nPOS_CHOICES = [(p.id, p.name) for p in Position.objects.all()]\nclass Em...
[ 1 ]
[]
[]
[ "django", "django_admin", "django_forms", "django_models", "python" ]
stackoverflow_0004933076_django_django_admin_django_forms_django_models_python.txt
Q: What's the format of the intermediate instruction in CPython? For example, 0 STORE_NAME 0 (sys) is part of the instruction for import sys. Is there any documentation for this instruction format? What's more, is this format a standard of Python? Or implementation specific? A: That is Python bytecode. It is specif...
What's the format of the intermediate instruction in CPython?
For example, 0 STORE_NAME 0 (sys) is part of the instruction for import sys. Is there any documentation for this instruction format? What's more, is this format a standard of Python? Or implementation specific?
[ "That is Python bytecode. It is specific to CPython, and even to specific versions.\n" ]
[ 5 ]
[]
[]
[ "cpython", "python" ]
stackoverflow_0004934019_cpython_python.txt
Q: send and recieve http request with python, need to send session cookies aswell I am testing my login function at my server (auto ip ban after x failed attempts). I found a simple python script that send http request like this: import urllib, urllib2, re, os, sys, cookielib def main(): host = 'http://192.168....
send and recieve http request with python, need to send session cookies aswell
I am testing my login function at my server (auto ip ban after x failed attempts). I found a simple python script that send http request like this: import urllib, urllib2, re, os, sys, cookielib def main(): host = 'http://192.168.1.133/intro.php' user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1...
[ "Replace\nheaders = {'User-Agent': user_agent}\n\nwith\nheaders = {\n 'User-Agent': user_agent,\n 'Cookie': '__utma=48024167.372656243.1297092510.1297169678.1297174274.6...'\n}\n\n" ]
[ 0 ]
[]
[]
[ "cookies", "http", "http_headers", "post", "python" ]
stackoverflow_0004934197_cookies_http_http_headers_post_python.txt
Q: wx.ScrolledWindow not repainting when scrolled I have a little app that I am working on with wxPython. I have a scrolled window using wx.ScrolledWindow. It seems to refuse to repaint the contents when it is scrolled. Example: Code that created above example: import wx class SaveEdFrame(wx.Frame): def __init_...
wx.ScrolledWindow not repainting when scrolled
I have a little app that I am working on with wxPython. I have a scrolled window using wx.ScrolledWindow. It seems to refuse to repaint the contents when it is scrolled. Example: Code that created above example: import wx class SaveEdFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = wx....
[ "I think the problem there is that your wx.StaticText widgets are children of the SaveEdFrame, not the ScrolledWindow. The ScrolledWindow is being redrawn over them as you scroll it. Try:\n headerLabel = wx.StaticText(self.scroll, -1, \"TestStr %s\" % key)\n self.mainSizer.Add(headerLabel)\n\n" ]
[ 2 ]
[]
[]
[ "python", "windows_7", "wxpython", "wxwidgets" ]
stackoverflow_0004931485_python_windows_7_wxpython_wxwidgets.txt
Q: How to stop multithreading returning combined data using python When using a multithreading, I get combined data The list is : A,B,C. If I MT this, the fdata [] contains data from A,B and C. How do I Get fdata too hold only one set of data. I tried del fdata didnt help. I need some kind of lock. class WorkerThre...
How to stop multithreading returning combined data using python
When using a multithreading, I get combined data The list is : A,B,C. If I MT this, the fdata [] contains data from A,B and C. How do I Get fdata too hold only one set of data. I tried del fdata didnt help. I need some kind of lock. class WorkerThread(threading.Thread): def __init__(self, queue): t...
[ "fdata should always contain the contents of the CSV file, after all you did for-loop over the rows, so it should always include A B and C... Maybe you should explain more of what you're trying to do.\nAs to your second question -\nYour thread object has an ident see thread.get_ident()\n\nReturn the ‘thread identif...
[ 1 ]
[]
[]
[ "csv", "multithreading", "python" ]
stackoverflow_0004929673_csv_multithreading_python.txt
Q: Is there a way to extract text information from a postscript file? (.ps .eps) I want to extract the text information contained in a postscript image file (the captions to my axis labels). These images were generated with pgplot. I have tried ps2ascii and ps2txt on Ubuntu but they didn't produce any useful results....
Is there a way to extract text information from a postscript file? (.ps .eps)
I want to extract the text information contained in a postscript image file (the captions to my axis labels). These images were generated with pgplot. I have tried ps2ascii and ps2txt on Ubuntu but they didn't produce any useful results. Does anyone know of another method? Thanks
[ "It's likely that pgplot drew the fonts in the text directly with lines rather than using text. Especially since pgplot is designed to output to a huge range of devices including plotters where you would have to do this.\nEdit:\nIf you have enough plots to be worth\n the effort than it's a very simple\n imag...
[ 6 ]
[]
[]
[ "image", "postscript", "python", "text" ]
stackoverflow_0004934669_image_postscript_python_text.txt
Q: Python and ReportLab: add a string at the end of every page I'm building a pdf document with reportlab, using the Paragraph class: doc = SimpleDocTemplate(response, leftMargin=lateral_margin, rightMargin=lateral_margin, topMargin=top_bottom_margin, bottomMargin=top_bottom_margin) Document = [] Document.append(...
Python and ReportLab: add a string at the end of every page
I'm building a pdf document with reportlab, using the Paragraph class: doc = SimpleDocTemplate(response, leftMargin=lateral_margin, rightMargin=lateral_margin, topMargin=top_bottom_margin, bottomMargin=top_bottom_margin) Document = [] Document.append(Paragraph("bla bla bla bla", my_style)) doc.build(Document) No...
[ "Your build call can include onFirstPage and onLaterPages arguments, which are functions invoked when the page starts. You can draw on the canvas in those functions to create fixed-position elements on each page, like page headers and footers.\n" ]
[ 3 ]
[]
[]
[ "django", "python", "reportlab" ]
stackoverflow_0004934864_django_python_reportlab.txt
Q: How to install a python library manually I built quickfix engine (http://www.quickfixengine.org/) for one of my tasks and also built in python support for it. Unfortunately this is a multi user env and I dont have access to the python installation path. Thus the make install command tries to copy over the files an...
How to install a python library manually
I built quickfix engine (http://www.quickfixengine.org/) for one of my tasks and also built in python support for it. Unfortunately this is a multi user env and I dont have access to the python installation path. Thus the make install command tries to copy over the files and fails. I managed to comment out the two line...
[ "I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.\nIn this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicat...
[ 19, 3, 2 ]
[]
[]
[ "package", "python", "quickfix" ]
stackoverflow_0004933224_package_python_quickfix.txt
Q: How to deal with the sqlalchemy's DB table blocking policy? Can someone explain, how can I avoid application freezing when I, for example, have a list of entities and an ability to move to detail pages. So, I open the list, and one sqlalchemy session starts, then I open one detail page and another one goes, then ...
How to deal with the sqlalchemy's DB table blocking policy?
Can someone explain, how can I avoid application freezing when I, for example, have a list of entities and an ability to move to detail pages. So, I open the list, and one sqlalchemy session starts, then I open one detail page and another one goes, then another one, and application freeze, because one session blocks a...
[ "SQL Server's default isolation mode locks entire tables very aggressively. (The above example seems like perhaps you're emitting an UPDATE and then emitting SELECT in a different transaction while the previous transaction is pending, though session.merge() does not accept a list and the contents of the table aren...
[ 2 ]
[]
[]
[ "python", "sql_server", "sqlalchemy" ]
stackoverflow_0004931209_python_sql_server_sqlalchemy.txt
Q: Email title and link from rss-feed and email them I'm doing a bit of an experiment in Python. I'm making a script which checks a rss-feed for new items, and then sends the title and link of the items via email. I've got the script to work to a certain level: when it runs it will take the link+title of the newest i...
Email title and link from rss-feed and email them
I'm doing a bit of an experiment in Python. I'm making a script which checks a rss-feed for new items, and then sends the title and link of the items via email. I've got the script to work to a certain level: when it runs it will take the link+title of the newest item and email it, regardless of wether it emailed that ...
[ "For the simplest method see the python smtplib documentation example. (I won't repeat the code here.) It's all you need for basic email sending. \nFor nicer/more complicated email content also look into python's email module, of course.\n", "for the feed parsing part, you could consider following the advise give...
[ 0, 0 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0004934701_feedparser_python.txt
Q: using python 2.3 on ubuntu 10.04 i need to run some old python programs on a ubuntu 10.04 system. it seems, that there are no python 2.3 packages for ubuntu 10.04 available. so i got python 2.3 directly from python.org: http://www.python.org/download/releases/2.3/ but "make" python fails with a buffer overflow. ha...
using python 2.3 on ubuntu 10.04
i need to run some old python programs on a ubuntu 10.04 system. it seems, that there are no python 2.3 packages for ubuntu 10.04 available. so i got python 2.3 directly from python.org: http://www.python.org/download/releases/2.3/ but "make" python fails with a buffer overflow. has anyone suggestions how to get python...
[ "This appears to be an old bug in Python 2.3. From here: https://bugs.launchpad.net/ubuntu/+source/gcc-defaults/+bug/286334\nThe solution is to run configure with BASECFLAGS=-U_FORTIFY_SOURCE.\n./configure BASECFLAGS=-U_FORTIFY_SOURCE\n\nThen run make as you usually would.\n", "You could decompile your python co...
[ 3, 0 ]
[]
[]
[ "python", "ubuntu_10.04" ]
stackoverflow_0004934925_python_ubuntu_10.04.txt
Q: Detecting Type of Video Stream I have 2 video streams (1) VLC Generated Compressed MP4 UDP stream (2) DV Uncompressed UDP Stream Both are destined to a host. At this Unix receiving host, I would like to detect type of stream coming using Bash or Python Scripting (without tcpdump, I do not have root priv.) ANY idea...
Detecting Type of Video Stream
I have 2 video streams (1) VLC Generated Compressed MP4 UDP stream (2) DV Uncompressed UDP Stream Both are destined to a host. At this Unix receiving host, I would like to detect type of stream coming using Bash or Python Scripting (without tcpdump, I do not have root priv.) ANY idea guys how to implement ? Thank you....
[ "what about trying pyffmpeg out. you should be able to get the container info from that.\n" ]
[ 1 ]
[]
[]
[ "bash", "multimedia", "python", "streaming", "video_streaming" ]
stackoverflow_0004935387_bash_multimedia_python_streaming_video_streaming.txt
Q: Can 64-bit python create 32-bit Windows executables I have a new 64-bit Windows machine and use python for various things and so would prefer to install 64-bit python. However, one of my python projects creates a Windows executable that is then run on a 32-bit Windows machine (created using py2exe). How do I use 6...
Can 64-bit python create 32-bit Windows executables
I have a new 64-bit Windows machine and use python for various things and so would prefer to install 64-bit python. However, one of my python projects creates a Windows executable that is then run on a 32-bit Windows machine (created using py2exe). How do I use 64-bit python and py2exe to create a 32-bit executable? If...
[ "You can install both 32 and 64 bit Python on the machine and use the py2exe associated with each installation.\nHowever, unless you actually need the extra address space of 64 bit, then you may as well just stick to 32 bit Python for compatibility. You may well find that 3rd party modules will have better availabi...
[ 23 ]
[]
[]
[ "32bit_64bit", "py2exe", "python" ]
stackoverflow_0004935502_32bit_64bit_py2exe_python.txt
Q: Setup a cron task that parses a friend's checkins on Facebook I want to setup a cron job that logs in to my facebook account, takes the latest checkin information for my friends, and then exports a JSON file with that information, so that I (and others) could use it somewhere else. As I have no experience with ser...
Setup a cron task that parses a friend's checkins on Facebook
I want to setup a cron job that logs in to my facebook account, takes the latest checkin information for my friends, and then exports a JSON file with that information, so that I (and others) could use it somewhere else. As I have no experience with server-side scripting, do you think that this is possible? What would ...
[ "This is not an exact answer to my question, but a cleaner and more elaborate way to solve the same problem.\nFacebook supports \"Real-time updates\" on their Graph API: \n\nThe Graph API supports real-time\n updates to enable your application\n using Facebook to subscribe to changes\n in data from Facebook. You...
[ 0 ]
[]
[]
[ "crontab", "facebook", "facebook_graph_api", "php", "python" ]
stackoverflow_0004784189_crontab_facebook_facebook_graph_api_php_python.txt
Q: Python - Remove accents from all files in folder I'm trying to remove all accents from a all coding files in a folder.. I already have success in building the list of files, the problem is that when I try to use unicodedata to normalize I get the error: ** Traceback (most recent call last): File "/usr/lib/gedit-...
Python - Remove accents from all files in folder
I'm trying to remove all accents from a all coding files in a folder.. I already have success in building the list of files, the problem is that when I try to use unicodedata to normalize I get the error: ** Traceback (most recent call last): File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 336, in __ru...
[ "It looks like the file might be encoded with the cp1252 codec:\nIn [18]: print('\\xf3'.decode('cp1252'))\nó\n\nunicode(line) is failing because unicode is trying to decode line with the utf-8 codec instead, hence the error UnicodeDecodeError: 'utf8' codec can't decode....\nYou might try decoding line with cp1252 f...
[ 4, 1 ]
[]
[]
[ "filesystems", "python" ]
stackoverflow_0004935347_filesystems_python.txt
Q: See current frame without an error In Python, is there a way to see the current stack frame? That is, I want to see a list of files which were called to get to my current location. Essentially, I want to see try: 1/0 except: traceback.print_exc() without actually raising an error. A: You want a stack trace...
See current frame without an error
In Python, is there a way to see the current stack frame? That is, I want to see a list of files which were called to get to my current location. Essentially, I want to see try: 1/0 except: traceback.print_exc() without actually raising an error.
[ "You want a stack trace, not a stack frame (the stack frame is one area in the stack holding e.g. the local variables of the current function). The traceback module has various means to get a stack trace without raising an exception. To print a stack trace directly, use traceback.print_stack().\n", "You could use...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004935532_python.txt
Q: Django: gettext raises ValueError: 'plural forms expression could be dangerous' If a auto generated django.po file contains the following line in its header "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" "manage.py runserver" raises gettext.py", line 93, in c2py raise ValueError, 'plural forms expression ...
Django: gettext raises ValueError: 'plural forms expression could be dangerous'
If a auto generated django.po file contains the following line in its header "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" "manage.py runserver" raises gettext.py", line 93, in c2py raise ValueError, 'plural forms expression could be dangerous' ValueError: plural forms expression could be dangerous If i remo...
[ "It means that your translator forgot to fill it in properly.\n" ]
[ 1 ]
[]
[]
[ "django", "django_haystack", "gettext", "python" ]
stackoverflow_0004935704_django_django_haystack_gettext_python.txt
Q: Generating matplotlib graphs without a running X server Matplotlib seems to require the $DISPLAY environment variable which means a running X server.Some web hosting services do not allow a running X server session.Is there a way to generate graphs using matplotlib without a running X server? [username@hostname ~]...
Generating matplotlib graphs without a running X server
Matplotlib seems to require the $DISPLAY environment variable which means a running X server.Some web hosting services do not allow a running X server session.Is there a way to generate graphs using matplotlib without a running X server? [username@hostname ~]$ python2.6 Python 2.6.5 (r265:79063, Nov 23 2010, 02:02:03) ...
[ "@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg') before importing matplotlib.pyplot, and then continue as normal. \nE.g.\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(...
[ 356, 22 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0004931376_matplotlib_python.txt
Q: Parsing python with PLY I'm trying to write a python parser, and in my opiniion it could parse an "if statement" but it doesn't. It shows me a "syntax error" message. Can someone tell me what I'm doing wrong? Thanks in advance. The code is here: https://github.com/narke/py2neko I modified the input string like t...
Parsing python with PLY
I'm trying to write a python parser, and in my opiniion it could parse an "if statement" but it doesn't. It shows me a "syntax error" message. Can someone tell me what I'm doing wrong? Thanks in advance. The code is here: https://github.com/narke/py2neko I modified the input string like this: s = '''if 5: print 1...
[ "From your code:\ns = \"if 5:\\n\"\ncheck_syntax(s)\n\nif 5:\\n is not valid syntax because it is not a complete if statement. You need to provide a suite (code to execute) if the expression is True. For example:\n>>> if 5:\n... \n File \"<stdin>\", line 2\n\n ^\nIndentationError: expected an indented block\n...
[ 1 ]
[]
[]
[ "parsing", "ply", "python" ]
stackoverflow_0004935847_parsing_ply_python.txt
Q: Backup Script in Python can some one please provide me with an explanation of the code especially the use of maxversions and statements following the line "for f in files:". I want to understand what xrange(MAXVERSION) means? What is the use of indexing i.e for index in xrange(MAXVERSIONS): backup = '%s.%2.2d' % ...
Backup Script in Python
can some one please provide me with an explanation of the code especially the use of maxversions and statements following the line "for f in files:". I want to understand what xrange(MAXVERSION) means? What is the use of indexing i.e for index in xrange(MAXVERSIONS): backup = '%s.%2.2d' % (destpath, index) The code:...
[ "The script tries to recursively copy the contents of a directory (defaults to current directory) to a backup directory (defaults to .bak in the current directory);\nfor each filename.ext, it creates a duplicate named filename.ext.00; if filename.ext.00 already exists, it creates filename.ext.01 instead, and so on....
[ 3 ]
[]
[]
[ "python", "unix" ]
stackoverflow_0004906509_python_unix.txt
Q: What is the difference between ' ' and " " in python? Possible Duplicates: Is there any difference between “string” and 'string' in Python? Single quotes vs. double quotes in Python I have noted that I can use both single and double quotes to delimit strings in python, and that whichever one I don't use to delim...
What is the difference between ' ' and " " in python?
Possible Duplicates: Is there any difference between “string” and 'string' in Python? Single quotes vs. double quotes in Python I have noted that I can use both single and double quotes to delimit strings in python, and that whichever one I don't use to delimit the string, I can use freely inside it without any need...
[ "There is no difference at runtime. The only difference between the two types of quotes is the one you have already pointed out:\n\nSingle quotes need to be escaped inside single quoted string literals but not inside double-quoted string literals.\nDouble quotes need to be escaped inside double quoted string litera...
[ 20 ]
[]
[]
[ "python", "string" ]
stackoverflow_0004936224_python_string.txt
Q: MySQL from_unixtime() and Python time.ctime() not agreeing I have some data that uses unixtime. I'm using Python and MySQL. I have noticed that the MySQL GUI Tools function from_unixtime() doesn't equal Python's output of time.ctime() or even the MySQL cmd line interface... MySQL Command Line: #This returns the ...
MySQL from_unixtime() and Python time.ctime() not agreeing
I have some data that uses unixtime. I'm using Python and MySQL. I have noticed that the MySQL GUI Tools function from_unixtime() doesn't equal Python's output of time.ctime() or even the MySQL cmd line interface... MySQL Command Line: #This returns the correct time mysql> select from_unixtime(1295147016.45300); +--...
[ "The time zone is different in both the cases. Just fix the time-zone in MySQL GUI tools and you're good to go.\n" ]
[ 1 ]
[]
[]
[ "mysql", "python", "time", "unix_timestamp" ]
stackoverflow_0004936235_mysql_python_time_unix_timestamp.txt
Q: python: how to encrypt a file? Can anybody help(or point to some examples) about how to encrypt files with python? I have to use following parameters to encrypt file: block size=8 iv=qwertyui12345678 method=des3_cbc Also I have no idea about what iv means Please help. Thanks in advance. A: You will need to use ...
python: how to encrypt a file?
Can anybody help(or point to some examples) about how to encrypt files with python? I have to use following parameters to encrypt file: block size=8 iv=qwertyui12345678 method=des3_cbc Also I have no idea about what iv means Please help. Thanks in advance.
[ "You will need to use the Python Crypto Toolkit\nIV is the Initialisation Vector.\n", "Use pycrypto - note that implmenting crypto properly, even using a library for the hard parts, is tricky. If security matters get expert help.\n", "IV stands for Initialization Vector. Block cipher algorithms can be used in ...
[ 5, 3, 3 ]
[]
[]
[ "des", "encryption", "python" ]
stackoverflow_0004936543_des_encryption_python.txt
Q: How can you tell if a Python program has anything to read from stdin? I'm writing a chat program in Python that needs to connect to a server before user input from sys.stdin is accepted. If a connection cannot be made then the program exits. Running this from the shell, if a connection fails and input was sent whi...
How can you tell if a Python program has anything to read from stdin?
I'm writing a chat program in Python that needs to connect to a server before user input from sys.stdin is accepted. If a connection cannot be made then the program exits. Running this from the shell, if a connection fails and input was sent while attempting to connect, the input is echoed to the shell after the progra...
[ "I think that you need to check this SO question about non-blocking I/O on stdin\nNon-blocking read on a subprocess.PIPE in python\n", "There are two general solutions to this problem:\n\nWhen exiting because you couldn't connect to the server, read any remaining input from stdin and discard it. This solves your ...
[ 3, 3 ]
[]
[]
[ "io", "python" ]
stackoverflow_0004936594_io_python.txt
Q: Natural Binary Code - finding first n numbers Outputting/finding first n numbers of Natural Binary Code: import math def binary_print(n): m = int(math.ceil(math.log(n, 2))) for i in range(n): b = str(bin(i)[2:]) print((m - len(b)) * '0' + b) My question is: Do you know any other way to d...
Natural Binary Code - finding first n numbers
Outputting/finding first n numbers of Natural Binary Code: import math def binary_print(n): m = int(math.ceil(math.log(n, 2))) for i in range(n): b = str(bin(i)[2:]) print((m - len(b)) * '0' + b) My question is: Do you know any other way to do this in Python? Maybe faster? Or shorter (less co...
[ "Well this is shorter, not sure about faster:\ndef binary_print(n):\n print '\\n'.join('{:0{}b}'.format(x, (n-1).bit_length()) for x in range(n))\n\nExample usage:\n>>> binary_print(6)\n000\n001\n010\n011\n100\n101\n\n", "def binary_values(n):\n fmt = \"{0:0\"+str((n-1).bit_length())+\"b}\"\n for i in ra...
[ 5, 4 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0004936658_binary_python.txt
Q: sorl-thumbnail unit tests fail by 1 pixel (!) I'm using sorl-thumbnail in a Django 1.2 (currently 1.2 RC) project and getting a surprising failure of four of sorl's built-in unit tests. Essentially, the resized images are all 1px shorter than the unit tests expect them to be. See below for details I'm developing o...
sorl-thumbnail unit tests fail by 1 pixel (!)
I'm using sorl-thumbnail in a Django 1.2 (currently 1.2 RC) project and getting a surprising failure of four of sorl's built-in unit tests. Essentially, the resized images are all 1px shorter than the unit tests expect them to be. See below for details I'm developing on OSX 10.5.8 (not Snow Leopard) with Python 2.5.1 (...
[ "Here's the hack that I used to work around this. I put the following in tests.py in my own app:\ndef monkeypatch_sorl_tests():\n from sorl.thumbnail.tests.base import BaseTest\n from sorl.thumbnail.tests.fields import FieldTest, ThumbnailFieldTest, ImageWithThumbnailsFieldTest\n def always_pass(*args, **k...
[ 3 ]
[]
[]
[ "django", "python", "python_imaging_library", "sorl_thumbnail" ]
stackoverflow_0002827608_django_python_python_imaging_library_sorl_thumbnail.txt
Q: Idiomatic way of specifying default arguments whose presence/non-presence matter I often see python code that takes default arguments and has special behaviour when they are not specified. If I for example want behavior like this: def getwrap(dict, key, default = ??): if ???: # default is specified ret...
Idiomatic way of specifying default arguments whose presence/non-presence matter
I often see python code that takes default arguments and has special behaviour when they are not specified. If I for example want behavior like this: def getwrap(dict, key, default = ??): if ???: # default is specified return dict.get(key, default) else: return dict[key] If I were to roll my ow...
[ "I usually prefer\ndef getwrap(my_dict, my_key, default=None):\n if default is None:\n return my_dict[my_key]\n else:\n return my_dict.get(my_key, default)\n\nbut of course this assumes that None is never a valid default value.\n", "You could do it based on *args and/or **kwargs.\nHere's an al...
[ 6, 1 ]
[]
[]
[ "default_arguments", "python" ]
stackoverflow_0004936550_default_arguments_python.txt
Q: Grouping a series in Python Title edit: capitalization fixed and 'for python' added. Is there a better or more standard way to do what I'm describing? I want input like this: [1, 1, 1, 0, 2, 2, 0, 2, 2, 0, 0, 3, 3, 0, 1, 1, 1, 1, 1, 2, 2, 2] to be transformed to this: [0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3, 0, 0, ...
Grouping a series in Python
Title edit: capitalization fixed and 'for python' added. Is there a better or more standard way to do what I'm describing? I want input like this: [1, 1, 1, 0, 2, 2, 0, 2, 2, 0, 0, 3, 3, 0, 1, 1, 1, 1, 1, 2, 2, 2] to be transformed to this: [0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0] or, even bet...
[ "To get the labels you can use itertools groupby:\n>>> import itertools\n>>> numbers = [1, 1, 1, 0, 2, 2, 0, 2, 2, 0, 0, 3, 3, 0, 1, 1, 1, 1, 1, 2, 2, 2]\n>>> list(k for k, g in itertools.groupby(numbers))\n[1, 0, 2, 0, 2, 0, 3, 0, 1, 2]\n\nAnd to remove the zeros you can use a comprehension:\n>>> list(k for k, g i...
[ 8 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0004937163_matplotlib_python.txt
Q: Python / Django - Edit Model Forms After Creation I have a strong background in PHP / ZEND and I'm now using learning Python / Django. In Zend you can take a form element object and edit it pretty much at any time. This is great because you can take a form object and make small alterations to it on demand withou...
Python / Django - Edit Model Forms After Creation
I have a strong background in PHP / ZEND and I'm now using learning Python / Django. In Zend you can take a form element object and edit it pretty much at any time. This is great because you can take a form object and make small alterations to it on demand without created a completely new form object. I am trying to...
[ "You answered your own question: that's (almost) exactly how you do it!\n# tested on 1.2.3 \nform = VoteForm(initial={})\nform.fields['field_name'].widget = forms.HiddenInput() # make sure you call widget()\n\nform.as_p() # shows new widget\n\n", "Another way is to override the form's init() method, something li...
[ 4, 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0004926481_django_django_forms_python.txt
Q: issue regarding tokenize.py In python2.x tokenize() function has two arguments namely, 'readline' and 'tokeneater'. Second argument takes care of the output mechanism for tokenize() and is called once for each token. Now we know that in python3.x second argument 'tokeneater' is not there. How is output mechanism i...
issue regarding tokenize.py
In python2.x tokenize() function has two arguments namely, 'readline' and 'tokeneater'. Second argument takes care of the output mechanism for tokenize() and is called once for each token. Now we know that in python3.x second argument 'tokeneater' is not there. How is output mechanism in python3.x being taken care of ?...
[ "In Python 3.x, tokenize generates a stream of 5-tuples as its output, just as Python 2.x's generate_tokens does.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004937445_python.txt
Q: Queryset from a ManyToMany relation I'm creating a little calendar app in Django. I have two model classes; Calendar and Event. An event can be in multiple calendars. Because of this I'm using a ManyToMany relation. This is my model from django.db import models class Calendar(models.Model): title = models.Cha...
Queryset from a ManyToMany relation
I'm creating a little calendar app in Django. I have two model classes; Calendar and Event. An event can be in multiple calendars. Because of this I'm using a ManyToMany relation. This is my model from django.db import models class Calendar(models.Model): title = models.CharField(max_length = 255) def __unico...
[ "Django automatically provides a way to access the related objects in a ManyToMany relationship:\nevents = my_calendar.events.all()\n\nSee the docs on many-to-many relationships.\nIf you don't already have a calendar instance, but just an ID or name, you can do the whole thing in one query:\nevents = Event.objects....
[ 1, 1, 0 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0004937226_django_django_models_many_to_many_python.txt
Q: TDD django models If you're trying to do Test Driven Development, is it sane to write tests that check the column type of your models as you write your models? Like before you write your model, you write a test and say I want an ID field that is an integer field. A: I think it's a bit overkill to test the underl...
TDD django models
If you're trying to do Test Driven Development, is it sane to write tests that check the column type of your models as you write your models? Like before you write your model, you write a test and say I want an ID field that is an integer field.
[ "I think it's a bit overkill to test the underlying framework within your app testing, in general. Unless you have a suspicion that it isn't well-tested and/or it is something that may change a lot (say you live by developing against trunk), it should be a reasonable assumption that your framework will operate as ...
[ 7, 6, 3 ]
[]
[]
[ "django", "python", "tdd" ]
stackoverflow_0004937762_django_python_tdd.txt
Q: 3D Polygons in Python As far as I am aware there is no inbuilt polygon functionality for Python. I want to create a 3D map and figured that polygons would be the best way to go about it. Not wanting to reinvent the wheel I did some googling and found that there's a lot of Python stuff out there, but I couldn't fin...
3D Polygons in Python
As far as I am aware there is no inbuilt polygon functionality for Python. I want to create a 3D map and figured that polygons would be the best way to go about it. Not wanting to reinvent the wheel I did some googling and found that there's a lot of Python stuff out there, but I couldn't find what I wanted. Thus befor...
[ "One of the most complete geography/mapping systems available for Python that I know about is GeoDjango. This works on top of the Django, an MVC framework. With it comes a large collection of polygon, line and distance calculation tools that can even take into account the curvature of the earth's surface if need ...
[ 4, 2, 0 ]
[]
[]
[ "3d", "polygon", "python" ]
stackoverflow_0000432080_3d_polygon_python.txt
Q: please help me in solving the below error below is the error details bias = ord(password[position % password_length]) Indentation error = expected an indented block 1. '''crypt module 2. 3. Contains a simple function, "crypt", that will both encrypt and decrypt a string 4. of text by...
please help me in solving the below error
below is the error details bias = ord(password[position % password_length]) Indentation error = expected an indented block 1. '''crypt module 2. 3. Contains a simple function, "crypt", that will both encrypt and decrypt a string 4. of text by XORing it with a password or phrase.''' 5. ...
[ "Remove those line numbers, and fix those indentations. Your code is unusable when it's unindented, but here's a working version with formatting:\n'''crypt module\n\nContains a simple function, \"crypt\", that will both encrypt and decrypt a string\n\nof text by XORing it with a password or phrase.'''\n\nimport Str...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004937244_python.txt
Q: How to compare two lists and get all indices of matches This is probably a simple question that I am just missing but I have two lists containing strings and I want to "bounce" one, element by element, against the other returning the index of the matches. I expect there to be multiple matches and want all of the i...
How to compare two lists and get all indices of matches
This is probably a simple question that I am just missing but I have two lists containing strings and I want to "bounce" one, element by element, against the other returning the index of the matches. I expect there to be multiple matches and want all of the indices. I know that list.index() gets the first and you can ...
[ "Personally I'd start with:\nmatches = [item for item in list1 if item in list2]\n", "This does not answer the question. See my comment below.\nAs a start:\nlist(i[0] == i[1] for i in zip(list1, list2))\n\n", "I'm not sure how you want these packaged up, but this does the work:\ndef matches(lst, value):\n re...
[ 10, 3, 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004937634_python.txt
Q: build bot master config error I installed buildbot and this is my master.cfg: c = BuildmasterConfig = {} from buildbot.buildslave import BuildSlave c['slaves'] = [BuildSlave("windows", "windows32")] c['slavePortnum'] = 9989 from buildbot.scheduler import Scheduler c['schedulers'] = [] c['schedulers'].append(Sch...
build bot master config error
I installed buildbot and this is my master.cfg: c = BuildmasterConfig = {} from buildbot.buildslave import BuildSlave c['slaves'] = [BuildSlave("windows", "windows32")] c['slavePortnum'] = 9989 from buildbot.scheduler import Scheduler c['schedulers'] = [] c['schedulers'].append(Scheduler( name="start_schedul...
[ "Looks like you don't have twisted.mail installed.\n", "You forgot to add the mail subclass from the status class to buildbot\nfrom buildbot.status import mail\n\nAdd this and it should work; btw your config file is missing a lot of stuff; usually if you keep the default one that comes with buildbot and modify it...
[ 2, 0 ]
[]
[]
[ "buildbot", "python", "twisted" ]
stackoverflow_0004906928_buildbot_python_twisted.txt
Q: Python: partition list of names into equally sized sublists I have a list of names, e.g. ['Agrajag', 'Colin', 'Deep Thought', ... , 'Zaphod Beeblebrox', 'Zarquon']. Now I want to partition this list into approximately equally sized sublists, so that the boundaries of the subgroups are at the first letter of the na...
Python: partition list of names into equally sized sublists
I have a list of names, e.g. ['Agrajag', 'Colin', 'Deep Thought', ... , 'Zaphod Beeblebrox', 'Zarquon']. Now I want to partition this list into approximately equally sized sublists, so that the boundaries of the subgroups are at the first letter of the names, e.g A-F, G-L, M-P, Q-Z, not A-Fe, Fi-Mo, Mu-Pra, Pre-Z. I co...
[ "Here's something that might work. I feel certain there's a simpler way though... probably involving itertools. Note that num_pages only roughly determines how many pages you'll actually get.\nEDIT: Whoops! There was a bug -- it was cutting off the last group! The below should be fixed, but note that the length of ...
[ 4, 1 ]
[]
[]
[ "group_by", "python" ]
stackoverflow_0004938224_group_by_python.txt
Q: Python lists/dictionaries vs. numpy arrays: performance vs. memory control I have to iteratively read data files and store the data into (numpy) arrays. I chose to store the data into a dictionary of "data fields": {'field1': array1,'field2': array2,...}. Case 1 (lists): Using lists (or collections.deque()) for "a...
Python lists/dictionaries vs. numpy arrays: performance vs. memory control
I have to iteratively read data files and store the data into (numpy) arrays. I chose to store the data into a dictionary of "data fields": {'field1': array1,'field2': array2,...}. Case 1 (lists): Using lists (or collections.deque()) for "appending" new data arrays, the code is efficient. But, when I concatenate the ar...
[ "Here's what is going on based on what I've observed. There isn't really a memory leak. Instead, Python's memory management code (possibly in connection with the memory management of whatever OS you are in) is deciding to keep the space used by the original dictionary (the one without the concatenated arrays) in th...
[ 3 ]
[]
[]
[ "memory_management", "performance", "python" ]
stackoverflow_0004935892_memory_management_performance_python.txt
Q: Import RRD data into Python Data Structures Does anyone have a good method for importing rrd data into python? The only libraries I have found so far are just wrappers for the command line or provide importing data into rrd and graphing it. I am aware of the export and dump options of rrd, but I am wondering if so...
Import RRD data into Python Data Structures
Does anyone have a good method for importing rrd data into python? The only libraries I have found so far are just wrappers for the command line or provide importing data into rrd and graphing it. I am aware of the export and dump options of rrd, but I am wondering if someone has already done the heavy lifting here.
[ "Here's an excerpt from a script that I wrote to get cacti rrd data out. It's not likely to be exactly what you want, but it might give you a good start. The intent of my script is to turn Cacti into a data warehouse, so I tend to pull out a lot of averages, max, or min data. I also have some flags for tossing u...
[ 1 ]
[]
[]
[ "python", "rrd" ]
stackoverflow_0004831237_python_rrd.txt
Q: How to schedule jobs in to client systems using python? i have 4 systems , where in one i am using as a master and the rest 3 as slaves. I want to execute a set of functions in client systems and fetch back the result, to achieve this i had previously used Parallel Python , unfortunately as soon as job_server is c...
How to schedule jobs in to client systems using python?
i have 4 systems , where in one i am using as a master and the rest 3 as slaves. I want to execute a set of functions in client systems and fetch back the result, to achieve this i had previously used Parallel Python , unfortunately as soon as job_server is created in it , it internally executes the given function usin...
[ "There was a talk at a Pycon in the past few years about a tool that managed remote processes via ssh, which sounded really cool and I meant to check out. I've forgotten what the tool was, but you might find it by looking at the Pycon talks for the past few years.\nThe Python Parallel Processing wiki page has a big...
[ 1, 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004935999_python.txt
Q: how can i use Mercurial to run unit tests for Python and also do code coverage analysis. I am using ubuntu 10.10 A: Using Mercurial hooks of course! As far as what tools you want to do for the test running and the code coverage, that's up to you, but mercurial hooks are the way to arbitrarily run things when t...
how can i use Mercurial to run unit tests for Python
and also do code coverage analysis. I am using ubuntu 10.10
[ "Using Mercurial hooks of course! As far as what tools you want to do for the test running and the code coverage, that's up to you, but mercurial hooks are the way to arbitrarily run things when there's been a commit.\n", "Here's a link to an example using Mercurial hooks that might help you.\n" ]
[ 1, 1 ]
[]
[]
[ "mercurial", "python", "python_unittest" ]
stackoverflow_0004938967_mercurial_python_python_unittest.txt
Q: Catching the url path following a python cgi script? It's better if I do an example to explain my question: Filename of cgi script: 'awesome' URL: http://omgpython.com/awesome 'awesome' script runs normally. I append a 'fake' path: '/omg/so/fake' URL: http://omgpython.com/awesome/omg/so/fake' 'awesome' script ru...
Catching the url path following a python cgi script?
It's better if I do an example to explain my question: Filename of cgi script: 'awesome' URL: http://omgpython.com/awesome 'awesome' script runs normally. I append a 'fake' path: '/omg/so/fake' URL: http://omgpython.com/awesome/omg/so/fake' 'awesome' script runs normally without any errors, but is it possible to catc...
[ "You want os.environ['PATH_INFO']. In the second example it will contain \"/omg/so/fake\".\n" ]
[ 2 ]
[]
[]
[ "cgi", "python", "url" ]
stackoverflow_0004939067_cgi_python_url.txt
Q: Type error trying to load fixtures with Content_type natural keys in Django I am using the --natural option when dumping one of my model into a fixtures, so that I won't run into Content_typ ID problem when deploying. Results is here: { "pk": 1, "model": "seo.opportunitymetadatamodel", "fields": {...
Type error trying to load fixtures with Content_type natural keys in Django
I am using the --natural option when dumping one of my model into a fixtures, so that I won't run into Content_typ ID problem when deploying. Results is here: { "pk": 1, "model": "seo.opportunitymetadatamodel", "fields": { "_content_type": [ "opportunity", "joboppo...
[ "I can only guess right now, but after looking at Django's source code and your error message I think the format of your fixture might be broken. The example you posted, is that the whole content of the file? If yes, then I think you need to put that model in a list, like this (pay attention to the outer brackets):...
[ 4 ]
[]
[]
[ "django", "fixtures", "python" ]
stackoverflow_0004935227_django_fixtures_python.txt
Q: Error inserting (unicode?) text into sqlite3 database I have an sqlite3 database that I have created which I'm filling with data from a db2 database. I get an error when I run the following: for row in db2_connection.execute(query): sqlite3_connection.execute("INSERT INTO MY_TABLE VALUES (?, ?, ?)", row) Her...
Error inserting (unicode?) text into sqlite3 database
I have an sqlite3 database that I have created which I'm filling with data from a db2 database. I get an error when I run the following: for row in db2_connection.execute(query): sqlite3_connection.execute("INSERT INTO MY_TABLE VALUES (?, ?, ?)", row) Here's the error: File "example.py", line 72, in load_micr_db ...
[ "Use string literals prefixed with a u.\nprint u'I am a Unicode string.'\n\n\"Unicode in Python, Completely Demystified\"\n" ]
[ 3 ]
[]
[]
[ "python", "sqlite", "unicode" ]
stackoverflow_0004939169_python_sqlite_unicode.txt
Q: How to tell thread stack usage from Python? I'd like to log the stack usage of a long-running thread (that is, one that is active during the whole life of the application), how can I do it? Something like "xxxxKB used" would be enough. (Python 2.6.6, FreeBSD 8.2-RC3) A: Since you specified FreeBSD, the resource ...
How to tell thread stack usage from Python?
I'd like to log the stack usage of a long-running thread (that is, one that is active during the whole life of the application), how can I do it? Something like "xxxxKB used" would be enough. (Python 2.6.6, FreeBSD 8.2-RC3)
[ "Since you specified FreeBSD, the resource module that comes with Python (but only works for Unix-y environments) might be helpful. Specifically, resource.getrusage(resource.RUSAGE_BOTH) provides will give you the resource usage of that process and all child processes.\nIt would look like you'd be interested in th...
[ 0 ]
[]
[]
[ "freebsd", "memory_management", "python" ]
stackoverflow_0004938633_freebsd_memory_management_python.txt
Q: python: Replacing special characters in a string I read the artist of a song from its MP3 tag, then create a folder based on that name. The problem I have is when the name contains a special character like 'AC\DC'. So I wrote this code to deal with that. def replace_all(text): print "replace_all" dictionary ...
python: Replacing special characters in a string
I read the artist of a song from its MP3 tag, then create a folder based on that name. The problem I have is when the name contains a special character like 'AC\DC'. So I wrote this code to deal with that. def replace_all(text): print "replace_all" dictionary = {'\\':"", '?':"", '/':"", '...':"", ':':"", chr(148)...
[ "I found this code, though I don't understand it.\ndef strip_accents(s):\n return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))\n\nIt enabled me to remove the accent marks from the path of proposed dir/filenames.\n", "I suggest using unicode for both input text and the ...
[ 3, 0 ]
[]
[]
[ "python", "special_characters" ]
stackoverflow_0004932497_python_special_characters.txt
Q: Store an instance of a connection - twisted.web How I store an instance of a connection in twisted.web? I have seen request.getSession() but I searched and there are very few examples of how it is stored and retrieved later. Thanks. Update: I want to store the ldap connection in a session for retrieve later def ...
Store an instance of a connection - twisted.web
How I store an instance of a connection in twisted.web? I have seen request.getSession() but I searched and there are very few examples of how it is stored and retrieved later. Thanks. Update: I want to store the ldap connection in a session for retrieve later def render_POST(self, request): command = request.pa...
[ "There are plenty of examples in the documentation of twisted. If you prefer a quick summary on how to use sessions.\nfrom twisted.web.resource import Resource\n\nclass ShowSession(Resource):\n def render_GET(self, request):\n return 'Your session id is: ' + request.getSession().uid\n\nclass ExpireSession...
[ 4 ]
[]
[]
[ "python", "session", "twisted", "twisted.web" ]
stackoverflow_0004936994_python_session_twisted_twisted.web.txt
Q: Django ModelForm with User data in Generic View I have a model with a foreign key to group (the other fields don't matter): class Project(models.Model) : group = models.ForeignKey(Group) ... I have a model form for this model: class AddProjectForm(forms.ModelForm): class Meta: model = Project fie...
Django ModelForm with User data in Generic View
I have a model with a foreign key to group (the other fields don't matter): class Project(models.Model) : group = models.ForeignKey(Group) ... I have a model form for this model: class AddProjectForm(forms.ModelForm): class Meta: model = Project fields = ["group","another"] In my urls, I am using thi...
[ "This is gonna look dirty, since the generic view instantiates the form_class with no parameters. If you really want to use the generic_view you're gonna have to generate the class dynamically :S\ndef FormForUser(user):\n class TmpClass(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(TmpCl...
[ 2, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0004938089_django_django_forms_python.txt
Q: Setting environment variables in the current environment with python (win32com) I'm trying to use python to set environment variables that will persist in Pythons parent environment, even after python exits back to the shell, but will not persist once the parent shell is closed. Opening a new shell should require...
Setting environment variables in the current environment with python (win32com)
I'm trying to use python to set environment variables that will persist in Pythons parent environment, even after python exits back to the shell, but will not persist once the parent shell is closed. Opening a new shell should require that the python script be run again in order to set the environment correctly. Based...
[ "The linked post tells how to change the default environment which will affect new processes. It manipulates registry values.\n\"A process can never directly change the environment variables of another process that is not a child of that process\", says MS documentation. So you'll never reach your stated goal from ...
[ 1, 0 ]
[]
[]
[ "python", "pywin32", "winapi", "windows" ]
stackoverflow_0004939417_python_pywin32_winapi_windows.txt
Q: How do I write a regex function in Python that checks if a user has only letters and numbers? I only want my usernames to have letters, numbers, and underscores. No other symbols, spaces, or anything else. How can I write a regex to check if it's only letters/numbers/underscores? A: Basically: import re regex = ...
How do I write a regex function in Python that checks if a user has only letters and numbers?
I only want my usernames to have letters, numbers, and underscores. No other symbols, spaces, or anything else. How can I write a regex to check if it's only letters/numbers/underscores?
[ "Basically:\nimport re\nregex = re.compile(\"^[a-zA-Z0-9_]+$\")\nif regex.match(some_string):\n do_something()\n\n", ">>> re.match('^\\w+$', '4tg25g_3yg')\n<_sre.SRE_Match object at 0x7f8093f198b8>\n\n", "\"^[a-zA-Z0-9_]+$\"\n\nor\n\"^[\\w_]+$\"\n\n", "Something like this should work\nimport re\nif re.matc...
[ 4, 3, 2, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0004939669_python_regex_string.txt
Q: Installing pyOpenSSL on Amazon Linux (EC2) I'm using the first default AMI for amazon Linux on ec2 and can't seem to install pyOpenSSL. I tried: sudo wget http://launchpad.net/pyopenssl/main/0.11/+download/pyOpenSSL-0.11.tar.gz && easy_install pyOpenSSL-0.11.tar.gz. Results were: error: can't create or remove file...
Installing pyOpenSSL on Amazon Linux (EC2)
I'm using the first default AMI for amazon Linux on ec2 and can't seem to install pyOpenSSL. I tried: sudo wget http://launchpad.net/pyopenssl/main/0.11/+download/pyOpenSSL-0.11.tar.gz && easy_install pyOpenSSL-0.11.tar.gz. Results were: error: can't create or remove files in install directory The following error occu...
[ "yum install pyOpenSSL. Should have tried this to begin with\n" ]
[ 10 ]
[]
[]
[ "amazon_ec2", "easy_install", "openssl", "pyopenssl", "python" ]
stackoverflow_0004891417_amazon_ec2_easy_install_openssl_pyopenssl_python.txt
Q: Recursive use of Scrapy to scrape webpages from a website I have recently started to work with Scrapy. I am trying to gather some info from a large list which is divided into several pages(about 50). I can easily extract what I want from the first page including the first page in the start_urls list. However I don...
Recursive use of Scrapy to scrape webpages from a website
I have recently started to work with Scrapy. I am trying to gather some info from a large list which is divided into several pages(about 50). I can easily extract what I want from the first page including the first page in the start_urls list. However I don't want to add all the links to these 50 pages to this list. I ...
[ "use urllib2 to download a page. Then use either re (regular expressions) or BeautifulSoup (an HTML parser) to find the link to the next page you need. Download that with urllib2. Rinse and repeat.\nScapy is great, but you dont need it to do what you're trying to do\n", "Why don't you want to add all the links to...
[ 1, 0 ]
[]
[]
[ "python", "scrapy", "web_scraping" ]
stackoverflow_0004876799_python_scrapy_web_scraping.txt
Q: Use argparse to run 1 of 2 functions in my script I currently have 2 functions in my .py script. #1 connects to the database and does some processing. #2 does some other processing on files Currently before I run the script, I have to manually comment/uncomment the function I want to run in my main if statement bl...
Use argparse to run 1 of 2 functions in my script
I currently have 2 functions in my .py script. #1 connects to the database and does some processing. #2 does some other processing on files Currently before I run the script, I have to manually comment/uncomment the function I want to run in my main if statement block. How can I use argparse, so it asks me which functi...
[ "It is possible to tell ArgumentParser objects about the function or object that has your desired behavior directly, by means of action='store_const' and const=<stuff> pairs in an add_argument() call, or with a set_defaults() call (the latter is most useful when you're using sub-parsers). If you do that, you can lo...
[ 4, 2, 0 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0004938738_argparse_python.txt
Q: BeautifulSoup always returns null when I use findAll I'm trying to use BeautifulSoup to parse some webpages, and it always returns null whenever I use findAll even though I can access stuff like soup.title and whatnot just fine. I'm trying to use this link to parse right now, and this is what I get when I try doin...
BeautifulSoup always returns null when I use findAll
I'm trying to use BeautifulSoup to parse some webpages, and it always returns null whenever I use findAll even though I can access stuff like soup.title and whatnot just fine. I'm trying to use this link to parse right now, and this is what I get when I try doing stuff with it: >>> site = urllib2.urlopen('http://www.ne...
[ "You are using an old version of BeautifulSoup that doesn't have the findAll method. I believe the equivalent method for old versions was called fetch. The findAll method was added in BeautifulSoup version 3.0.0, when the method names were changed to be more consistent. From the documentation:\n\nPrevious versions ...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0004940282_beautifulsoup_python.txt
Q: Python MySQLdb won't release table lock I have a program that reads a file and inserts data into a Database. I am writing a test harness for that program in python. The python harness connects to the database to get a few configuration parameters before generating the test data. It then wait 10 seconds to allow th...
Python MySQLdb won't release table lock
I have a program that reads a file and inserts data into a Database. I am writing a test harness for that program in python. The python harness connects to the database to get a few configuration parameters before generating the test data. It then wait 10 seconds to allow the program being tested to process the file an...
[ "You need to do connection.commit() before cursor.close().\nNote that MySQL does not actually support cursors-- the Python wrapper emulates them. This can cause your code to not work in unexpected ways, like in this example.\n" ]
[ 4 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004937950_mysql_python.txt