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: Google App Engine map static_dir to remote url I have files on a remote FTP server that are accessible over web. My mate developer works with static files to build a frontend for our project - he works with JS/CSS/HTML etc. Then he uploads the files to FTP server. Now these files are accessible over web standard w...
Google App Engine map static_dir to remote url
I have files on a remote FTP server that are accessible over web. My mate developer works with static files to build a frontend for our project - he works with JS/CSS/HTML etc. Then he uploads the files to FTP server. Now these files are accessible over web standard way. Is that possible for us to setup GAE app the way...
[ "NO, you can't declare a remote static_dir in app.yaml .\nWhat you and your friend would probably want is a remote source code repository using git or mercurial; have a look to github for a free hosting solution for example. \n" ]
[ 3 ]
[]
[]
[ "ftp", "google_app_engine", "python" ]
stackoverflow_0005040448_ftp_google_app_engine_python.txt
Q: ElementTree XPath strange behaviour Hi I'm using ElementTree (1.3) with Python 2.7 and enjoy XPath functionality, however one of search results surprised me. My XML example: <OTF> <FECS state="disabled" version="2.2.0.0"> <BackEndCompatibility major="2.2" state="disabled"> <BackEnd state="disabled"...
ElementTree XPath strange behaviour
Hi I'm using ElementTree (1.3) with Python 2.7 and enjoy XPath functionality, however one of search results surprised me. My XML example: <OTF> <FECS state="disabled" version="2.2.0.0"> <BackEndCompatibility major="2.2" state="disabled"> <BackEnd state="disabled" version="2.2.0.0"/> </BackEndCompati...
[ "For question No1:\nWhen I replaced lines \n found = list(txml.findall(\".//BackEnd[@version='%s']\" % version))\n return found and found[0] or None\n\nwith\n found = txml.findall(\".//BackEnd[@version='%s']\" % version)\n if found:\n return found[0]\n return None\n\nthen correct result is re...
[ 1 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0005019001_elementtree_python_xml.txt
Q: Controlling Python application with C# Hey, This issue was addressed before but not in this angle. I'm trying to control a Python application with C#. The application runs an unknown time and I need to hold the main C# application form until It "knows" when the Python application is done processing. I should mark...
Controlling Python application with C#
Hey, This issue was addressed before but not in this angle. I'm trying to control a Python application with C#. The application runs an unknown time and I need to hold the main C# application form until It "knows" when the Python application is done processing. I should mark that the Python Application has its own GUI...
[ "Redirect stdin and the push characters in that way (rather than sendkeys)?\n", "Have you looked into IronPython - it allows you to execute python code from within you .NET application natively.\n", "SendKeys can only send keystrokes to the active application. Since you are forcing it to start without creating ...
[ 1, 0, 0 ]
[]
[]
[ "c#", "python", "user_interface" ]
stackoverflow_0005035891_c#_python_user_interface.txt
Q: Tracking Django/FastCGI Process Errors I run a Django based site on Nginx with FastCGI server. The site generally works great. But every 2-3 days, the site run into unknown problem and stop responding to any requests. Munin graphs shows IO blocks read & write per second increases 500% during the problem. I also wr...
Tracking Django/FastCGI Process Errors
I run a Django based site on Nginx with FastCGI server. The site generally works great. But every 2-3 days, the site run into unknown problem and stop responding to any requests. Munin graphs shows IO blocks read & write per second increases 500% during the problem. I also wrote a python script to record the the follow...
[ "You've limited the number of children to 25 so when there are 25 processes running and processing requests any further ones will block and the site will appear to not be responding.\nIt sounds to me like you have an infinite (or very long) loop that is causing the processes to block. I suggest you add an idle-time...
[ 1 ]
[]
[]
[ "django", "fastcgi", "python" ]
stackoverflow_0005041678_django_fastcgi_python.txt
Q: Python socket doesn't close connection properly I am new to socket programming and ran into a puzzling problem: I have a windows program which I cannot alter (proprietary software) but which tries to connect to a specific ip and port with a tcp socket. On my linux box I wrote a little python script to serve the so...
Python socket doesn't close connection properly
I am new to socket programming and ran into a puzzling problem: I have a windows program which I cannot alter (proprietary software) but which tries to connect to a specific ip and port with a tcp socket. On my linux box I wrote a little python script to serve the socket to the win prog. This works fine until I kill my...
[ "You are experiencing the TIME_WAIT state of connected sockets. Even though you've closed your socket, it still has lingering consequences for a couple minutes. The reasons for this, as well as a socket flag you can set to disable the behavior (SO_REUSEADDR), are explained in the UNIX guide socket FAQ.\nIn short,...
[ 33, 2 ]
[]
[]
[ "linux", "networking", "python", "sockets", "windows" ]
stackoverflow_0005040491_linux_networking_python_sockets_windows.txt
Q: asp.net in IronPython, speed execution of code, first time vs second time differences I'm observing this behavior, when I run the same code for the second time with different parameters in webforms with IronPython, it runs quite faster. I thought first this had to do with asp.net temporary files, but when I restar...
asp.net in IronPython, speed execution of code, first time vs second time differences
I'm observing this behavior, when I run the same code for the second time with different parameters in webforms with IronPython, it runs quite faster. I thought first this had to do with asp.net temporary files, but when I restart the server it gets slow for the first time again. It's quite a code it has to run so it's...
[ "I do not do a lot of work with .NET or IronPython, so this might be widely off the mark, but why not just precompile your files using the aspnet_compiler.exe before you redeploy?\n" ]
[ 0 ]
[]
[]
[ "asp.net", "ironpython", "python", "webforms" ]
stackoverflow_0005041892_asp.net_ironpython_python_webforms.txt
Q: How do I enable transactional DDL in pysqlite? I am using pysqlite which, by default, does not enable transactional DDL (although DDL is transactional from the sqlite3 client). How do I enable transactional DDL within pysqlite? A: pysqlite always performs an implicit commit unless the lowercased query string sta...
How do I enable transactional DDL in pysqlite?
I am using pysqlite which, by default, does not enable transactional DDL (although DDL is transactional from the sqlite3 client). How do I enable transactional DDL within pysqlite?
[ "pysqlite always performs an implicit commit unless the lowercased query string starts with optional whitespace and one of 'select', 'insert', 'update' , 'delete', or 'replace'. There is no elegant way to turn this off. To work around this, you could edit the pysqlite C source code.\n" ]
[ 1 ]
[]
[]
[ "pysqlite", "python", "sqlite" ]
stackoverflow_0005042663_pysqlite_python_sqlite.txt
Q: libgmail login() runs with error I just installed libgmail on CentOS 5, python 2.6 with easy_install. There was a problem, until i installed mechanize manually. After that easy_install said OK and i wrote 1st test program from the sample i googled: import libgmail ga = libgmail.GmailAccount("someaccount@g...
libgmail login() runs with error
I just installed libgmail on CentOS 5, python 2.6 with easy_install. There was a problem, until i installed mechanize manually. After that easy_install said OK and i wrote 1st test program from the sample i googled: import libgmail ga = libgmail.GmailAccount("someaccount@gmail.com", "mypassword") ga.login(...
[ "libgmail is deprecated and has stopped developing, since gmail started offering imap access.\nUse imaplib or similar (twisted.mail comes to mind, example code here).\n" ]
[ 2 ]
[]
[]
[ "libgmail", "mechanize", "python" ]
stackoverflow_0005043465_libgmail_mechanize_python.txt
Q: How can I fix encoding errors in a string in python I have a python script as a subversion pre-commit hook, and I encounter some problems with UTF-8 encoded text in the submit messages. For example, if the input character is "å" the output is "?\195?\165". What would be the easiest way to replace those character p...
How can I fix encoding errors in a string in python
I have a python script as a subversion pre-commit hook, and I encounter some problems with UTF-8 encoded text in the submit messages. For example, if the input character is "å" the output is "?\195?\165". What would be the easiest way to replace those character parts with the corresponding byte values? Regexp doesn't w...
[ "I do the same things in my code and you should be able to use:\n...\nu_changed_path = unicode(changed_path, 'utf-8')\n...\nWhen using the approach above, I've only run into issues with characters like line feeds and such. If you post some code, it could help.\n" ]
[ 1 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0005043810_encoding_python.txt
Q: Converting Timestamps in Python to UNIX Timestamps from time import time time() # Gives me 1298046251.375916 I need to convert 01/01/2011 01:48:36.157 to a similar timestamp and am rather unfamiliar with Pythons date / time library. What is the easiest way to accomplish this? Is there a equivalent strtotime featu...
Converting Timestamps in Python to UNIX Timestamps
from time import time time() # Gives me 1298046251.375916 I need to convert 01/01/2011 01:48:36.157 to a similar timestamp and am rather unfamiliar with Pythons date / time library. What is the easiest way to accomplish this? Is there a equivalent strtotime feature? Considering MongoDB wants a datetime object it that...
[ "Short anwser:\n>>> datetime.datetime.strptime ?\nType: builtin_function_or_method\nBase Class: <type 'builtin_function_or_method'>\nString Form: <built-in method strptime of type object at 0xb70b3520>\nNamespace: Interactive\nDocstring:\n string, format -> new datetime parsed from a string (like time....
[ 3 ]
[]
[]
[ "datetime", "mongodb", "parsing", "python" ]
stackoverflow_0005043834_datetime_mongodb_parsing_python.txt
Q: unicode string formatting I just saw this in a piece of uncommented code. Is there ever a reason to do this? new_var = u'%s' % (child.tag) where child is an instance and tag is an attribute of that instance? It seems like this does it more simply: new_var = unicode(child.tag) A: They are identical, and it's...
unicode string formatting
I just saw this in a piece of uncommented code. Is there ever a reason to do this? new_var = u'%s' % (child.tag) where child is an instance and tag is an attribute of that instance? It seems like this does it more simply: new_var = unicode(child.tag)
[ "They are identical, and it's just a matter of preference. In terms of the Zen of Python and such, there's really not a \"better\" way as both are explicit in that they are getting a unicode representation of child.tag. Mechanically they do the same thing:\n>>> class foo(object):\n def __init__(self, val):\n ...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005043730_python.txt
Q: Is it more efficient to create a dictionary in python using zip or a list comprehension? Lets say I want to set up a basic text encoding using a dictionary in python. Two ways of doing this come to mind immediately - using zip, and using list comprehension. characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ .,!;" dict_a = d...
Is it more efficient to create a dictionary in python using zip or a list comprehension?
Lets say I want to set up a basic text encoding using a dictionary in python. Two ways of doing this come to mind immediately - using zip, and using list comprehension. characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ .,!;" dict_a = dict((x, characters[x]) for x in xrange(0, 31)) dict_b = dict(zip(xrange(0, 31), characters)) ...
[ "The enumerate function is probably the easiest way to create your dict:\ndict_c = dict(enumerate(characters))\n\nHowever, I'm not sure what that gives you that you can't do with the string. The following seem equivalent to me:\n>>> dict_c[3]\n'D'\n>>> characters[3]\n'D'\n\n" ]
[ 7 ]
[]
[]
[ "dictionary", "list_comprehension", "optimization", "python", "zip" ]
stackoverflow_0005043912_dictionary_list_comprehension_optimization_python_zip.txt
Q: "from x import y as z" vs. "import x.y as z" I'm assuming they are functionally the same, bar some negligible under-the-hood differences. If so, which form is more Pythonic? A: The x.y form makes it implicit that packages and modules are involved, and should be the preferred form when that is the case. If t is a...
"from x import y as z" vs. "import x.y as z"
I'm assuming they are functionally the same, bar some negligible under-the-hood differences. If so, which form is more Pythonic?
[ "The x.y form makes it implicit that packages and modules are involved, and should be the preferred form when that is the case.\nIf t is a symbol defined in module y, then:\n>>> from x.y import t as z\n>>>\n\n...but!\n>>> import x.y.t as z\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>...
[ 8 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0005028366_python_python_import.txt
Q: Subprocess.Popen behaves differently in interpreter, executable scripts Let's say you have the following: command = shlex.split("mcf -o -q -e -w %s %s" % (SOLFILE, NETFILE)) task = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = task.communicate() print "stdout: %s" % std...
Subprocess.Popen behaves differently in interpreter, executable scripts
Let's say you have the following: command = shlex.split("mcf -o -q -e -w %s %s" % (SOLFILE, NETFILE)) task = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = task.communicate() print "stdout: %s" % stdout #debugging print "stderr: %s" % stderr #debugging if stderr: sys.exit...
[ "I wrote a little test script to test the subprocess module with.\n#!/bin/bash\n\necho echo to stderr 1>&2\necho echo to stdout\n\nThen I wrote a small Python script that calls it:\n#!/usr/bin/python\n\nimport subprocess\n\ncommand = ('./joe.sh',)\ntask = subprocess.Popen(command, stdout=subprocess.PIPE,\n ...
[ 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0005043857_python_subprocess.txt
Q: extending an image with Python Imaging Library I am trying to increase the height of an image using PIL but I don't want the image to be resized; I actually want a strip of blank pixels at the bottom of the image. Any way of doing this with PIL? I guess one way would be to make a new image of the required size and...
extending an image with Python Imaging Library
I am trying to increase the height of an image using PIL but I don't want the image to be resized; I actually want a strip of blank pixels at the bottom of the image. Any way of doing this with PIL? I guess one way would be to make a new image of the required size and copy the old image into it but I can't seem to find...
[ "Oops, just realized you can do image.crop() and it will resize the image for you.\n" ]
[ 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0005044083_python_python_imaging_library.txt
Q: Does someone run YUI3 uploader with Django successfully? I'm trying to use YUI3 uploader with Django backend. However, after write a simple uploader in the frontend, I found the function in views.py has never been invoke in Django. And, I didn't see any error message or warning in the browser and backend log.. I d...
Does someone run YUI3 uploader with Django successfully?
I'm trying to use YUI3 uploader with Django backend. However, after write a simple uploader in the frontend, I found the function in views.py has never been invoke in Django. And, I didn't see any error message or warning in the browser and backend log.. I did return the corresponding crossdomain.xml when the uploader ...
[ "HTML Fragment:\n<head>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{ MEDIA_URL }}photos/css/upload.css\" />\n<script type=\"text/javascript\" src=\"{{ MEDIA_URL }}js/lib/yui.min.js\"></script>\n<script type=\"text/javascript\" src=\"{{ MEDIA_URL }}photos/js/upload.js\"></script>\n<script type=\"text/javasc...
[ 0 ]
[]
[]
[ "django", "javascript", "python", "uploader", "yui" ]
stackoverflow_0005037556_django_javascript_python_uploader_yui.txt
Q: convert attributes of an object to a string in python I have a list of of objects defined by class Track(object): def __init__(self, title, artist, album, source, dest): self.title = title self.artist = artist self.album = album self.source = source self.dest = dest On a gui I have a button...
convert attributes of an object to a string in python
I have a list of of objects defined by class Track(object): def __init__(self, title, artist, album, source, dest): self.title = title self.artist = artist self.album = album self.source = source self.dest = dest On a gui I have a button that I tied to an event. The output is supposed to print ...
[ "You'll want to override the __str__ and/or __unicode__ special methods for your custom class.\nclass Track(object):\n ...\n def __str__(self):\n return \"'%s' by %s on the album '%s'\\nSource: %s\\nDest: %s\" % \\\n (self.title, self.artist, self.album, self.source, self.dest)\n def __un...
[ 1 ]
[ "Maybe \ndef onPrintBtn(self, event):\n print \"onPrintBtn\"\n\n for track in self.TrackOlv:\n print(repr(track))\n\n??\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0005044065_python.txt
Q: Python script to change resolv.conf [Permission issue] Hey everybody, I am just newbie at Python. I wanted to write a script in Python to change DNS. But I learned that resolv.conf is read-only file, after writing that code. Because I took that error: IOError: [Errno 13] Permission denied: '/etc/resolv.conf' myFi...
Python script to change resolv.conf [Permission issue]
Hey everybody, I am just newbie at Python. I wanted to write a script in Python to change DNS. But I learned that resolv.conf is read-only file, after writing that code. Because I took that error: IOError: [Errno 13] Permission denied: '/etc/resolv.conf' myFile= open("/etc/resolv.conf", "w") Then, I made a little sea...
[ "/etc/resolv.conf is typically owned by root. Unless your script is run in such a way that it has root privileges, it won't be able to change the file.\n", "Chmod you must run as root before your script. And when you get permissions, your script will run without errors\n", "You should never allow for a file lik...
[ 6, 0, 0 ]
[]
[]
[ "chmod", "file_io", "python" ]
stackoverflow_0005040603_chmod_file_io_python.txt
Q: How pass an argument as method of a module Hi I want call f('append','more','arguments',a=1,b=2) but append is a method(function) of pyquery module so arg[0] is my method I want make e.arg[0]('<div id="cool"></div>') run like e.append('<div id="cool"></div>') -- so I want pass "append" as argument import...
How pass an argument as method of a module
Hi I want call f('append','more','arguments',a=1,b=2) but append is a method(function) of pyquery module so arg[0] is my method I want make e.arg[0]('<div id="cool"></div>') run like e.append('<div id="cool"></div>') -- so I want pass "append" as argument import pyquery d = pq('<div id="guido"></div>') ...
[ "I would recommend against passing method names around in strings if you can avoid it (pass a reference to the method itself instead), but if you can't, what you want is getattr(), a function that gets an attribute of an object by a name contained in a string. This will let you get a reference to the desired method...
[ 4, 1 ]
[]
[]
[ "argument_passing", "python" ]
stackoverflow_0005044124_argument_passing_python.txt
Q: Python string.split more than one value in for loop Basically this works fine: >>> x,y = "x=y".split("=") >>> print x x But this gives an error: >>> for x, y in "x=y".split("="): ... print x ... Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 1 value to unp...
Python string.split more than one value in for loop
Basically this works fine: >>> x,y = "x=y".split("=") >>> print x x But this gives an error: >>> for x, y in "x=y".split("="): ... print x ... Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 1 value to unpack I am wondering what the difference is, and how I cou...
[ "Split on \"=\" gives you two values:\n\"x\", \"y\"\n\nThe fact that those values match your variable names is incidental. You could also do:\nx,xx = \"x=y\".split(\"=\")\n\nI suspect what you are likely planning is to take a list:\n\"foo=bar,blah=boo,etc=something\"\n\nAnd split it, for which you could do:\nfor x,...
[ 11, 3, 2, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0005044181_python_split_string.txt
Q: PyTables batch get and update I have daily stock data as an HDF5 file created using PyTables. I would like to get a group of rows, process it as an array and then write it back to disk (update rows) using PyTables. I couldn't figure out a way to do this cleanly. Could you please let me know what will be the best w...
PyTables batch get and update
I have daily stock data as an HDF5 file created using PyTables. I would like to get a group of rows, process it as an array and then write it back to disk (update rows) using PyTables. I couldn't figure out a way to do this cleanly. Could you please let me know what will be the best way to accomplish this? My data: Sy...
[ "If I understand well, the next should do what you want:\ncondition = 'Symbol == \"abcd\"'\nindices = table.getWhereList(condition) # get indices\nrows_array = table[indices] # get values\nnew_rows = compute(rows_array) # compute new values\ntable[indices] = new_rows # update the indices with new values\n\nHop...
[ 10 ]
[]
[]
[ "hdf5", "pytables", "python" ]
stackoverflow_0005037172_hdf5_pytables_python.txt
Q: Retrieving information stored in other sessions with gae-sessions I made a simple login system with gae-sessions, and I want to show a logged in user how many users are logged in and who they are. To count the number of people logged in, when I log a user in I immediately save the session to the datastore with sav...
Retrieving information stored in other sessions with gae-sessions
I made a simple login system with gae-sessions, and I want to show a logged in user how many users are logged in and who they are. To count the number of people logged in, when I log a user in I immediately save the session to the datastore with save(persist_even_if_using_cookie=True). Then I use SessionModel.all().cou...
[ "The Session object and the SessionModel are separate from each other. SessionModel only stores the contents of the session, it can't be read from like a Session object.\nI have a feeling that this is a bad idea, and you should find another way to store/retrieve the list of logged in users. This method may return ...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "session" ]
stackoverflow_0005042566_google_app_engine_python_session.txt
Q: How can I profile memory of multithread program in Python? Is there a way to profile memory of a multithread program in Python? For CPU profiling, I am using the cProfile to create seperate profiler stats for each thread and later combine them. However, I couldn't find a way to do this with memory profilers. I am...
How can I profile memory of multithread program in Python?
Is there a way to profile memory of a multithread program in Python? For CPU profiling, I am using the cProfile to create seperate profiler stats for each thread and later combine them. However, I couldn't find a way to do this with memory profilers. I am using heapy. Is there a way to combine stats in heapy like the ...
[ "If you are happy to profile objects rather than raw memory, you can use the gc.get_objects() function so you don't need a custom metaclass. In more recent Python versions, sys.getsizeof() will also let you take a shot at figuring out how much underlying memory is in use by those objects.\n", "There are ways to g...
[ 8, 3, 1 ]
[ "I've used Yappi, which I've had success with for a few special multi-threaded cases. It's got great documentation so you shouldn't have too much trouble setting it up.\nFor memory specific profiling, check out Heapy. Be warned, it may create some of the largest log files you've ever seen!\n" ]
[ -1 ]
[ "memory_profiling", "multithreading", "profiling", "python" ]
stackoverflow_0004799166_memory_profiling_multithreading_profiling_python.txt
Q: How do I count the total number of lines of files in a given directory? in python How can I use Python to count the total number of lines in the files in a given directory? A: In pseudo-code (non-executable): total_length = 0 file_list = fetch_file_list() # USE: os.walk or glob.glob depending on whether you wan...
How do I count the total number of lines of files in a given directory? in python
How can I use Python to count the total number of lines in the files in a given directory?
[ "In pseudo-code (non-executable):\ntotal_length = 0\nfile_list = fetch_file_list() \n# USE: os.walk or glob.glob depending on whether you want to filter the files.\nfor file_path in file_list:\n file_path = make_path_absolute(file_path)\n # This can be as simple as os.path.join(your_root_path, file_path)\n ...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005044547_python.txt
Q: profiling fuse-python I am currently writing a fuse using fuse-python. It's already doing what it should. However, after it's mounted for a few weeks, it's becoming noticeably slow. So I wanted to profile it. I know about a few point where it could be optimized. But these should not be the culprits. However, fuse-...
profiling fuse-python
I am currently writing a fuse using fuse-python. It's already doing what it should. However, after it's mounted for a few weeks, it's becoming noticeably slow. So I wanted to profile it. I know about a few point where it could be optimized. But these should not be the culprits. However, fuse-python hangs in an infinite...
[ "Python installs a handler that raises KeyboardInterrupt on SIGINT. If a non-default signal handler is detected when fuse's main is called, it will not replace the handler with its own, which normally calls fuse_session_exit and cleans up. After you've called fuse's main, the KeyboardInterrupt is swallowed by CFUNC...
[ 8 ]
[]
[]
[ "fuse", "profiling", "python", "signals" ]
stackoverflow_0005044375_fuse_profiling_python_signals.txt
Q: Use bash instead of sh as the shell of choice for python command namespace functions I need to use a commandline that is suited to bash style, e.g. diff x <(cat y | tail +2) However, sh -c of the above line gives an error, hence commands.getoutput of the above line fails. However, bash -c of the above does what...
Use bash instead of sh as the shell of choice for python command namespace functions
I need to use a commandline that is suited to bash style, e.g. diff x <(cat y | tail +2) However, sh -c of the above line gives an error, hence commands.getoutput of the above line fails. However, bash -c of the above does what I want to get done. Can somebody suggest how to make python use bash. I understand I can ...
[ "You can do commands.getoutput(\"bash -c 'diff x <(tail +2 y)'\"), perhaps (note that cat is unnecessary).\nHowever: commands.getoutput('tail +2 y | diff x -') doesn't require Bash.\n" ]
[ 3 ]
[]
[]
[ "bash", "python", "shell" ]
stackoverflow_0005044534_bash_python_shell.txt
Q: Designing a Django voting system without using accounts We are considering implementing a voting system (up, down votes) without using any type of credentials--no app accounts nor OpenID or anything of that sort. Concerns in order: Prevent robot votes Allow individuals under a NAT to vote without overriding/inval...
Designing a Django voting system without using accounts
We are considering implementing a voting system (up, down votes) without using any type of credentials--no app accounts nor OpenID or anything of that sort. Concerns in order: Prevent robot votes Allow individuals under a NAT to vote without overriding/invalidating someone else's vote Preventing (or, at the very least...
[ "To address your concerns:\n1: a simple Captcha would probably do the trick, if you google \"django captcha\", there are a bunch of plugins. I've never used them myself, so I can't say which is the best.\n2 & 3: Using Django's sessions addresses both of these problems - with it you could save a cookie on the user...
[ 4, 0 ]
[]
[]
[ "django", "django_authentication", "django_forms", "python", "voting" ]
stackoverflow_0005035348_django_django_authentication_django_forms_python_voting.txt
Q: What is the most performant way to store a list of Tuples in App-Engine? When storing and retrieving a datastore entity that contains a list of tuples what is the most efficient way of storing this list? When I have encountered this problem the tuples could be anything from key value pairs, to a datetime and sam...
What is the most performant way to store a list of Tuples in App-Engine?
When storing and retrieving a datastore entity that contains a list of tuples what is the most efficient way of storing this list? When I have encountered this problem the tuples could be anything from key value pairs, to a datetime and sample results, to (x, y) coordinates. The number of tuples is variable and range...
[ "I use Method 3. Blobstore may require an extra fetch, but db.BlobProperty does not. For objects where it is important that it comes out of storage exactly as it was put in I use PickleProperty (which can be found in tipfy, and some other utility libraries).\nFor objects where I just need its state stored I wrote...
[ 5 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005044653_google_app_engine_google_cloud_datastore_python.txt
Q: How to match two arrays I have two arrays A = [a, b, c, d] and B = [a1, a2, b1, b2, b3, c1, c2, c3, d1, d2, d3, d4] I want to match between the two arrays. Match Result: [a : a1, a2] [b : b1, b2, b3] [c : c1, c2, c3] [d : d1, d2, d3, d4] A: In pretty Python: di = {} for item in A: di[item] = filter(lambda ...
How to match two arrays
I have two arrays A = [a, b, c, d] and B = [a1, a2, b1, b2, b3, c1, c2, c3, d1, d2, d3, d4] I want to match between the two arrays. Match Result: [a : a1, a2] [b : b1, b2, b3] [c : c1, c2, c3] [d : d1, d2, d3, d4]
[ "In pretty Python:\ndi = {}\nfor item in A:\n di[item] = filter(lambda v: v.startswith(item), B)\n\n", "These solutions works fine both in python and IronPython.\nImperative solution:\nA = [\"a\", \"b\", \"c\", \"d\"]\nB = [\"a1\", \"a2\", \"b1\", \"b2\", \"b3\", \"c1\", \"c2\", \"c3\", \"d1\", \"d2\", \"d3\",...
[ 2, 1, 0 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0005044491_ironpython_python.txt
Q: numpy and pil reshape arrays pil to numpy conversion leads to arrays like: a = array([ [[r,g,b],[r,g,b].....[r,g,b],[r,g,b]] , [[r,g,b],[r,g,b.....]] , int8) triplets of rgb values; within rows so : a[0] = [[r,g,b],[r,g,b].....[r,g,b],[r,g,b]] = first row is there a quick way to convert such triplets numpy arr...
numpy and pil reshape arrays
pil to numpy conversion leads to arrays like: a = array([ [[r,g,b],[r,g,b].....[r,g,b],[r,g,b]] , [[r,g,b],[r,g,b.....]] , int8) triplets of rgb values; within rows so : a[0] = [[r,g,b],[r,g,b].....[r,g,b],[r,g,b]] = first row is there a quick way to convert such triplets numpy arrays back and ford to (well especia...
[ "Does a.T give you what you want?\nI'm assuming you've created your array using numpy's asarray function.\nimport Image, numpy\nim = Image.open('test.png')\na = numpy.asarray(im)\nR,G,B,A = a.T\n\nThe above will give you 4 separate 2D arrays, one for each band.\n", "ahum so answers work, i can type them... well\n...
[ 4, 0 ]
[]
[]
[ "numpy", "python", "python_imaging_library" ]
stackoverflow_0005036653_numpy_python_python_imaging_library.txt
Q: Python: how to create a function pointer with a set argument? My problem: Given the following: def foo(a,b) I am trying to call the python 'map' function while passing in a list for 'a' but use a set value for 'b.' Another relevant fact is that 'b' is user input and thus, I cannot use the syntax: def foo(a,b='def...
Python: how to create a function pointer with a set argument?
My problem: Given the following: def foo(a,b) I am trying to call the python 'map' function while passing in a list for 'a' but use a set value for 'b.' Another relevant fact is that 'b' is user input and thus, I cannot use the syntax: def foo(a,b='default value') I want my 'map' call to look like this: map(foo_wrapp...
[ "You can use functools.partial() for this purpose:\nfrom functools import partial\n\ndef f(a, b):\n return a + b\n\nx = range(10)\nprint map(partial(f, b=3), x)\n\nprints\n[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n\n", "You want something akin to currying. You can just use lambda here:\nmap(lambda x: f(x,3), a)\n\n"...
[ 7, 7, 1 ]
[]
[]
[ "function_pointers", "global_variables", "python" ]
stackoverflow_0005044633_function_pointers_global_variables_python.txt
Q: How to prevent lxml prom compacting elements? Having following Python code: >>> from lxml import etree >>> root = etree.XML("<a><b></b></a>") >>> etree.tostring(root) '<a><b/></a>' How can I force lxml to use "long" version? Like >>> etree.tostring(root) '<a><b></b></a>' A: >>> import lxml.html >>> html = lxml....
How to prevent lxml prom compacting elements?
Having following Python code: >>> from lxml import etree >>> root = etree.XML("<a><b></b></a>") >>> etree.tostring(root) '<a><b/></a>' How can I force lxml to use "long" version? Like >>> etree.tostring(root) '<a><b></b></a>'
[ ">>> import lxml.html\n>>> html = lxml.html.fromstring('<a><b></b></a>')\n>>> lxml.html.tostring(html)\n'<a><b></b></a>'\n\nMixing works as well:\n>>> from lxml import etree\n>>> import lxml.html\n>>> xml = etree.XML('<a><b/></a>')\n>>> lxml.html.tostring(xml)\n'<a><b></b></a>'\n\n", "Why do you want to? Both are...
[ 3, 2, 1 ]
[]
[]
[ "elementtree", "lxml", "python", "xml", "xml_serialization" ]
stackoverflow_0002921332_elementtree_lxml_python_xml_xml_serialization.txt
Q: Writing an image from PIL's 'Image' class into a model instance's ImageFile field I want to load an image and manipulate it using Python Imaging Library and then store it in a model's ImageField. The following outlines what I'm trying to do, minus the manipulation: #The model class DjInfo(models.Model): ...
Writing an image from PIL's 'Image' class into a model instance's ImageFile field
I want to load an image and manipulate it using Python Imaging Library and then store it in a model's ImageField. The following outlines what I'm trying to do, minus the manipulation: #The model class DjInfo(models.Model): dj_name = models.CharField(max_length=30) picture = models.ImageField(uploa...
[ "You could do this:\nimage = Image.open('test.png')\ntf = tempfile.TemporaryFile(mode='r+b')\nname = tf.name\ndel tf\nimage.save(name, 'png')\ndji=DjInfo()\ndji.picture.save('test.png', name)\n\nBut I suspect there is a better way using cStringIO or some other buffer object saving the extra step of writing a temp f...
[ -1 ]
[]
[]
[ "django", "python", "python_imaging_library" ]
stackoverflow_0005044602_django_python_python_imaging_library.txt
Q: Calculating pi in Python using geometry I'm posting this code with the hope that this community will be willing to assist me in ironing out some bugs I can't seem to be able to tackle. It's quite short, is intended to guess pi, and is not intended to replace already efficiently working approaches. This is not an a...
Calculating pi in Python using geometry
I'm posting this code with the hope that this community will be willing to assist me in ironing out some bugs I can't seem to be able to tackle. It's quite short, is intended to guess pi, and is not intended to replace already efficiently working approaches. This is not an assignment. # this code is completely broken ...
[ "# Not broken anymore, prints 3.1415559...\n\nfrom math import sqrt\n\ndef get_y(x, r):\n return sqrt((r**2.0)-(x**2.0)) # First mistake: ** is exponentiation, not ^\n\ndef get_distance(x1, y1, x2, y2):\n return sqrt( (x2-x1)**2.0 + (y2-y1)**2.0 )\n\ndef c(r):\n # def range(b): # redundant\n # a = 0...
[ 8 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0005045660_algorithm_python.txt
Q: Django Storage Backend for S3 I'm looking for a good Django custom storage backend for use with Amazon S3. I've been googling around and found a lot of blog posts with code snippets or half-baked gist.github.com one-off jobs. But I can't seem to find a solid, well-tested one. Is there a widely accepted standard Am...
Django Storage Backend for S3
I'm looking for a good Django custom storage backend for use with Amazon S3. I've been googling around and found a lot of blog posts with code snippets or half-baked gist.github.com one-off jobs. But I can't seem to find a solid, well-tested one. Is there a widely accepted standard Amazon S3 Django custom storage backe...
[ "Have you checked out django-storages? I would lean towards the boto library as I have had good experiences with boto.\n" ]
[ 33 ]
[]
[]
[ "amazon_s3", "boto", "django", "python" ]
stackoverflow_0005044982_amazon_s3_boto_django_python.txt
Q: Is it a good idea to generate and store a random number as a hash value for my class? I have a class that essentially wraps a list, and lists apparently can't have hash values. My idea was to generate a random number and store that as the hash value. A: If you have two instances that are equivalent then they mu...
Is it a good idea to generate and store a random number as a hash value for my class?
I have a class that essentially wraps a list, and lists apparently can't have hash values. My idea was to generate a random number and store that as the hash value.
[ "If you have two instances that are equivalent then they must return the same __hash__ value. If you generate one randomly you can't guarantee this will be the case, so you will get strange behaviour.\nCan you use a tuple instead of a list? Can you just ignore the list in the computation of the hash? It's OK if non...
[ 3, 1, 1, 0 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0005046877_hash_python.txt
Q: Python - do I need to learn about old style classes? I am currently learning Python 2.6.5 and I found out about old style classes and new style classes. I understand that these classes are still existing only for backward compatibility and that they are removed in Python 3. So the question is this: as a newcomer ...
Python - do I need to learn about old style classes?
I am currently learning Python 2.6.5 and I found out about old style classes and new style classes. I understand that these classes are still existing only for backward compatibility and that they are removed in Python 3. So the question is this: as a newcomer to the language, do I need to learn about the classic clas...
[ "No. Don't bother. Simply inherit all your classes from object (or from classes that inherit from object) and you will be good to go. Then when you transition to Python 3 you can forget that bit of syntax.\nThere's no advantage to using or even learning about old-style classes at this point.\nSo just make sure a...
[ 13, 4 ]
[]
[]
[ "class", "language_features", "python", "types" ]
stackoverflow_0005046903_class_language_features_python_types.txt
Q: Python - Remove a row from numpy array? Hi all what I wan't should be really simple for somebody here..I want to remove a row from a numpy array in a loop like: for i in range(len(self.Finalweight)): if self.Finalweight[i] >= self.cutoffOutliers: "remove line[i from self.wData" I'm trying to r...
Python - Remove a row from numpy array?
Hi all what I wan't should be really simple for somebody here..I want to remove a row from a numpy array in a loop like: for i in range(len(self.Finalweight)): if self.Finalweight[i] >= self.cutoffOutliers: "remove line[i from self.wData" I'm trying to remove outliers from a dataset. My full code o...
[ "There is actually a tool in NumPy specifically made to mask out outliers and invalid data points: masked arrays. Example from the linked page:\nx = numpy.array([1, 2, 3, -1, 5])\nmx = numpy.ma.masked_array(x, mask=[0, 0, 0, 1, 0])\nprint mx.mean()\n\nprints\n2.75\n\n" ]
[ 2 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0005045511_arrays_numpy_python.txt
Q: Attaching debugger to python script running on apache I'm very new to this and am not sure if this is feasible. All the requests for a specific file format to apache are redirected to a python script. Based on certain conditions, this script generates the output and returns that to the client. I am using Eclipse +...
Attaching debugger to python script running on apache
I'm very new to this and am not sure if this is feasible. All the requests for a specific file format to apache are redirected to a python script. Based on certain conditions, this script generates the output and returns that to the client. I am using Eclipse + Pydev as my IDE. Once I make changes to the script, I uplo...
[ "What about remote debugging in PyDev\nIt is not exactly what you requested; you were talking about attaching to a process, while with remote debugging, you have the process connecting to your debugging server.\nThat said, I have been using this feature a lot to debug scripts running in apache / mod_python, and it ...
[ 1 ]
[]
[]
[ "apache", "apache2", "python", "remote_debugging" ]
stackoverflow_0005047200_apache_apache2_python_remote_debugging.txt
Q: Django/PIL Error - Caught an exception while rendering: The _imagingft C module is not installed I'm trying to run a webapp/site on my machine, it's running on OSX 10.6.2 and I'm having some problems: Caught an exeption while rending: The _imagingft C module is not installed Doing import _imagingft in python give...
Django/PIL Error - Caught an exception while rendering: The _imagingft C module is not installed
I'm trying to run a webapp/site on my machine, it's running on OSX 10.6.2 and I'm having some problems: Caught an exeption while rending: The _imagingft C module is not installed Doing import _imagingft in python gives me this: >>> import _imagingft Traceback (most recent call last): File "<stdin>", line 1, in <modul...
[ "Before (re)installing PIL add the following sysmlinks to enable freetype on Mac 10.6 Snow Leopard:\nln -s /usr/X11/include/freetype2 /usr/local/include/\nln -s /usr/X11/include/ft2build.h /usr/local/include/\nln -s /usr/X11/lib/libfreetype.6.dylib /usr/local/lib/\nln -s /usr/X11/lib/libfreetype.6.dylib /usr/local/...
[ 9, 3, 2, 1, 0 ]
[]
[]
[ "django", "macos", "python", "python_imaging_library" ]
stackoverflow_0002478123_django_macos_python_python_imaging_library.txt
Q: How do I build a python string from a raw (binary) ctype buffer? I'm playing with Python and ctypes and I can't figure out how to resolve this problem. I call to a C function which fills a raw binary data. My code looks like this: class Client(): def __init__(self): self.__BUFSIZE = 1024*1024 self.__buf...
How do I build a python string from a raw (binary) ctype buffer?
I'm playing with Python and ctypes and I can't figure out how to resolve this problem. I call to a C function which fills a raw binary data. My code looks like this: class Client(): def __init__(self): self.__BUFSIZE = 1024*1024 self.__buf = ctypes.create_string_buffer(self.__BUFSIZE) self.client = ctype...
[ "You can access a buffer returned by create_string_buffer() as a Python string by using its raw attribute:\na = ctypes.create_string_buffer(10)\na.raw \n# '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n\nTo only access the first n bytes, use\na.raw[:n]\n\n" ]
[ 8 ]
[]
[]
[ "ctypes", "python", "string" ]
stackoverflow_0005047536_ctypes_python_string.txt
Q: Check version of Python library that doesn't define __version__ I'm dealing with a Python library that does not define the __version__ variable (sqlalchemy-migrate), and I want to have different behavior in my code based on what version of the library I have installed. Is there a way to check at runtime what vers...
Check version of Python library that doesn't define __version__
I'm dealing with a Python library that does not define the __version__ variable (sqlalchemy-migrate), and I want to have different behavior in my code based on what version of the library I have installed. Is there a way to check at runtime what version of the library is installed (other than, say, checking the output...
[ "This being Python, the accepted way of doing this is generally to call something in the library that behaves differently depending on the version you have installed, something like:\nimport somelibrary\ntry:\n somelibrary.this_only_exists_in_11()\n SOME_LIBRARY_VERSION = 1.1\nexcept AttributeError:\n SOME...
[ 4, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004996647_python.txt
Q: Python Function Argument I am having two issues with my code - I am not sure how to link my populateArray function with my main function; I'm not sure what argument I need to pass Also, I have been having trouble with the file path of the file to be opened - the path is correct and the file exists with data in. He...
Python Function Argument
I am having two issues with my code - I am not sure how to link my populateArray function with my main function; I'm not sure what argument I need to pass Also, I have been having trouble with the file path of the file to be opened - the path is correct and the file exists with data in. Here is my code: network = [] ...
[ "Remove def main():, just have it as:\nif __name__ == \"__main__\":\n populateArray()\n\nMake sure to indent your program properly after you remove the def stmt.\nYou can also refer to your file name directly, if you are in the same directory.\n", "The path of the file to be opened is relative to the where your...
[ 5, 1, 0, 0 ]
[ "If you want to populate, as I guess, the \"network\" list (not \"array\"!) in the global scope, you need to bring it global.\ndef populateArray():\n global network\n # The rest of the function code goes here\n\nBut, i'd rather do something like:\nnetwork = populateArray()\n\nand make populateArray() return t...
[ -1 ]
[ "python" ]
stackoverflow_0005036012_python.txt
Q: Pythonic way of setting a default Is there a simple way of of setting a default in python - specifically setting a default in a dict? For instance, let's say I have a dict called foo, which may or may not have something assigned on the key bar. The verbose way of doing this is: if not foo.has_key('bar'): foo['ba...
Pythonic way of setting a default
Is there a simple way of of setting a default in python - specifically setting a default in a dict? For instance, let's say I have a dict called foo, which may or may not have something assigned on the key bar. The verbose way of doing this is: if not foo.has_key('bar'): foo['bar'] = 123 One alternative would be: fo...
[ "Doesn't anyone read the documentation?\nfoo.setdefault('bar', 123)\n\n", "You could check out defaultdict\n", "(Wrong first part of the answer edited away)\nDicts have a setdefault() method that works just as get(), only it inserts the value if the key was missing.\nfoo.setdefault('bar', 123)\n\nCheers.\n" ]
[ 5, 3, 1 ]
[]
[]
[ "default_value", "python" ]
stackoverflow_0005048019_default_value_python.txt
Q: Properly handling a keyPressEvent in a Subclassed PyQT LineEdit So I have a QLineEdit that I want to catch a shift keypress in. Here's my code: class NoteText(QtGui.QLineEdit): def __init__(self, parent): super (NoteText, self).__init__(parent) def keyPressEvent(self, event): if (event.mo...
Properly handling a keyPressEvent in a Subclassed PyQT LineEdit
So I have a QLineEdit that I want to catch a shift keypress in. Here's my code: class NoteText(QtGui.QLineEdit): def __init__(self, parent): super (NoteText, self).__init__(parent) def keyPressEvent(self, event): if (event.modifiers() & QtCore.Qt.ShiftModifier): self.shift = True ...
[ "I guess you want the default behavior of the overridden keyPressEvent method you should call the base class implementation, smth like this:\ndef keyPressEvent(self, event):\n if (event.modifiers() & QtCore.Qt.ShiftModifier):\n self.shift = True\n print 'Shift!'\n # call base class keyPressEvent...
[ 6 ]
[]
[]
[ "pyqt", "python", "subclassing" ]
stackoverflow_0005047558_pyqt_python_subclassing.txt
Q: How to import modules into web.py templates? I have following piece of code: render = web.template.render('templates/') app = web.application(urls, globals()) I read about template imports in the web.py cookbook. Now, when I try to import re in a template: render = web.template.render('templates/', globals={'re':...
How to import modules into web.py templates?
I have following piece of code: render = web.template.render('templates/') app = web.application(urls, globals()) I read about template imports in the web.py cookbook. Now, when I try to import re in a template: render = web.template.render('templates/', globals={'re':re}) app = web.application(urls, globals()) I got...
[ "I'm guessing there is something else you are doing in your script or template that is causing that error. If you showed the complete example, then it would be easier to see. Here is a working example:\nimport web\nimport re\n\nurls = ('/', 'index')\nrender = web.template.render('templates/', globals={'re':re})\nap...
[ 5 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0005047009_python_web.py.txt
Q: editing a single .txt line in python 3.1 i have some data stored in a .txt file in this format: ----------|||||||||||||||||||||||||-----------||||||||||| 1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943 1020414646canBeFollowedBySpaces 3292532113435532419963 don't ask... i have many lines of this, and ...
editing a single .txt line in python 3.1
i have some data stored in a .txt file in this format: ----------|||||||||||||||||||||||||-----------||||||||||| 1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943 1020414646canBeFollowedBySpaces 3292532113435532419963 don't ask... i have many lines of this, and i need a way to add more digits to the end of ...
[ "As a general principle, there's no shortcut to \"inserting\" new data in the middle of a text file. You will need to make a copy of the entire original file in a new file, modifying your desired line(s) of text on the way.\nFor example:\nwith open(\"input.txt\") as infile:\n with open(\"output.txt\", \"w\") as ...
[ 6, 4, 2, 0 ]
[]
[]
[ "line", "python", "python_3.x", "text", "text_files" ]
stackoverflow_0005048217_line_python_python_3.x_text_text_files.txt
Q: Check if current process is running using Python? I need to add a function to my python script that checks if the current script is already running. If it is then it will quit, if not it continues running the script. I've looked into methods of doing this but I cant figure out how to do it. A: I think you mean "...
Check if current process is running using Python?
I need to add a function to my python script that checks if the current script is already running. If it is then it will quit, if not it continues running the script. I've looked into methods of doing this but I cant figure out how to do it.
[ "I think you mean \"cross-platform single instance of application written in python\". Try this workable solution: Python: single instance of program\n", "You need to communicate using a shared resource. In the simplest sense, you use the resource as a mutex. Lock or pid files are commonly used this way on *nix...
[ 9, 1 ]
[]
[]
[ "process", "python" ]
stackoverflow_0005048515_process_python.txt
Q: Problem with a function in Python 2.5 - what the argument should be; if an "if" statement is appropriate; making an accumulator work I would appreciate help on this code. I'm trying to get a function to print results. The program takes random numbers and determines whether they are even or odd. That works. It ...
Problem with a function in Python 2.5 - what the argument should be; if an "if" statement is appropriate; making an accumulator work
I would appreciate help on this code. I'm trying to get a function to print results. The program takes random numbers and determines whether they are even or odd. That works. It is supposed to then give a tally of how many numbers are odd and how many are even. I'm trying to build that into the "tally_status_count...
[ "import random\n\ndef main():\n even_total = 0\n odd_total = 0\n\n for i in xrange(10):\n nbr = random.randint(1,10)\n if nbr % 2 == 0:\n even_total += 1\n else:\n odd_total += 1\n\n print 'even total', even_total\n print 'odd total', odd_total\n\nif __name_...
[ 1, 1 ]
[]
[]
[ "accumulator", "function", "python" ]
stackoverflow_0005048675_accumulator_function_python.txt
Q: python-constraint: setting a constraint dependent on a function's output I've been making a system that takes in data about drivers, potential passengers and their locations, and attempts to optimise the number of passengers that can get a lift with a driver given some constraints. I am using the python-constraint...
python-constraint: setting a constraint dependent on a function's output
I've been making a system that takes in data about drivers, potential passengers and their locations, and attempts to optimise the number of passengers that can get a lift with a driver given some constraints. I am using the python-constraint module, and the decision variables are represented thusly: p = [(passenger, d...
[ "The lambda form in Python provides a way to create anonymous (nameless) functions. The following two definitions are equivalent:\nname = lambda arguments: expression\n\ndef name(arguments):\n return expression\n\nSince the body of a lambda expression is itself an expression, the body may not contain any statem...
[ 4 ]
[]
[]
[ "constraints", "python", "shortest_path" ]
stackoverflow_0005006418_constraints_python_shortest_path.txt
Q: Beaker Cache complains TypeError Beaker cache complains a TypeError. I've searched on Google, even tracked beaker's issue tracker but couldn't find anything. I cache the queries like the following method @staticmethod def get_queries(query): @cache.cache(query, type = 'file', expire = 300) def load(query):...
Beaker Cache complains TypeError
Beaker cache complains a TypeError. I've searched on Google, even tracked beaker's issue tracker but couldn't find anything. I cache the queries like the following method @staticmethod def get_queries(query): @cache.cache(query, type = 'file', expire = 300) def load(query): entries = db.get_expensive_qu...
[ "Your code calls cache.cache with an integer for expire, which is correct, but clearly either expiretime or storedtime is winding up with a string. [From the error message it has to be expiretime. --ed] So here's what I think happened:\n(1) You called cache.cache with a string expire at some point. [Maybe even fr...
[ 0 ]
[]
[]
[ "beaker", "caching", "python" ]
stackoverflow_0005048598_beaker_caching_python.txt
Q: How to alphabetically sort array of dictionaries on single key? I want to sort the list of friends returned by Facebook's Graph API. The result after sorting needs to be an alphabetical order of friends by name. [ { "name": "Joe Smith", "id": "6500000" }, { "name": "An...
How to alphabetically sort array of dictionaries on single key?
I want to sort the list of friends returned by Facebook's Graph API. The result after sorting needs to be an alphabetical order of friends by name. [ { "name": "Joe Smith", "id": "6500000" }, { "name": "Andrew Smith", "id": "82000" }, { "name":...
[ "sorted(flist, key=lambda friend: friend[\"name\"])\n\n", "import operator\n\nsorted(my_list, key=operator.itemgetter(\"name\"))\n\nAlso, itemgetter can take a few arguments, and returns a tuple of those items, so you can sort on a number of keys like this:\nsorted(my_list, key=operator.itemgetter(\"name\", \"age...
[ 8, 4, -1 ]
[]
[]
[ "dictionary", "facebook", "list", "python", "sorting" ]
stackoverflow_0005048841_dictionary_facebook_list_python_sorting.txt
Q: Getting Started with Python YQL I want to try to use the Yahoo Fantasy Sports API for my fantasy football league, but it seems like I can only access the data if I authenticate with Yahoo. Makes sense. However, I am new to Python and have no idea how to get started. I found a python module on the web link text ...
Getting Started with Python YQL
I want to try to use the Yahoo Fantasy Sports API for my fantasy football league, but it seems like I can only access the data if I authenticate with Yahoo. Makes sense. However, I am new to Python and have no idea how to get started. I found a python module on the web link text but I don't know how to "install" a f...
[ "Just use easysinstall\n\nc:/python25/scripts/easy_install.exe yql \n\nReplace path with your computer's python path if necessary.\n" ]
[ 3 ]
[]
[]
[ "python", "yql" ]
stackoverflow_0003571952_python_yql.txt
Q: Non-blocking http server , java nio , python tornado eventlet Hi I am trying to Understand if tornado/eventlet based http sever are better than threaded sever. While goggling the subject I am seeing that these are single thread event base server which run a single handler function after select/poll/epoll on socke...
Non-blocking http server , java nio , python tornado eventlet
Hi I am trying to Understand if tornado/eventlet based http sever are better than threaded sever. While goggling the subject I am seeing that these are single thread event base server which run a single handler function after select/poll/epoll on socket. My first question is that is this tornado/eventlet similar to n...
[ "Nonblocking servers are the best choice provided all your libraries provides nonblocking apis. As mentioned in your second question if a library blocks (eg database lib making a blocking call), the entire process/thread blocks and the system hangs. Not all of the libraries available are asynchronous which makes i...
[ 4 ]
[]
[]
[ "asynchronous", "http", "java", "nonblocking", "python" ]
stackoverflow_0005025770_asynchronous_http_java_nonblocking_python.txt
Q: Python subprocesses experience mysterious delay in receiving stdin EOF I reduced a problem I was seeing in my application down into the following test case. In this code, a parent process concurrently spawns 2 (you can spawn more) subprocesses that read a big message from the parent over stdin, sleep for 5 seconds...
Python subprocesses experience mysterious delay in receiving stdin EOF
I reduced a problem I was seeing in my application down into the following test case. In this code, a parent process concurrently spawns 2 (you can spawn more) subprocesses that read a big message from the parent over stdin, sleep for 5 seconds, and write something back. However, there's unexpected waiting happening so...
[ "After way too much time, I figured it out, after a quote from this post jumped out at me:\n\nSee the \"I/O on Pipes and FIFOs\" section of pipe(7) (\"man 7 pipe\")\n\"If all file descriptors referring to the write end of a pipe have\n been closed, then an attempt to read(2) from the pipe will see\n end-of-file (...
[ 6 ]
[]
[]
[ "pipe", "python", "subprocess" ]
stackoverflow_0004940607_pipe_python_subprocess.txt
Q: Non Blocking Server in Python Can someone please tell how to write a Non-Blocking server code using the socket library alone.Thanks A: Frankly, just don't (unless it's for an exercise). The Twisted Framework will do everything network-related for you, so you have to write only your protocol without caring about ...
Non Blocking Server in Python
Can someone please tell how to write a Non-Blocking server code using the socket library alone.Thanks
[ "Frankly, just don't (unless it's for an exercise). The Twisted Framework will do everything network-related for you, so you have to write only your protocol without caring about the transport layer. Writing socket code is not easy, so why not use code somebody else wrote and tested.\n", "Why socket alone? It's s...
[ 5, 2, 0, 0 ]
[]
[]
[ "nonblocking", "python", "sockets" ]
stackoverflow_0001515686_nonblocking_python_sockets.txt
Q: How to convert python3-pyqt code into .app file for mac os x? for python2.x py2app will do the work. But for python3 code which one is alternate to go ahead? Or is there any other way to get single .app file? A: py2app claims to support Python 3, so you should be able to use it.
How to convert python3-pyqt code into .app file for mac os x?
for python2.x py2app will do the work. But for python3 code which one is alternate to go ahead? Or is there any other way to get single .app file?
[ "py2app claims to support Python 3, so you should be able to use it.\n" ]
[ 0 ]
[]
[]
[ "macos", "python", "python_3.x" ]
stackoverflow_0003307083_macos_python_python_3.x.txt
Q: My model field gives me Value u'0' is not a valid choice error? FOOBAR = ( (0, 'foo'), (1, 'bar'), ) class Foobaz(models.Model): type = models.CharField(max_length=1, choices=FOOBAR, \ verbose_name=_('foobar type')) class FoobazForm(forms.ModelForm): class M...
My model field gives me Value u'0' is not a valid choice error?
FOOBAR = ( (0, 'foo'), (1, 'bar'), ) class Foobaz(models.Model): type = models.CharField(max_length=1, choices=FOOBAR, \ verbose_name=_('foobar type')) class FoobazForm(forms.ModelForm): class Meta: model = Foobaz fields = ('type') In views foo_form ...
[ "All I know about django is that it is a candidate for least euphonous package name of the decade, so this is a guess:\nUsers key in characters, not integers, so you should use:\nFOOBAR = (\n ('0', 'foo'),\n ('1', 'bar'),\n )\n\nUpdate Google is our friend: Here's some seemingly relevant documentation.\n" ...
[ 2 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0005049675_django_django_forms_django_models_python.txt
Q: Migrating an Asterisk interaction program to a web app from a command line python script I am trying to create a small web application to interact with the Asterisk telephony platform. There is a lot of similiar stuff out there but I want the learning experience of making my own. Here is what I have now: A simple...
Migrating an Asterisk interaction program to a web app from a command line python script
I am trying to create a small web application to interact with the Asterisk telephony platform. There is a lot of similiar stuff out there but I want the learning experience of making my own. Here is what I have now: A simple python script that allows someone to interact with the manager interface via the command line...
[ "I'd recommend just wrapping the code you have in a wsgi interface, which is python standard for web services (something like cgi but with functions instead of programs, so it has simpler interface and can be precompiled in the web server).\nThe WSGI web contains links to many python web application frameworks too,...
[ 1, 1 ]
[]
[]
[ "asterisk", "asteriskami", "php", "python", "web_applications" ]
stackoverflow_0005049793_asterisk_asteriskami_php_python_web_applications.txt
Q: Python localhost server/client network code to add/subtract/multiply/divide two numbers? I've recently been reading "Foundations of Python Network Programming" as I am interested in computer networks and for practice made up some code based off of the first few sample programs I saw in the book.. in this case I "w...
Python localhost server/client network code to add/subtract/multiply/divide two numbers?
I've recently been reading "Foundations of Python Network Programming" as I am interested in computer networks and for practice made up some code based off of the first few sample programs I saw in the book.. in this case I "wrote" a TCP server that binds to the localhost and a random port and a client that connects to...
[ "Twisted is about the best network engine on offer anywhere. It will handle everything you want in a nice and friendly chunk of code which is both CPU and IO friendly to your machine.\nhttp://twistedmatrix.com/trac/\n" ]
[ 2 ]
[ "Going forward it is going to be much easier to use some sort of network package instead of just relying on the python standard library. I think 0MQ would be a good place to start, it has easy to work with and learn python bindings, most of what you are learning already still applies, and it is fast and efficient....
[ -1, -1 ]
[ "networking", "python" ]
stackoverflow_0005049895_networking_python.txt
Q: Python. The coding of a string >>> word = '\u041a\u041e\u041b' >>> print u'\u041a\u041e\u041b' КОЛ >>> print word \u041a\u041e\u041b How to transform string as a variable to a readable kind (how print word)? A: >>> print '\u041a\u041e\u041b'.decode('unicode-escape') КОЛ
Python. The coding of a string
>>> word = '\u041a\u041e\u041b' >>> print u'\u041a\u041e\u041b' КОЛ >>> print word \u041a\u041e\u041b How to transform string as a variable to a readable kind (how print word)?
[ ">>> print '\\u041a\\u041e\\u041b'.decode('unicode-escape')\nКОЛ\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0005050267_python.txt
Q: How can i ignore server response to save bandwidth? I am using a server to send some piece of information to another server every second. The problem is that the other server response is few kilobytes and this consumes the bandwidth on the first server ( about 2 GB in an hour ). I would like to send the request an...
How can i ignore server response to save bandwidth?
I am using a server to send some piece of information to another server every second. The problem is that the other server response is few kilobytes and this consumes the bandwidth on the first server ( about 2 GB in an hour ). I would like to send the request and ignore the return ( not even receive it to save bandwid...
[ "A 5K reply is small stuff and is probably below the standard TCP window size of your OS. This means that even if you close your network connection just after sending the request and checking just the very first bytes of the reply (to be sure that request has been really received) probably the server already sent y...
[ 2, 2, 1 ]
[]
[]
[ "python", "response" ]
stackoverflow_0005049244_python_response.txt
Q: How to check network bandwidth with Python? As asked, I would like my script to check network bandwidth giving me any idea how fast user can surf through web. Is there any library, which allows me to specify size of package to be send and gives ping time or whatever? A: This answer mentions a Python implementati...
How to check network bandwidth with Python?
As asked, I would like my script to check network bandwidth giving me any idea how fast user can surf through web. Is there any library, which allows me to specify size of package to be send and gives ping time or whatever?
[ "This answer mentions a Python implementation of ping that returns the ICMP packet's round-trip time. You can use the improved code from the comment: https://gist.github.com/255009.\nBut note that since it uses raw sockets, your Python script will need to run as root.\n" ]
[ 1 ]
[]
[]
[ "bandwidth", "ping", "python" ]
stackoverflow_0005050405_bandwidth_ping_python.txt
Q: Django django-admin-tools DashboardModule - HTML Content The django-admin-tools says, we can use HTML (or) Text in the children. But It's escaping the given HTML Tags. All the tags have been displayed as given without rendering. self.children.append(modules.DashboardModule( title = 'Example', ...
Django django-admin-tools DashboardModule - HTML Content
The django-admin-tools says, we can use HTML (or) Text in the children. But It's escaping the given HTML Tags. All the tags have been displayed as given without rendering. self.children.append(modules.DashboardModule( title = 'Example', children = ['<b>bold example</b>',], ))
[ "edit the template\n\nadmin_tools/dashboard/module.html\n\nand add \n\n{% autoescape off %} {% endautoescape\n %}\n\n", "From the documentation:\npre_content\nText or HTML content to display above the module content. Default value: None.\n\ncontent\nThe module text or HTML content. Default value: None.\n\npost_c...
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0005043993_django_django_admin_python.txt
Q: Relationship between objects and classes in Python 3 I thought that I realized this relationship: In Python everything is an object, and every object has a type. But what about classes? A class is a blueprint of an object, and an object is instance of a class. But I have read in an article that in Python, classes ...
Relationship between objects and classes in Python 3
I thought that I realized this relationship: In Python everything is an object, and every object has a type. But what about classes? A class is a blueprint of an object, and an object is instance of a class. But I have read in an article that in Python, classes are themselves objects. I thought that an object cannot ex...
[ "Everything that can be given a name in Python is an object - including functions, classes and metaclasses. Every object has an associated type or class (these are two names for the same thing -- \"type\" and \"class\" are the same in Python 3). The type itself is an object again, and has itself an associated typ...
[ 8 ]
[]
[]
[ "class", "object", "oop", "python", "types" ]
stackoverflow_0005050654_class_object_oop_python_types.txt
Q: magnetic field visualization with quiver-function in Python I want to visualize the magnetic field of a wire with the quiver function. #Calculation of a magnetic field of a wire import matplotlib import numpy as np import matplotlib.pyplot as plt from pylab import * I = 100000000000 constant = 1e-7/(4*np.pi) #...
magnetic field visualization with quiver-function in Python
I want to visualize the magnetic field of a wire with the quiver function. #Calculation of a magnetic field of a wire import matplotlib import numpy as np import matplotlib.pyplot as plt from pylab import * I = 100000000000 constant = 1e-7/(4*np.pi) # wire elements; always lenght one coord = [(10,10,0), (11,10,0), ...
[ "it looks like quiver only supports 2d plots right now, but you could make it 3d by plotting multiple 2d layers into a 3d plot. You can follow my example to see how to do these layers.\n", "ValueError: too many values to unpack\n\nThat means you have more values on the RHS than variables on the LHS\n" ]
[ 1, 0 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0005050657_matplotlib_numpy_python.txt
Q: Why is RabbitMQ not persisting messages on a durable queue? I am using RabbitMQ with Django through Celery. I am using the most basic setup: # RabbitMQ connection settings BROKER_HOST = 'localhost' BROKER_PORT = '5672' BROKER_USER = 'guest' BROKER_PASSWORD = 'guest' BROKER_VHOST = '/' I imported a Celery task and...
Why is RabbitMQ not persisting messages on a durable queue?
I am using RabbitMQ with Django through Celery. I am using the most basic setup: # RabbitMQ connection settings BROKER_HOST = 'localhost' BROKER_PORT = '5672' BROKER_USER = 'guest' BROKER_PASSWORD = 'guest' BROKER_VHOST = '/' I imported a Celery task and queued it to run one year later. From the iPython shell: In [1]:...
[ "Making a queue durable is not the same as making the messages on it persistent. Durable queues mean they come up again automatically when the server has restarted - which has obviously happened in your case. But this doesn't affect the messages themselves.\nTo make messages persistent, you have to also mark the me...
[ 22, 6 ]
[]
[]
[ "celery", "django", "python", "rabbitmq" ]
stackoverflow_0005046944_celery_django_python_rabbitmq.txt
Q: Access to field in extended flatpage in django How to access field in extended flatpage in django? I wrote this: class ExtendedFlatPage(FlatPage): teaser = CharField(max_length=150) class ExtendedFlatPageForm(FlatpageForm): teaser = CharField(max_length=150) class Meta: model = ExtendedFlat...
Access to field in extended flatpage in django
How to access field in extended flatpage in django? I wrote this: class ExtendedFlatPage(FlatPage): teaser = CharField(max_length=150) class ExtendedFlatPageForm(FlatpageForm): teaser = CharField(max_length=150) class Meta: model = ExtendedFlatPage class ExtendedFlatPageAdmin(FlatPageAdmin): ...
[ "Yes, as rebus mentioned the FlatpageFallbackMiddleware will pass default FlatPage model instance to the template. But in your case template variable {{ flatpage }} will also remember if it's ExtendedFlatPage instance, as described here in django-docs.\nSo to treat your flatpage as ExtendedFlatPage you have to use:...
[ 6, 0 ]
[]
[]
[ "django", "django_flatpages", "python" ]
stackoverflow_0004507760_django_django_flatpages_python.txt
Q: Calling functions with argparse I'm having issues calling functions from argpars. This is a simplified version of my script and this works, printing whatever value I give -s or -p import argparse def main(): parser = argparse.ArgumentParser(description="Do you wish to scan for live hosts or conduct a port sc...
Calling functions with argparse
I'm having issues calling functions from argpars. This is a simplified version of my script and this works, printing whatever value I give -s or -p import argparse def main(): parser = argparse.ArgumentParser(description="Do you wish to scan for live hosts or conduct a port scan?") parser.add_argument("-s", d...
[ "It is not identical, see this question for explanation why.\nYou have (at least) 2 options:\n\nPass the args as an argument to your function\nMake args a global variable.\n\nI'm not sure if others agree, but personally I would move all the parser functionality to be inside the if statement, i.e, the main would loo...
[ 7, 2 ]
[]
[]
[ "argparse", "function", "python" ]
stackoverflow_0005050920_argparse_function_python.txt
Q: in need of a simple example that shows serverside python program passing data to webserver are there any simple examples you know of that demonstrate how a python program can pass data to a webserver? ive been looking for so long but i still cannot find any. something simple will do. say for example, a python prog...
in need of a simple example that shows serverside python program passing data to webserver
are there any simple examples you know of that demonstrate how a python program can pass data to a webserver? ive been looking for so long but i still cannot find any. something simple will do. say for example, a python program that generates some text or number that the webserver accepts and updates a field in a local...
[ "Generally speaking the easiest way to do this would be with urllib2.\nDepending on what exactly you mean by \"updates a field in a local site\" you probably either want to send data in a GET or POST variable. Below are examples of doing each:\nGET request:\nimport urllib2\n\nresponse = urllib2.urlopen('http://exa...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005051019_python.txt
Q: what's differece between the django's cache ?the The per-site cache,The per-view cache,Specifying per-view cache and Template fragment caching i know the django has some cache method such as the The per-site cache,The per-view cache,Specifying per-view cache and Template fragment caching but what's differece betwe...
what's differece between the django's cache ?the The per-site cache,The per-view cache,Specifying per-view cache and Template fragment caching
i know the django has some cache method such as the The per-site cache,The per-view cache,Specifying per-view cache and Template fragment caching but what's differece between those cache ? the per-site cache means the cache system cache the whole site ? how can i understand the words 'cache the whole site'?
[ "I think the docs do a great job of describing this but I will paste it here and give a little description as well. \nCache the whole site means django will attempt to cache every view you've set up via middleware.\nPer site cache docs\nhttp://docs.djangoproject.com/en/dev/topics/cache/#the-per-site-cache\n\nOnce t...
[ 7 ]
[]
[]
[ "caching", "django", "memcached", "python" ]
stackoverflow_0005050876_caching_django_memcached_python.txt
Q: Problem with django nose and south having multiple databases I had a django project with one database (default). South was installed for generating migration scripts and nose as a test framework. Models were built on this database. All tests were run successfully. Subsequently, I needed to connect a second databas...
Problem with django nose and south having multiple databases
I had a django project with one database (default). South was installed for generating migration scripts and nose as a test framework. Models were built on this database. All tests were run successfully. Subsequently, I needed to connect a second database (legacy), which I also added to the DATABASES configuration. I a...
[ "Your path of least resistance is probably to write your own test running management command. To do so you can either override the existing command or simply create a separate command with your desired behavior.\nThe docs for creating custom management commands can be found on the official django docs and you can ...
[ 0 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0004909575_django_django_south_python.txt
Q: app-engine and python. how to go to subpath I know users.create_logout('example') can direct to users to the path under the current path. like /main/example/, but what if i want to direct the users to the subpath of the example, say /main/example/example1, how do I do that? Thank you a lot A: The docs say: crea...
app-engine and python. how to go to subpath
I know users.create_logout('example') can direct to users to the path under the current path. like /main/example/, but what if i want to direct the users to the subpath of the example, say /main/example/example1, how do I do that? Thank you a lot
[ "The docs say:\n\ncreate_logout_url(dest_url)\n Returns\n a URL that, when visited, signs the\n user out, then redirects the user back\n to the URL given as dest_url. This URL\n is suitable for links, buttons and\n redirects. dest_url can be full URL or\n a path relative to your application's\n domain.\n\n....
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005051023_google_app_engine_python.txt
Q: Python sqlite3 module not rolling back transactions Consider this test case: import sqlite3 con1 = sqlite3.connect('test.sqlite') con1.isolation_level = None con2 = sqlite3.connect('test.sqlite') con2.isolation_level = None cur1 = con1.cursor() cur2 = con2.cursor() cur1.execute('CREATE TABLE foo (bar INTEGER, baz...
Python sqlite3 module not rolling back transactions
Consider this test case: import sqlite3 con1 = sqlite3.connect('test.sqlite') con1.isolation_level = None con2 = sqlite3.connect('test.sqlite') con2.isolation_level = None cur1 = con1.cursor() cur2 = con2.cursor() cur1.execute('CREATE TABLE foo (bar INTEGER, baz STRING)') con1.isolation_level = 'IMMEDIATE' cur1.execut...
[ "You can't both commit and rollback the same transaction. con1.commit() ends your transaction on that cursor. The next con1.rollback() is either being silently ignored or is rolling back an empty transaction.\n" ]
[ 3 ]
[]
[]
[ "python", "rollback", "sqlite" ]
stackoverflow_0005051151_python_rollback_sqlite.txt
Q: Python variable's between Modules/Classes SiteGrab.py class ThreadManager: bla bla bla bla While True: #### Ask if/unitl all sites are resolved if allsites got = True: for i in range(allsites): HTML[i].insert(0, "this is a peice of text") break def ...
Python variable's between Modules/Classes
SiteGrab.py class ThreadManager: bla bla bla bla While True: #### Ask if/unitl all sites are resolved if allsites got = True: for i in range(allsites): HTML[i].insert(0, "this is a peice of text") break def GetDNS(self): global HTML retu...
[ "\nI would like to be notified AS EACH website is finished.\n\nBy whom? How? This makes very little sense. Do you want it to \"bing!\" when it's done? Add that to the script.\n\nI want them to trickle in as they finish.\n\nTrickle in to where? A file? A directory? \nWhat does execute.py do with these sites? ...
[ 0, 0, 0 ]
[]
[]
[ "class", "python", "variables" ]
stackoverflow_0005051218_class_python_variables.txt
Q: Biopython CodonTable error? I am writing some code intended to translate ambiguous DNA codes into possible amino acids and I am seeing some strange translation from the Biopython 1.56 package. It appears to be translating ambiguous DNA codes to 'J' which does not exist as a code for anything. I am running python...
Biopython CodonTable error?
I am writing some code intended to translate ambiguous DNA codes into possible amino acids and I am seeing some strange translation from the Biopython 1.56 package. It appears to be translating ambiguous DNA codes to 'J' which does not exist as a code for anything. I am running python 2.6.1 on Mac OS 10.6.6. For exa...
[ "J is Leucine (L) or Isoleucine (I), used in mass-spec (NMR).\nSee also http://biostar.stackexchange.com/questions/5688/biopython-translation-error\n" ]
[ 4 ]
[]
[]
[ "biopython", "python" ]
stackoverflow_0005045967_biopython_python.txt
Q: Elegant Way To Share Variable Between Windows Form and Python Script Running In Background Process I am trying to figure out an elegant way to share a variable between a windows form app and a python script running in the background. The variable would be used solely to update a progress bar in the windows form b...
Elegant Way To Share Variable Between Windows Form and Python Script Running In Background Process
I am trying to figure out an elegant way to share a variable between a windows form app and a python script running in the background. The variable would be used solely to update a progress bar in the windows form based on the the long running process in the python script. More specifically, a windows timer will fire...
[ "Easiest solution is probably to just have the python script print to stdout: say each time an item is processed, print a line with a number representing how many items have been processed (or a percentage). Then have the forms application read the output line by line, updating the progressbar based on that informa...
[ 1, 0 ]
[]
[]
[ "global_variables", "python", "winforms" ]
stackoverflow_0005030586_global_variables_python_winforms.txt
Q: emails as email.Message class objects in Python How do I use poplib, and download mails as message instances from email.Message class from email module in Python? I am writing a program, which analyzes, all emails for specific information, storing parts of the message into a database. I can download the entire mai...
emails as email.Message class objects in Python
How do I use poplib, and download mails as message instances from email.Message class from email module in Python? I am writing a program, which analyzes, all emails for specific information, storing parts of the message into a database. I can download the entire mail as text, howver walking through text searching for ...
[ "use the FeedParser class in the email.feedparser module to construct an email.Message object from the messages read from the server with poplib.\nspecifically:\nimport poplib\nimport email\n\npop = poplib.POP3( \"server...\" )\n[establish connection, authenticate, ...]\nraw = pop.retr( 1 )\npop.close()\n\nparser =...
[ 3, 2 ]
[]
[]
[ "email", "parsing", "pop3", "python" ]
stackoverflow_0001674962_email_parsing_pop3_python.txt
Q: Attribute errors in basic Python script This is a very basic portscan/ping sweep script. The two functions work fine when I just use them individually in another script, but as soon as I try them in this script I get attribute errors #!/usr/bin/python2.7 import argparse import socket import sys def main(): ...
Attribute errors in basic Python script
This is a very basic portscan/ping sweep script. The two functions work fine when I just use them individually in another script, but as soon as I try them in this script I get attribute errors #!/usr/bin/python2.7 import argparse import socket import sys def main(): parser = argparse.ArgumentParser(description=...
[ "When you call portscan, you call it with args.ip, not args.\nYou could fix it by doing this:\nif args.ip != None:\n portscan(args)\n\nAlternatively, if you want to only pass in the ip, you need to remember that you're giving the function the IP, and not the arguments object.\nThe same goes for pingsweep. \n", ...
[ 1, 1, 0 ]
[]
[]
[ "attributeerror", "python" ]
stackoverflow_0005051758_attributeerror_python.txt
Q: Sharing a database between Twisted and Django I am developing a multiplayer gaming server that uses Django for the webserver (HTML frontend, user authentication, games available, leaderboard, etc.) and Twisted to handle connections between the players and the games and to interface with the games themselves. The ...
Sharing a database between Twisted and Django
I am developing a multiplayer gaming server that uses Django for the webserver (HTML frontend, user authentication, games available, leaderboard, etc.) and Twisted to handle connections between the players and the games and to interface with the games themselves. The gameserver, the webserver, and the database may run...
[ "First of all I'd identify why you need both Django and Twisted. Assuming you are comfortable with Twisted using twisted.web and auth will easily be sufficient and you'll be able to reuse your database layer for both the frontend and backend apps.\nAlternatively you could look at it the other way, what is Twisted ...
[ 10, 2 ]
[]
[]
[ "database", "django", "python", "twisted" ]
stackoverflow_0005051408_database_django_python_twisted.txt
Q: Android , Read in binary data and write it to file Im trying to read in image file from a server , with the code below . It keeps going into the exception. I know the correct number of bytes are being sent as I print them out when received. Im sending the image file from python like so #open the image file and rea...
Android , Read in binary data and write it to file
Im trying to read in image file from a server , with the code below . It keeps going into the exception. I know the correct number of bytes are being sent as I print them out when received. Im sending the image file from python like so #open the image file and read it into an object imgfile = open (marked_image...
[ "The best way to get a bitmap from a server is to execute the following.\nHttpClient client = new DefaultHttpClient();\n\nHttpGet get = new HttpGet(\"http://yoururl\");\n\nHttpResponse response = client.execute(get);\nInputStream is = response.getEntity().getContent();\n\nBitmap image = BitmapFactory.decodeStream(i...
[ 1, 0, -1 ]
[]
[]
[ "android", "file_io", "python", "sockets" ]
stackoverflow_0005032153_android_file_io_python_sockets.txt
Q: Matrix multiplication running times Python < C++ < Matlab - Explain I have a matrix M thats's 16384 x 81. I want to compute M * M.t (the result will be 16384x16384). My question is: could somebody please explain the running time differences? Using OpenCV in C++ the following code takes 18 seconds #include <cv.h> #...
Matrix multiplication running times Python < C++ < Matlab - Explain
I have a matrix M thats's 16384 x 81. I want to compute M * M.t (the result will be 16384x16384). My question is: could somebody please explain the running time differences? Using OpenCV in C++ the following code takes 18 seconds #include <cv.h> #include <cstdio> using namespace cv; int main(void) { Mat m(16384, 81, ...
[ "What CPU are you running on? For modern x86 and x64 chips with dynamic clocking, getTickCount and getTickFrequency cannot be trusted.\n18 seconds is long enough to get acceptable precision from the standard OS functions based on the timer interrupt.\nAnd what BLAS are you using with OpenCV? MatLab installs some ...
[ 3 ]
[]
[]
[ "c++", "matlab", "matrix_multiplication", "opencv", "python" ]
stackoverflow_0005051545_c++_matlab_matrix_multiplication_opencv_python.txt
Q: Semantic error using if/else to make abecedarian series My program is supposed to output: Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. suffix="ack" prefix="JKLMNOPQ" for i in prefix: if prefix=="Q" or "O": suffix="uack" else: suffix="ack" print i + suffix But instead it outp...
Semantic error using if/else to make abecedarian series
My program is supposed to output: Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. suffix="ack" prefix="JKLMNOPQ" for i in prefix: if prefix=="Q" or "O": suffix="uack" else: suffix="ack" print i + suffix But instead it outputs Juack, Kuack, Luack, Muack Nuack Ouack Puack Quack
[ "\nYou are comparing prefix (a string containing several letters) - instead of the current character, i - to single letters. They are never equal. I'd suggest better names (which would make the error obvious): prefixes = \"JK...\" and for prefix in prefixes:.\nYou are coercing \"O\" to a boolean by using it, withou...
[ 5, 1, 1 ]
[]
[]
[ "for_loop", "if_statement", "python", "traversal" ]
stackoverflow_0005051981_for_loop_if_statement_python_traversal.txt
Q: function arguments in python I'm trying to wrap my head around the way positional and keyword arguments work in python, and, it seems, I'm failing rather miserably. Given a function with a call signature matplotlib.pyplot.plot(*args,**kwargs), it can be called as import matplotlib.pyplot as plt x=[1,2,3] y=[5,6,...
function arguments in python
I'm trying to wrap my head around the way positional and keyword arguments work in python, and, it seems, I'm failing rather miserably. Given a function with a call signature matplotlib.pyplot.plot(*args,**kwargs), it can be called as import matplotlib.pyplot as plt x=[1,2,3] y=[5,6,7] plt.plot(x,y,'ro-') plt.show() ...
[ "You need it this way:\ndef mplot(x,y,fmt,*args,**kwargs):\n #do stuff with x, y and fmt\n return plt.plot(*args,**kwargs)\n\nI'm assuming that your intention is to consume the x, y and fmt in your mplot routine and then pass the remaining parameters to plt.plot.\n\nI don't believe that this is actually what yo...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005052136_matplotlib_python.txt
Q: erlang interface to python I've been expanding on python version of Armstrong's classical example of interfaces. Everything works fine while I communicate bytes. But, I'd like to communicate long integers and floats. Mabye even (oh, no) strings. Here is my code: http://pastebin.com/epxgDmvu http://pastebin.com/rD7...
erlang interface to python
I've been expanding on python version of Armstrong's classical example of interfaces. Everything works fine while I communicate bytes. But, I'd like to communicate long integers and floats. Mabye even (oh, no) strings. Here is my code: http://pastebin.com/epxgDmvu http://pastebin.com/rD7CWRkz First of all, all that I k...
[ "At a low (from programming point of view) level you always send/receive only a bunch of bytes through different external interfaces (pipes, network, files...) independently from a programming language you're using. For example when you work with pipes (which you got calling open_port/2) you send/receive data as a ...
[ 5 ]
[]
[]
[ "erlang", "python" ]
stackoverflow_0005050758_erlang_python.txt
Q: Cross platform process enumerator for Python? I need a cross-platform module which allows me to enumerate processes on the machine. It needs to work on Windows and Unix, and get things like PID and Process Names. Is there such module? A: psutil should work nicely for this. "psutil is a module providing an interf...
Cross platform process enumerator for Python?
I need a cross-platform module which allows me to enumerate processes on the machine. It needs to work on Windows and Unix, and get things like PID and Process Names. Is there such module?
[ "psutil should work nicely for this.\n\"psutil is a module providing an interface for retrieving information on all running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by command line tools like ps, top, kill, lsof and netstat.\"\n" ]
[ 5 ]
[]
[]
[ "process_management", "python" ]
stackoverflow_0005052672_process_management_python.txt
Q: Error when using lambda function with Cython I am trying to use Cython to speed up a piece of code. Cython is giving an error that reads "Expected an identifier or literal" when I use lambda functions. As far as I can tell, lambda functions are meant to be supported in Cython 0.13. Am I incorrect on this point?...
Error when using lambda function with Cython
I am trying to use Cython to speed up a piece of code. Cython is giving an error that reads "Expected an identifier or literal" when I use lambda functions. As far as I can tell, lambda functions are meant to be supported in Cython 0.13. Am I incorrect on this point? If they are, indeed, supported, do I need to do ...
[ "In my opinion you should change h_z = lambda e_1: -inf with h_z = lambda e_1: -float('inf') unless you have defined inf somewhere else.\n", "I'm able to compile the below simplified Cython code and run it fine using Cython 0.14.1 on OS X 10.6.6. I don't know the details as to why it doesn't work on 0.13. The e...
[ 2, 0 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0004295684_cython_python.txt
Q: How to create the subpaths that exactly match to the users’ name After I direct the users to their pages, like /example/john, how do I make the webapp.RequestHandler to handle the this page? If I do this ('/user.*', UsersSubPath) that matches the all pages after /user/, If I do ('/user/user.name*', UsersSubPath), ...
How to create the subpaths that exactly match to the users’ name
After I direct the users to their pages, like /example/john, how do I make the webapp.RequestHandler to handle the this page? If I do this ('/user.*', UsersSubPath) that matches the all pages after /user/, If I do ('/user/user.name*', UsersSubPath), that’s not working either since it can’t substitute the user.name by t...
[ "You need to capture that part of the URL using a regular expression, and then pass that captured text to your handler method as an argument, something like this:\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import util\n\n\nclass ExampleHandler(webapp.RequestHandler):\n def get(sel...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005053028_google_app_engine_python.txt
Q: How to run console application silently in Python (on windows) Possible Duplicate: How do I eliminate Windows consoles from spawned processes in Python (2.7)? Hi, In my application I am using external console application. I am catching its output (from std out) and process it. What is happening though that ever...
How to run console application silently in Python (on windows)
Possible Duplicate: How do I eliminate Windows consoles from spawned processes in Python (2.7)? Hi, In my application I am using external console application. I am catching its output (from std out) and process it. What is happening though that every time I start this application the console window is popping out w...
[ "Create a Windows shortcut to the Python script and then set the shortcut's Run property to Minimized.\n", "You could try using a utility like hstart. You might have to redirect the output to a file and then read from that after the command finishes, though. Cygwin has a similar tool called run.exe if you have ...
[ 0, 0 ]
[]
[]
[ "console_application", "popen", "python", "windows" ]
stackoverflow_0005052730_console_application_popen_python_windows.txt
Q: Extending numpy with cython I am trying to wrap a header file which has lots of functions like this test.h void test(int N, int* data_in, int* data_out); so that I can use those from numpy. Right now I have the following cython code: test.pyx import numpy as np cimport numpy as np ctypedef np.int_t itype_t cde...
Extending numpy with cython
I am trying to wrap a header file which has lots of functions like this test.h void test(int N, int* data_in, int* data_out); so that I can use those from numpy. Right now I have the following cython code: test.pyx import numpy as np cimport numpy as np ctypedef np.int_t itype_t cdef extern from 'VolumeForm.h': ...
[ "This issue is currently being discussed on the Cython mailing list; apparently it stems from a small bug in one of the Cython libraries:\nhttp://codespeak.net/mailman/listinfo/cython-dev\nFor the moment, one potential workaround is to use NumPy arrays of dtype np.long, and then to write 'ctypedef np.long_t itype_t...
[ 4, 2 ]
[]
[]
[ "cython", "numpy", "python", "word_wrap" ]
stackoverflow_0001944006_cython_numpy_python_word_wrap.txt
Q: How to get current access_token in graph api? i working on graph api in python in appengine , and i want to get access_token to to be able to create a new album base_url = "https://graph.facebook.com/me/albums" encoded_album_name= urllib.quote("refacingme.appspot.com") name="&name="+encoded_album_name ...
How to get current access_token in graph api?
i working on graph api in python in appengine , and i want to get access_token to to be able to create a new album base_url = "https://graph.facebook.com/me/albums" encoded_album_name= urllib.quote("refacingme.appspot.com") name="&name="+encoded_album_name type="&type=post" access_token="&access_toke...
[ "The best way I've found to get the access token is to use the get_user_from_cookie method of the facebook python sdk. There's an example usage in the comments of the file: \nhttps://github.com/facebook/python-sdk/blob/master/src/facebook.py\nThis requires that the cookie gets set from the facebook javascript sdk ...
[ 0 ]
[]
[]
[ "facebook_graph_api", "google_app_engine", "python" ]
stackoverflow_0005049812_facebook_graph_api_google_app_engine_python.txt
Q: python: generate 24bit hash i need to genereate 24bit-length hashes from strings. After some googling, I've fount this: http://code.activestate.com/recipes/164274-fixed-size-cache/ , but, as for me, it is a bit overcomplex. Is there any other simple way to generate 24 bit hash? thanks! A: Does it need to by cryp...
python: generate 24bit hash
i need to genereate 24bit-length hashes from strings. After some googling, I've fount this: http://code.activestate.com/recipes/164274-fixed-size-cache/ , but, as for me, it is a bit overcomplex. Is there any other simple way to generate 24 bit hash? thanks!
[ "Does it need to by cryptographically secure? I think you could probably just truncate one of the hashes from hashlib.\n", "You could compute a 24-bit CRC check value and use it as a hash value. The Wikipedia article on cyclic redundancy check describes how to do this for n-bit CRCs and even has several generator...
[ 4, 1 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0005050353_hash_python.txt
Q: simple python question about urlopen I am trying to make a program that deletes all the tags in html document. So I made a program like this. import urllib loc_left = 0 while loc_left != -1 : html_code = urllib.urlopen("http://www.python.org/").read() loc_left = html_code.find('<') loc_right = html_co...
simple python question about urlopen
I am trying to make a program that deletes all the tags in html document. So I made a program like this. import urllib loc_left = 0 while loc_left != -1 : html_code = urllib.urlopen("http://www.python.org/").read() loc_left = html_code.find('<') loc_right = html_code.find('>') str_in_braket = html_cod...
[ "You've named a script string.py. The urllib module imports this, thinking that it's the same string module that's in the stdlib, and then your code uses an attribute on the now partially-defined urllib module that doesn't yet exist. Name your script something else.\n", "Step one is to download the document so yo...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005053504_python.txt
Q: Python search through file I'm working on a python script that tries to add itself to startup on Linux via ~/.bashrc. I want the script to search through ~/.bashrc to see if it's already added. If it is then I just want to continue with normal execution. If not, I want it to add itself to ~/.bashrc then continue. ...
Python search through file
I'm working on a python script that tries to add itself to startup on Linux via ~/.bashrc. I want the script to search through ~/.bashrc to see if it's already added. If it is then I just want to continue with normal execution. If not, I want it to add itself to ~/.bashrc then continue. This is what I'm currently tryin...
[ "you need to search the whole file and then either add the line or not, as the loop you have only checks the first line. because it break the loop right after either finding or not finding the name on the line.\nyou want:\nfound = False\nfor line in fileopen:\n if fname in line:\n found = True\n br...
[ 0, 0, 0 ]
[]
[]
[ "file", "python", "search", "startup", "system" ]
stackoverflow_0005053301_file_python_search_startup_system.txt
Q: Quitting Python socket client with open connection? The following script receiving data from a socket connection does not react to the CTRL+C signal sent in order to exit: #!/usr/bin/python # -*- coding: utf-8 -*- """ """ import socket HOST = '192.168.178.1' PORT = 1012 s = socket.socket(socket.AF_INET, socket.SOC...
Quitting Python socket client with open connection?
The following script receiving data from a socket connection does not react to the CTRL+C signal sent in order to exit: #!/usr/bin/python # -*- coding: utf-8 -*- """ """ import socket HOST = '192.168.178.1' PORT = 1012 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while 1: data = s.r...
[ "Use Select\nimport socket\nimport select\n\nHOST = '192.168.178.1'\nPORT = 1012\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setblocking(1)\ns.connect((HOST, PORT))\ntime_out=None\nready=[[s],[],[], time_out]\n\nif ready:\n s.recv(1024)\n\ns.close()\n\n", "One solution is to close the socket from ...
[ 0, 0 ]
[]
[]
[ "exit", "python", "signals", "sockets" ]
stackoverflow_0005052466_exit_python_signals_sockets.txt
Q: python, psycopg2, and bound parameters I have this guy: query = 'DELETE FROM boyd.%s WHERE teamid = %s AND id = %s AND year = %s' % (statstype, '%s', '%s', '%s') self.executequery(query, values[0:3]) Which strikes me as ugly. The first %s is actually supplied by the variable, the other three are bound variables: ...
python, psycopg2, and bound parameters
I have this guy: query = 'DELETE FROM boyd.%s WHERE teamid = %s AND id = %s AND year = %s' % (statstype, '%s', '%s', '%s') self.executequery(query, values[0:3]) Which strikes me as ugly. The first %s is actually supplied by the variable, the other three are bound variables: do I really need to go % (statstype, '%s', '...
[ "If you use double %% signs, one % will still remain after string interpolation:\nquery = 'DELETE FROM boyd.%s WHERE teamid = %%s AND id = %%s AND year = %%s' % (statstype)\nself.executequery(query, values[0:3])\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005053809_python.txt
Q: CDF 9/7 Discrete Wavelet Transform (Convolution) I'm trying to write a simple self-contained program that does a single level of a discrete wavelet transform on a 1D list, using the CDF 9/7 wavelets, and then reconstructs it. I'm just using the convolution/filter-bank method to get a grasp on how it works. In othe...
CDF 9/7 Discrete Wavelet Transform (Convolution)
I'm trying to write a simple self-contained program that does a single level of a discrete wavelet transform on a 1D list, using the CDF 9/7 wavelets, and then reconstructs it. I'm just using the convolution/filter-bank method to get a grasp on how it works. In other words, convolve the list with a filter to get the sc...
[ "Actually I solved it myself by comparing the coefficients, and then the reconstruction, with the code from this lifting implementation:\nhttp://www.embl.de/~gpau/misc/dwt97.c\nBasically, I\n1) Made the boundary conditions symmetric, instead of periodic\n2) Had to offset the convolutions (and the upsampling) in cer...
[ 2 ]
[]
[]
[ "haar_wavelet", "python", "wavelet" ]
stackoverflow_0005049984_haar_wavelet_python_wavelet.txt
Q: Adding dictionary indexes through a function I've been trying on how to add a new index in a dictionary using a for loop. I want to keep adding indexes with a for loop each time I enter the value, the 'index' through a function. So the dictionary just keep growing. For example: My dictionary has it's values as li...
Adding dictionary indexes through a function
I've been trying on how to add a new index in a dictionary using a for loop. I want to keep adding indexes with a for loop each time I enter the value, the 'index' through a function. So the dictionary just keep growing. For example: My dictionary has it's values as lists, and to add values to that list, I can use ...
[ "Firstly, as delnan noticed, you seem to have got a little confused in your addStuff function. I'm guessing you want it to add an item v to the list in the dictionary with key i. However, what your function actually does is add item v to every list in the dictionary regardless of what key it has. The value i you ...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005053403_python.txt
Q: django urls.py regex isn't working This is for Django 1.2.5 and Python 2.7 on Wamp Server running apache version 2.2.17. My problem is that the my URLConf in urls.py isn't redirecting, it's just throwing a 404 error. urls.py: from django.conf.urls.defaults import * # Uncomment the next two lines to enable the ad...
django urls.py regex isn't working
This is for Django 1.2.5 and Python 2.7 on Wamp Server running apache version 2.2.17. My problem is that the my URLConf in urls.py isn't redirecting, it's just throwing a 404 error. urls.py: from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: #from django.contrib import admin #...
[ "Yes, your url should look like this:\n(r'^app/$', 'app.views.index'),\n\nUsing the include statement means you are pointing to a new urlconf file!\nhttp://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs\nSo it's looking for a module index which doesn't exist (as opposed to a function if yo...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005054146_django_python.txt
Q: Is it possible to 'import * from DIRECTORY', then somehow (anyhow) iterate over the loaded modules? Let me explain the use case... In a simple python web application framework designed for Google App Engine, I'd like to have my models loaded automatically from a 'models' directory, so all that's needed to add a mo...
Is it possible to 'import * from DIRECTORY', then somehow (anyhow) iterate over the loaded modules?
Let me explain the use case... In a simple python web application framework designed for Google App Engine, I'd like to have my models loaded automatically from a 'models' directory, so all that's needed to add a model to the application is place a file user.py (for example), which contains a class called 'User', in th...
[ "You can read from the filesystem in GAE just fine; you just can't write to the filesystem.\nfrom models import * will only import modules listed in __all__ in models/__init__.py; there's no automatic way to import all modules in a package if they're not declared to be part of the package. You just need to read the...
[ 4, 1, 1 ]
[]
[]
[ "google_app_engine", "import", "python" ]
stackoverflow_0005054191_google_app_engine_import_python.txt