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: how should i refactor a piece of code that is present in many different functions, but has return statement in it The code snippet is coming from django view code, but it doesn't matter much. Let's say I have the following piece of code... def unsubscribe(request): #start of block user = request.user sid = r...
how should i refactor a piece of code that is present in many different functions, but has return statement in it
The code snippet is coming from django view code, but it doesn't matter much. Let's say I have the following piece of code... def unsubscribe(request): #start of block user = request.user sid = request.POST.get('subscription_id') try: sub = Subscription.objects.get(id=sid) except ObjectDoesNotExist: r...
[ "Factor out the duplicated chunk and have the difference be passed in, creating wrapper functions that pass in the difference:\ndef alter_subscription(request, make_active):\n # start of block\n # (...)\n # end of block\n sub.is_active = make_active\n sub.save()\n return ajax_response(True)\n\ndef unsubscribe...
[ 3, 1, 1 ]
[]
[]
[ "django", "python", "refactoring" ]
stackoverflow_0004447451_django_python_refactoring.txt
Q: Why file read is faster on reading again? SIZE = 1<<16 def justread(file): with open(file, 'rb') as f: while f.read(SIZE): pass The first time I run this function on a 700MB file it took 19 secs. When I repeated reading the same file again the time it took dropped to 0.5secs. I repeated th...
Why file read is faster on reading again?
SIZE = 1<<16 def justread(file): with open(file, 'rb') as f: while f.read(SIZE): pass The first time I run this function on a 700MB file it took 19 secs. When I repeated reading the same file again the time it took dropped to 0.5secs. I repeated this with many files and the results were similar...
[ "The operating system caches the file in memory upon the first read, and the second time it is read from memory instead of from hard disk. Of course memory is much faster.\n", "Your operating system is caching the file.\nWhat? This means, the first time you read the file, your program had to go look for the info...
[ 13, 4 ]
[]
[]
[ "file", "linux", "python" ]
stackoverflow_0004449473_file_linux_python.txt
Q: PySerial - cannot send STX Ok, so I am a complete noob to pySerial. I am trying to communicate to a piece of lab equipment, but am having trouble just sending the STX (Start of Text) command. So far, my basic code looks like: ser = serial.Serial(0, 19200, timeout=1,parity=serial.PARITY_ODD, rtscts=0) ser.write(0...
PySerial - cannot send STX
Ok, so I am a complete noob to pySerial. I am trying to communicate to a piece of lab equipment, but am having trouble just sending the STX (Start of Text) command. So far, my basic code looks like: ser = serial.Serial(0, 19200, timeout=1,parity=serial.PARITY_ODD, rtscts=0) ser.write(0x02) #ASCII STX is 0x2 in hex B...
[ "The write function in serial class accepts bytes or strings. You are passing an integer so the result is unknown, maybe is casting it to str so you are sending the char '2'.\nThe correct way to do it is :\nser = serial.Serial(0, 19200, timeout=1,parity=serial.PARITY_ODD, rtscts=0)\nser.write(chr(0x02)) #ASCII STX ...
[ 5, 0 ]
[]
[]
[ "pyserial", "python" ]
stackoverflow_0004449261_pyserial_python.txt
Q: PyGTK and threadings I'm kinda' new in Python, I'm learning it by myself and all I have to say is that it's a wonderful programming language. Even if I'm learning it in the straight way, for now I know (as a beginner) how to work with GTK, threads, urllib and other modules. But I need an answer from experienced P...
PyGTK and threadings
I'm kinda' new in Python, I'm learning it by myself and all I have to say is that it's a wonderful programming language. Even if I'm learning it in the straight way, for now I know (as a beginner) how to work with GTK, threads, urllib and other modules. But I need an answer from experienced PyGTK users. Take a look to...
[ "It sounds like you're already doing the obvious thing. In your callback function, simply check that the URL it came from matches the row that's selected at present, and if it doesn't, ignore it.\n", "Only the thread running the mainloop should update the GUI, so your download worker has to communicate back anywa...
[ 1, 0 ]
[]
[]
[ "callback", "multithreading", "pygtk", "python" ]
stackoverflow_0004432015_callback_multithreading_pygtk_python.txt
Q: Cython Install GCC error Trying to install Cython on a small VPS running Ubuntu Server. Did sudo apt-get install gcc and then python setup.py install In the Cython directory, but I get this peculiar error. running install running build running build_py running build_ext building 'Cython.Plex.Scanners' extension ...
Cython Install GCC error
Trying to install Cython on a small VPS running Ubuntu Server. Did sudo apt-get install gcc and then python setup.py install In the Cython directory, but I get this peculiar error. running install running build running build_py running build_ext building 'Cython.Plex.Scanners' extension gcc -pthread -fno-strict-alias...
[ "You need the developer version of Python - i.e. the Python header files (Python.h)\nsudo apt-get install python-dev\n\n", "You need the headers included in the development version of Python, i.e. python.h. It should be packaged in Ubuntu as python-dev.\n" ]
[ 37, 4 ]
[]
[]
[ "cython", "gcc", "installation", "python" ]
stackoverflow_0004450111_cython_gcc_installation_python.txt
Q: Is there a better way to build lists like this? I'm new to Python and I am loving it, but was wondering if there was a better way to do a couple list manipulations. This one is relatively sane, but it seems like I might have missed a built-in function. def zip_plus(source_list, additional_list): """ Like...
Is there a better way to build lists like this?
I'm new to Python and I am loving it, but was wondering if there was a better way to do a couple list manipulations. This one is relatively sane, but it seems like I might have missed a built-in function. def zip_plus(source_list, additional_list): """ Like zip but does plus operation where zip makes a tuple ...
[ "def zip_plus(first, second):\n return [x+y for (x,y) in zip(first, second)]\n\ndef zip_join2(first, second):\n return [(x[0], x[1]+y[1]) for (x,y) in zip(first, second)]\n\n", "First, to be more Pythonic, I'd avoid mutating inputs.\nSecond, you probably want something more like a dict instead of a list of ...
[ 4, 3, 1, 1 ]
[]
[]
[ "list", "python", "zip" ]
stackoverflow_0004446823_list_python_zip.txt
Q: Python, find out that a list does not have specific item Let's say there is a list a that contains both numbers and letters. Is there quick way to find out that the list doesn't contain some specific element. I plan to use it in conditions. A: Maybe 3 not in [1, 2, "a"] # True A: Note: If you can put the eleme...
Python, find out that a list does not have specific item
Let's say there is a list a that contains both numbers and letters. Is there quick way to find out that the list doesn't contain some specific element. I plan to use it in conditions.
[ "Maybe\n3 not in [1, 2, \"a\"]\n# True\n\n", "Note: If you can put the elements as keys of a dict then testing for membership is much quicker thanks to the hashing algorithm. Will only be an issue if your list is very long or your app does a lot of this kind of thing. Otherwise, \"X not in Y\" as Sven says.\n", ...
[ 23, 3, 2, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0004450752_if_statement_python.txt
Q: confusion in url and template in django My url is : 1. http://localhost:8000/docs/[slug] 2. http://localhost:8000/docs/[slug]/login 1. url calls before number 2. url I want to send the slug value to the function mapped by the url 2. In template what should i wrote for form action event. A: I agree, this is n...
confusion in url and template in django
My url is : 1. http://localhost:8000/docs/[slug] 2. http://localhost:8000/docs/[slug]/login 1. url calls before number 2. url I want to send the slug value to the function mapped by the url 2. In template what should i wrote for form action event.
[ "I agree, this is nearly incomprehensible, but I'm going to give it a go in terms of an answer.\nIn terms of calling sequence, there is none. A user might first visit url 2 or url 1. You have no way of guaranteeing which they will try to access first because they might directly input the url into their browser. The...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004303481_django_python.txt
Q: Python: Expanding List of Class Objects this is a quick one. Suppose I got a multidimensional list of class objects, named table, and I need to access the class attribute .name. I don't want to use nested loops, and of course to print this, I need to use format(). for i in range(3): print '{0} - {1} - {2}'.for...
Python: Expanding List of Class Objects
this is a quick one. Suppose I got a multidimensional list of class objects, named table, and I need to access the class attribute .name. I don't want to use nested loops, and of course to print this, I need to use format(). for i in range(3): print '{0} - {1} - {2}'.format(*table[i].name) Obviously that didn't wo...
[ "{arg_name.attribute_name} also works:\nfor row in table:\n print(' - '.join('{0.name}'.format(elt) for elt in row))\n\n", "\nI don't want to use nested loops\n\nThis is silly. To iterate over each element of a multidimensional array, you need to use nested loops. They may be implicit (map or a list comprehens...
[ 4, 1, 1 ]
[]
[]
[ "attributes", "class", "format", "python" ]
stackoverflow_0004450998_attributes_class_format_python.txt
Q: Strange 2 dimensional list behaviour in python Why does python do the following? >>> bla = [[]] * 5 >>> bla[3].append("blub") >>> print bla [['blub'], ['blub'], ['blub'], ['blub'], ['blub']] I would expect [[], [], [], ['blub'], []] A: This is a common point of confusion with Python, to do with the implicit pas...
Strange 2 dimensional list behaviour in python
Why does python do the following? >>> bla = [[]] * 5 >>> bla[3].append("blub") >>> print bla [['blub'], ['blub'], ['blub'], ['blub'], ['blub']] I would expect [[], [], [], ['blub'], []]
[ "This is a common point of confusion with Python, to do with the implicit pass-by-reference. When you type\nx = []\n\nthat binds the name x to point to an empty list in memory. When you do \nx = [[]] * 5\n\nthat binds the name x to point to a list of five things, each one of which is a reference to the same empty l...
[ 6, 4 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004451553_list_python.txt
Q: Python (newbie) Parse XML from API call I've look for some tutorials/other questions on stack/documentation and still can't figure it out. ugh!!! Making the API request and the parsing out (want to assign to variables but that's a bonus to this question), This is what I'm trying. Why can't I list the title and lin...
Python (newbie) Parse XML from API call
I've look for some tutorials/other questions on stack/documentation and still can't figure it out. ugh!!! Making the API request and the parsing out (want to assign to variables but that's a bonus to this question), This is what I'm trying. Why can't I list the title and link for the items? #!/usr/bin/python # Screen ...
[ "items = root.findall('items')\n\nshould be\nitems = root.findall('items/item')\n\n", "This works for me. Note I'm using urllib2 to get through a proxy:\nimport urllib2\nfrom xml.etree import ElementTree as ET\n\nshow = 'heroes'\nseason = '4'\nlanguage = 'en'\nlimit = '1'\n\nrequestURL = 'http://api.allsubs.org/i...
[ 4, 3, 2 ]
[]
[]
[ "api", "parsing", "python", "xml" ]
stackoverflow_0004451600_api_parsing_python_xml.txt
Q: Dump data from django Feincms I'm using feincms in a django project and I want to use manage.py dumpdata but I get nothing: python manage.py dumpdata feincms [] A: If you want to dump the page data you need to run dumpdata on the page app. The page models live there, not in feincms: python mana...
Dump data from django Feincms
I'm using feincms in a django project and I want to use manage.py dumpdata but I get nothing: python manage.py dumpdata feincms []
[ "If you want to dump the page data you need to run dumpdata on the page app. The page models live there, not in feincms:\n python manage.py dumpdata page\n\n", "I don't know FeinCMS, but looking at the GitHub repo it seems that the feincms application only contains abstract models. If you want to dump the data, y...
[ 8, 0, 0 ]
[]
[]
[ "django", "django_manage.py", "feincms", "python" ]
stackoverflow_0003380586_django_django_manage.py_feincms_python.txt
Q: Common Lisp -- List unpacking? (similar to Python) In Python, assuming the following function is defined: def function(a, b, c): ... do stuff with a, b, c ... I am able to use the function using Python's sequence unpacking: arguments = (1, 2, 3) function(*arguments) Does similar functionality exist in Common...
Common Lisp -- List unpacking? (similar to Python)
In Python, assuming the following function is defined: def function(a, b, c): ... do stuff with a, b, c ... I am able to use the function using Python's sequence unpacking: arguments = (1, 2, 3) function(*arguments) Does similar functionality exist in Common Lisp? So that if I have a function: (defun function (a ...
[ "\nUse the apply function:\n(apply #'function arguments)\n\nExample:\nCL-USER> (apply #'(lambda (a b c) (+ a b c)) '(1 2 3))\n6 \n\n", "apply\n" ]
[ 23, 11 ]
[]
[]
[ "common_lisp", "iterable_unpacking", "lisp", "list", "python" ]
stackoverflow_0004451854_common_lisp_iterable_unpacking_lisp_list_python.txt
Q: how can i improve my multi threading usage to decrease run time, python Machine Info cpu_num 8 CPUs cpu_speed 2826 MHz mem_total 8173980 KB swap_total 16777208 KB Benchmarking When I increase the number of threads the performances gains i get look like (the numbers are averaged over 10 runs) Number of Threa...
how can i improve my multi threading usage to decrease run time, python
Machine Info cpu_num 8 CPUs cpu_speed 2826 MHz mem_total 8173980 KB swap_total 16777208 KB Benchmarking When I increase the number of threads the performances gains i get look like (the numbers are averaged over 10 runs) Number of Threads Time 1 1.322187 2 0.789151 3 ...
[ "The reason behind a non linear increment of performance as the number of threads approach the number of cores might lie in this:\nsome_task()#do processor heavy task \n\nThe GIL is released around I/O heavy operations; if some_task() is CPU bound you are just occupying the GIL one thread at the time, thus sacrifi...
[ 4, 2 ]
[]
[]
[ "multithreading", "optimization", "python" ]
stackoverflow_0004451714_multithreading_optimization_python.txt
Q: What does Postgres do when BEGIN is run on a connection in autocommit mode? I'm trying to better understand the concept of 'autocommit' when working with a Postgres (psycopg) connection. Let's say I have a fresh connection, set its isolation level to ISOLATION_LEVEL_AUTOCOMMIT, then run this SQL directly, without...
What does Postgres do when BEGIN is run on a connection in autocommit mode?
I'm trying to better understand the concept of 'autocommit' when working with a Postgres (psycopg) connection. Let's say I have a fresh connection, set its isolation level to ISOLATION_LEVEL_AUTOCOMMIT, then run this SQL directly, without using the cursor begin/rollback methods (as an exercise; not saying I actually w...
[ "Autocommit mode means that each statement implicitly begins and ends the transaction.\nIn your case, if autocommit is off:\n\nThe client will implicitly start the transaction for the first statement\nThe BEGIN will issue a warning saying that the transaction is already started\nThe ROLLBACK will roll back all four...
[ 3, 1, 1 ]
[]
[]
[ "autocommit", "postgresql", "psycopg", "python", "sql" ]
stackoverflow_0002478518_autocommit_postgresql_psycopg_python_sql.txt
Q: Python tool for performance profiling Possible Duplicate: How can you profile a Python script? What visual tools do you know, something similar to JProfiler for Java, to analyze performance of Python applications? A: You can use cProfile or profile to profile your code. And if you need memory profiling, you c...
Python tool for performance profiling
Possible Duplicate: How can you profile a Python script? What visual tools do you know, something similar to JProfiler for Java, to analyze performance of Python applications?
[ "You can use cProfile or profile to profile your code.\nAnd if you need memory profiling, you can use guppy.\n" ]
[ 3 ]
[]
[]
[ "java", "jprofiler", "performance", "python" ]
stackoverflow_0004452732_java_jprofiler_performance_python.txt
Q: if __name__ == "__main__": equivalent in C# With python, I can use if __name__ == "__main__": for using the module both as a library and a program. Can I mimic this feature in C#? I see a class in C# can have a 'static void Main()', but I'm not sure if every class can have a Main() without a problem. ADDED /m:CL...
if __name__ == "__main__": equivalent in C#
With python, I can use if __name__ == "__main__": for using the module both as a library and a program. Can I mimic this feature in C#? I see a class in C# can have a 'static void Main()', but I'm not sure if every class can have a Main() without a problem. ADDED /m:CLASS_NAME is a way to specify the class to run the...
[ "You can compile a C# project as a program (executable) with a Main() method, and you'd still be able to use it as a library. No special syntax required.\nYou could add a Main() method to every class, but I doubt it's useful.\n.NET applications usually have different structures than Python ones; trying to fit the s...
[ 6, 6, 1 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0004452735_c#_python.txt
Q: Python. Define "attribute initial method" I have: class C: aaa=2 class B: def __init__ (self,name): self.name self.value How can i define class C so when i dynamically set attribute to instance it make that attribute instance of class B. And attribute name of class B have to have attri...
Python. Define "attribute initial method"
I have: class C: aaa=2 class B: def __init__ (self,name): self.name self.value How can i define class C so when i dynamically set attribute to instance it make that attribute instance of class B. And attribute name of class B have to have attribute name equal string of name of that new att...
[ "Just smartly override __setattr__. If you want to do it only for a specific attribute, then put in a special case for the attribute name that you want to look for:\n>>> class B:\n def __init__(self, name, value):\n self.name = name\n self.value = value\n\n\n>>> class C:\n def __setattr__(self,...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004452919_python.txt
Q: image file from MemoryStream (IronPython web service) I used to use CPython + PIL + bottle to serve image files on my web site. I used the code below to serve the image data from the PIL memory directly. # works well in CPython @route('/test') def index(): response.set_content_type('image/png') img = DrawS...
image file from MemoryStream (IronPython web service)
I used to use CPython + PIL + bottle to serve image files on my web site. I used the code below to serve the image data from the PIL memory directly. # works well in CPython @route('/test') def index(): response.set_content_type('image/png') img = DrawSomePILImage() output = StringIO.StringIO() img.save...
[ "It's this line:\ncontents = System.Text.ASCIIEncoding.ASCII.GetString(stream.ToArray()) \n\nIn doing this, you are sending a string which is the encoded form of the bytes in the image when in reality, you just want to send the bytes.\nI imagine if you change it to this:\ncontents = stream.ToArray()\n\nIt might wor...
[ 0, 0 ]
[]
[]
[ ".net", "image", "ironpython", "python" ]
stackoverflow_0004452374_.net_image_ironpython_python.txt
Q: Search for item in list with 2MILLION items - Python I have a list of strings made of 1.9-2 MILLION items. The following code: items = [...] item_in_list = items[-1] in items takes 0.1 seconds With sqlite3 it takes 0.7 seconds Now problem is I need to perform this check 1 million times and I would like to comple...
Search for item in list with 2MILLION items - Python
I have a list of strings made of 1.9-2 MILLION items. The following code: items = [...] item_in_list = items[-1] in items takes 0.1 seconds With sqlite3 it takes 0.7 seconds Now problem is I need to perform this check 1 million times and I would like to complete this within minutes rather than days. More precisely I'...
[ "Put both collections into frozensets.\nlittle performance test:\nimport random\nfrom timeit import Timer\n\ndef random_strings(size):\n alpha = 'abcdefghijklmnopqrstuvwxyz'\n min = 3\n max = 8\n strings = []\n for count in xrange(1, size):\n current = ''\n for x in random.sample(alpha,...
[ 4, 1, 0, 0 ]
[]
[]
[ "django", "python", "search", "sql", "sqlite" ]
stackoverflow_0004453092_django_python_search_sql_sqlite.txt
Q: Data corruption: Where's the bug‽ Last edit: I've figured out what the problem was (see my own answer below) but I cannot mark the question as answered, it would seem. If someone can answer the questions I have in my answer below, namely, is this a bug in Cython or is this Cython's intended behavior, I will mark ...
Data corruption: Where's the bug‽
Last edit: I've figured out what the problem was (see my own answer below) but I cannot mark the question as answered, it would seem. If someone can answer the questions I have in my answer below, namely, is this a bug in Cython or is this Cython's intended behavior, I will mark that answer as accepted, because that w...
[ "Oy, I hate to do this (answer my own question), but I found the answer: It is a quirk of Cython which I am going to have to look into (I don't know if it is an intended quirk, or if it is a bug).\nThe problem comes with the memcpy line. I cast the second parameter to <const_void*>, which matches the Cython defin...
[ 2, 0 ]
[]
[]
[ "cython", "mcrypt", "python", "python_extensions" ]
stackoverflow_0004451977_cython_mcrypt_python_python_extensions.txt
Q: PyQt: how to handle auto-resize of widgets when their content changes I am having some issues with the size of qt4 widgets when their content changes. I will illustrate my problems with two simple scenarios: Scenario 1: I have a QLineEdit widget. Sometimes, when I'm changing its content using QLineEdit.setText(), ...
PyQt: how to handle auto-resize of widgets when their content changes
I am having some issues with the size of qt4 widgets when their content changes. I will illustrate my problems with two simple scenarios: Scenario 1: I have a QLineEdit widget. Sometimes, when I'm changing its content using QLineEdit.setText(), the one-line string doesn't fit into the widget at its current size anymore...
[ "I'm answering in C++ here, since that's what I'm most familiar with, and your problem isn't specific to PyQt.\nNormally, you just need to call QWidget::updateGeometry() when the sizeHint() may have changed, just like you need to call QWidget::update() when the contents may have changed.\nYour problem, however, is ...
[ 8, 2, 2, 1, 0 ]
[]
[]
[ "c++", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0001153714_c++_pyqt4_python_qt_qt4.txt
Q: Either Python, PyQT, QT, or Windows Vista is finding my dll, no matter what I rename it to. Is this normal? I'm experimenting with PyQT, and I was trying to figure out how to get it to work with Firebird. I built the Firebird driver, but couldn't get it to work, so I was thinking maybe I wasn't putting it in the r...
Either Python, PyQT, QT, or Windows Vista is finding my dll, no matter what I rename it to. Is this normal?
I'm experimenting with PyQT, and I was trying to figure out how to get it to work with Firebird. I built the Firebird driver, but couldn't get it to work, so I was thinking maybe I wasn't putting it in the right place. So I tried experimenting with the SQLite driver, since PyQT came with it already installed, with work...
[ "Yes, Qt plugin infrastructure is a fairly simple and robust one.\nIt attempts to load every file in sqldrivers directory. If it is successful, each dll then runs a function that registers all the features such a plugin supports.\nThen, you application initalizes. If all the features it needs are available, it work...
[ 0 ]
[]
[]
[ "dll", "pyqt4", "python", "qt4", "windows_vista" ]
stackoverflow_0004068906_dll_pyqt4_python_qt4_windows_vista.txt
Q: Make CSRF middleware work in Django's 404 error pages I put a login box alone with a keyword search box in 404.html in a Django project so in case a 404 error is raised, visitors get more options to jump to other parts. But the CSRF middleware doesn't work in 404 error page with no csrf token rendered. I tried mov...
Make CSRF middleware work in Django's 404 error pages
I put a login box alone with a keyword search box in 404.html in a Django project so in case a 404 error is raised, visitors get more options to jump to other parts. But the CSRF middleware doesn't work in 404 error page with no csrf token rendered. I tried move 'django.middleware.csrf.CsrfViewMiddleware' to first of M...
[ "Looks like they've fixed this in Django http://code.djangoproject.com/ticket/14565\nThat said, it doesn't seem to be in the latest release, so I created a custom error view with the same contents as 'django.views.defaults.page_not_found', making the changes found in the ticket diff file.\n", "My idea is you shou...
[ 1, 0 ]
[]
[]
[ "csrf", "django", "middleware", "python" ]
stackoverflow_0002474310_csrf_django_middleware_python.txt
Q: Python: Check the occurrences in a list against a value lst = [1,2,3,4,1] I want to know 1 occurs twice in this list, is there any efficient way to do? A: lst.count(1) would return the number of times it occurs. If you're going to be counting items in a list, O(n) is what you're going to get. The general functi...
Python: Check the occurrences in a list against a value
lst = [1,2,3,4,1] I want to know 1 occurs twice in this list, is there any efficient way to do?
[ "lst.count(1) would return the number of times it occurs. If you're going to be counting items in a list, O(n) is what you're going to get.\nThe general function on the list is list.count(x), and will return the number of times x occurs in a list.\n", "Are you asking whether every item in the list is unique?\nlen...
[ 48, 20, 4, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004446380_list_python.txt
Q: Nested While Loops not working I'm trying to use a while-loop to find a match between two values. One is static while the other is an entry in a list. This is the code: while count != 10: for x in rawinput[pos]: a = ord(x) hash = hash + a print hashlist[247] print hash print wordli...
Nested While Loops not working
I'm trying to use a while-loop to find a match between two values. One is static while the other is an entry in a list. This is the code: while count != 10: for x in rawinput[pos]: a = ord(x) hash = hash + a print hashlist[247] print hash print wordlist[247] while hash != hashlist[...
[ "The code you posted doesn't nest any while loops. \nwhile count != 10:\n\n for x in rawinput[pos]:\n a = ord(x)\n hash = hash + a\n\nThis is the only relevant code. This is an infinite loop assuming count didn't start at 10.\n", "Thing 1: the Pythonic way of doing something 10 times is \nfor _ in ...
[ 3, 3, 1, 0 ]
[]
[]
[ "match", "python", "while_loop" ]
stackoverflow_0004453876_match_python_while_loop.txt
Q: AES encryption of files with Python I am looking to implement a simple project that backs up files and encrypts them using AES. The normal backing up part is done thanks to how Python handles everything ... however I need to encrypt the data also. So my questions are: Is AES the best encryption algorithm for encr...
AES encryption of files with Python
I am looking to implement a simple project that backs up files and encrypts them using AES. The normal backing up part is done thanks to how Python handles everything ... however I need to encrypt the data also. So my questions are: Is AES the best encryption algorithm for encrypting the files or I can do better? What...
[ "Ideally, you would not be at a cipher level in order to secure your data. If nothing else, use an existing, proven secure, framework such as GPG to handle file encryption. This is driven home by your question regarding AES: you haven't even mentioned what cipher modes you were considering (CBC, XTR, CTR, CFB, EBC,...
[ 2, 1 ]
[ "Check pyOpenSSL or PyCrypto.\n" ]
[ -1 ]
[ "aes", "encryption", "python" ]
stackoverflow_0004453724_aes_encryption_python.txt
Q: Socket Thread and PyGTK I'm trying to write a instant messaging program, the basic ui is almost finished and i'm looking into the receiving part of messages. I have an UI class and a threaded Receive_Socket class. Each time the socket of the Received_Socket class receive a message, it does a gobject.idle_add() to ...
Socket Thread and PyGTK
I'm trying to write a instant messaging program, the basic ui is almost finished and i'm looking into the receiving part of messages. I have an UI class and a threaded Receive_Socket class. Each time the socket of the Received_Socket class receive a message, it does a gobject.idle_add() to call an UI method in order to...
[ "\nNo. Don't use threads. Instead, use glib.io_add_watch to make gtk/glib itself call your function when the socket is ready to read. That way you won't freeze your gui and won't need threads. You also won't need idle_add.\nIf you do 1, you won't have this problem, since messages will arrive in order and there will...
[ 3 ]
[]
[]
[ "pygtk", "python", "python_multithreading", "sockets" ]
stackoverflow_0004453655_pygtk_python_python_multithreading_sockets.txt
Q: Practices while releasing the python/ruby/script based web applications on production I am purely a windows programmer and spend all my time hacking VC++. Recently I have been heading several web based applications and myself built applications with python (/pylons framework) and doing projects on rails. All the ...
Practices while releasing the python/ruby/script based web applications on production
I am purely a windows programmer and spend all my time hacking VC++. Recently I have been heading several web based applications and myself built applications with python (/pylons framework) and doing projects on rails. All the web projects are hosted on ubuntu linux. The RELEASE procedures and check list we followed...
[ "I would create a branch in SVN for every release of web application and when the release is ready there, I would check it out on the server and set to be run or move it into the place of the old version.\n", "Is SVN checkout and svn update are the right methods to update the latest build files into the server? \...
[ 3, 2, 2, 0 ]
[]
[]
[ "linux", "python", "release", "ruby", "scripting" ]
stackoverflow_0002059337_linux_python_release_ruby_scripting.txt
Q: Add two rows with foreign key - SQL I'm worndering how I can add 2 rows, of which 1 depends on another, in 1 transaction. INSERT INTO users (username) VALUES ('malcom.reynolds') INSERT INTO spaceships (name, owner) VALUES ('Serenity', <<Malcom Reynold's row ID>>) Reason I an doing is that the library I'm using ...
Add two rows with foreign key - SQL
I'm worndering how I can add 2 rows, of which 1 depends on another, in 1 transaction. INSERT INTO users (username) VALUES ('malcom.reynolds') INSERT INTO spaceships (name, owner) VALUES ('Serenity', <<Malcom Reynold's row ID>>) Reason I an doing is that the library I'm using does not return the rowid, and I need to...
[ "Look at http://msdn.microsoft.com/en-us/library/aa259185%28SQL.80%29.aspx\nINSERT INTO users (username) VALUES ('malcom.reynolds');\n\nINSERT INTO spaceships (name, owner) \nVALUES ('Serenity', SCOPE_IDENTITY() )\n\n", "You can use the T-SQL scope_identity to return the new ID from the first INSERT statement.\nB...
[ 4, 4, 4, 2 ]
[]
[]
[ "django", "pyodbc", "python", "sql", "sql_server" ]
stackoverflow_0004454219_django_pyodbc_python_sql_sql_server.txt
Q: Python Type Error (probably simple) I'm trying open a txt file and read it, but I'm getting a type error and I'm unsure why. If you you could please provide a reasoning along with the correct syntax, I'm trying to get a better grasp of what's going on underneath. Here's the code, it's pretty simple I think: from...
Python Type Error (probably simple)
I'm trying open a txt file and read it, but I'm getting a type error and I'm unsure why. If you you could please provide a reasoning along with the correct syntax, I'm trying to get a better grasp of what's going on underneath. Here's the code, it's pretty simple I think: from sys import argv script = argv filename ...
[ "argv is a list, not a string. You want\nscript = argv[0]\nfilename = argv[1]\n\nConsider using argparse instead of handing sys.argv directly:\n>>> import argparse\n>>> parser = argparse.ArgumentParser(description=\"Print a file.\")\n>>> parser.add_argument(\"path\", type=str, nargs=1, help=\"Path to the file to be...
[ 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004454946_python.txt
Q: Python loop to [:-1] So, I notice that calling array[:-1] is going to clone the array. Say I have a large array with like 3000 elements in it. I don't want it to be cloned as I iterate over it! I just want to iterate to the 2nd last one. for item in array[ :-1 ] : # do something with the item So do I have to ...
Python loop to [:-1]
So, I notice that calling array[:-1] is going to clone the array. Say I have a large array with like 3000 elements in it. I don't want it to be cloned as I iterate over it! I just want to iterate to the 2nd last one. for item in array[ :-1 ] : # do something with the item So do I have to resort to a counter variab...
[ "for item in itertools.islice(array, len(array) - 1):\n\n", "Check out itertools.islice:\nfrom itertools import islice\nfor item in islice(array, 0, len(array) - 1):\n # do something with item\n\nThis is about half of what you want; it eliminates the need to say array[i] but not the need to specify len(array) ...
[ 6, 4, 2, 0 ]
[]
[]
[ "list", "performance", "python" ]
stackoverflow_0004455079_list_performance_python.txt
Q: Can I set the permissions of the contents of a dynamically generated zip file in Google App Engine? In my app engine script (using the Python API), I'm using this code to dynamically generate zip files and serve them back to the user. When I download and extract the generated zip file and I'm running OS X, the per...
Can I set the permissions of the contents of a dynamically generated zip file in Google App Engine?
In my app engine script (using the Python API), I'm using this code to dynamically generate zip files and serve them back to the user. When I download and extract the generated zip file and I'm running OS X, the permissions of each file extracted from the archive is 0, forcing me to chmod them. I'd rather not have my u...
[ "Yup, see the docs for the Python zipfile module. Specifically, the signature of the writestr method, which is:\n\nZipFile.writestr(zinfo_or_arcname,\n bytes[, compress_type])\n\nThe first argument can be the filename, or a ZipInfo object, which allows you to specify information about the file to be stored. I beli...
[ 1 ]
[]
[]
[ "google_app_engine", "permissions", "python", "zip" ]
stackoverflow_0004452842_google_app_engine_permissions_python_zip.txt
Q: Post to another python cgi-script from the current cgi-script I have a python script called nav.py that loads pages. These pages have forms in them to post to other scripts that do the actual work. When I'm finished with these I would like to reload nav.py from inside the other scripts so that it takes the user ba...
Post to another python cgi-script from the current cgi-script
I have a python script called nav.py that loads pages. These pages have forms in them to post to other scripts that do the actual work. When I'm finished with these I would like to reload nav.py from inside the other scripts so that it takes the user back to the page they were just on. Is there a way to do this with th...
[ "I don't know if this is the best way to do it but it works for my purposes. At the end of my script i just print a page with a form and hidden fields with my data just in case the javascript is slow and it tries to render the page before the javascript submits the form.\nprint(\"Content-Type: text/html\\n\\n\")\np...
[ 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0004455394_cgi_python.txt
Q: Is there any use for Bash scripting anymore? I just finished my second year as a university CS student, so my "real-world" knowledge is lacking. I learned Java my first year, continued with Java and picked up C and simple Bash scripting my second. This summer I'm trying to learn Perl (God help me). I've dabble...
Is there any use for Bash scripting anymore?
I just finished my second year as a university CS student, so my "real-world" knowledge is lacking. I learned Java my first year, continued with Java and picked up C and simple Bash scripting my second. This summer I'm trying to learn Perl (God help me). I've dabbled with Python a bit in the past. My question is, n...
[ "Among other things, bash is useful when most of what you're doing is communicating and piping between various programs (many of which are also standard). And there are many environments where bash (or at least a POSIX shell) is available but Perl and Python are not.\nAnd of course, you should distinguish between ...
[ 61, 37, 27, 26, 17, 14, 8, 6, 4, 3, 2, 2, 2, 2, 1, 1, 1, 1 ]
[]
[]
[ "bash", "comparison", "perl", "python", "scripting" ]
stackoverflow_0002872041_bash_comparison_perl_python_scripting.txt
Q: Why does a 'for' loop in python change unreferenced lists? I'm working on a py script which reads in lines from a csv file, manipulates them, and puts them back out. So far I have the csv to list conversion working. The problem I am having is when I iterate over the temporary lists, the for loops change ALL the te...
Why does a 'for' loop in python change unreferenced lists?
I'm working on a py script which reads in lines from a csv file, manipulates them, and puts them back out. So far I have the csv to list conversion working. The problem I am having is when I iterate over the temporary lists, the for loops change ALL the temp lists, instead of just the one I want. Here is a simple examp...
[ "Python has nothing but references. row is a reference to the actual element within l or y. Mutating row mutates that element, and adding it to another object adds the original element.\n", "Your three lists are different, but there are only two elements shared between them:\n>>> y[0] is t[0] is z[0]\nTrue\n>>> y...
[ 7, 4, 0 ]
[]
[]
[ "for_loop", "list", "python", "scope", "variables" ]
stackoverflow_0004455885_for_loop_list_python_scope_variables.txt
Q: Executing a python script from inittab not as root I have a python script which I would like to launch from inittab, shown below s1:respawn:/home/a_user/app/script.py I believe initab executes as root, so the a_user's envrinment is not available The script needs to know "a_user" home directory for ini file settin...
Executing a python script from inittab not as root
I have a python script which I would like to launch from inittab, shown below s1:respawn:/home/a_user/app/script.py I believe initab executes as root, so the a_user's envrinment is not available The script needs to know "a_user" home directory for ini file settings and log file storage. I would like to avoid hard codi...
[ "Use runuser (or the distro's equvalent) to run it as a different user. runuser does change $HOME, but other similar commands may not.\n", "you could copy python binary to python-suid,\nchown it to user you want to run scripts as and chown u+s python-suid\nthen in script #!/usr/bin/python-suid\n" ]
[ 1, 1 ]
[]
[]
[ "python", "root" ]
stackoverflow_0004455973_python_root.txt
Q: Powershell integration with Python (not IronPython) I know it is possible to use Powershell from within IronPython, but is this possible using CPython beyond using Popen() and other similar calls? I'm trying to do some very basic NET framework programming (windows Forms, etc.) like you can do inside of IronPython ...
Powershell integration with Python (not IronPython)
I know it is possible to use Powershell from within IronPython, but is this possible using CPython beyond using Popen() and other similar calls? I'm trying to do some very basic NET framework programming (windows Forms, etc.) like you can do inside of IronPython using CPython. Thanks! Any help appreciated.
[ "I am not sure why you got downvoted as this is a legitimate question. I think the best integration you are going to get trying to integrate PowerShell into CPython will be through spawning a new process and passing in the PowerShell script you want run. Unfortunately this will also mean parsing any output that is ...
[ 3 ]
[]
[]
[ "powershell", "python" ]
stackoverflow_0004455999_powershell_python.txt
Q: Error while trying to create a detail page I've got two classes in my model, like thus: from django.db import models class nonprofit(models.Model): organization = models.CharField(max_length=200) city = models.CharField(max_length=200) website = models.URLField(max_length=120, blank=True) ...........
Error while trying to create a detail page
I've got two classes in my model, like thus: from django.db import models class nonprofit(models.Model): organization = models.CharField(max_length=200) city = models.CharField(max_length=200) website = models.URLField(max_length=120, blank=True) ........ def __unicode__(self): return self...
[ "Typo:\ne = get_object_or_404(executive, d=id)\n\nshould be:\ne = get_object_or_404(executive, id=id)\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004456169_django_python.txt
Q: Executing and reading the output of a binary in python/bash/perl script I have an executable that does the following: 1. outputs the string BEGIN 2. wait for some random time 3. outputs the string END I want to do the following with a python/bash/perl script on MacOS: execute the program mentioned before from com...
Executing and reading the output of a binary in python/bash/perl script
I have an executable that does the following: 1. outputs the string BEGIN 2. wait for some random time 3. outputs the string END I want to do the following with a python/bash/perl script on MacOS: execute the program mentioned before from command line record the time between the BEGIN message and the END message outpu...
[ "The easiest (best?) way to do this in bash is to just call date and have it output it's time in seconds. The timer.sh script will call your executable (randbegend.sh for my testing purposes) and then look for the BEGIN and END lines to trigger the call to date. Once your executable quits, timer.sh will then calc...
[ 1, 1, 0, 0 ]
[]
[]
[ "bash", "linux", "perl", "python", "scripting" ]
stackoverflow_0004455954_bash_linux_perl_python_scripting.txt
Q: django redirecting '/' to a flat page I'm trying to get '/' to redirect to '/first-page' where '/first-page' is a built-in flat page with the slug first-page I'm looking for something like (r'^/', 'redirect_to', {'url': '/flat-page'}), A: Use Django's generic views urlpatterns = patterns('django.views.generic.s...
django redirecting '/' to a flat page
I'm trying to get '/' to redirect to '/first-page' where '/first-page' is a built-in flat page with the slug first-page I'm looking for something like (r'^/', 'redirect_to', {'url': '/flat-page'}),
[ "Use Django's generic views\nurlpatterns = patterns('django.views.generic.simple',\n ('^$', 'redirect_to', {'url': '/first-page'}),\n)\nurlpatterns += patterns('myProject.myApp',\n ...\n)\n\nor\nurlpatterns = patterns('',\n ('^$', 'django.views.generic.simple.redirect_to', {'url': '/first-page'}),\n ......
[ 3, 1, 1 ]
[]
[]
[ "django", "python", "routing" ]
stackoverflow_0004456125_django_python_routing.txt
Q: posting checkbox data to views in Django I am absolutely baffled about this. I am using a checkbox form to get a list of items (tags) to view from the user, so that they can customize the view on their page. data=request.POST data has the value: <QueryDict: {…, u'tags': [u' blue', u'hi', u'sky'], …}> but when I...
posting checkbox data to views in Django
I am absolutely baffled about this. I am using a checkbox form to get a list of items (tags) to view from the user, so that they can customize the view on their page. data=request.POST data has the value: <QueryDict: {…, u'tags': [u' blue', u'hi', u'sky'], …}> but when I try to retrieve the list of tags: debug=data[...
[ "request.POST is a QueryDict - if you're expecting multiple values for a key, use its getlist method.:\ndebug = data.getlist('tags')\n\n" ]
[ 5 ]
[]
[]
[ "checkbox", "django", "html", "post", "python" ]
stackoverflow_0004455219_checkbox_django_html_post_python.txt
Q: If I just want a simple comment box below my entry, should I use Django's comment framework or write my own? I'm split between writing my own comments model (pretty easy model, foreign key it to the entry) or using the full-out Django comment framework. I mean, for right now, I just want a basic box for people to ...
If I just want a simple comment box below my entry, should I use Django's comment framework or write my own?
I'm split between writing my own comments model (pretty easy model, foreign key it to the entry) or using the full-out Django comment framework. I mean, for right now, I just want a basic box for people to post a comment. That's it.
[ "Um... yes?\nMore seriously - whatever makes you happier. If you're in a hurry, roll your own; if you have a bit more time, by all means get to know the Django system; it'll probably be worthwhile in the longer run.\n" ]
[ 1 ]
[]
[]
[ "django", "frameworks", "python", "templates" ]
stackoverflow_0004456444_django_frameworks_python_templates.txt
Q: Python Multidimensional Array - Adding additional values to beginning and end of each row How do I add 0's to the beginning and end of each row of a multidimensional array? This is the function I am trying to apply to each row. def zero(ltr): for x in range (1,int((N+1)/2)): ltr = append(([0]), ltr) ...
Python Multidimensional Array - Adding additional values to beginning and end of each row
How do I add 0's to the beginning and end of each row of a multidimensional array? This is the function I am trying to apply to each row. def zero(ltr): for x in range (1,int((N+1)/2)): ltr = append(([0]), ltr) ltr = append(ltr,([0])) return ltr I have tried using both for row in a: zero(row) ...
[ "It is not possible to add entries to single rows of a two-dimensional array. All rows must always have the same length. But you can add entries to all rows at once.\nIf a is a two-dimensional NumPy array, you can use numpy.hstack to add zeros to left and the right:\na = numpy.array([[ 0., 1., 2., 3.],\n ...
[ 4, 0 ]
[]
[]
[ "iteration", "multidimensional_array", "numpy", "python" ]
stackoverflow_0004456477_iteration_multidimensional_array_numpy_python.txt
Q: Python3 sleep() problem I was writing a simple program on Python 3.1 and I stumbled upon this: If I run this on the IDLE it works as intended - prints "Initializing." and then adds two dots, one after each second, and waits for input. from time import sleep def initialize(): print('Initializing.', end='') ...
Python3 sleep() problem
I was writing a simple program on Python 3.1 and I stumbled upon this: If I run this on the IDLE it works as intended - prints "Initializing." and then adds two dots, one after each second, and waits for input. from time import sleep def initialize(): print('Initializing.', end='') sleep(1) print(" .", end...
[ "This is because the output is being buffered.\nYou should add a sys.stdout.flush() after each write\n", "It sounds like the difference is that stdout is automatically being flushed in IDLE. For efficiency, programming languages often save up a bunch of print calls before writing to the screen, which is a slow pr...
[ 23, 5 ]
[]
[]
[ "flush", "python", "python_3.x", "sleep" ]
stackoverflow_0004456581_flush_python_python_3.x_sleep.txt
Q: Can't seem to access cookie in Python (2.4) I have a CGI script for which I've successfully set a cookie (which I can see in Firefox/Chrome!) which has (say) the name uid and the content 1. I don't seem to understand how to access this cookie from another CGI script--and I'm working in Python 2.4 so a lot of the e...
Can't seem to access cookie in Python (2.4)
I have a CGI script for which I've successfully set a cookie (which I can see in Firefox/Chrome!) which has (say) the name uid and the content 1. I don't seem to understand how to access this cookie from another CGI script--and I'm working in Python 2.4 so a lot of the examples I've found may not apply. This code print...
[ "First thing is are you sure the webserver or the framework is setting the HTTP_COOKIE environment variable?\nOtherwise, in one of your script you may want to store the cookies in the CookieJar file in the file system and access the set cookies from there.\nimport cookielib\n\nCOOKIEFILE = 'Cookies.lwp'\ncookiejar ...
[ 0, 0 ]
[]
[]
[ "cgi", "cookies", "python" ]
stackoverflow_0004456405_cgi_cookies_python.txt
Q: aggregate dictionary items into summary results I have a dictionary like mydict={ (a,1):0, (a,2):0, (a,3):0, (a,4):1, (a,5):2, (a,6):2, (a,7)=0, (a,8)=0, } I want to summarize it in to mysummarydict={ (a,1,3):0, (a,4,4):1, ...
aggregate dictionary items into summary results
I have a dictionary like mydict={ (a,1):0, (a,2):0, (a,3):0, (a,4):1, (a,5):2, (a,6):2, (a,7)=0, (a,8)=0, } I want to summarize it in to mysummarydict={ (a,1,3):0, (a,4,4):1, (a,5,6):2, (a,7,8):0 } These values are fr...
[ "from itertools import groupby\nfrom operator import itemgetter\n\nmydict={\n ('a', 1): 0,\n ('a', 2): 0,\n ('a', 3): 0,\n ('a', 4): 1,\n ('a', 5): 2,\n ('a', 6): 2,\n ('a', 7): 0,\n ('a', 8): 0, \n}\n\ndata = mydict.items()\ndata.sort()\n\ndef group...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0004454069_dictionary_python.txt
Q: Convert binary files into ascii in Python I have a bunch of binary files that contain data in the following format: i\xffhh\xffhh\xffhh\xffih\xffhh\xffhh\xffhh\xffhh\xffhi\xffii\xffjj\xffjj\xffjj\xffjk\xffkk\xffkk\xffkl\xffll\xffmm\xffmn\xffnn\xffon\xffno\xffop\xffop\xffpp\xffqq\xffrq\xffrs\xffst\xfftt\xfftt\xffu...
Convert binary files into ascii in Python
I have a bunch of binary files that contain data in the following format: i\xffhh\xffhh\xffhh\xffih\xffhh\xffhh\xffhh\xffhh\xffhi\xffii\xffjj\xffjj\xffjj\xffjk\xffkk\xffkk\xffkl\xffll\xffmm\xffmn\xffnn\xffon\xffno\xffop\xffop\xffpp\xffqq\xffrq\xffrs\xffst\xfftt\xfftt\xffuv\xffvu\xffuv\xffvv\xffvw\xffwx\xffwx\xffxy\xff...
[ "I'm absolutely shocked and stunned and not a little bit amazed at all the waffle like \"you have letters like hh which shouldn't be part of a hex number\" and \"they seem to start making sense right at the first \\x7f\". Hasn't anybody seen any repr() output?\nThe following shows how it might have ended up like th...
[ 4, 3, 0 ]
[]
[]
[ "ascii", "binary", "decoding", "python" ]
stackoverflow_0004218760_ascii_binary_decoding_python.txt
Q: First time programming in livewires module, How do I make a start page for my executable game? I want my game to go to a title slide first and return to that slide when the character dies (its an asteroids clone) any help would be much appreciated. A: Check out the pygame module. There are a number of tutorials ...
First time programming in livewires module, How do I make a start page for my executable game?
I want my game to go to a title slide first and return to that slide when the character dies (its an asteroids clone) any help would be much appreciated.
[ "Check out the pygame module. There are a number of tutorials that will get you up running fairly quickly.\nExample from lecture 3 of \"Python game programming\" (first tutorial):\nimport pygame, sys,os\nfrom pygame.locals import * \n\npygame.init() \n\nwindow = pygame.display.set_mode((468, 60)) \npygame.display.s...
[ 0 ]
[]
[]
[ "livewires", "python" ]
stackoverflow_0004457223_livewires_python.txt
Q: force creating object when using raw_id_fields in Django I'm using raw_id_fields in my admin.py to change the ForeignKey's select box to an input box. When saving the form, it checks if the object that I wrote in the ForeignKey box exists, if not, it raises an error saying "Select a valid choice. That choice is no...
force creating object when using raw_id_fields in Django
I'm using raw_id_fields in my admin.py to change the ForeignKey's select box to an input box. When saving the form, it checks if the object that I wrote in the ForeignKey box exists, if not, it raises an error saying "Select a valid choice. That choice is not one of the available choices." What I want to do is skipping...
[ "you can overwrite your model's save() by adding codes to create the object directly if it doesn't exist.\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004298011_django_django_models_python.txt
Q: get exception type in python 1.5.2 How can I get the type of an Exception in python 1.5.2? doing this: try: raise "ABC" except Exception as e: print str(e) gives an SyntaxError: except Exception as e: ^ SyntaxError: invalid syntax EDIT: this does not work: try: a = 3 b = no...
get exception type in python 1.5.2
How can I get the type of an Exception in python 1.5.2? doing this: try: raise "ABC" except Exception as e: print str(e) gives an SyntaxError: except Exception as e: ^ SyntaxError: invalid syntax EDIT: this does not work: try: a = 3 b = not_existent_variable except Exception, e:...
[ "It's \nexcept Exception, e:\n\nIn Python 1 and 2. (Although as also works in Python 2.6 and 2.7).\n(Why on earth are you using 1.5.2!?)\nTo then get the type of the error you use type(e). To get the type name in Python 2 you use type(e).__name__, I have no idea if that works in 1.5.2, you'll have to check the docs...
[ 10 ]
[]
[]
[ "exception", "python", "raise", "syntax_error" ]
stackoverflow_0004458755_exception_python_raise_syntax_error.txt
Q: How to make a command line interface or interpreter in Python I have already developed class1.py, class2.py, etc. with functions implemented inside each class. e.g. Operator.py has add, minus, time, divide functions. How can I build a command line interface for these classes? Also for this CLI, is it an infinite ...
How to make a command line interface or interpreter in Python
I have already developed class1.py, class2.py, etc. with functions implemented inside each class. e.g. Operator.py has add, minus, time, divide functions. How can I build a command line interface for these classes? Also for this CLI, is it an infinite loop inside the main() for interaction? And how can the CLI give so...
[ "Derive from cmd.Cmd, overriding the various methods as necessary.\n", "\nUse the cmd module:\n\n\nReference : Custom (interactive) shell with Python\n\n\nOther packages\n\nYou can also use various modules hosted at pypi that is built on top of cmd module \n\nhttp://pypi.python.org/pypi/Custom%20Interactive%20Con...
[ 5, 1, 1, 0 ]
[]
[]
[ "command_line_interface", "python" ]
stackoverflow_0003910160_command_line_interface_python.txt
Q: Precomputed Kernels with LibSVM in Python I've been searching the net for ~3 hours but I couldn't find a solution yet. I want to give a precomputed kernel to libsvm and classify a dataset, but: How can I generate a precomputed kernel? (for example, what is the basic precomputed kernel for Iris data?) In the libsv...
Precomputed Kernels with LibSVM in Python
I've been searching the net for ~3 hours but I couldn't find a solution yet. I want to give a precomputed kernel to libsvm and classify a dataset, but: How can I generate a precomputed kernel? (for example, what is the basic precomputed kernel for Iris data?) In the libsvm documentation, it is stated that: For precomp...
[ "First of all, some background to kernels and SVMs...\nIf you want to pre-compute a kernel for n vectors (of any dimension), what need to do is calculate the kernel function between each pair of examples. The kernel function takes two vectors and gives a scalar, so you can think of a precomputed kernel as a nxn mat...
[ 17, 8, 4, 3 ]
[]
[]
[ "libsvm", "machine_learning", "python" ]
stackoverflow_0002474460_libsvm_machine_learning_python.txt
Q: Flexible English date phrase library for Python? I'm looking for a function that can convert an English date phrase to some kind of Python date object representing the appropriate date. An example of the kinds of things I'm looking for (though I'm flexible): Three days from now yesterday In a month Next year Janu...
Flexible English date phrase library for Python?
I'm looking for a function that can convert an English date phrase to some kind of Python date object representing the appropriate date. An example of the kinds of things I'm looking for (though I'm flexible): Three days from now yesterday In a month Next year January 18, 2011 Next Wednesday Is there such a thing? Is...
[ "parsedatetime, always a classic: http://code.google.com/p/parsedatetime/\n", "I think the best bet here would be the mxDateTime. The documentation seems to suggest that it does what you're looking for.\n" ]
[ 1, 0 ]
[]
[]
[ "date", "dsl", "python" ]
stackoverflow_0004458705_date_dsl_python.txt
Q: how to optimally count elements in a python list This is almost the same question than here, except that I am asking about the most efficient solution for a sorted result. I have a list (about 10 integers randomly between 0 and 12), for example: the_list = [5, 7, 6, 5, 5, 4, 4, 7, 5, 4] I want to create a functio...
how to optimally count elements in a python list
This is almost the same question than here, except that I am asking about the most efficient solution for a sorted result. I have a list (about 10 integers randomly between 0 and 12), for example: the_list = [5, 7, 6, 5, 5, 4, 4, 7, 5, 4] I want to create a function that returns a list of tuples (item, counts) ordered...
[ "Change where you sort for a savings of about 20%.\nChange this: \ndef dupli(the_list):\n return [(item, the_list.count(item)) for item in sorted(set(the_list))]\n\nTo this:\ndef dupli(the_list):\n count = the_list.count # this optimization added courtesy of Sven's comment\n result = [(item, count(item)) f...
[ 4, 3, 2, 0, 0, 0 ]
[]
[]
[ "count", "list", "performance", "python" ]
stackoverflow_0004456700_count_list_performance_python.txt
Q: Bug when drawing a QImage on a widget with PIL and PyQt I'm trying to write a small graphic application, and I need to construct some image using PIL that I show in a widget. The image is correctly constructed (I can check with im.show()), I can convert it to a QImage, that I can save normally to disk (using QImag...
Bug when drawing a QImage on a widget with PIL and PyQt
I'm trying to write a small graphic application, and I need to construct some image using PIL that I show in a widget. The image is correctly constructed (I can check with im.show()), I can convert it to a QImage, that I can save normally to disk (using QImage.save), but if I try to draw it directly on my QWidget, it o...
[ "Had the same problem, then noticed, that ImageQt objects are not QImages, but can simply be casted to those\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#written by Sebastian Stetter in 2010\n\n\nimport sys\nfrom PIL import Image\nfrom PIL.ImageQt import ImageQt\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore impo...
[ 4, 1 ]
[]
[]
[ "image", "pyqt", "python", "python_imaging_library", "qt" ]
stackoverflow_0003041728_image_pyqt_python_python_imaging_library_qt.txt
Q: In what order does python display dictionary keys? >>> D = {'a': 1, 'b': 2, 'c': 3} >>> D {'a': 1, 'c': 3, 'b': 2} I just did this in the Python shell and I'm just wondering why the key 'c' would be after the key 'b'??? A: The order has to do with how they work internally and what order they end up in the hasht...
In what order does python display dictionary keys?
>>> D = {'a': 1, 'b': 2, 'c': 3} >>> D {'a': 1, 'c': 3, 'b': 2} I just did this in the Python shell and I'm just wondering why the key 'c' would be after the key 'b'???
[ "The order has to do with how they work internally and what order they end up in the hashtable. That in turn depends on the keys hash-value, the order they were inserted, and which Python implementation you are using.\nThe order is arbitrary (but not random) and it will never be useful to know which order it will b...
[ 17, 7, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004458169_python.txt
Q: django hosting error , about alwaysdata.com this is my alwaysdata page - http://zjm.alwaysdata.net/: It is not configured successful ,but when i Visit the http://zjm.alwaysdata.net/mysite/public/ it show my main page : so what can i do to show my main-page on the http://zjm.alwaysdata.net/ thanks updated thi...
django hosting error , about alwaysdata.com
this is my alwaysdata page - http://zjm.alwaysdata.net/: It is not configured successful ,but when i Visit the http://zjm.alwaysdata.net/mysite/public/ it show my main page : so what can i do to show my main-page on the http://zjm.alwaysdata.net/ thanks updated this is my django.fcgi : #!/usr/bin/python import os...
[ "You should configure your domain (zjm.alwaysdata.net) to point to your /public directory on the server : /home/zjm/www/mysite/public/\n" ]
[ 1 ]
[]
[]
[ "django", "fastcgi", "hosting", "python" ]
stackoverflow_0004457955_django_fastcgi_hosting_python.txt
Q: Python for loop not working on custom container EDIT: I added __iter__ to my Map class (i forgot it didn't inherit from Tree), but now the for loop returns "generator objects": <generator object _next at 0x82a4b94> Traceback (most recent call last): File "Map.py", line 43, in <module> print "First: %s, Secon...
Python for loop not working on custom container
EDIT: I added __iter__ to my Map class (i forgot it didn't inherit from Tree), but now the for loop returns "generator objects": <generator object _next at 0x82a4b94> Traceback (most recent call last): File "Map.py", line 43, in <module> print "First: %s, Second: %s" % (pair.first(), pair.second()) AttributeError...
[ "You Map class have not __iter__ method, so for calls __getitem__ instead. You should inherit Map from SearchTree or implement __iter__ in Map.\n", "I believe that in order to use the map as an iterator in the conditional, the Map class has to implement next and iter. Am I mistaken in this?\nBasically you'd be ad...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004451922_python.txt
Q: Multi threaded webserver vs single threaded We have a simple webserver for internal use that has only one duty: listen for requests, read them, and push the data in a database. The db and webserver are both located on the same machine. The db is a mysql-db and the server is a python webserver (BaseHTTPServer.HTTPS...
Multi threaded webserver vs single threaded
We have a simple webserver for internal use that has only one duty: listen for requests, read them, and push the data in a database. The db and webserver are both located on the same machine. The db is a mysql-db and the server is a python webserver (BaseHTTPServer.HTTPServer) which runs single threaded. The problem i...
[ "Having several threads or processes will indeed help you (indeed it's in practice required) when you want to handle more than one request at a time.\nThat doesn't mean that the two requests will be handled faster. Having a pool of processes or threads is very helpful for webserver performance, but that's not reall...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "database", "multithreading", "python", "webserver" ]
stackoverflow_0004458890_database_multithreading_python_webserver.txt
Q: running a python script with cron It might be very simple question, but how could I run a python script on my fedora dist every 2 days? Thanks Antonis A: It is a question on cron. First is add a SHEBANG line on top of your python script. #!/usr/bin/env python Make your script executable with chmod +x And do a c...
running a python script with cron
It might be very simple question, but how could I run a python script on my fedora dist every 2 days? Thanks Antonis
[ "It is a question on cron.\nFirst is add a SHEBANG line on top of your python script.\n#!/usr/bin/env python\n\nMake your script executable with chmod +x\nAnd do a crontab -e and add 0 0 */2 * * /path/to/your/pythonscript.py\n" ]
[ 66 ]
[]
[]
[ "cron", "python" ]
stackoverflow_0004460262_cron_python.txt
Q: ValueError: invalid literal for int() with base 10: 'MSIE' After I run my Python code on a big file of only HTTP headers, it gives me the above error. Any idea what that means? Here is a piece of the code: users = output.split(' ')[1] accesses = output.split(' ')[3] ave_accesses = int(accesses)/int(users) Basical...
ValueError: invalid literal for int() with base 10: 'MSIE'
After I run my Python code on a big file of only HTTP headers, it gives me the above error. Any idea what that means? Here is a piece of the code: users = output.split(' ')[1] accesses = output.split(' ')[3] ave_accesses = int(accesses)/int(users) Basically the 'users' are users who have accessed a website and 'access...
[ "It means that you are trying to convert a string to an integer, and the value of the string is 'MSIE'. The traceback will have a filename near this error and the line number (e.g., /my/module.py:123). Open the file and go to the line the error occurred, you should see a call to int() with a parameter. That paramet...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004460509_python.txt
Q: Getting locals in given order with Python I have some functions that have huge inputs (some of them has 28 etc), I have to print those variables by same sequence with inputs. I'm getting those variables with locals() functions. However this function gives me a dictionary which has totally different sequence. So, ...
Getting locals in given order with Python
I have some functions that have huge inputs (some of them has 28 etc), I have to print those variables by same sequence with inputs. I'm getting those variables with locals() functions. However this function gives me a dictionary which has totally different sequence. So, how can I get these variables without changing ...
[ "Give a look at this other SO question. They suggest several ways of doing what you want. The easiest one seems to be using inspect instead of locals.\n" ]
[ 2 ]
[]
[]
[ "dictionary", "local", "python" ]
stackoverflow_0004460716_dictionary_local_python.txt
Q: A basic question about python class definitions What is the difference between saying: class foo: pass and class foo(object): pass ? A: The latter declares a new-style class. A: "Classes and instances come in two flavors: old-style (or classic) and new-style." http://docs.python.org/reference/datamo...
A basic question about python class definitions
What is the difference between saying: class foo: pass and class foo(object): pass ?
[ "The latter declares a new-style class.\n", "\"Classes and instances come in two flavors: old-style (or classic) and new-style.\"\nhttp://docs.python.org/reference/datamodel.html#new-style-and-classic-classes\n", "Old-style classes don't extend the built-in 'object' type. New-style classes do. If you're writing...
[ 4, 3, 2 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0004460950_programming_languages_python.txt
Q: Run command for all files in parallel I have the following command on the build-server as a part of the build process: os.system ('signtool sign /a /t http://timestamp.verisign.com/scripts/timstamp.dll "%s\\*.exe"' % (dir) ) This command signs each executable file in the specified directory. Is there a way to run...
Run command for all files in parallel
I have the following command on the build-server as a part of the build process: os.system ('signtool sign /a /t http://timestamp.verisign.com/scripts/timstamp.dll "%s\\*.exe"' % (dir) ) This command signs each executable file in the specified directory. Is there a way to run this command in parallel for each executab...
[ "Perhaps multiprocessing could be of help here?\nSpecifically, multiprocessing.Pool.map() might be relevant to your needs.\n", "You could use threads. This tutorial shows how to do something similar to what you're asking for using threads.\n", "The above answers are perfectly sensible ways of approaching things...
[ 1, 1, 1 ]
[]
[]
[ "parallel_processing", "python" ]
stackoverflow_0004458560_parallel_processing_python.txt
Q: python unicode: How can I judge if a string needs to be decoded into utf-8? I have a function accepting requests from the network. Most of the time, the string passed in is not unicode, but sometimes it is. I have code to convert everything to unicode, but it reports this error: message.create(username, unicode(bo...
python unicode: How can I judge if a string needs to be decoded into utf-8?
I have a function accepting requests from the network. Most of the time, the string passed in is not unicode, but sometimes it is. I have code to convert everything to unicode, but it reports this error: message.create(username, unicode(body, "utf-8"), self.get_room_name(),\ TypeError: decoding Unicode is not supported...
[ "\nYou do not decode to UTF-8, you encode to UTF-8 or decode from.\nYou can safely decode from UTF8 even if it's just ASCII. ASCII is a subset of UTF8.\nThe easiest way to detect if it needs decoding or not is\nif not isinstance(data, unicode):\n # It's not Unicode!\n data = data.decode('UTF8')\n\n\n" ]
[ 5 ]
[ "You can use either this:\ntry:\n body = unicode(body)\nexcept UnicodeDecodeError:\n body = body.decode('utf8')\n\nOr this:\ntry:\n body = unicode(body, 'utf8')\nexcept TypeError:\n body = unicode(body)\n\n", "Mark Pilgrim wrote a Python library to guess text encodings:\n\nhttp://chardet.feedparser.org/\n...
[ -1, -1, -1 ]
[ "python", "unicode", "utf_8" ]
stackoverflow_0004461183_python_unicode_utf_8.txt
Q: Python strange send email behavior I have basic script that can send properly emails: #!/usr/bin/python import smtplib sender = 'demo@mail.com' receivers = ['demo2@mail.com'] message = """From:Email cronjob <demo@mail.com> Subject: Anything Some more text """ message = message + "\nso far so good...
Python strange send email behavior
I have basic script that can send properly emails: #!/usr/bin/python import smtplib sender = 'demo@mail.com' receivers = ['demo2@mail.com'] message = """From:Email cronjob <demo@mail.com> Subject: Anything Some more text """ message = message + "\nso far so good" try: smtpObj = smtplib.SMTP('...
[ "Indent your code properly and make sure the the email headers like From and Subject are in their own line separated by atleast a newline (\\n) character and then there is the body of the email. You should have a consistent behavior in both your examples.\n", "This worked out: \nmessage = \"\"\"From: %s\\nTo: %s\...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004459994_python.txt
Q: Debugging Django App Installation I've installed a Django application on a new host, but the runserver fails. The first HTTP hit get the error "Import by filename is not supported." The final error reads: File "/usr/lib/pymodules/python2.6/django/utils/importlib.py" in import_module 35. __import__(name) wh...
Debugging Django App Installation
I've installed a Django application on a new host, but the runserver fails. The first HTTP hit get the error "Import by filename is not supported." The final error reads: File "/usr/lib/pymodules/python2.6/django/utils/importlib.py" in import_module 35. __import__(name) where the value of name is '/webcode/urls...
[ "Simple things to check first for Django: file permissions, MEDIA.ROOT, urls.py, ROOT_URLCONF in settings_local.py\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004461909_django_python.txt
Q: User Based Exception program not working This code does not work. Please tell what the error is.... class Error(Exception): def __init__(self,mssg): self.mssg = mssg class InputError(Error): def __init__(self,val): super("Input Error") print val Now I write in other part of my pro...
User Based Exception program not working
This code does not work. Please tell what the error is.... class Error(Exception): def __init__(self,mssg): self.mssg = mssg class InputError(Error): def __init__(self,val): super("Input Error") print val Now I write in other part of my program a = raw_input("Enter a number from 0-9: "...
[ "The problem is that you're using super() incorrectly. The proper way is:\nclass InputError(Error):\n def __init__(self, val):\n super(InputError, self).__init__(val)\n print val\n\n", "super() is used to access methods of a superclass that have been overridden in the subclass, not to instantiate...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004461985_python.txt
Q: Python, suds, manage array answer I'm using suds library to fetch a list of products from a webservice. This is a sample code: from suds.client import Client url = 'WSDLURL' client = Client(url) result = client.service.Research('value') Result contains: (ArrayOfProducts){ Product[] = (Product){ ...
Python, suds, manage array answer
I'm using suds library to fetch a list of products from a webservice. This is a sample code: from suds.client import Client url = 'WSDLURL' client = Client(url) result = client.service.Research('value') Result contains: (ArrayOfProducts){ Product[] = (Product){ Id = 218 Code = "C024" ...
[ "Perfect... Thanks to J.F. Sebastian I find the right way...\nThis is the working code:\nfrom suds.client import Client\nurl = 'wsdl'\nclient = Client(url)\nhtml_out = \"\"\nresult = client.service.Research('a')\nfor p in result.Product:\n print p.Id\n print p.Name\n\n" ]
[ 5 ]
[]
[]
[ "arrays", "python", "soap", "suds", "web_services" ]
stackoverflow_0004459604_arrays_python_soap_suds_web_services.txt
Q: What does Python return when instantiating new classes? I'm finding loads of quirks with Python when instantiating a new class. I'm sure it's just because I'm not used to the language, but even so, the behaviour I can see is really strange. If I open up iPython and type the following: class Person: def __init_...
What does Python return when instantiating new classes?
I'm finding loads of quirks with Python when instantiating a new class. I'm sure it's just because I'm not used to the language, but even so, the behaviour I can see is really strange. If I open up iPython and type the following: class Person: def __init__(self, name): self.name = name def hello(self):...
[ "Well, you removed the relevant part (the traceback) and replaced it by ... in your paste.\nBut it looks like you have an error in the representation of the class.\nHere's a simulation of the error:\n>>> class MyClass(object):\n... def __repr__(self):\n... return True()\n...\n>>> c = MyClass()\n>>> c\n\...
[ 4, 1 ]
[]
[]
[ "class", "oop", "python" ]
stackoverflow_0004461560_class_oop_python.txt
Q: Django: correct way to group a bunch of media's I send several forms to a template, and I want to put all required media in the <head> tag. Some forms might require the same media (for instance, the same JS file), so I would like to unify all medias before putting them in the <head>. Question is, how do I do that?...
Django: correct way to group a bunch of media's
I send several forms to a template, and I want to put all required media in the <head> tag. Some forms might require the same media (for instance, the same JS file), so I would like to unify all medias before putting them in the <head>. Question is, how do I do that? I know you can unify two medias by doing m1 + m2, bu...
[ "The best way I could find was doing it using list comprehensions and reduce:\nmedia = reduce(lambda x, y: x + y, [form.media for form in forms])\n\nWonder if there's an easier way...\n", "What happens if you just use {{ form.media }} for each form, and link up the media in the form's Meta? I seem to remember tha...
[ 2, 0 ]
[]
[]
[ "django", "django_forms", "media", "python" ]
stackoverflow_0004456591_django_django_forms_media_python.txt
Q: Datastore in Google App Engine How do i store data which is more than 10 MB in google app engine? put() from datastore allows only 1 MB. do I need to slice my data into chunks of 1MB each and store ? or is there any other way ? A: Using the datastore, yes, you'll need to use smaller chunks. You could also use ...
Datastore in Google App Engine
How do i store data which is more than 10 MB in google app engine? put() from datastore allows only 1 MB. do I need to slice my data into chunks of 1MB each and store ? or is there any other way ?
[ "Using the datastore, yes, you'll need to use smaller chunks. You could also use the Blobstore API.\n" ]
[ 6 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004462218_google_app_engine_google_cloud_datastore_python.txt
Q: Lookup table for unhashable in Python I need to create a mapping from objects of my own custom class (derived from dict) to objects of another custom class. As I see it there are two ways of doing this: I can make the objects hashable. I'm not sure how I would do this. I know I can implement __hash__() but I'm un...
Lookup table for unhashable in Python
I need to create a mapping from objects of my own custom class (derived from dict) to objects of another custom class. As I see it there are two ways of doing this: I can make the objects hashable. I'm not sure how I would do this. I know I can implement __hash__() but I'm unsure how to actually calculate the hash (wh...
[ "Mappings with mutable objects as keys are generally difficult. Is that really what you want? If you consider your objects to be immutable (there is no way to really enforce immutability in Python), or you know they will not be changed while they are used as keys in a mapping, you can implement your own hash-functi...
[ 3, 2, 1, 1 ]
[]
[]
[ "hash", "lookup", "lookup_tables", "python" ]
stackoverflow_0004462119_hash_lookup_lookup_tables_python.txt
Q: django-mptt not linking data together correctly Hay, I'm using MPTT to create some tree-like data from a model which contains conversations, and i want them to be ordered by a 'votes' field. The model looks like this at the moment, very basic. class Thread(MPTTModel): message = models.CharField(max_length=100)...
django-mptt not linking data together correctly
Hay, I'm using MPTT to create some tree-like data from a model which contains conversations, and i want them to be ordered by a 'votes' field. The model looks like this at the moment, very basic. class Thread(MPTTModel): message = models.CharField(max_length=100) parent = models.ForeignKey('self', null=True, bl...
[ "{% load mptt_tags %}\n<ul class=\"root\">\n {% recursetree nodes %} \n <li>\n {{ node.message }}\n {% if not node.is_leaf_node %}\n <ul class=\"children\">\n {{ children }}\n </ul>\n {% endif %}\n </li>\n ...
[ 2 ]
[]
[]
[ "django", "mptt", "python" ]
stackoverflow_0004423290_django_mptt_python.txt
Q: Python nested loop from files I have the following code: inputActionFile = '../action.txt' inputDaerahFile = '../daerah.txt' inputStuffFile = '../stuff.txt' inputTermsFile = '../terms.txt' outputFile = 'hasil.out' inputAction = open(inputActionFile, 'r') inputDaerah = open(inputDaerahFile, 'r') inputStuff = open...
Python nested loop from files
I have the following code: inputActionFile = '../action.txt' inputDaerahFile = '../daerah.txt' inputStuffFile = '../stuff.txt' inputTermsFile = '../terms.txt' outputFile = 'hasil.out' inputAction = open(inputActionFile, 'r') inputDaerah = open(inputDaerahFile, 'r') inputStuff = open(inputStuffFile, 'r') inputTerms = ...
[ "Each loop will just go through the file once. After having sucessfully looped through \nfor termsLine in inputTerms:\n\nOnce, every time it gets there, it will skip this loop, as you have reached the end of the inputTerms file.\nYou need to either reopen each file in each loop, (or at least seek(0) on them), or re...
[ 3, 2, 0 ]
[]
[]
[ "bash", "nested_loops", "python" ]
stackoverflow_0004458465_bash_nested_loops_python.txt
Q: python: shuffle characters in string to get all possible string combinations just looking for a script in Python which receives some string and returns all possible strings made up of all the possible combinations of the chars in the original string... I've found scripts to shuffle randomly the chars in a string, ...
python: shuffle characters in string to get all possible string combinations
just looking for a script in Python which receives some string and returns all possible strings made up of all the possible combinations of the chars in the original string... I've found scripts to shuffle randomly the chars in a string, but they only return one randome combination, and what I'm looking for is all the ...
[ "itertools.permutations\n>>> import itertools\n>>> import pprint\n>>> pprint.pprint(list(itertools.permutations(\"spam\")))\n[('s', 'p', 'a', 'm'),\n ('s', 'p', 'm', 'a'),\n ('s', 'a', 'p', 'm'),\n ('s', 'a', 'm', 'p'),\n ('s', 'm', 'p', 'a'),\n ('s', 'm', 'a', 'p'),\n ('p', 's', 'a', 'm'),\n ('p', 's', 'm', 'a'),\...
[ 12, 5 ]
[]
[]
[ "combinations", "python", "string" ]
stackoverflow_0004462570_combinations_python_string.txt
Q: lighttpd django fastcgi and auto-reloading? I'm wondering if anyone has ever gotten fcgi to auto-reload with this setup? this to work? I have tried implementing a reload mechanism using django's autoreload.py (copying it to my own location and calling autoreload.main(start), unfortunately, I get errors when the fo...
lighttpd django fastcgi and auto-reloading?
I'm wondering if anyone has ever gotten fcgi to auto-reload with this setup? this to work? I have tried implementing a reload mechanism using django's autoreload.py (copying it to my own location and calling autoreload.main(start), unfortunately, I get errors when the fork occurs like: django/core/servers/fastcgi.py", ...
[ "I got this to work using this technique:\nhttp://code.google.com/p/modwsgi/wiki/ReloadingSourceCode\nUsing the monitor script, running it just before I load my fastcgi process and a little help from supervisord make this work.\n" ]
[ 0 ]
[]
[]
[ "django", "fastcgi", "lighttpd", "python" ]
stackoverflow_0004446311_django_fastcgi_lighttpd_python.txt
Q: Enhance SQLAlchemy syntax for polymorphic identity I have a declarative base class Entity which defines the column name as polymorphic, e.g. class Entity(DeclarativeBase): name = Column('name', String(40)) __mapper_args__ = {'polymorphic_on':name} In subclasses, I could now say class Experiment(Entity): ...
Enhance SQLAlchemy syntax for polymorphic identity
I have a declarative base class Entity which defines the column name as polymorphic, e.g. class Entity(DeclarativeBase): name = Column('name', String(40)) __mapper_args__ = {'polymorphic_on':name} In subclasses, I could now say class Experiment(Entity): __mapper_args__ = {'polymorphic_identity': "experimen...
[ "Shame on me but the problem could easily be solved by not using the dict_ but by setting the attribute directly on cls.\nclass Meta(DeclarativeMeta):\n def __init__(cls, *args, **kw):\n if getattr(cls, '_decl_class_registry', None) is None:\n return # they use this in the docs, so maybe its no...
[ 7, 1 ]
[]
[]
[ "metaclass", "python", "sqlalchemy" ]
stackoverflow_0004460830_metaclass_python_sqlalchemy.txt
Q: Newbie Python Regex question: Pulling dates from webpage I'm looking to use Python to pull a regular string of text from a webpage - the source code runs like this: <br /><strong>Date: 06/12/2010</strong> <br /> It always begins <strong>Date: & ends </strong> I've already scraped the text of the webpage and j...
Newbie Python Regex question: Pulling dates from webpage
I'm looking to use Python to pull a regular string of text from a webpage - the source code runs like this: <br /><strong>Date: 06/12/2010</strong> <br /> It always begins <strong>Date: & ends </strong> I've already scraped the text of the webpage and just want to pull the date and similarly structured information...
[ "You can use a regular expression:\nimport re\npattern = re.compile(r'<strong>Date:(?P<date>.*?)</strong>') # re.MULTILINE?\n# Then use it with\npattern.findall(text) # Returns all matches\n# or\nmatch = pattern.search(text) # grabs the first match\nmatch.groupdict() # gives a dictionary with key 'date'\n# or\nmatc...
[ 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004462784_python_regex.txt
Q: Iterate recursion (in a Python Tree) I've written a Tree class in Python but I'm having issues creating in iterator for it I want to be able to do phonebook = MyTree() # Build up tree for node in phonebook: print "%s: %s" % (node.key(), node.data()) But it's not working (says generator object doesn't have ke...
Iterate recursion (in a Python Tree)
I've written a Tree class in Python but I'm having issues creating in iterator for it I want to be able to do phonebook = MyTree() # Build up tree for node in phonebook: print "%s: %s" % (node.key(), node.data()) But it's not working (says generator object doesn't have key() and data()). My Tree class's __iter__ ...
[ "Try changing\nif curr.left is not None and curr.left is not TreeNode.NULL:\n yield self._next(curr.left)\n\nyield curr\n\nif curr.right is not None and curr.right is not TreeNode.NULL:\n yield self._next(curr.right) \n\ninto\nif curr.left is not None and curr.left is not TreeNode.NULL:\n for x in self._...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004463015_python.txt
Q: Using pyodbc, and html.py to generate a table I just started to play around with python, and i really like it. I am able to connect to my database using pydobc and print the results. However, i need help taking the next step to placing the information in a table in a 'form' import pyodbc connection = pyodbc.connec...
Using pyodbc, and html.py to generate a table
I just started to play around with python, and i really like it. I am able to connect to my database using pydobc and print the results. However, i need help taking the next step to placing the information in a table in a 'form' import pyodbc connection = pyodbc.connect(MY STRING) cur = connection.cursor() cur.execute...
[ "So if you're running Python through IDLE and you're aiming at a browser view/interface. The next step is to get a development server running on your local machine. All the template engines come with cookbook instructions on how to do this. Bottle is a very simple example. \nI personally use the development serve...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004462725_python.txt
Q: Android MonkeyRunner doesn't start Hey, im trying to start the Monkeyrunner-Example-Project with my App. When he trys to install the apk, it returns this error: device.installPackage-> 101208 13:43:52.900:S [pool-1-thread-1] [com.android.monkeyrunner.adb.AdbMonkeyDevice] Error starting command: monkey --port 12345...
Android MonkeyRunner doesn't start
Hey, im trying to start the Monkeyrunner-Example-Project with my App. When he trys to install the apk, it returns this error: device.installPackage-> 101208 13:43:52.900:S [pool-1-thread-1] [com.android.monkeyrunner.adb.AdbMonkeyDevice] Error starting command: monkey --port 12345 101208 13:43:52.900:S [pool-1-thread-1]...
[ "Take a look at the monkeyrunner fails for emulator: Error starting command: monkey --port 12345 thread from the Android Developers group. It should point you in the right direction for both issues. \nIf you still require assistance, please provide more details (ex. show your Python script).\n" ]
[ 1 ]
[]
[]
[ "android", "monkeyrunner", "python" ]
stackoverflow_0004387869_android_monkeyrunner_python.txt
Q: Python - run external script Does someone know if I have a script one.py which is written the following way: if __name__ == '__main__': # Do something And I want to call that main function from another script. How should I do that? I guess it would be something like (let's say this is launcher.py) # 'one' sta...
Python - run external script
Does someone know if I have a script one.py which is written the following way: if __name__ == '__main__': # Do something And I want to call that main function from another script. How should I do that? I guess it would be something like (let's say this is launcher.py) # 'one' stands for import from `one.py` modul...
[ "Define your script like:\ndef main():\n # Do something\n\nif __name__ == '__main__':\n # Processing of possible input parameters here and passing to main\n main()\n\nThen you can do\n# 'one' stands for import from `one.py` module\nimport one\n\nif __name__ == '__main__':\n one.main()\n\nOf course you c...
[ 8, 1 ]
[]
[]
[ "program_entry_point", "python" ]
stackoverflow_0004463639_program_entry_point_python.txt
Q: How to run Python nose tests with a different version of Python We have CentOS with the ancient Python 2.4 interpreter. But we would like to write out tests with a newer 2.5/2.6 syntax. Assuming we have a second Python interpreter installed (e.g. python2.6) is there any way to run the 'nosetests' shell command and...
How to run Python nose tests with a different version of Python
We have CentOS with the ancient Python 2.4 interpreter. But we would like to write out tests with a newer 2.5/2.6 syntax. Assuming we have a second Python interpreter installed (e.g. python2.6) is there any way to run the 'nosetests' shell command and tell it to use a specific python interpreter instead of the default ...
[ "The nosetests file is in Python, so it should just be a matter of running it in your new version. Find where the file is:\nwhich nosetests\n\nThen:\npython2.6 /usr/bin/nosetests\n\nAdjusting the name and path to match your system. I've not tested, but that should work.\n", "Well, what I'd do is to install a diff...
[ 21, 4 ]
[]
[]
[ "centos", "nose", "python", "unit_testing" ]
stackoverflow_0004463240_centos_nose_python_unit_testing.txt
Q: PyObjC + Python 3.0 Questions By default, a Cocoa-Python application uses the default Python runtime which is version 2.5. How can I configure my Xcode project so that it would use the newer Python 3.0 runtime? I tried replacing the Python.framework included in the project with the newer version but it did not wor...
PyObjC + Python 3.0 Questions
By default, a Cocoa-Python application uses the default Python runtime which is version 2.5. How can I configure my Xcode project so that it would use the newer Python 3.0 runtime? I tried replacing the Python.framework included in the project with the newer version but it did not work. And another thing, are PyObjc mo...
[ "PyObjC does not yet work with Python 3.0. According to Ronald Oussoren, a (the?) PyObjC developer, Python 3.0 support is possible, but not yet implemented:\n\nSupport for Python 3.x is on my todo\n list but is non-trivial to achieve.\n PyObjC contains a large amount of\n pretty low-level C code, getting the\n ...
[ 9, 2 ]
[]
[]
[ "cocoa", "pyobjc", "python", "xcode" ]
stackoverflow_0000666148_cocoa_pyobjc_python_xcode.txt
Q: Best practice for pylons app global tmpl_context settings? I'm writing a pylons application, and I'm wondering if there is a best practice for where to set some application specific values of the template context object (tmpl_context)? Currently, I've added a __before__() method to the BaseController and am settin...
Best practice for pylons app global tmpl_context settings?
I'm writing a pylons application, and I'm wondering if there is a best practice for where to set some application specific values of the template context object (tmpl_context)? Currently, I've added a __before__() method to the BaseController and am setting up the tmpl_context object with values there but am wondering ...
[ "I think the BaseController is a good place to put that, either in __call__() or in __before__().\n", "a __before__ method is a right place to do it.\n" ]
[ 0, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0004425137_pylons_python.txt
Q: Value too large for defined data type I am reading data from a special device that is producing around 20 MB/s /dev/dvb/adapter0/dvr0 I need to read the contents and copy to other fifos device_fd = os.open(video_device_file, os.O_RDONLY) while True: if jobm.has_jobs(): chunk = os.read(...
Value too large for defined data type
I am reading data from a special device that is producing around 20 MB/s /dev/dvb/adapter0/dvr0 I need to read the contents and copy to other fifos device_fd = os.open(video_device_file, os.O_RDONLY) while True: if jobm.has_jobs(): chunk = os.read( device_fd, 1024 * 1000 ) fifo...
[ "I don't know what your jobm object is, I assume it's created by you because this is the only Google result for a similar object, so correct me if I'm wrong.\nYou seem to be opening the video device for reading, the video device is constantly producing video data, and instead of reading it, you're idling. You don't...
[ 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0004463975_linux_python.txt
Q: Python: Combine "if 'x' in dict" and "for i in dict['x']" Really two questions: If I have a dictionary (that originally came from parsing a json message) that has an optional array in it: dict_with = {'name':'bob','city':'san francisco','kids': {'name': 'alice'} } dict_without = {'name':'bob','city':'san francisc...
Python: Combine "if 'x' in dict" and "for i in dict['x']"
Really two questions: If I have a dictionary (that originally came from parsing a json message) that has an optional array in it: dict_with = {'name':'bob','city':'san francisco','kids': {'name': 'alice'} } dict_without = {'name':'bob','city':'san francisco' } I would normally have code like: if 'kids' in dict: fo...
[ "for x in d.get(\"kids\", ()):\n print \"kid:\", x\n\n", "An empty sequence results in no iteration.\nfor k in D.get('kids', ()):\n\n", "[x for x in dict_with.get('kids')], You can use this filter, map - a functional programming tools with the list comprehension.\n\nlist comprehension are more concise to wri...
[ 10, 7, 4 ]
[]
[]
[ "json", "python" ]
stackoverflow_0004464274_json_python.txt
Q: Do a mass db.delete on App Engine, without eating CPU We've got a reasonably-sized database on Google App Engine - just over 50,000 entities - that we want to clear out stale data from. The plan was to write a deferred task to iterate over the entities we no longer wanted, and delete them in batches. One complicat...
Do a mass db.delete on App Engine, without eating CPU
We've got a reasonably-sized database on Google App Engine - just over 50,000 entities - that we want to clear out stale data from. The plan was to write a deferred task to iterate over the entities we no longer wanted, and delete them in batches. One complication is that our entities also have child entities that we a...
[ "We recently added a bulk-delete handler, documented here. It takes the most efficient possible approach to bulk deletion, though it still consumes CPU quota.\n", "If you want to spread out the CPU burn, you could create a map reduce job. It will still iterate over every entity (this is a current limitation of th...
[ 2, 1 ]
[]
[]
[ "bigtable", "cpu_usage", "google_app_engine", "python" ]
stackoverflow_0004448123_bigtable_cpu_usage_google_app_engine_python.txt
Q: Twisted - should this code be run in separate threads I am running some code that has X workers, each worker pulling tasks from a queue every second. For this I use twisted's task.LoopingCall() function. Each worker fulfills its request (scrape some data) and then pushes the response back to another queue. All thi...
Twisted - should this code be run in separate threads
I am running some code that has X workers, each worker pulling tasks from a queue every second. For this I use twisted's task.LoopingCall() function. Each worker fulfills its request (scrape some data) and then pushes the response back to another queue. All this is done in the reactor thread since I am not deferring th...
[ "No, you shouldn't use threads. You can't call LoopingCall from a thread (unless you use reactor.callFromThread), but it wouldn't help you make your code faster.\nIf you notice a performance problem, you may want to profile your workload, figure out where the CPU-intensive work is, and then put that work into mult...
[ 2, 1, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0004462678_python_twisted.txt
Q: How can I copy data from a SQL_ASCII to a UTF8 postgresql db using SQLAlchemy? I am writing a db data migration tool using SQLAlchemy's expression language as the basic tool. My source database may be in UTF8, or it may be in SQL_ASCII. My target DB will always be in UTF8. I'm using the psycopg2 driver in SQLAlche...
How can I copy data from a SQL_ASCII to a UTF8 postgresql db using SQLAlchemy?
I am writing a db data migration tool using SQLAlchemy's expression language as the basic tool. My source database may be in UTF8, or it may be in SQL_ASCII. My target DB will always be in UTF8. I'm using the psycopg2 driver in SQLAlchemy 0.6.6 My general migration process looks like this: for t in target_tables: l...
[ "It turns out that the solution was to set the connection client_encoding to 'latin1'\nI accomplished this using a PoolListener like so:\nclass EncodingListener(PoolListener):\n\n def connect(self, dbapi_con, con_record):\n with closing(dbapi_con.cursor()) as cur:\n cur.execute('show client_enc...
[ 1, 0 ]
[]
[]
[ "character_encoding", "postgresql", "python", "sqlalchemy", "unicode" ]
stackoverflow_0004445094_character_encoding_postgresql_python_sqlalchemy_unicode.txt
Q: Jython logging gets time wrong I have a Jython script that uses the Python logging module for logging. On one machine the script logs fine and on the other the time logged is shifted five hours into the future. Presumably this has to do with the machine being at GMT-5. What do you think can cause this issue? Here'...
Jython logging gets time wrong
I have a Jython script that uses the Python logging module for logging. On one machine the script logs fine and on the other the time logged is shifted five hours into the future. Presumably this has to do with the machine being at GMT-5. What do you think can cause this issue? Here's how I create the logging object: l...
[ "I think I found the issue. Apparently Java itself was getting the time wrong, and the reason was that the timezone was not set properly for Java on the problematic machine. export TZ='US/East' in /etc/profile.d/java.sh seems to solve the issue.\nThis took me some time to figure out because running date from the sh...
[ 1, 0, 0 ]
[]
[]
[ "jython", "logging", "python", "timestamp" ]
stackoverflow_0004463395_jython_logging_python_timestamp.txt
Q: How to stream bot sensors with pyserial? I am trying to stream an iRobot Create's sensors with pyserial. I import openinterface.py, setup the bot variable with the CreateBot function, and then call bot.stream_sensors(6) Then I receive this error - "Streaming thread error! tuple index out of range" The only reason ...
How to stream bot sensors with pyserial?
I am trying to stream an iRobot Create's sensors with pyserial. I import openinterface.py, setup the bot variable with the CreateBot function, and then call bot.stream_sensors(6) Then I receive this error - "Streaming thread error! tuple index out of range" The only reason I am calling the function with 6 is because th...
[ "Looking through the openinterface.py source, it looks like your getting the \"Illegal sensor id\" error because the given ID value you use when you call stream_sensors() doesn't match against a dictionary with known sensor ID's. The sensor ID dictionary is specified in the class SensorPacketDecoderAPI:\nclass Sens...
[ 1 ]
[]
[]
[ "pyserial", "python", "robot", "sensors" ]
stackoverflow_0004240646_pyserial_python_robot_sensors.txt
Q: alternatives to DYLD_LIBRARY_PATH/LD_LIBRARY_PATH I'm developing python C++ extensions for use in both OSX and linux. Currently, I can run my code with a wrapper script wrapper.sh: #!/bin/bash ...
alternatives to DYLD_LIBRARY_PATH/LD_LIBRARY_PATH
I'm developing python C++ extensions for use in both OSX and linux. Currently, I can run my code with a wrapper script wrapper.sh: #!/bin/bash trunk=`dirname $0` ...
[ "For python extensions, consider using PYTHONPATH: the Python interpreter will search the PYTHONPATH for .py/.pyc/.pyo/.so modules, as well as packages. See docs for Python 2.x as well as docs for Python 3.x; specifically the section named \"The Module Search Path\" on both pages. This also references information...
[ 0, 0 ]
[]
[]
[ "bash", "macos", "python", "python_c_extension" ]
stackoverflow_0004464765_bash_macos_python_python_c_extension.txt
Q: Expanding my search function I am looking at trying to expand my search function for my small project. Right now I have the ability to search using a char field but I want to add a few checkboxes. Some projects have been flagged with the SRED checkbox and I want to be able to also search for SRED only projects. ...
Expanding my search function
I am looking at trying to expand my search function for my small project. Right now I have the ability to search using a char field but I want to add a few checkboxes. Some projects have been flagged with the SRED checkbox and I want to be able to also search for SRED only projects. Here is my current search setup. m...
[ "You need to pass project to Form constructor and then add box fields if necessary:\nform = SearchProjectForm(project, request.POST)\n\nand:\nclass SearchProjectForm(forms.Form):\n text = forms.CharField(label = \"Search\")\n\n def __init__(self, project, *args, **kwargs):\n form = forms.Form.__init__(se...
[ 1 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0004464841_django_django_views_python.txt
Q: alternate different shas of the same file. why? can somebody give me a reason why i get alternate shas of the same file? but the same for every second sha? >>> f = open('480p.m4v') >>> sha1 = str(hashlib.sha224(str(f)).hexdigest()) >>> sha1 '4aa8cf11b849b77f608302fdcdad3703dce54c33ba4bac80fa0ef700' >>> f.close...
alternate different shas of the same file. why?
can somebody give me a reason why i get alternate shas of the same file? but the same for every second sha? >>> f = open('480p.m4v') >>> sha1 = str(hashlib.sha224(str(f)).hexdigest()) >>> sha1 '4aa8cf11b849b77f608302fdcdad3703dce54c33ba4bac80fa0ef700' >>> f.close() >>> f = open('480p.m4v') >>> sha2 = str(hashlib.sh...
[ "The reason you're getting different hashes is because you're not really hashing the contents of the file, only the file object's string representation. For example:\n>>> f = open('480p.m4v')\n>>> print str(f)\n<open file '480p.m4v', mode 'r' at 0x0224C9D0>\n\nYou'll note that the address of the object is obviously...
[ 8, 2, 0 ]
[]
[]
[ "python", "sha" ]
stackoverflow_0004464809_python_sha.txt
Q: Why is the return value of an empty python regexp search a match? When passing an empty string to a regular expression object, the result of a search is a match object an not None. Should it be None since there is nothing to match? import re m = re.search("", "some text") if m is None: print "Returned None" e...
Why is the return value of an empty python regexp search a match?
When passing an empty string to a regular expression object, the result of a search is a match object an not None. Should it be None since there is nothing to match? import re m = re.search("", "some text") if m is None: print "Returned None" else: print "Return a match" Incidentally, using the special symbol...
[ "Empty pattern matches any part of the string.\nCheck this:\nimport re\n\nre.search(\"\", \"ffff\")\n<_sre.SRE_Match object at 0xb7166410>\n\nre.search(\"\", \"ffff\").start()\n0\n\nre.search(\"$\", \"ffff\").start()\n4\n\nAdding $ doesn't yield the same result. Match is at the end, because it is the only place it ...
[ 12, 3, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004464955_python_regex.txt
Q: C / C++ equivalents to the Python Standard Library I depend heavily on Python's standard library, both for useful data structures and manipulators (e.g., collections and itertools) and for utilities (e.g., optparse, json, and logging), to skip the boilerplate and just Get Things Done. Looking through documentation...
C / C++ equivalents to the Python Standard Library
I depend heavily on Python's standard library, both for useful data structures and manipulators (e.g., collections and itertools) and for utilities (e.g., optparse, json, and logging), to skip the boilerplate and just Get Things Done. Looking through documentation on the C++ standard library, it seems entirely about da...
[ "The Poco library is more like other languages' standard libraries.\nActually the Poco web site's logo says \"C++ now comes with batteries included!\", which seems to be precisely what you're asking for.\nI didn't like it when I tried because I found it too C-like and with too many dependencies between parts (diffi...
[ 5, 4, 1, 1, 0 ]
[]
[]
[ "c++", "c++_standard_library", "python", "standard_library" ]
stackoverflow_0004465329_c++_c++_standard_library_python_standard_library.txt
Q: Is it possible to download packages for Win32 in zip format? Everything seems to be only available in self-extracting .exe. My company blocks executable files from being downloaded. A: Pretty close. Download the source - a .tar.gz archive, so you need something beyond window's built-in zip handling to unpack it ...
Is it possible to download packages for Win32 in zip format?
Everything seems to be only available in self-extracting .exe. My company blocks executable files from being downloaded.
[ "Pretty close. Download the source - a .tar.gz archive, so you need something beyond window's built-in zip handling to unpack it - and run python setup.py install.\n", "You could try to \"easy-install\" the package\n", "The self-extracting exe is only necessary if the package contains C-code that needs to be co...
[ 1, 1, 0, 0 ]
[]
[]
[ "package", "python" ]
stackoverflow_0004464853_package_python.txt